28#include "common/config.h"
46#include <glm/gtc/constants.hpp>
51wgpu::Sampler Graphics::makeSampler(
const TextureSampler&
s, uint32_t mipLevels)
const {
52 WGPUSamplerDescriptor
d{};
53 d.label =
sv(
"eve_sampler");
54 d.addressModeU =
s.repeatU ? WGPUAddressMode_Repeat : WGPUAddressMode_ClampToEdge;
55 d.addressModeV =
s.repeatV ? WGPUAddressMode_Repeat : WGPUAddressMode_ClampToEdge;
56 d.addressModeW =
s.repeatW ? WGPUAddressMode_Repeat : WGPUAddressMode_ClampToEdge;
60 d.mipmapFilter = WGPUMipmapFilterMode_Nearest;
64 d.mipmapFilter =
s.mipmap ==
MipmapMode::Nearest ? WGPUMipmapFilterMode_Nearest : WGPUMipmapFilterMode_Linear;
65 d.lodMinClamp =
s.minLod;
66 d.lodMaxClamp = std::min(std::max(
s.maxLod, 0.f),
float(mipLevels - 1));
67 if (
d.lodMaxClamp <
d.lodMinClamp)
d.lodMaxClamp =
d.lodMinClamp;
69 float aniso =
s.maxAnisotropy > 1.f ?
s.maxAnisotropy : 1.f;
70 d.maxAnisotropy =
static_cast<uint16_t
>(std::min(std::max(aniso, 1.f), std::max(maxSamplerAnisotropy, 1.f)));
71 return device.CreateSampler(
reinterpret_cast<const wgpu::SamplerDescriptor*
>(&
d));
86 if (!data)
throw Exception(
"newTexture: null ImageData");
88 return newTexture(data->getWidth(), data->getHeight(),
static_cast<const uint8_t*
>(data->getData()),
info);
92 if (!data)
throw Exception(
"newTexture: null ImageData");
93 if (data->getFormat() !=
"RGBA8")
throw Exception(
"newTexture: only RGBA8 supported");
94 return newTexture(data->getWidth(), data->getHeight(),
static_cast<const uint8_t*
>(data->getData()),
info);
98 if (!data || contentKey.empty() || data->getFormat() !=
"RGBA8")
100 "RGBA8 image and nonempty content key are required", {},
101 {},
"graphics.texture.shared"));
102 if (
auto found = sharedTexturesByContent.find(contentKey);
found != sharedTexturesByContent.end())
107 sharedTexturesByContent.emplace(contentKey,
texture);
109 }
catch (
const std::exception&
error) {
120 if (
info.sampler.maxAnisotropy < 1.f)
info.sampler.maxAnisotropy = 1.f;
122 auto gpu = std::make_unique<GpuTexture>();
125 gpu->samplerState =
info.sampler;
128 WGPUTextureDescriptor td{};
129 td.label =
sv(
"eve_tex2d");
130 td.dimension = WGPUTextureDimension_2D;
131 td.size.width =
static_cast<uint32_t
>(
width);
132 td.size.height =
static_cast<uint32_t
>(
height);
133 td.size.depthOrArrayLayers = 1;
135 td.format = WGPUTextureFormat_RGBA8Unorm;
136 td.mipLevelCount =
gpu->mipLevels;
137 td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst | WGPUTextureUsage_RenderAttachment;
138 gpu->texture = device.CreateTexture(
reinterpret_cast<const wgpu::TextureDescriptor*
>(&td));
142 WGPUTextureViewDescriptor vd{};
143 vd.format = WGPUTextureFormat_RGBA8Unorm;
144 vd.dimension = WGPUTextureViewDimension_2D;
146 vd.mipLevelCount =
gpu->mipLevels;
147 vd.baseArrayLayer = 0;
148 vd.arrayLayerCount = 1;
149 gpu->view =
gpu->texture.CreateView(
reinterpret_cast<const wgpu::TextureViewDescriptor*
>(&vd));
150 gpu->sampler = makeSampler(
info.sampler,
gpu->mipLevels);
155 tex->mipmapCount = int(
gpu->mipLevels);
156 tex->sampler =
info.sampler;
157 tex->gpuHandle =
gpu.get();
159 ownedGpuTextures.push_back(std::move(
gpu));
160 ownedTextures.push_back(std::unique_ptr<Texture>(tex));
166 uploadTexturePixelsMips(gt, rgba,
w,
h);
169void Graphics::uploadTexturePixelsMips(GpuTexture* gt,
const uint8_t* rgba,
int w,
int h) {
172 WGPUTexelCopyBufferLayout
layout{};
174 layout.bytesPerRow =
static_cast<uint32_t
>(
w * 4);
175 layout.rowsPerImage =
static_cast<uint32_t
>(
h);
176 WGPUExtent3D extent{
static_cast<uint32_t
>(
w),
static_cast<uint32_t
>(
h), 1};
178 for (uint32_t
m = 0;
m < gt->mipLevels; ++
m) {
179 WGPUTexelCopyTextureInfo dst{};
180 dst.texture = gt->texture.Get();
182 dst.aspect = WGPUTextureAspect_All;
183 queue.WriteTexture(
reinterpret_cast<const wgpu::TexelCopyTextureInfo*
>(&dst), rgba,
184 static_cast<uint64_t
>(
w) *
h * 4,
185 reinterpret_cast<const wgpu::TexelCopyBufferLayout*
>(&
layout),
186 reinterpret_cast<const wgpu::Extent3D*
>(&extent));
187 if (
m + 1 < gt->mipLevels) {
189 const int nextW = std::max(
w / 2, 1);
190 const int nextH = std::max(
h / 2, 1);
191 std::vector<uint8_t>
next(
size_t(nextW) *
size_t(nextH) * 4u);
192 for (
int y = 0;
y < nextH; ++
y) {
193 const int y0 = std::min(
y * 2,
h - 1);
194 const int y1 = std::min(y0 + 1,
h - 1);
195 for (
int x = 0;
x < nextW; ++
x) {
196 const int x0 = std::min(
x * 2,
w - 1);
197 const int x1 = std::min(x0 + 1,
w - 1);
198 for (
int c = 0;
c < 4; ++
c) {
200 acc += rgba[(size_t(y0) *
w + x0) * 4u +
c];
201 acc += rgba[(size_t(y0) *
w + x1) * 4u +
c];
202 acc += rgba[(size_t(y1) *
w + x0) * 4u +
c];
203 acc += rgba[(size_t(y1) *
w + x1) * 4u +
c];
204 next[(size_t(
y) * nextW +
x) * 4u +
c] = uint8_t((acc + 2u) / 4u);
212 layout.bytesPerRow =
static_cast<uint32_t
>(
w * 4);
213 layout.rowsPerImage =
static_cast<uint32_t
>(
h);
214 extent = {
static_cast<uint32_t
>(
w),
static_cast<uint32_t
>(
h), 1};
224 if (faceSize <= 0 || !rgbaFaces)
throw Exception(
"newCubemap: invalid size or null data");
228 if (
info.sampler.maxAnisotropy < 1.f)
info.sampler.maxAnisotropy = 1.f;
230 auto gpu = std::make_unique<GpuTexture>();
231 gpu->width = faceSize;
232 gpu->height = faceSize;
233 gpu->samplerState =
info.sampler;
237 WGPUTextureDescriptor td{};
238 td.label =
sv(
"eve_cubemap");
239 td.dimension = WGPUTextureDimension_2D;
240 td.size.width =
static_cast<uint32_t
>(faceSize);
241 td.size.height =
static_cast<uint32_t
>(faceSize);
242 td.size.depthOrArrayLayers = 6;
244 td.format = WGPUTextureFormat_RGBA8Unorm;
245 td.mipLevelCount =
gpu->mipLevels;
246 td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst;
247 gpu->texture = device.CreateTexture(
reinterpret_cast<const wgpu::TextureDescriptor*
>(&td));
250 size_t mipOffset = 0;
253 for (uint32_t mip = 0; mip <
gpu->mipLevels; ++mip) {
254 const size_t mipFaceBytes = size_t(mipW) * mipH * 4u;
255 for (
int f = 0;
f < 6; ++
f) {
256 const uint8_t*
pixels = mipChain.data() + mipOffset + size_t(
f) * mipFaceBytes;
257 WGPUTexelCopyBufferLayout
layout{};
259 layout.bytesPerRow =
static_cast<uint32_t
>(mipW * 4);
260 layout.rowsPerImage =
static_cast<uint32_t
>(mipH);
261 WGPUExtent3D extent{
static_cast<uint32_t
>(mipW),
static_cast<uint32_t
>(mipH), 1};
262 WGPUTexelCopyTextureInfo dst{};
263 dst.texture =
gpu->texture.Get();
265 dst.aspect = WGPUTextureAspect_All;
266 dst.origin = {0, 0,
static_cast<uint32_t
>(
f)};
267 queue.WriteTexture(
reinterpret_cast<const wgpu::TexelCopyTextureInfo*
>(&dst),
pixels,
268 static_cast<uint64_t
>(mipW) * mipH * 4,
269 reinterpret_cast<const wgpu::TexelCopyBufferLayout*
>(&
layout),
270 reinterpret_cast<const wgpu::Extent3D*
>(&extent));
272 mipOffset += mipFaceBytes * 6u;
273 mipW = std::max(mipW / 2, 1);
274 mipH = std::max(mipH / 2, 1);
277 WGPUTextureViewDescriptor vd{};
278 vd.format = WGPUTextureFormat_RGBA8Unorm;
279 vd.dimension = WGPUTextureViewDimension_Cube;
281 vd.mipLevelCount =
gpu->mipLevels;
282 vd.baseArrayLayer = 0;
283 vd.arrayLayerCount = 6;
284 gpu->view =
gpu->texture.CreateView(
reinterpret_cast<const wgpu::TextureViewDescriptor*
>(&vd));
285 gpu->sampler = makeSampler(
info.sampler,
gpu->mipLevels);
288 tex->width = faceSize;
289 tex->height = faceSize;
290 tex->pixelWidth = faceSize;
291 tex->pixelHeight = faceSize;
293 tex->mipmapCount = int(
gpu->mipLevels);
294 tex->sampler =
info.sampler;
295 tex->gpuHandle =
gpu.get();
297 ownedGpuTextures.push_back(std::move(
gpu));
298 ownedTextures.push_back(std::unique_ptr<Texture>(tex));
303 if (faceSize <= 0)
throw Exception(
"newHDRCubemap: invalid face size");
304 auto gpu = std::make_unique<GpuTexture>();
305 gpu->width = faceSize;
306 gpu->height = faceSize;
313 WGPUTextureDescriptor td{};
314 td.label =
sv(
"eve_hdr_reflection_probe_staging");
315 td.dimension = WGPUTextureDimension_2D;
316 td.size = {
static_cast<uint32_t
>(faceSize),
static_cast<uint32_t
>(faceSize), 6};
318 td.format = WGPUTextureFormat_RGBA16Float;
319 td.mipLevelCount =
gpu->mipLevels;
320 td.usage = WGPUTextureUsage_TextureBinding | WGPUTextureUsage_CopyDst | WGPUTextureUsage_CopySrc |
321 WGPUTextureUsage_RenderAttachment;
322 gpu->texture = device.CreateTexture(
reinterpret_cast<const wgpu::TextureDescriptor*
>(&td));
324 WGPUTextureViewDescriptor vd{};
325 vd.format = WGPUTextureFormat_RGBA16Float;
326 vd.dimension = WGPUTextureViewDimension_Cube;
328 vd.mipLevelCount =
gpu->mipLevels;
329 vd.baseArrayLayer = 0;
330 vd.arrayLayerCount = 6;
331 gpu->view =
gpu->texture.CreateView(
reinterpret_cast<const wgpu::TextureViewDescriptor*
>(&vd));
332 gpu->sampler = makeSampler(
gpu->samplerState,
gpu->mipLevels);
340 ownedGpuTextures.push_back(std::move(
gpu));
341 ownedTextures.emplace_back(
texture);
347 if (!canvas || !canvas->hdr || !cubemap || !cubemap->
gpuHandle || face < 0 || face >= 6)
return false;
352 wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
353 WGPUTexelCopyTextureInfo src{};
354 src.texture = canvas->color.Get();
356 src.aspect = WGPUTextureAspect_All;
357 src.origin = {0, 0, 0};
358 WGPUTexelCopyTextureInfo dst{};
359 dst.texture =
target->texture.Get();
361 dst.aspect = WGPUTextureAspect_All;
362 dst.origin = {0, 0,
static_cast<uint32_t
>(face)};
363 WGPUExtent3D extent{
static_cast<uint32_t
>(canvas->width),
static_cast<uint32_t
>(canvas->height), 1};
364 encoder.CopyTextureToTexture(
reinterpret_cast<const wgpu::TexelCopyTextureInfo*
>(&src),
365 reinterpret_cast<const wgpu::TexelCopyTextureInfo*
>(&dst),
366 reinterpret_cast<const wgpu::Extent3D*
>(&extent));
367 wgpu::CommandBuffer command = encoder.Finish();
368 queue.Submit(1, &command);
373 if (!
sources || faceCount < 1 || faceCount > 6 || !cubemap || !cubemap->
gpuHandle)
return false;
377 std::array<OffscreenCanvas*, 6> canvases{};
378 for (
int face = 0; face < faceCount; ++face) {
380 if (!canvas || !canvas->hdr ||
target->width != canvas->width ||
target->height != canvas->height)
return false;
381 canvases[
static_cast<size_t>(face)] = canvas;
384 wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
385 for (
int face = 0; face < faceCount; ++face) {
386 const auto* canvas = canvases[
static_cast<size_t>(face)];
387 WGPUTexelCopyTextureInfo src{};
388 src.texture = canvas->color.Get();
390 src.aspect = WGPUTextureAspect_All;
391 src.origin = {0, 0, 0};
392 WGPUTexelCopyTextureInfo dst{};
393 dst.texture =
target->texture.Get();
395 dst.aspect = WGPUTextureAspect_All;
396 dst.origin = {0, 0,
static_cast<uint32_t
>(face)};
397 WGPUExtent3D extent{
static_cast<uint32_t
>(canvas->width),
static_cast<uint32_t
>(canvas->height), 1};
398 encoder.CopyTextureToTexture(
reinterpret_cast<const wgpu::TexelCopyTextureInfo*
>(&src),
399 reinterpret_cast<const wgpu::TexelCopyTextureInfo*
>(&dst),
400 reinterpret_cast<const wgpu::Extent3D*
>(&extent));
402 wgpu::CommandBuffer command = encoder.Finish();
403 queue.Submit(1, &command);
408 if (!cubemap || !cubemap->
gpuHandle)
return false;
411 sampleCount = std::clamp(sampleCount, 8, 512);
412 wgpuInstanceProcessEvents(instance.Get());
413 OffscreenTimestampReadback* timestampSlot =
nullptr;
414 if (offscreenTimestampSupported && offscreenTimestampQuerySet && offscreenTimestampResolveBuffer) {
415 for (
size_t candidate = 0; candidate < offscreenTimestampReadbacks.size(); ++candidate) {
416 const size_t index = (offscreenTimestampReadbackCursor + candidate) % offscreenTimestampReadbacks.size();
418 timestampSlot = &offscreenTimestampReadbacks[
index];
419 offscreenTimestampReadbackCursor = (
index + 1) % offscreenTimestampReadbacks.size();
425 if (!reflectionProbeFilterPipeline) {
426 WGPUBindGroupLayoutEntry
entries[3]{};
428 entries[0].visibility = WGPUShaderStage_Fragment;
429 entries[0].texture.sampleType = WGPUTextureSampleType_Float;
430 entries[0].texture.viewDimension = WGPUTextureViewDimension_Cube;
432 entries[1].visibility = WGPUShaderStage_Fragment;
433 entries[1].sampler.type = WGPUSamplerBindingType_Filtering;
435 entries[2].visibility = WGPUShaderStage_Fragment;
436 entries[2].buffer.type = WGPUBufferBindingType_Uniform;
437 entries[2].buffer.hasDynamicOffset =
true;
438 entries[2].buffer.minBindingSize = 16;
439 WGPUBindGroupLayoutDescriptor bgl{};
440 bgl.label =
sv(
"eve_reflection_probe_filter_bgl");
443 reflectionProbeFilterSetLayout =
444 device.CreateBindGroupLayout(
reinterpret_cast<const wgpu::BindGroupLayoutDescriptor*
>(&bgl));
445 WGPUBindGroupLayout rawLayout = reflectionProbeFilterSetLayout.Get();
446 WGPUPipelineLayoutDescriptor pld{};
447 pld.label =
sv(
"eve_reflection_probe_filter_layout");
448 pld.bindGroupLayoutCount = 1;
449 pld.bindGroupLayouts = &rawLayout;
450 reflectionProbeFilterPipelineLayout =
451 device.CreatePipelineLayout(
reinterpret_cast<const wgpu::PipelineLayoutDescriptor*
>(&pld));
453 wgpu::ShaderModule
module = makeWgslModule(device, shaders::kReflectionProbeFilterWgsl);
454 WGPUColorTargetState colorTarget{};
455 colorTarget.format = WGPUTextureFormat_RGBA16Float;
456 colorTarget.writeMask = WGPUColorWriteMask_All;
457 WGPUFragmentState fragment{};
458 fragment.module =
module.Get();
459 fragment.entryPoint =
sv(
"fs_main");
460 fragment.targetCount = 1;
461 fragment.targets = &colorTarget;
462 WGPURenderPipelineDescriptor pipeline{};
463 pipeline.label =
sv(
"eve_reflection_probe_filter");
464 pipeline.layout = reflectionProbeFilterPipelineLayout.Get();
465 pipeline.vertex.module =
module.Get();
466 pipeline.vertex.entryPoint =
sv(
"vs_main");
467 pipeline.fragment = &fragment;
468 pipeline.primitive.topology = WGPUPrimitiveTopology_TriangleList;
469 pipeline.primitive.frontFace = WGPUFrontFace_CCW;
470 pipeline.primitive.cullMode = WGPUCullMode_None;
471 pipeline.multisample.count = 1;
472 pipeline.multisample.mask = 0xFFFFFFFFu;
473 reflectionProbeFilterPipeline =
474 device.CreateRenderPipeline(
reinterpret_cast<const wgpu::RenderPipelineDescriptor*
>(&pipeline));
477 const uint32_t passCount = (
target->mipLevels - 1u) * 6u;
478 WGPUBufferDescriptor bufferDesc{};
479 bufferDesc.label =
sv(
"eve_reflection_probe_filter_params");
480 bufferDesc.size = uint64_t(passCount) * 256u;
481 bufferDesc.usage = WGPUBufferUsage_Uniform | WGPUBufferUsage_CopyDst;
482 wgpu::Buffer paramsBuffer = device.CreateBuffer(
reinterpret_cast<const wgpu::BufferDescriptor*
>(&bufferDesc));
483 WGPUTextureViewDescriptor sourceViewDesc{};
484 sourceViewDesc.format = WGPUTextureFormat_RGBA16Float;
485 sourceViewDesc.dimension = WGPUTextureViewDimension_Cube;
486 sourceViewDesc.baseMipLevel = 0;
487 sourceViewDesc.mipLevelCount = 1;
488 sourceViewDesc.baseArrayLayer = 0;
489 sourceViewDesc.arrayLayerCount = 6;
490 wgpu::TextureView sourceView =
491 target->texture.CreateView(
reinterpret_cast<const wgpu::TextureViewDescriptor*
>(&sourceViewDesc));
492 WGPUBindGroupEntry groupEntries[3]{};
493 groupEntries[0].binding = 0;
494 groupEntries[0].textureView = sourceView.Get();
495 groupEntries[1].binding = 1;
496 groupEntries[1].sampler =
target->sampler.Get();
497 groupEntries[2].binding = 2;
498 groupEntries[2].buffer = paramsBuffer.Get();
499 groupEntries[2].size = 16;
500 WGPUBindGroupDescriptor groupDesc{};
501 groupDesc.label =
sv(
"eve_reflection_probe_filter_group");
502 groupDesc.layout = reflectionProbeFilterSetLayout.Get();
503 groupDesc.entryCount = 3;
504 groupDesc.entries = groupEntries;
505 wgpu::BindGroup
group = device.CreateBindGroup(
reinterpret_cast<const wgpu::BindGroupDescriptor*
>(&groupDesc));
507 wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
508 uint32_t passIndex = 0;
509 for (uint32_t mip = 1; mip <
target->mipLevels; ++mip) {
510 const bool diffuse = mip + 1u ==
target->mipLevels;
511 const float roughness = diffuse ? 1.f : float(mip) / float(
target->mipLevels - 1u);
512 for (uint32_t face = 0; face < 6; ++face, ++passIndex) {
513 const float params[4] = {float(face),
roughness, diffuse ? 1.f : 0.f, float(sampleCount)};
514 queue.WriteBuffer(paramsBuffer, uint64_t(passIndex) * 256u,
params,
sizeof(
params));
515 WGPUTextureViewDescriptor viewDesc{};
516 viewDesc.format = WGPUTextureFormat_RGBA16Float;
517 viewDesc.dimension = WGPUTextureViewDimension_2D;
518 viewDesc.baseMipLevel = mip;
519 viewDesc.mipLevelCount = 1;
520 viewDesc.baseArrayLayer = face;
521 viewDesc.arrayLayerCount = 1;
522 wgpu::TextureView faceView =
523 target->texture.CreateView(
reinterpret_cast<const wgpu::TextureViewDescriptor*
>(&viewDesc));
524 WGPURenderPassColorAttachment attachment{};
525 attachment.view = faceView.Get();
526 attachment.loadOp = WGPULoadOp_Clear;
527 attachment.storeOp = WGPUStoreOp_Store;
528 WGPURenderPassDescriptor passDesc{};
529 passDesc.colorAttachmentCount = 1;
530 passDesc.colorAttachments = &attachment;
531 WGPUPassTimestampWrites timestampWrites{};
533 timestampWrites.querySet = offscreenTimestampQuerySet.Get();
534 timestampWrites.beginningOfPassWriteIndex = passIndex == 0 ? 0 : UINT32_MAX;
535 timestampWrites.endOfPassWriteIndex = passIndex + 1u == passCount ? 1 : UINT32_MAX;
536 passDesc.timestampWrites = ×tampWrites;
538 wgpu::RenderPassEncoder pass =
539 encoder.BeginRenderPass(
reinterpret_cast<const wgpu::RenderPassDescriptor*
>(&passDesc));
540 pass.SetPipeline(reflectionProbeFilterPipeline);
541 const uint32_t
offset = passIndex * 256u;
548 encoder.ResolveQuerySet(offscreenTimestampQuerySet, 0, 2, offscreenTimestampResolveBuffer, 0);
549 encoder.CopyBufferToBuffer(offscreenTimestampResolveBuffer, 0, timestampSlot->buffer, 0,
sizeof(uint64_t) * 2);
551 wgpu::CommandBuffer command = encoder.Finish();
552 queue.Submit(1, &command);
554 timestampSlot->pending =
true;
555 WGPUBufferMapCallbackInfo
callback{};
556 callback.mode = WGPUCallbackMode_AllowProcessEvents;
557 callback.callback = [](WGPUMapAsyncStatus
status, WGPUStringView,
void* userdata1,
void*) {
558 auto*
slot =
static_cast<OffscreenTimestampReadback*
>(userdata1);
559 if (
status == WGPUMapAsyncStatus_Success &&
slot &&
slot->owner) {
561 static_cast<const uint64_t*
>(
slot->buffer.GetConstMappedRange(0,
sizeof(uint64_t) * 2));
562 if (ticks && ticks[1] >= ticks[0]) {
563 slot->owner->completedOffscreenTimestampMs.fetch_add(
float(ticks[1] - ticks[0]) * 1.0e-6f);
565 slot->buffer.Unmap();
570 wgpuBufferMapAsync(timestampSlot->buffer.Get(), WGPUMapMode_Read, 0,
sizeof(uint64_t) * 2,
callback);
583 auto texIt = std::find_if(ownedTextures.begin(), ownedTextures.end(),
584 [&](
const std::unique_ptr<Texture>&
t) { return t.get() == texture; });
585 if (texIt == ownedTextures.end())
return false;
586 for (
auto it = texturesByPath.begin(); it != texturesByPath.end();) {
588 it = texturesByPath.erase(it);
592 for (
auto it = sharedTexturesByContent.begin(); it != sharedTexturesByContent.end();) {
594 it = sharedTexturesByContent.erase(it);
598 (void)texIt->release();
599 ownedTextures.erase(texIt);
603 if (
texture->gpuHandle == whiteTexture ||
texture->gpuHandle == flatNormalTexture ||
604 texture->gpuHandle == flatNormalTexture3D ||
texture->gpuHandle == defaultEnvCubemap)
608 auto gpuIt = std::find_if(ownedGpuTextures.begin(), ownedGpuTextures.end(),
609 [&](
const std::unique_ptr<GpuTexture>&
g) { return g.get() == gpu; });
610 if (gpuIt == ownedGpuTextures.end())
return false;
612 auto texIt = std::find_if(ownedTextures.begin(), ownedTextures.end(),
613 [&](
const std::unique_ptr<Texture>&
t) { return t.get() == texture; });
614 if (texIt == ownedTextures.end())
return false;
617 for (
auto it = texturesByPath.begin(); it != texturesByPath.end();) {
619 it = texturesByPath.erase(it);
623 for (
auto it = sharedTexturesByContent.begin(); it != sharedTexturesByContent.end();) {
625 it = sharedTexturesByContent.erase(it);
631 ownedGpuTextures.erase(gpuIt);
633 (void)texIt->release();
634 ownedTextures.erase(texIt);
640 const auto ownedTexture =
641 std::find_if(ownedTextures.begin(), ownedTextures.end(),
642 [
texture](
const std::unique_ptr<Texture>& candidate) { return candidate.get() == texture; });
643 if (ownedTexture == ownedTextures.end())
return false;
647 std::find_if(ownedGpuTextures.begin(), ownedGpuTextures.end(),
648 [
gpu](
const std::unique_ptr<GpuTexture>& candidate) { return candidate.get() == gpu; });
649 if (
owned == ownedGpuTextures.end() ||
gpu->isCube)
return false;
655 std::span<const std::uint8_t> rgba, std::size_t bytesPerRow) {
661 const auto ownedTexture =
662 std::find_if(ownedTextures.begin(), ownedTextures.end(),
663 [
texture](
const std::unique_ptr<Texture>& candidate) { return candidate.get() == texture; });
664 if (ownedTexture == ownedTextures.end())
666 "texture is not an owned 2D texture",
667 "graphics.updateTextureRegions.texture"));
670 std::find_if(ownedGpuTextures.begin(), ownedGpuTextures.end(),
671 [
gpu](
const std::unique_ptr<GpuTexture>& candidate) { return candidate.get() == gpu; });
672 if (!
gpu ||
owned == ownedGpuTextures.end() ||
gpu->isCube)
674 "texture is not an owned 2D texture",
675 "graphics.updateTextureRegions.texture"));
678 "partial updates require a single-mip texture",
679 "graphics.updateTextureRegions.mipmaps"));
685 "invalid texture region",
686 "graphics.updateTextureRegions.region"));
687 const std::size_t packedRow = std::size_t(
region.width) * 4U;
688 const std::size_t stride =
region.bytesPerRow == 0 ? packedRow :
region.bytesPerRow;
689 if (stride < packedRow || stride > std::numeric_limits<std::uint32_t>::max())
691 "texture row stride is out of range",
692 "graphics.updateTextureRegions.bytesPerRow"));
693 if (std::size_t(
region.height - 1) > (std::numeric_limits<std::size_t>::max() - packedRow) / stride)
695 "texture region byte count overflows",
696 "graphics.updateTextureRegions.bytesPerRow"));
697 const std::size_t requiredBytes = stride * std::size_t(
region.height - 1) + packedRow;
698 if (
region.rgba.size() < requiredBytes)
700 "source bytes do not cover the texture region",
701 "graphics.updateTextureRegions.bytes"));
705 const std::size_t packedRow = std::size_t(
region.width) * 4U;
706 const std::size_t stride =
region.bytesPerRow == 0 ? packedRow :
region.bytesPerRow;
707 const std::size_t requiredBytes = stride * std::size_t(
region.height - 1) + packedRow;
708 WGPUTexelCopyTextureInfo dst{};
709 dst.texture =
gpu->texture.Get();
711 dst.origin = {std::uint32_t(
region.x), std::uint32_t(
region.y), 0};
712 dst.aspect = WGPUTextureAspect_All;
713 WGPUTexelCopyBufferLayout
layout{};
715 layout.bytesPerRow = std::uint32_t(stride);
717 WGPUExtent3D extent{std::uint32_t(
region.width), std::uint32_t(
region.height), 1};
718 queue.WriteTexture(
reinterpret_cast<const wgpu::TexelCopyTextureInfo*
>(&dst),
region.rgba.data(), requiredBytes,
719 reinterpret_cast<const wgpu::TexelCopyBufferLayout*
>(&
layout),
720 reinterpret_cast<const wgpu::Extent3D*
>(&extent));
727GpuTexture* Graphics::gpuForTextureOrWhite(
Texture*
t)
const {
728 GpuTexture*
g = gpuForTexture(
t);
729 return g ?
g : whiteTexture;
732wgpu::BindGroup Graphics::makeTex2DBindGroup(GpuTexture*
color, GpuTexture*
depth, GpuTexture* motion,
733 GpuTexture* extra, GpuTexture* specular) {
736 GpuTexture*
m = motion ? motion :
c;
737 GpuTexture* e = extra ? extra :
c;
738 GpuTexture*
s = specular ? specular :
c;
739 WGPUBindGroupEntry
entries[11]{};
743 entries[1].textureView =
d->view.Get();
745 entries[2].sampler =
c->sampler.Get();
747 entries[3].sampler =
d->sampler.Get();
749 entries[4].buffer = currentUboArena().buffer.Get();
752 entries[5].textureView =
m->view.Get();
754 entries[6].sampler =
m->sampler.Get();
756 entries[7].textureView = e->view.Get();
758 entries[8].sampler = e->sampler.Get();
760 entries[9].textureView =
s->view.Get();
762 entries[10].sampler =
s->sampler.Get();
763 WGPUBindGroupDescriptor
desc{};
764 desc.label =
sv(
"eve_tex2d_group");
765 desc.layout = tex2DSetLayout.Get();
766 desc.entryCount = 11;
768 return device.CreateBindGroup(
reinterpret_cast<const wgpu::BindGroupDescriptor*
>(&
desc));
771wgpu::BindGroup Graphics::makeMeshBindGroup(GpuTexture*
albedo, GpuTexture*
normal, GpuTexture* env, GpuTexture*
height,
772 GpuTexture*
depth, GpuTexture* sceneColor, uint32_t frameUboOffset,
773 uint32_t shadowUboOffset, uint32_t pushUboOffset,
774 const wgpu::Buffer& skinBuffer) {
777 GpuTexture* e = env ? env : defaultEnvCubemap;
778 auto localProbe = [&](
int index) -> GpuTexture* {
783 return defaultEnvCubemap;
785 GpuTexture* probe0 = localProbe(0);
786 GpuTexture* probe1 = localProbe(1);
788 GpuTexture*
d =
depth ?
depth : flatDepthTexture3D;
789 GpuTexture*
c = sceneColor ? sceneColor : whiteTexture;
790 GpuTexture* shadow = shadowDepthArray ? shadowDepthArray : defaultShadowTex;
791 wgpu::TextureView aoView_ =
792 aoReady ? aoView[(aoWriteIndex + 1) % 2] : (whiteTexture ? whiteTexture->
view : wgpu::TextureView());
793 wgpu::TextureView decalAlbedoView = gpuForTextureOrWhite(decalFlatAlbedo)->
view;
794 wgpu::TextureView decalNormalView = gpuForTextureOrWhite(decalFlatNormal)->
view;
795 wgpu::TextureView decalParamsView = gpuForTextureOrWhite(decalFlatParams)->
view;
796 if (decalReady && lastDecalSlot < decalSlots.size()) {
797 decalAlbedoView = decalSlots[lastDecalSlot].albedoView;
798 decalNormalView = decalSlots[lastDecalSlot].normalView;
799 decalParamsView = decalSlots[lastDecalSlot].paramsView;
802 MeshBindGroupKey
key{
reinterpret_cast<uintptr_t
>(currentUboArena().buffer.Get()),
803 reinterpret_cast<uintptr_t
>(
a->view.Get()),
804 reinterpret_cast<uintptr_t
>(
n->view.Get()),
805 reinterpret_cast<uintptr_t
>(e->view.Get()),
806 reinterpret_cast<uintptr_t
>(
h->view.Get()),
807 reinterpret_cast<uintptr_t
>(
d->view.Get()),
808 reinterpret_cast<uintptr_t
>(shadow->view.Get()),
809 reinterpret_cast<uintptr_t
>(shadow->sampler.Get()),
810 reinterpret_cast<uintptr_t
>(aoView_.Get()),
811 reinterpret_cast<uintptr_t
>(decalAlbedoView.Get()),
812 reinterpret_cast<uintptr_t
>(decalNormalView.Get()),
813 reinterpret_cast<uintptr_t
>(decalParamsView.Get()),
814 reinterpret_cast<uintptr_t
>(probe0->view.Get()),
815 reinterpret_cast<uintptr_t
>(probe1->view.Get()),
816 reinterpret_cast<uintptr_t
>(
c->view.Get()),
817 reinterpret_cast<uintptr_t
>(skinBuffer.Get())};
818 auto cached = meshBindGroupCache_.find(
key);
819 if (cached != meshBindGroupCache_.end())
return cached->second;
820 if (meshBindGroupCache_.size() >= kMaxMeshBindGroupCache) meshBindGroupCache_.clear();
822 WGPUBindGroupEntry
entries[21]{};
824 entries[0].buffer = currentUboArena().buffer.Get();
825 entries[0].size =
sizeof(Mesh3DUBO);
827 entries[1].textureView =
a->view.Get();
829 entries[2].textureView =
n->view.Get();
831 entries[3].textureView = e->view.Get();
833 entries[4].buffer = currentUboArena().buffer.Get();
834 entries[4].size =
sizeof(ShadowUBO);
836 entries[5].textureView = shadow->view.Get();
838 entries[6].textureView =
h->view.Get();
844 entries[7].sampler =
a->sampler.Get();
846 entries[8].sampler = shadow->sampler.Get();
848 entries[9].textureView =
d->view.Get();
850 entries[10].textureView = aoView_.Get();
852 entries[11].sampler = mainSampler.Get();
854 entries[12].textureView = decalAlbedoView.Get();
856 entries[13].textureView = decalNormalView.Get();
858 entries[14].textureView = decalParamsView.Get();
860 entries[15].buffer = currentUboArena().buffer.Get();
863 entries[16].textureView = probe0->view.Get();
865 entries[17].textureView = probe1->view.Get();
867 entries[18].textureView =
c->view.Get();
869 entries[19].sampler =
c->sampler.Get();
872 entries[20].buffer = skinBuffer.Get();
873 entries[20].size = skinBuffer.GetSize();
874 (void)frameUboOffset;
875 (void)shadowUboOffset;
877 WGPUBindGroupDescriptor
desc{};
878 desc.label =
sv(
"eve_mesh_group");
879 desc.layout = mesh3dSetLayout.Get();
880 desc.entryCount = 21;
882 wgpu::BindGroup bg = device.CreateBindGroup(
reinterpret_cast<const wgpu::BindGroupDescriptor*
>(&
desc));
883 meshBindGroupCache_.emplace(
key, bg);
887wgpu::BindGroup Graphics::makeMesh3DClusteredBindGroup(GpuTexture*
albedo, GpuTexture*
normal, GpuTexture* env,
888 GpuTexture*
height, GpuTexture*
depth, wgpu::TextureView aoView,
889 uint32_t frameUboOffset, uint32_t shadowUboOffset) {
892 GpuTexture* e = env ? env : defaultEnvCubemap;
893 auto localProbe = [&](
int index) -> GpuTexture* {
898 return defaultEnvCubemap;
900 GpuTexture* probe0 = localProbe(0);
901 GpuTexture* probe1 = localProbe(1);
903 GpuTexture*
d =
depth ?
depth : flatDepthTexture3D;
904 GpuTexture* shadow = shadowDepthArray ? shadowDepthArray : defaultShadowTex;
905 ClusteredStorage& st = clusteredStorage[currentFrameSlot()];
906 wgpu::TextureView decalAlbedoView = gpuForTextureOrWhite(decalFlatAlbedo)->
view;
907 wgpu::TextureView decalNormalView = gpuForTextureOrWhite(decalFlatNormal)->
view;
908 wgpu::TextureView decalParamsView = gpuForTextureOrWhite(decalFlatParams)->
view;
909 if (decalReady && lastDecalSlot < decalSlots.size()) {
910 decalAlbedoView = decalSlots[lastDecalSlot].albedoView;
911 decalNormalView = decalSlots[lastDecalSlot].normalView;
912 decalParamsView = decalSlots[lastDecalSlot].paramsView;
915 WGPUBindGroupEntry
entries[20]{};
917 entries[0].buffer = currentUboArena().buffer.Get();
918 entries[0].size =
sizeof(Mesh3DClusteredUBO);
920 entries[1].textureView =
a->view.Get();
922 entries[2].textureView =
n->view.Get();
924 entries[3].textureView = e->view.Get();
926 entries[4].buffer = currentUboArena().buffer.Get();
927 entries[4].size =
sizeof(ShadowUBO);
929 entries[5].textureView = shadow->view.Get();
931 entries[6].textureView =
h->view.Get();
933 entries[7].sampler =
a->sampler.Get();
935 entries[8].sampler = shadow->sampler.Get();
937 entries[9].textureView =
d->view.Get();
939 entries[10].buffer = st.lights.Get();
940 entries[10].size = st.lightsCap;
942 entries[11].buffer = st.table.Get();
943 entries[11].size = st.tableCap;
945 entries[12].buffer = st.indices.Get();
946 entries[12].size = st.indicesCap;
948 entries[13].textureView = aoView.Get();
950 entries[14].sampler = mainSampler.Get();
952 entries[15].textureView = decalAlbedoView.Get();
954 entries[16].textureView = decalNormalView.Get();
956 entries[17].textureView = decalParamsView.Get();
958 entries[18].textureView = probe0->view.Get();
960 entries[19].textureView = probe1->view.Get();
962 (void)frameUboOffset;
963 (void)shadowUboOffset;
964 WGPUBindGroupDescriptor
desc{};
965 desc.label =
sv(
"eve_mesh3d_clustered_group");
966 desc.layout = mesh3dClusteredSetLayout.Get();
967 desc.entryCount = 20;
969 return device.CreateBindGroup(
reinterpret_cast<const wgpu::BindGroupDescriptor*
>(&
desc));
std::vector< QuestEvent > pending
std::unordered_map< std::string, QuestRuntime > entries
graphics::Texture * albedo
wgpu::PopErrorScopeStatus status
std::shared_ptr< OceanGpuSpectrum > gpu
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
Local-probe upload record kept off the high-fanout IGraphics3D header.
AbilityActivationGroup group
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
void dropDeferredFileTexture(Texture *texture)
Drop deferred file texture.
static constexpr uint32_t kPushConstantBytes
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Texture * newCubemap(int faceSize, const uint8_t *rgbaFaces) override
Creates a cubemap. @ownership Caller deletes unless documented otherwise.
float getMaxAnisotropy() const override
Returns the max anisotropy.
ResultRef< Texture > newSharedTexture(image::ImageData *data, const std::string &contentKey) override
Reuse immutable imported pixels. Graphics owns the returned texture until release or shutdown.
eve::Result< void > updateTextureRegions(Texture *texture, std::span< const TextureRegionUpload > regions) override
Updates texture regions.
Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false) override
Creates a texture. @ownership Caller deletes unless documented otherwise.
bool copyHDRCanvasesToCubemap(Canvas *const *sources, int faceCount, Texture *cubemap) override
Copies hdr canvases to cubemap.
bool copyHDRCanvasToCubemapFace(Canvas *source, Texture *cubemap, int face) override
Copies hdr canvas to cubemap face.
eve::Result< void > updateTextureRegion(Texture *texture, int x, int y, int width, int height, std::span< const std::uint8_t > rgba, std::size_t bytesPerRow=0) override
Updates texture region.
bool filterHDRReflectionCubemap(Texture *cubemap, int sampleCount=64) override
Filter hdr reflection cubemap.
bool releaseTexture(Texture *texture) override
Release texture.
Texture * newHDRCubemap(int faceSize) override
Creates a hdr cubemap. @ownership Caller deletes unless documented otherwise.
bool updateTexture(Texture *texture, int width, int height, const uint8_t *rgba) override
Updates texture.
Offscreen render target (RGBA8Unorm color, optional Depth32Float). 2D batches are flushed into the ca...
Represents raw pixel data.
WGPUStringView sv(const char *s)
Build a WGPUStringView from a C string (null-safe, length auto-computed).
std::vector< uint8_t > buildGgxCubemapMipChain(const uint8_t *rgbaFaces, uint32_t faceSize, uint32_t mipLevels, uint32_t sampleCount=32u)
Build a mip-major RGBA8 IBL chain: GGX specular mips plus final diffuse irradiance.
int mipmapCountForSize(int width, int height)
Full mip chain count for a 2D image (including base level). @cost O(1); uses integer log2 of the larg...
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Options for Graphics::newTexture / newCubemap. When generateMipmaps is true and sampler....
static TextureCreateInfo withMipmaps(bool aniso=true, float maxAniso=16.f)
With mipmaps.
One borrowed RGBA8 source rectangle for a batched texture update. @ownership rgba remains owned by th...
static TextureSampler linear()
Linear.
Texture resources backed by a wgpu texture + view + sampler + bind groups.