载入中...
搜索中...
未找到
GraphicsTexture.cpp
浏览该文件的文档.
1// Vulkan backend implementation — texture creation, upload and reload.
2//
3// Split out of Graphics2D.cpp (pure move; shared helpers live in
4// GraphicsInternal.h). Keep the include list tight: the embedded shader
5// .inc arrays are unused here and would trip -Wunused-const-variable under
6// strict-warning CI builds.
7
9
10#include <utility>
13
14#include "common/Diagnostic.h"
15#include "common/Exception.h"
16#include "common/Resource.h"
17#include "common/Result.h"
18#include "image/Image.h"
19#include "image/ImageData.h"
20#include "zeroerr/assert.h"
21
22#include <algorithm>
23#include <array>
24#include <atomic>
25#include <cstdint>
26#include <cstring>
27#include <limits>
28#include <memory>
29#include <string>
30#include <vector>
31
32#if __has_include("graphics/shaders/reflection_probe_filter_comp_spv.inc")
33#include "graphics/shaders/reflection_probe_filter_comp_spv.inc"
34#define EVENGINE_HAS_REFLECTION_PROBE_FILTER_SPV 1
35#endif
36
37
38namespace eve::graphics::vulkan {
39
40namespace {
41uint64_t nextTextureContentIdentity() {
42 static std::atomic<uint64_t> next{1};
43 auto value = next.load(std::memory_order_relaxed);
44 while (value != UINT64_MAX) {
45 if (next.compare_exchange_weak(value, value + 1, std::memory_order_relaxed)) return value;
46 }
47 // Saturation disables snapshots instead of reusing an old identity.
48 return 0;
49}
50} // namespace
51
53 const auto owned = std::find_if(ownedTextures.begin(), ownedTextures.end(),
54 [texture](const auto &candidate) { return candidate.get() == texture; });
55 if (!texture || owned == ownedTextures.end())
57 "Texture is not owned by this graphics device",
58 "graphics.texture.content_identity"));
59 auto *gpu = static_cast<GpuTexture *>(texture->gpuHandle);
60 const auto resource = std::find_if(ownedGpuTextures.begin(), ownedGpuTextures.end(),
61 [gpu](const auto &candidate) { return candidate.get() == gpu; });
62 if (!gpu || resource == ownedGpuTextures.end() || gpu->isCube || gpu->isArray || gpu->isVolume || gpu->isHDR ||
63 gpu->viewOverride || !gpu->contentIdentity)
65 "Texture requires a realized owned RGBA8 2D resource",
66 "graphics.texture.content_identity"));
67 return Result<uint64_t>::success(gpu->contentIdentity);
68}
69
70template <class TextureImage>
71void recordTextureCopies(vk::CommandBuffer cb, TextureImage &image, vkb::GenericBuffer &staging, uint32_t width,
72 uint32_t height, uint32_t depth, uint32_t mipLevels, uint32_t layers,
73 uint32_t bytesPerPixel = 4) {
74 vk::DeviceSize offset = 0;
75 for (uint32_t mip = 0; mip < mipLevels; ++mip) {
76 const uint32_t mipWidth = std::max(width >> mip, 1u);
77 const uint32_t mipHeight = std::max(height >> mip, 1u);
78 const uint32_t mipDepth = std::max(depth >> mip, 1u);
79 for (uint32_t layer = 0; layer < layers; ++layer) {
80 image.copy(cb, staging.buffer, mip, layer, mipWidth, mipHeight, mipDepth, uint32_t(offset));
81 offset += vk::DeviceSize(mipWidth) * mipHeight * mipDepth * bytesPerPixel;
82 }
83 }
84 image.setLayout(cb, vk::ImageLayout::eShaderReadOnlyOptimal);
85}
86
87template <class TextureImage>
88void uploadTextureForAllShaderStages(vkb::Device &device, vk::CommandPool commandPool, vk::Queue graphicsQueue,
89 TextureImage &image, uint32_t width, uint32_t height, uint32_t mipLevels,
90 uint32_t layers, const std::vector<uint8_t> &bytes, uint32_t bytesPerPixel = 4,
91 uint32_t depth = 1) {
92 vkb::GenericBuffer staging(
93 device, vk::BufferUsageFlagBits::eTransferSrc, vk::DeviceSize(bytes.size()),
94 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
95 staging.updateLocal(vkb::FrameSlot::gpuIdle(), bytes.data(), vk::DeviceSize(bytes.size()));
96
97 vkb::executeImmediately(device.instance, commandPool, graphicsQueue, [&](vk::CommandBuffer cb) {
98 recordTextureCopies(cb, image, staging, width, height, depth, mipLevels, layers, bytesPerPixel);
99 });
100 staging.release();
101}
102
103void Graphics::writeCombinedImageDescriptor(GpuTexture *gpu) {
104 if (!gpu || !gpu->descriptorSet || !gpu->sampler) return;
105 vk::ImageView view = gpu->imageView();
106 if (!view) return;
107 vkb::UnboundSet unbound = vkb::UnboundSet::reopenAfterIdle(gpu->descriptorSet);
108 vkb::DescriptorSetUpdater updater;
109 updater.beginDescriptorSet(unbound)
110 .beginImages(0, 0, vk::DescriptorType::eCombinedImageSampler)
111 .image(vkb::SampledImage::forLaterSample(gpu->sampler, view))
112 .beginImages(1, 0, vk::DescriptorType::eCombinedImageSampler)
113 .image(vkb::SampledImage::forLaterSample(gpu->sampler, view))
114 .update(device.instance);
115 gpu->descriptorSet = std::move(unbound).publish();
116}
117
118Texture *Graphics::newTexture(int w, int h, const uint8_t *rgba, bool repeatU, bool repeatV) {
121 info.sampler.repeatV = repeatV;
122 return newTexture(w, h, rgba, info);
123}
124
125Texture *Graphics::newTexture(int w, int h, const uint8_t *rgba, const TextureCreateInfo &rawInfo) {
126 ASSERT(initialized);
127 ASSERT_GT(w, 0);
128 ASSERT_GT(h, 0);
129 ASSERT(rgba != nullptr);
130 if (!initialized) throw Exception("newTexture: graphics not initialized");
131 if (w <= 0 || h <= 0 || !rgba) throw Exception("newTexture: invalid args");
132
133 TextureCreateInfo info = normalizeTextureInfo(rawInfo);
134 const uint32_t mipLevels =
135 info.generateMipmaps ? uint32_t(mipmapCountForSize(w, h)) : 1u;
136
137 auto gpu = std::make_unique<GpuTexture>();
138 gpu->width = w;
139 gpu->height = h;
140 gpu->isCube = false;
141 gpu->mipLevels = mipLevels;
142 gpu->samplerState = info.sampler;
143 gpu->image = vkb::TextureImage2D(device, uint32_t(w), uint32_t(h), mipLevels);
144 gpu->contentIdentity = nextTextureContentIdentity();
145
146 std::vector<uint8_t> bytes =
147 (mipLevels > 1) ? buildMipChain2D(rgba, uint32_t(w), uint32_t(h), mipLevels)
148 : std::vector<uint8_t>(rgba, rgba + size_t(w) * size_t(h) * 4);
149 uploadTextureForAllShaderStages(device, uploadPool,
150 device.getQueue(vkb::QueueType::graphics), gpu->image,
151 uint32_t(w), uint32_t(h), mipLevels, 1, bytes);
152
153 gpu->sampler = createVkSampler(info.sampler, mipLevels);
154
155 auto sets = vkb::DescriptorSetBuilder().layout(texSetLayout).build(device.instance, descriptorPool);
156
157 gpu->descriptorSet = vkb::BoundSet{sets[0]};
158 writeCombinedImageDescriptor(gpu.get());
159 registerBindlessTexture2D(gpu.get());
160
161 auto tex = std::make_unique<Texture>();
162 tex->width = w;
163 tex->height = h;
164 tex->pixelWidth = w;
165 tex->pixelHeight = h;
166 tex->mipmapCount = int(mipLevels);
167 tex->sampler = info.sampler;
168 tex->gpuHandle = gpu.get();
169
170 Texture *raw = tex.get();
171 ownedTextures.push_back(std::move(tex));
172 ownedGpuTextures.push_back(std::move(gpu));
173 return raw;
174}
175
176Result<Texture *> Graphics::newTextureMipChain(uint32_t width, uint32_t height, uint32_t levels,
177 std::span<const uint8_t> rgba) {
178 auto fail = [](DiagnosticCode code, std::string message) {
179 return Result<Texture*>::failure(Diagnostic::error(code, std::move(message), {}, {}, "graphics.texture.mips"));
180 };
181 if (!initialized) return fail(DiagnosticCode::Failed, "graphics is not initialized");
182 const auto maximum = device.physical_device.properties.limits.maxImageDimension2D;
183 if (!width || !height || width > maximum || height > maximum)
184 return fail(DiagnosticCode::InvalidArgument, "mip dimensions exceed device limits");
185 uint64_t expected = 0;
186 uint32_t count = 0, w = width, h = height;
187 for (;;) {
188 expected += uint64_t(w) * h * 4;
189 ++count;
190 if (w == 1 && h == 1) break;
191 w = std::max(w / 2, 1u);
192 h = std::max(h / 2, 1u);
193 }
194 if (levels != count || expected != rgba.size() || expected > UINT32_MAX)
195 return fail(DiagnosticCode::InvalidArgument, "mip count, packed bytes or staging offset budget invalid");
196 std::unique_ptr<GpuTexture> gpu;
197 try {
198 // Reserve both registries before allocating GPU state; publication then cannot allocate.
199 ownedTextures.reserve(ownedTextures.size() + 1);
200 ownedGpuTextures.reserve(ownedGpuTextures.size() + 1);
201 auto tex = std::make_unique<Texture>();
202 std::vector<uint8_t> bytes(rgba.begin(), rgba.end());
203 gpu = std::make_unique<GpuTexture>();
204 gpu->width = int(width);
205 gpu->height = int(height);
206 gpu->mipLevels = levels;
207 gpu->samplerState = TextureSampler::linearMipmap();
208 gpu->image = vkb::TextureImage2D(device, width, height, levels);
209 gpu->contentIdentity = nextTextureContentIdentity();
210 uploadTextureForAllShaderStages(device, uploadPool, device.getQueue(vkb::QueueType::graphics), gpu->image,
211 width, height, levels, 1, bytes);
212 gpu->sampler = createVkSampler(gpu->samplerState, levels);
213 auto sets = vkb::DescriptorSetBuilder().layout(texSetLayout).build(device.instance, descriptorPool);
214 gpu->descriptorSet = vkb::BoundSet{sets[0]};
215 writeCombinedImageDescriptor(gpu.get());
216 tex->width = tex->pixelWidth = int(width);
217 tex->height = tex->pixelHeight = int(height);
218 tex->mipmapCount = int(levels);
219 tex->sampler = gpu->samplerState;
220 tex->gpuHandle = gpu.get();
221 registerBindlessTexture2D(gpu.get());
222 auto *result = tex.get();
223 ownedTextures.push_back(std::move(tex));
224 ownedGpuTextures.push_back(std::move(gpu));
226 } catch (const std::exception &error) {
227 if (gpu) {
228 unregisterBindlessTexture(gpu.get());
229 if (gpu->descriptorSet) device->freeDescriptorSets(descriptorPool, {gpu->descriptorSet.handle});
230 if (gpu->sampler) device->destroySampler(gpu->sampler);
231 }
232 return fail(DiagnosticCode::Failed, error.what());
233 }
234}
235
237 std::span<const uint16_t> rgbaHalf) {
238 auto fail = [](DiagnosticCode code, std::string message) {
239 return Result<Texture*>::failure(Diagnostic::error(code, std::move(message), {}, {}, "graphics.texture.array"));
240 };
241 if (!initialized) return fail(DiagnosticCode::Failed, "graphics is not initialized");
242 const auto &limits = device.physical_device.properties.limits;
243 const uint64_t texels = uint64_t(width) * height * layers;
244 if (!width || !height || !layers || width > limits.maxImageDimension2D || height > limits.maxImageDimension2D ||
245 layers > limits.maxImageArrayLayers || texels > SIZE_MAX / 4 || rgbaHalf.size() != texels * 4)
246 return fail(DiagnosticCode::InvalidArgument, "array dimensions or packed RGBA16F size are invalid");
247 std::unique_ptr<GpuTexture> gpu;
248 try {
249 ownedTextures.reserve(ownedTextures.size() + 1);
250 ownedGpuTextures.reserve(ownedGpuTextures.size() + 1);
251 auto tex = std::make_unique<Texture>();
252 gpu = std::make_unique<GpuTexture>();
253 vk::ImageCreateInfo imageInfo{{},
254 vk::ImageType::e2D,
255 vk::Format::eR16G16B16A16Sfloat,
256 {width, height, 1},
257 1,
258 layers,
259 vk::SampleCountFlagBits::e1,
260 vk::ImageTiling::eOptimal,
261 vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst,
262 vk::SharingMode::eExclusive};
263 gpu->arrayImage =
264 vkb::GenericImage(device, imageInfo, vk::ImageViewType::e2DArray, vk::ImageAspectFlagBits::eColor, false);
265 gpu->isArray = true;
266 gpu->width = int(width);
267 gpu->height = int(height);
268 gpu->samplerState = TextureSampler::linear();
269 std::vector<uint8_t> bytes(rgbaHalf.size_bytes());
270 std::memcpy(bytes.data(), rgbaHalf.data(), bytes.size());
271 uploadTextureForAllShaderStages(device, uploadPool, device.getQueue(vkb::QueueType::graphics), gpu->arrayImage,
272 width, height, 1, layers, bytes, 8);
273 gpu->sampler = createVkSampler(gpu->samplerState, 1);
274 tex->width = tex->pixelWidth = int(width);
275 tex->height = tex->pixelHeight = int(height);
276 tex->layers = int(layers);
277 tex->sampler = gpu->samplerState;
278 tex->gpuHandle = gpu.get();
279 auto *result = tex.get();
280 ownedTextures.push_back(std::move(tex));
281 ownedGpuTextures.push_back(std::move(gpu));
283 } catch (const std::exception &error) {
284 if (gpu && gpu->sampler) device->destroySampler(gpu->sampler);
285 return fail(DiagnosticCode::Failed, error.what());
286 }
287}
288
290 std::span<const uint8_t> rgba) {
291 auto fail = [](DiagnosticCode code, std::string message) {
293 Diagnostic::error(code, std::move(message), {}, {}, "graphics.texture.volume"));
294 };
295 if (!initialized) return fail(DiagnosticCode::Failed, "graphics is not initialized");
296 const auto &limits = device.physical_device.properties.limits;
297 const uint64_t texels = uint64_t(width) * height * depth;
298 if (!width || !height || !depth || width > limits.maxImageDimension3D || height > limits.maxImageDimension3D ||
299 depth > limits.maxImageDimension3D || texels > SIZE_MAX / 4 || rgba.size() != texels * 4)
300 return fail(DiagnosticCode::InvalidArgument, "volume dimensions or packed RGBA8 size are invalid");
301 std::unique_ptr<GpuTexture> gpu;
302 try {
303 ownedTextures.reserve(ownedTextures.size() + 1);
304 ownedGpuTextures.reserve(ownedGpuTextures.size() + 1);
305 auto tex = std::make_unique<Texture>();
306 gpu = std::make_unique<GpuTexture>();
307 vk::ImageCreateInfo imageInfo{{},
308 vk::ImageType::e3D,
309 vk::Format::eR8G8B8A8Unorm,
310 {width, height, depth},
311 1,
312 1,
313 vk::SampleCountFlagBits::e1,
314 vk::ImageTiling::eOptimal,
315 vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferDst,
316 vk::SharingMode::eExclusive};
317 gpu->arrayImage =
318 vkb::GenericImage(device, imageInfo, vk::ImageViewType::e3D, vk::ImageAspectFlagBits::eColor, false);
319 gpu->isArray = true;
320 gpu->isVolume = true;
321 gpu->width = int(width);
322 gpu->height = int(height);
323 gpu->samplerState = TextureSampler::linear();
324 gpu->samplerState.repeatU = gpu->samplerState.repeatV = gpu->samplerState.repeatW = true;
325 std::vector<uint8_t> bytes(rgba.begin(), rgba.end());
326 uploadTextureForAllShaderStages(device, uploadPool, device.getQueue(vkb::QueueType::graphics), gpu->arrayImage,
327 width, height, 1, 1, bytes, 4, depth);
328 gpu->sampler = createVkSampler(gpu->samplerState, 1);
329 tex->width = tex->pixelWidth = int(width);
330 tex->height = tex->pixelHeight = int(height);
331 tex->depth = int(depth);
332 tex->sampler = gpu->samplerState;
333 tex->gpuHandle = gpu.get();
334 auto *result = tex.get();
335 ownedTextures.push_back(std::move(tex));
336 ownedGpuTextures.push_back(std::move(gpu));
338 } catch (const std::exception &error) {
339 if (gpu && gpu->sampler) device->destroySampler(gpu->sampler);
340 return fail(DiagnosticCode::Failed, error.what());
341 }
342}
343
344Texture *Graphics::newCubemap(int faceSize, const uint8_t *rgbaFaces) {
345 // IBL shaders query the actual GGX-prefiltered mip count; generate it by default.
346 return newCubemap(faceSize, rgbaFaces, TextureCreateInfo::withMipmaps(false));
347}
348
349Texture *Graphics::newCubemap(int faceSize, const uint8_t *rgbaFaces,
350 const TextureCreateInfo &rawInfo) {
351 ASSERT(initialized);
352 ASSERT_GT(faceSize, 0);
353 ASSERT(rgbaFaces != nullptr);
354 if (!initialized) throw Exception("newCubemap: graphics not initialized");
355 if (faceSize <= 0 || !rgbaFaces) throw Exception("newCubemap: invalid args");
356
357 TextureCreateInfo info = normalizeTextureInfo(rawInfo);
358 info.sampler.repeatU = false;
359 info.sampler.repeatV = false;
360 info.sampler.repeatW = false;
361 const uint32_t mipLevels =
362 info.generateMipmaps ? uint32_t(mipmapCountForSize(faceSize, faceSize)) : 1u;
363
364 const size_t faceBytes = size_t(faceSize) * size_t(faceSize) * 4u;
365 auto gpu = std::make_unique<GpuTexture>();
366 gpu->width = faceSize;
367 gpu->height = faceSize;
368 gpu->isCube = true;
369 gpu->mipLevels = mipLevels;
370 gpu->samplerState = info.sampler;
371 // Optimal-tiled images cannot start in PREINITIALIZED. Uploads transition
372 // every cube face from UNDEFINED before copying the staging buffer.
373 vk::ImageCreateInfo cubeInfo{};
374 cubeInfo.flags = vk::ImageCreateFlagBits::eCubeCompatible;
375 cubeInfo.imageType = vk::ImageType::e2D;
376 cubeInfo.format = vk::Format::eR8G8B8A8Unorm;
377 cubeInfo.extent = vk::Extent3D{uint32_t(faceSize), uint32_t(faceSize), 1};
378 cubeInfo.mipLevels = mipLevels;
379 cubeInfo.arrayLayers = 6;
380 cubeInfo.samples = vk::SampleCountFlagBits::e1;
381 cubeInfo.tiling = vk::ImageTiling::eOptimal;
382 cubeInfo.usage =
383 vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst;
384 cubeInfo.initialLayout = vk::ImageLayout::eUndefined;
385 gpu->cubeImage =
386 vkb::GenericImage(device, cubeInfo, vk::ImageViewType::eCube, vk::ImageAspectFlagBits::eColor, false);
387
388 std::vector<uint8_t> bytes =
389 (mipLevels > 1) ? buildMipChainCube(rgbaFaces, uint32_t(faceSize), mipLevels)
390 : std::vector<uint8_t>(rgbaFaces, rgbaFaces + faceBytes * 6u);
391 uploadTextureForAllShaderStages(device, uploadPool,
392 device.getQueue(vkb::QueueType::graphics), gpu->cubeImage,
393 uint32_t(faceSize), uint32_t(faceSize), mipLevels, 6, bytes);
394
395 gpu->sampler = createVkSampler(info.sampler, mipLevels);
396 // Cubemap sampled via mesh3d descriptor sets — no 2D texSetLayout binding required here.
397 registerBindlessTextureCube(gpu.get());
398
399 auto tex = std::make_unique<Texture>();
400 tex->width = faceSize;
401 tex->height = faceSize;
402 tex->pixelWidth = faceSize;
403 tex->pixelHeight = faceSize;
404 tex->layers = 6;
405 tex->mipmapCount = int(mipLevels);
406 tex->sampler = info.sampler;
407 tex->gpuHandle = gpu.get();
408
409 Texture *raw = tex.get();
410 ownedTextures.push_back(std::move(tex));
411 ownedGpuTextures.push_back(std::move(gpu));
412 return raw;
413}
414
416 if (!initialized || faceSize <= 0) return nullptr;
417 const uint32_t size = static_cast<uint32_t>(faceSize);
418 const uint32_t mipLevels = uint32_t(mipmapCountForSize(faceSize, faceSize));
419
420 auto gpu = std::make_unique<GpuTexture>();
421 try {
422 gpu->hdrCube = device.createCubemapRenderTarget(size, mipLevels);
423 } catch (const std::exception &) {
424 return nullptr;
425 }
426 gpu->width = faceSize;
427 gpu->height = faceSize;
428 gpu->isCube = true;
429 gpu->isHDR = true;
430 gpu->mipLevels = mipLevels;
431 gpu->samplerState = TextureSampler::linearMipmap();
432 gpu->sampler = createVkSampler(gpu->samplerState, mipLevels);
433
434 vkb::executeImmediately(
435 device.instance, uploadPool, device.getQueue(vkb::QueueType::graphics),
436 [&](vk::CommandBuffer command) { gpu->hdrCube.setLayout(command, vk::ImageLayout::eShaderReadOnlyOptimal); });
437 registerBindlessTextureCube(gpu.get());
438
439 auto texture = std::make_unique<Texture>();
440 texture->width = faceSize;
441 texture->height = faceSize;
442 texture->pixelWidth = faceSize;
443 texture->pixelHeight = faceSize;
444 texture->layers = 6;
445 texture->mipmapCount = int(mipLevels);
446 texture->sampler = gpu->samplerState;
447 texture->gpuHandle = gpu.get();
448 Texture *raw = texture.get();
449 ownedTextures.push_back(std::move(texture));
450 ownedGpuTextures.push_back(std::move(gpu));
451 return raw;
452}
453
455 auto *canvas = dynamic_cast<OffscreenCanvas *>(source);
456 if (!canvas || !canvas->isHDR() || !cubemap || !cubemap->gpuHandle || face < 0 || face >= 6)
457 return false;
458 auto *target = static_cast<GpuTexture *>(cubemap->gpuHandle);
459 if (!target->isCube || !target->isHDR || !target->hdrCube.valid() || canvas->getWidth() != target->width ||
460 canvas->getHeight() != target->height)
461 return false;
462 ensureOffscreen3DResources();
463 lastOffscreen3DGpuDurationMs = 0.f;
464 vkb::executeImmediately(device.instance, uploadPool,
465 device.getQueue(vkb::QueueType::graphics),
466 [&](vk::CommandBuffer command) {
467 if (offscreen3DTimestampQueryPool) {
468 command.resetQueryPool(offscreen3DTimestampQueryPool, 0, 2);
469 command.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe,
470 offscreen3DTimestampQueryPool, 0);
471 }
472 canvas->colorImage().setLayout(command,
473 vk::ImageLayout::eTransferSrcOptimal);
474 vk::ImageMemoryBarrier toCopy{};
475 toCopy.srcAccessMask = vk::AccessFlagBits::eShaderRead;
476 toCopy.dstAccessMask = vk::AccessFlagBits::eTransferWrite;
477 toCopy.oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
478 toCopy.newLayout = vk::ImageLayout::eTransferDstOptimal;
479 toCopy.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
480 toCopy.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
481 toCopy.image = target->hdrCube.image();
482 toCopy.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1,
483 uint32_t(face), 1};
484 command.pipelineBarrier(vk::PipelineStageFlagBits::eFragmentShader,
485 vk::PipelineStageFlagBits::eTransfer, {}, 0,
486 nullptr, 0, nullptr, 1, &toCopy);
487 vk::ImageCopy copy{};
488 copy.srcSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
489 copy.dstSubresource = {vk::ImageAspectFlagBits::eColor, 0,
490 uint32_t(face), 1};
491 copy.extent = vk::Extent3D{uint32_t(target->width),
492 uint32_t(target->height), 1};
493 command.copyImage(canvas->colorImage().image(), vk::ImageLayout::eTransferSrcOptimal,
494 target->hdrCube.image(), vk::ImageLayout::eTransferDstOptimal, 1,
495 &copy);
496 std::swap(toCopy.srcAccessMask, toCopy.dstAccessMask);
497 std::swap(toCopy.oldLayout, toCopy.newLayout);
498 command.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
499 vk::PipelineStageFlagBits::eFragmentShader,
500 {}, 0, nullptr, 0, nullptr, 1, &toCopy);
501 canvas->colorImage().setLayout(
502 command, vk::ImageLayout::eShaderReadOnlyOptimal);
503 if (offscreen3DTimestampQueryPool)
504 command.writeTimestamp(
505 vk::PipelineStageFlagBits::eBottomOfPipe,
506 offscreen3DTimestampQueryPool, 1);
507 });
508 if (offscreen3DTimestampQueryPool && offscreen3DTimestampPeriodNs > 0.f) {
509 std::array<uint64_t, 2> ticks{};
510 const vk::Result result = device->getQueryPoolResults(
511 offscreen3DTimestampQueryPool, 0, uint32_t(ticks.size()), sizeof(ticks), ticks.data(),
512 sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait);
513 if (result == vk::Result::eSuccess && ticks[1] >= ticks[0])
514 lastOffscreen3DGpuDurationMs =
515 float(double(ticks[1] - ticks[0]) * double(offscreen3DTimestampPeriodNs) * 1.0e-6);
516 }
517 return true;
518}
519
521 Texture *cubemap) {
522 if (!sources || faceCount < 1 || faceCount > 6 || !cubemap || !cubemap->gpuHandle)
523 return false;
524 auto *target = static_cast<GpuTexture *>(cubemap->gpuHandle);
525 if (!target->isCube || !target->isHDR || !target->hdrCube.valid()) return false;
526
527 std::array<OffscreenCanvas *, 6> canvases{};
528 for (int face = 0; face < faceCount; ++face) {
529 auto *canvas = dynamic_cast<OffscreenCanvas *>(sources[face]);
530 if (!canvas || !canvas->isHDR() || canvas->getWidth() != target->width ||
531 canvas->getHeight() != target->height)
532 return false;
533 canvases[static_cast<size_t>(face)] = canvas;
534 }
535
536 ensureOffscreen3DResources();
537 lastOffscreen3DGpuDurationMs = 0.f;
538 vkb::executeImmediately(device.instance, uploadPool,
539 device.getQueue(vkb::QueueType::graphics),
540 [&](vk::CommandBuffer command) {
541 if (offscreen3DTimestampQueryPool) {
542 command.resetQueryPool(offscreen3DTimestampQueryPool, 0, 2);
543 command.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe,
544 offscreen3DTimestampQueryPool, 0);
545 }
546 for (int face = 0; face < faceCount; ++face) {
547 auto *canvas = canvases[static_cast<size_t>(face)];
548 canvas->colorImage().setLayout(
549 command, vk::ImageLayout::eTransferSrcOptimal);
550
551 vk::ImageMemoryBarrier toCopy{};
552 toCopy.srcAccessMask = vk::AccessFlagBits::eShaderRead;
553 toCopy.dstAccessMask = vk::AccessFlagBits::eTransferWrite;
554 toCopy.oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
555 toCopy.newLayout = vk::ImageLayout::eTransferDstOptimal;
556 toCopy.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
557 toCopy.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
558 toCopy.image = target->hdrCube.image();
559 toCopy.subresourceRange =
560 vk::ImageSubresourceRange(vk::ImageAspectFlagBits::eColor,
561 0, 1, uint32_t(face), 1);
562 command.pipelineBarrier(
563 vk::PipelineStageFlagBits::eFragmentShader,
564 vk::PipelineStageFlagBits::eTransfer, {}, 0, nullptr, 0,
565 nullptr, 1, &toCopy);
566
567 vk::ImageCopy copy{};
568 copy.srcSubresource =
569 vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor,
570 0, 0, 1);
571 copy.dstSubresource =
572 vk::ImageSubresourceLayers(vk::ImageAspectFlagBits::eColor,
573 0, uint32_t(face), 1);
574 copy.extent = vk::Extent3D(uint32_t(canvas->getWidth()),
575 uint32_t(canvas->getHeight()), 1);
576 command.copyImage(canvas->colorImage().image(),
577 vk::ImageLayout::eTransferSrcOptimal, target->hdrCube.image(),
578 vk::ImageLayout::eTransferDstOptimal, 1, &copy);
579
580 std::swap(toCopy.srcAccessMask, toCopy.dstAccessMask);
581 std::swap(toCopy.oldLayout, toCopy.newLayout);
582 command.pipelineBarrier(
583 vk::PipelineStageFlagBits::eTransfer,
584 vk::PipelineStageFlagBits::eFragmentShader, {}, 0, nullptr,
585 0, nullptr, 1, &toCopy);
586 canvas->colorImage().setLayout(
587 command, vk::ImageLayout::eShaderReadOnlyOptimal);
588 }
589 if (offscreen3DTimestampQueryPool)
590 command.writeTimestamp(
591 vk::PipelineStageFlagBits::eBottomOfPipe,
592 offscreen3DTimestampQueryPool, 1);
593 });
594 if (offscreen3DTimestampQueryPool && offscreen3DTimestampPeriodNs > 0.f) {
595 std::array<uint64_t, 2> ticks{};
596 const vk::Result result = device->getQueryPoolResults(
597 offscreen3DTimestampQueryPool, 0, uint32_t(ticks.size()), sizeof(ticks), ticks.data(),
598 sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait);
599 if (result == vk::Result::eSuccess && ticks[1] >= ticks[0])
600 lastOffscreen3DGpuDurationMs =
601 float(double(ticks[1] - ticks[0]) * double(offscreen3DTimestampPeriodNs) * 1.0e-6);
602 }
603 return true;
604}
605
606bool Graphics::filterHDRReflectionCubemap(Texture *cubemap, int sampleCount) {
607#ifndef EVENGINE_HAS_REFLECTION_PROBE_FILTER_SPV
608 (void)cubemap;
609 (void)sampleCount;
610 return false;
611#else
612 if (!cubemap || !cubemap->gpuHandle) return false;
613 auto *target = static_cast<GpuTexture *>(cubemap->gpuHandle);
614 if (!target->isCube || !target->isHDR || !target->hdrCube.valid() || target->mipLevels < 2) return false;
615 sampleCount = std::clamp(sampleCount, 8, 512);
616 ensureOffscreen3DResources();
617 lastOffscreen3DGpuDurationMs = 0.f;
618
619 if (!reflectionProbeFilterPass.pipeline()) {
620 std::array<vk::DescriptorSetLayoutBinding, 2> bindings{
621 vk::DescriptorSetLayoutBinding{0, vk::DescriptorType::eCombinedImageSampler, 1,
622 vk::ShaderStageFlagBits::eCompute},
623 vk::DescriptorSetLayoutBinding{1, vk::DescriptorType::eStorageImage, 1,
624 vk::ShaderStageFlagBits::eCompute},
625 };
626 reflectionProbeFilterSetLayout = device->createDescriptorSetLayoutUnique(
627 vk::DescriptorSetLayoutCreateInfo{{}, uint32_t(bindings.size()), bindings.data()});
628 vk::DescriptorSetLayout layout = *reflectionProbeFilterSetLayout;
629 vk::PushConstantRange push{vk::ShaderStageFlagBits::eCompute, 0, 16};
630 reflectionProbeFilterPipelineLayout = device->createPipelineLayoutUnique(
631 vk::PipelineLayoutCreateInfo{{}, 1, &layout, 1, &push});
632 const std::vector<uint32_t> spv(reflection_probe_filter_comp_spv,
633 reflection_probe_filter_comp_spv +
634 reflection_probe_filter_comp_spv_count);
635 if (!reflectionProbeFilterPass.create(device, *reflectionProbeFilterPipelineLayout, spv))
636 return false;
637 }
638
639 vk::UniqueImageView sourceView = target->hdrCube.createBaseCubeView();
640 std::vector<vk::UniqueImageView> targetViews;
641 targetViews.reserve(target->mipLevels - 1u);
642 for (uint32_t mip = 1; mip < target->mipLevels; ++mip)
643 targetViews.push_back(target->hdrCube.createMipArrayView(mip));
644
645 std::array<vk::DescriptorPoolSize, 2> poolSizes{
646 vk::DescriptorPoolSize{vk::DescriptorType::eCombinedImageSampler,
647 target->mipLevels - 1u},
648 vk::DescriptorPoolSize{vk::DescriptorType::eStorageImage, target->mipLevels - 1u},
649 };
650 vk::UniqueDescriptorPool pool = device->createDescriptorPoolUnique(vk::DescriptorPoolCreateInfo{
651 {}, target->mipLevels - 1u, uint32_t(poolSizes.size()), poolSizes.data()});
652 std::vector<vk::DescriptorSetLayout> layouts(target->mipLevels - 1u,
653 *reflectionProbeFilterSetLayout);
654 std::vector<vk::DescriptorSet> sets = device->allocateDescriptorSets(
655 vk::DescriptorSetAllocateInfo{*pool, uint32_t(layouts.size()), layouts.data()});
656 for (size_t index = 0; index < sets.size(); ++index) {
657 vk::DescriptorImageInfo sourceImage{target->sampler, *sourceView,
658 vk::ImageLayout::eShaderReadOnlyOptimal};
659 vk::DescriptorImageInfo destinationImage{{}, *targetViews[index],
660 vk::ImageLayout::eGeneral};
661 std::array<vk::WriteDescriptorSet, 2> writes{
662 vk::WriteDescriptorSet{sets[index], 0, 0, 1,
663 vk::DescriptorType::eCombinedImageSampler, &sourceImage},
664 vk::WriteDescriptorSet{sets[index], 1, 0, 1,
665 vk::DescriptorType::eStorageImage, &destinationImage},
666 };
667 device->updateDescriptorSets(uint32_t(writes.size()), writes.data(), 0, nullptr);
668 }
669
670 struct FilterPush {
671 float roughness;
672 uint32_t sampleCount;
673 uint32_t diffuseMode;
674 uint32_t targetSize;
675 };
676 vkb::executeImmediately(device.instance, uploadPool,
677 device.getQueue(vkb::QueueType::graphics),
678 [&](vk::CommandBuffer command) {
679 if (offscreen3DTimestampQueryPool) {
680 command.resetQueryPool(offscreen3DTimestampQueryPool, 0, 2);
681 command.writeTimestamp(vk::PipelineStageFlagBits::eTopOfPipe,
682 offscreen3DTimestampQueryPool, 0);
683 }
684 for (uint32_t mip = 1; mip < target->mipLevels; ++mip) {
685 vk::ImageMemoryBarrier toWrite{};
686 toWrite.srcAccessMask = vk::AccessFlagBits::eShaderRead;
687 toWrite.dstAccessMask = vk::AccessFlagBits::eShaderWrite;
688 toWrite.oldLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
689 toWrite.newLayout = vk::ImageLayout::eGeneral;
690 toWrite.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
691 toWrite.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
692 toWrite.image = target->hdrCube.image();
693 toWrite.subresourceRange = {vk::ImageAspectFlagBits::eColor, mip,
694 1, 0, 6};
695 command.pipelineBarrier(vk::PipelineStageFlagBits::eFragmentShader,
696 vk::PipelineStageFlagBits::eComputeShader,
697 {}, 0, nullptr, 0, nullptr, 1, &toWrite);
698 const uint32_t size = std::max(uint32_t(target->width) >> mip, 1u);
699 const FilterPush push{
700 float(mip) / float(target->mipLevels - 1u),
701 uint32_t(sampleCount),
702 mip + 1u == target->mipLevels ? 1u : 0u, size};
703 command.bindDescriptorSets(
704 vk::PipelineBindPoint::eCompute,
705 *reflectionProbeFilterPipelineLayout, 0, 1,
706 &sets[static_cast<size_t>(mip - 1u)], 0, nullptr);
707 command.pushConstants(*reflectionProbeFilterPipelineLayout,
708 vk::ShaderStageFlagBits::eCompute, 0,
709 sizeof(push), &push);
710 reflectionProbeFilterPass.record(command, (size + 7u) / 8u,
711 (size + 7u) / 8u, 6);
712 std::swap(toWrite.srcAccessMask, toWrite.dstAccessMask);
713 std::swap(toWrite.oldLayout, toWrite.newLayout);
714 command.pipelineBarrier(vk::PipelineStageFlagBits::eComputeShader,
715 vk::PipelineStageFlagBits::eFragmentShader,
716 {}, 0, nullptr, 0, nullptr, 1, &toWrite);
717 }
718 if (offscreen3DTimestampQueryPool)
719 command.writeTimestamp(
720 vk::PipelineStageFlagBits::eBottomOfPipe,
721 offscreen3DTimestampQueryPool, 1);
722 });
723 if (offscreen3DTimestampQueryPool && offscreen3DTimestampPeriodNs > 0.f) {
724 std::array<uint64_t, 2> ticks{};
725 const vk::Result result = device->getQueryPoolResults(
726 offscreen3DTimestampQueryPool, 0, uint32_t(ticks.size()), sizeof(ticks), ticks.data(),
727 sizeof(uint64_t), vk::QueryResultFlagBits::e64 | vk::QueryResultFlagBits::eWait);
728 if (result == vk::Result::eSuccess && ticks[1] >= ticks[0])
729 lastOffscreen3DGpuDurationMs =
730 float(double(ticks[1] - ticks[0]) * double(offscreen3DTimestampPeriodNs) * 1.0e-6);
731 }
732 return true;
733#endif
734}
735
737 ASSERT(data != nullptr);
738 if (!data) throw Exception("newTexture: null ImageData");
739 if (data->getFormat() != "RGBA8")
740 throw Exception("newTexture: only RGBA8 ImageData supported for now");
741 return newTexture(data->getWidth(), data->getHeight(),
742 static_cast<const uint8_t *>(data->getData()));
743}
744
746 ASSERT(data != nullptr);
747 if (!data) throw Exception("newTexture: null ImageData");
748 if (data->getFormat() != "RGBA8")
749 throw Exception("newTexture: only RGBA8 ImageData supported for now");
750 return newTexture(data->getWidth(), data->getHeight(),
751 static_cast<const uint8_t *>(data->getData()), info);
752}
753
755 if (!data || contentKey.empty() || data->getFormat() != "RGBA8")
757 "RGBA8 image and nonempty content key are required", {},
758 {}, "graphics.texture.shared"));
759 if (auto found = sharedTexturesByContent.find(contentKey); found != sharedTexturesByContent.end())
760 return ResultRef<Texture>::success(std::ref(*found->second));
761 try {
762 Texture *texture = newTexture(data);
763 if (!texture) throw Exception("shared texture upload produced no texture");
764 sharedTexturesByContent.emplace(contentKey, texture);
765 return ResultRef<Texture>::success(std::ref(*texture));
766 } catch (const std::exception &error) {
768 Diagnostic::error(DiagnosticCode::Failed, error.what(), {}, {}, "graphics.texture.shared"));
769 }
770}
771
772
774 if (!texture) return false;
776 if (!texture->gpuHandle) {
777 auto texIt = std::find_if(ownedTextures.begin(), ownedTextures.end(),
778 [&](const std::unique_ptr<Texture> &t) {
779 return t.get() == texture;
780 });
781 if (texIt == ownedTextures.end()) return false;
782 for (auto it = texturesByPath.begin(); it != texturesByPath.end();) {
783 if (it->second == texture)
784 it = texturesByPath.erase(it);
785 else
786 ++it;
787 }
788 for (auto it = sharedTexturesByContent.begin(); it != sharedTexturesByContent.end();) {
789 if (it->second == texture)
790 it = sharedTexturesByContent.erase(it);
791 else
792 ++it;
793 }
794 (void)texIt->release();
795 ownedTextures.erase(texIt);
796 return true;
797 }
798 // Renderer-owned fallback textures must never be released by callers.
799 if (texture == whiteTexture || texture == flatNormalTexture || texture == flatNormalTexture3D ||
800 texture == defaultEnvCubemap || texture == defaultExtrasArray || texture == defaultColorsArray ||
801 texture == defaultVertexArray || texture == defaultMotionArray || texture == defaultVegetationFadeNoise)
802 return false;
803
804 auto *gpu = static_cast<GpuTexture *>(texture->gpuHandle);
805 auto gpuIt = std::find_if(ownedGpuTextures.begin(), ownedGpuTextures.end(),
806 [&](const std::unique_ptr<GpuTexture> &g) {
807 return g.get() == gpu;
808 });
809 if (gpuIt == ownedGpuTextures.end()) return false;
810
811 auto texIt = std::find_if(ownedTextures.begin(), ownedTextures.end(),
812 [&](const std::unique_ptr<Texture> &t) {
813 return t.get() == texture;
814 });
815 if (texIt == ownedTextures.end()) return false;
816
817 // Path-cached textures must leave the hot-reload cache once released.
818 for (auto it = texturesByPath.begin(); it != texturesByPath.end();) {
819 if (it->second == texture)
820 it = texturesByPath.erase(it);
821 else
822 ++it;
823 }
824 for (auto it = sharedTexturesByContent.begin(); it != sharedTexturesByContent.end();) {
825 if (it->second == texture)
826 it = sharedTexturesByContent.erase(it);
827 else
828 ++it;
829 }
830
831 // In-flight frames may still sample the image / sampler; drain first.
832 waitForSharedGpuResources();
833 unregisterBindlessTexture(gpu);
834 if ((*gpuIt)->sampler && !(*gpuIt)->sharedSampler) device->destroySampler((*gpuIt)->sampler);
835 texture->gpuHandle = nullptr;
836 ownedGpuTextures.erase(gpuIt);
837 // Transfer the CPU facade to the caller instead of destroying it.
838 (void)texIt->release();
839 ownedTextures.erase(texIt);
840 return true;
841}
842
843bool Graphics::replaceTexturePixels(Texture *tex, image::ImageData *data) {
844 if (!tex || !data) return false;
845 if (data->getFormat() != "RGBA8") return false;
846 return replaceTexturePixelsRGBA(tex, data->getWidth(), data->getHeight(),
847 static_cast<const uint8_t *>(data->getData()));
848}
849
850bool Graphics::updateTexture(Texture *tex, int width, int height, const uint8_t *rgba) {
851 if (!tex || width <= 0 || height <= 0 || !rgba) return false;
852 if (width != tex->width || height != tex->height) return false;
853 // Dynamic single-mip textures keep their image, sampler and descriptor set.
854 // Replacing the complete texture here used to allocate one descriptor set
855 // per frame from the shared pool, eventually raising ErrorOutOfPoolMemory.
856 if (tex->mipmapCount == 1) {
857 const auto bytes = std::span<const uint8_t>(rgba, size_t(width) * size_t(height) * 4u);
858 return updateTextureRegion(tex, 0, 0, width, height, bytes, size_t(width) * 4u).ok();
859 }
860 return replaceTexturePixelsRGBA(tex, width, height, rgba);
861}
862
864 int height) {
865 constexpr const char* context = "graphics.updateTextureFromResidentRgba8";
866 if (!tex || width <= 0 || height <= 0 || width != tex->width || height != tex->height || tex->mipmapCount != 1)
869 "Resident upload requires a matching owned single-mip texture", context));
870 const uint64_t required = uint64_t(width) * uint64_t(height) * 4u;
871 if (source.backend != GpuResidentBackend::Vulkan || source.nativeHandle == 0 ||
872 source.offsetBytes > source.sizeBytes || required > source.sizeBytes - source.offsetBytes ||
873 (source.offsetBytes & 3u) != 0)
877 "Resident RGBA8 buffer is incompatible with the Vulkan texture", context));
878
879 auto* gpu = static_cast<GpuTexture*>(tex->gpuHandle);
880 const auto owned =
881 std::find_if(ownedGpuTextures.begin(), ownedGpuTextures.end(),
882 [gpu](const std::unique_ptr<GpuTexture>& candidate) { return candidate.get() == gpu; });
883 if (!initialized || !gpu || owned == ownedGpuTextures.end() || gpu->isCube)
885 "Texture is not an owned Vulkan 2D texture", context));
886
887 VkBuffer rawBuffer = VK_NULL_HANDLE;
888 static_assert(sizeof(rawBuffer) <= sizeof(source.nativeHandle));
889 std::memcpy(&rawBuffer, &source.nativeHandle, sizeof(rawBuffer));
890 const vk::Buffer buffer(rawBuffer);
891
892 waitForSharedGpuResources();
893 vkb::executeImmediately(
894 device.instance, uploadPool, device.getQueue(vkb::QueueType::graphics), [&](vk::CommandBuffer cb) {
895 gpu->image.setLayout(cb, vk::ImageLayout::eTransferDstOptimal);
896 vk::BufferImageCopy copy{};
897 copy.bufferOffset = source.offsetBytes;
898 copy.imageSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
899 copy.imageExtent = vk::Extent3D{uint32_t(width), uint32_t(height), 1};
900 cb.copyBufferToImage(buffer, gpu->image.image(), vk::ImageLayout::eTransferDstOptimal, copy);
901
902 vk::ImageMemoryBarrier barrier{};
903 barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
904 barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
905 barrier.oldLayout = vk::ImageLayout::eTransferDstOptimal;
906 barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
907 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
908 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
909 barrier.image = gpu->image.image();
910 barrier.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
911 cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
912 vk::PipelineStageFlagBits::eVertexShader | vk::PipelineStageFlagBits::eFragmentShader |
913 vk::PipelineStageFlagBits::eComputeShader,
914 {}, 0, nullptr, 0, nullptr, 1, &barrier);
915 gpu->image.setCurrentLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
916 });
917 gpu->contentIdentity = nextTextureContentIdentity();
919}
920
922 int height,
923 std::span<const std::uint8_t> rgba,
924 std::size_t bytesPerRow) {
925 const TextureRegionUpload upload{x, y, width, height, rgba, bytesPerRow};
926 return updateTextureRegions(tex, std::span<const TextureRegionUpload>(&upload, 1));
927}
928
930 Texture *tex, std::span<const TextureRegionUpload> regions) {
931 if (!tex)
933 eve::DiagnosticCode::InvalidArgument, "texture must be non-null",
934 "graphics.updateTextureRegions.texture"));
935 if (tex->mipmapCount != 1)
937 eve::DiagnosticCode::Unsupported, "partial updates require a single-mip texture",
938 "graphics.updateTextureRegions.mipmaps"));
939
940 auto *gpu = static_cast<GpuTexture *>(tex->gpuHandle);
941 const auto owned = std::find_if(ownedGpuTextures.begin(), ownedGpuTextures.end(),
942 [gpu](const std::unique_ptr<GpuTexture> &candidate) {
943 return candidate.get() == gpu;
944 });
945 if (!gpu || owned == ownedGpuTextures.end() || gpu->isCube)
947 eve::DiagnosticCode::InvalidArgument, "texture is not an owned 2D texture",
948 "graphics.updateTextureRegions.texture"));
949 if (regions.empty()) return eve::Result<void>::success();
950
951 std::vector<std::size_t> packedOffsets;
952 packedOffsets.reserve(regions.size());
953 std::size_t packedSize = 0;
954 for (const TextureRegionUpload &region : regions) {
955 if (region.x < 0 || region.y < 0 || region.width <= 0 || region.height <= 0 ||
956 region.x > tex->width - region.width || region.y > tex->height - region.height)
958 eve::DiagnosticCode::InvalidArgument, "invalid texture region",
959 "graphics.updateTextureRegions.region"));
960 const std::size_t packedRow = std::size_t(region.width) * 4U;
961 const std::size_t stride = region.bytesPerRow == 0 ? packedRow : region.bytesPerRow;
962 const std::size_t requiredBytes = stride * std::size_t(region.height - 1) + packedRow;
963 if (stride < packedRow || region.rgba.size() < requiredBytes)
966 "source bytes do not cover the texture region",
967 "graphics.updateTextureRegions.bytes"));
968 packedOffsets.push_back(packedSize);
969 packedSize += packedRow * std::size_t(region.height);
970 }
971
972 std::vector<std::uint8_t> packed(packedSize);
973 for (std::size_t index = 0; index < regions.size(); ++index) {
974 const TextureRegionUpload &region = regions[index];
975 const std::size_t packedRow = std::size_t(region.width) * 4U;
976 const std::size_t stride = region.bytesPerRow == 0 ? packedRow : region.bytesPerRow;
977 for (int row = 0; row < region.height; ++row)
978 std::copy_n(region.rgba.data() + std::size_t(row) * stride, packedRow,
979 packed.data() + packedOffsets[index] + std::size_t(row) * packedRow);
980 }
981 vkb::GenericBuffer staging(
982 device, vk::BufferUsageFlagBits::eTransferSrc, vk::DeviceSize(packed.size()),
983 vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent);
984 staging.updateLocal(vkb::FrameSlot::gpuIdle(), packed.data(), vk::DeviceSize(packed.size()));
985
986 waitForSharedGpuResources();
987 vkb::executeImmediately(device.instance, uploadPool,
988 device.getQueue(vkb::QueueType::graphics),
989 [&](vk::CommandBuffer cb) {
990 gpu->image.setLayout(cb, vk::ImageLayout::eTransferDstOptimal);
991 std::vector<vk::BufferImageCopy> copies;
992 copies.reserve(regions.size());
993 for (std::size_t index = 0; index < regions.size(); ++index) {
994 const TextureRegionUpload &source = regions[index];
995 vk::BufferImageCopy copy{};
996 copy.bufferOffset = packedOffsets[index];
997 copy.imageSubresource = {vk::ImageAspectFlagBits::eColor, 0, 0, 1};
998 copy.imageOffset = vk::Offset3D{source.x, source.y, 0};
999 copy.imageExtent = vk::Extent3D{std::uint32_t(source.width),
1000 std::uint32_t(source.height), 1};
1001 copies.push_back(copy);
1002 }
1003 cb.copyBufferToImage(staging.buffer, gpu->image.image(),
1004 vk::ImageLayout::eTransferDstOptimal, copies);
1005
1006 vk::ImageMemoryBarrier barrier{};
1007 barrier.srcAccessMask = vk::AccessFlagBits::eTransferWrite;
1008 barrier.dstAccessMask = vk::AccessFlagBits::eShaderRead;
1009 barrier.oldLayout = vk::ImageLayout::eTransferDstOptimal;
1010 barrier.newLayout = vk::ImageLayout::eShaderReadOnlyOptimal;
1011 barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1012 barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1013 barrier.image = gpu->image.image();
1014 barrier.subresourceRange = {vk::ImageAspectFlagBits::eColor, 0, 1, 0, 1};
1015 cb.pipelineBarrier(vk::PipelineStageFlagBits::eTransfer,
1016 vk::PipelineStageFlagBits::eVertexShader |
1017 vk::PipelineStageFlagBits::eFragmentShader |
1018 vk::PipelineStageFlagBits::eComputeShader,
1019 {}, 0, nullptr, 0, nullptr, 1, &barrier);
1020 gpu->image.setCurrentLayout(vk::ImageLayout::eShaderReadOnlyOptimal);
1021 });
1022 staging.release();
1023 gpu->contentIdentity = nextTextureContentIdentity();
1025}
1026
1027bool Graphics::replaceTexturePixelsRGBA(Texture *tex, int w, int h, const uint8_t *rgba) {
1028 if (!tex || !rgba || w <= 0 || h <= 0 || !initialized) return false;
1029
1031 info.sampler = tex->sampler;
1032 info.generateMipmaps = tex->mipmapCount > 1;
1033 info = normalizeTextureInfo(info);
1034 const uint32_t mipLevels =
1035 info.generateMipmaps ? uint32_t(mipmapCountForSize(w, h)) : 1u;
1036
1037 auto gpu = std::make_unique<GpuTexture>();
1038 gpu->width = w;
1039 gpu->height = h;
1040 gpu->isCube = false;
1041 gpu->mipLevels = mipLevels;
1042 gpu->samplerState = info.sampler;
1043 gpu->image = vkb::TextureImage2D(device, uint32_t(w), uint32_t(h), mipLevels);
1044 gpu->contentIdentity = nextTextureContentIdentity();
1045 std::vector<uint8_t> bytes =
1046 (mipLevels > 1) ? buildMipChain2D(rgba, uint32_t(w), uint32_t(h), mipLevels)
1047 : std::vector<uint8_t>(rgba, rgba + size_t(w) * size_t(h) * 4);
1049 device.getQueue(vkb::QueueType::graphics), gpu->image,
1050 uint32_t(w), uint32_t(h), mipLevels, 1, bytes);
1051
1052 gpu->sampler = createVkSampler(info.sampler, mipLevels);
1053
1054 auto sets = vkb::DescriptorSetBuilder().layout(texSetLayout).build(device.instance, descriptorPool);
1055
1056 gpu->descriptorSet = vkb::BoundSet{sets[0]};
1057 writeCombinedImageDescriptor(gpu.get());
1058 registerBindlessTexture2D(gpu.get());
1059
1060 void *oldHandle = tex->gpuHandle;
1061 for (auto &owned : ownedGpuTextures) {
1062 if (owned.get() != oldHandle) continue;
1063 // Destroying the old image/sampler while an in-flight frame still
1064 // samples it is a typical TDR. Drain first, then drop cached sets.
1065 waitForSharedGpuResources();
1066 unregisterBindlessTexture(static_cast<GpuTexture *>(oldHandle));
1067 if (owned->sampler && !owned->sharedSampler) device->destroySampler(owned->sampler);
1068 owned = std::move(gpu);
1069 tex->gpuHandle = owned.get();
1070 tex->width = w;
1071 tex->height = h;
1072 tex->pixelWidth = w;
1073 tex->pixelHeight = h;
1074 tex->mipmapCount = int(mipLevels);
1075 tex->sampler = info.sampler;
1076 registerBindlessTexture2D(owned.get());
1077 invalidateTextureBindings();
1078 return true;
1079 }
1080
1081 // Texture not in owned list — attach as new ownership.
1082 tex->gpuHandle = gpu.get();
1083 registerBindlessTexture2D(static_cast<GpuTexture *>(tex->gpuHandle));
1084 tex->width = w;
1085 tex->height = h;
1086 tex->pixelWidth = w;
1087 tex->pixelHeight = h;
1088 tex->mipmapCount = int(mipLevels);
1089 tex->sampler = info.sampler;
1090 ownedGpuTextures.push_back(std::move(gpu));
1091 return true;
1092}
1093
1094
1095} // namespace eve::graphics::vulkan
double y
double x
LogicalId target
float w
Definition AnimClip.cpp:738
ActiveSource owned
Stable, structured diagnostics shared by engine modules.
double raw
std::string layout
ScriptFieldRegion region
std::string message
DiagnosticCode code
float maximum[3]
tensor::Graph g
Definition GpuGraph.cpp:7
vkb::Device & device
vk::UniqueImage image
float u
Definition Grass.cpp:233
int h
std::uint32_t height
std::uint32_t width
size_t offset
bool required
Poco::JSON::Object::Ptr result
std::uint64_t bytes
float roughness
std::shared_ptr< OceanGpuSpectrum > gpu
OceanSprayView view
std::vector< std::pair< std::uint64_t, OceanBoatReceipt > > sources
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string error
Definition Package.cpp:174
Texture * texture
TileLayer * layer
std::vector< ParticleBakeMaterial > bindings
Object::Ptr value
float t
Move-only, checked operation results for the common layer.
bool found
bool repeatV
bool repeatU
std::string_view source
std::string resource
int count
float size
Definition TreeMesh.cpp:158
std::uint32_t depth
const AssetImportLimits & limits
uint32_t index
const VegetationPresetContext & context
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.
Definition Exception.h:13
bool ok() const noexcept
Whether this result represents a non-failure outcome.
Definition Result.h:514
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Canvas public API.
Definition Canvas.h:17
virtual bool updateTexture(Texture *texture, int width, int height, const uint8_t *rgba)=0
Replace an existing texture's pixels in place (pointer stays stable).
virtual bool copyHDRCanvasesToCubemap(Canvas *const *sources, int faceCount, Texture *cubemap)
Copy consecutive RGBA16F canvases into cubemap base-level faces.
Definition Graphics.h:577
virtual bool releaseTexture(Texture *texture)
Eagerly releases a texture created by this Graphics.
Definition Graphics.h:732
void push(bool all)
Pushes .
virtual eve::Result< void > updateTextureFromResidentRgba8(Texture *texture, const GpuResidentBufferView &source, int width, int height)
Copy a same-device resident RGBA8 buffer into an existing texture.
Definition Graphics.h:630
virtual bool filterHDRReflectionCubemap(Texture *cubemap, int sampleCount=64)
Generate GGX specular mips and final diffuse irradiance for an HDR cubemap. @compatibility Preserves ...
Definition Graphics.h:588
virtual Texture * newTexture(int width, int height, const uint8_t *rgba, bool repeatU=false, bool repeatV=false)=0
Creates a texture. @ownership Caller deletes unless documented otherwise.
virtual eve::Result< void > updateTextureRegions(Texture *texture, std::span< const TextureRegionUpload > regions)=0
Validate then upload multiple independent mip-zero RGBA8 regions as one batch.
void dropDeferredFileTexture(Texture *texture)
Drop deferred file texture.
virtual 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)=0
Upload one tightly packed or row-strided RGBA8 rectangle into mip level zero.
virtual ResultRef< Texture > newSharedTexture(image::ImageData *data, const std::string &contentKey)
Reuse or upload immutable RGBA8 pixels under a caller-provided content key.
GPU texture created via Graphics::newTexture. Owns GPU resources through an opaque backend handle.
Definition Texture.h:15
TextureSampler sampler
Definition Texture.h:65
Result< Texture * > newTextureArrayRgba16f(uint32_t width, uint32_t height, uint32_t layers, std::span< const uint16_t > rgbaHalf) override
Creates a texture array rgba 16 f. @ownership Caller deletes unless documented otherwise.
Texture * newHDRCubemap(int faceSize) override
Creates a hdr cubemap. @ownership Caller deletes unless documented otherwise.
Result< Texture * > newTextureMipChain(uint32_t width, uint32_t height, uint32_t levels, std::span< const uint8_t > rgba) override
Creates a texture mip chain. @ownership Caller deletes unless documented otherwise.
Texture * newCubemap(int faceSize, const uint8_t *rgbaFaces) override
Creates a cubemap. @ownership Caller deletes unless documented otherwise.
bool copyHDRCanvasToCubemapFace(Canvas *source, Texture *cubemap, int face) override
Copies hdr canvas to cubemap face.
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.
Result< Texture * > newTexture3DRgba8(uint32_t width, uint32_t height, uint32_t depth, std::span< const uint8_t > rgba) override
Creates a texture 3 d rgba 8. @ownership Caller deletes unless documented otherwise.
eve::Result< uint64_t > textureContentIdentity(const Texture *texture) const
Return the current content identity of an owned, realized RGBA8 2D texture.
OffscreenCanvas public API.
Definition Canvas.h:15
Represents raw pixel data.
Definition ImageData.h:38
void uploadTextureForAllShaderStages(vkb::Device &device, vk::CommandPool commandPool, vk::Queue graphicsQueue, TextureImage &image, uint32_t width, uint32_t height, uint32_t mipLevels, uint32_t layers, const std::vector< uint8_t > &bytes, uint32_t bytesPerPixel=4, uint32_t depth=1)
void recordTextureCopies(vk::CommandBuffer cb, TextureImage &image, vkb::GenericBuffer &staging, uint32_t width, uint32_t height, uint32_t depth, uint32_t mipLevels, uint32_t layers, uint32_t bytesPerPixel=4)
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).
Definition HexMetrics.h:76
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Transient backend buffer slice shared between sibling GPU modules. @ownership Non-owning; nativeHandl...
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...
Definition Graphics.h:76
static TextureSampler linear()
Linear.
static TextureSampler linearMipmap()
Trilinear (linear + linear mips). Caller should create the texture with generateMipmaps.
GpuTexture public API.
Definition Graphics.h:264
glm::uvec4 info