diff --git a/devices/rtx/README.md b/devices/rtx/README.md index b60959a26..556dda7d9 100644 --- a/devices/rtx/README.md +++ b/devices/rtx/README.md @@ -62,7 +62,8 @@ change. This extension indicates that applications can use pointers to CUDA device memory when created shared and captured arrays when using VisRTX. All the normal -rules for shared and captured array data still apply. +rules for shared and captured array data still apply. Mapping a CUDA-backed +shared or captured array returns the supplied CUDA pointer, not a host mapping. #### "ANARI_NV_FRAME_BUFFERS_CUDA" diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 0efaac5e6..04d6bff2b 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -52,6 +52,8 @@ if (WIN32) endif() make_test(TestDeviceInit) +make_test(TestArrayMapping) +target_link_libraries(TestArrayMapping PRIVATE CUDA::cudart) make_test(TestEvictGPUArray) make_test(TestMultiThreadedObjectCreation) make_test(TestSpheres) @@ -102,6 +104,7 @@ if (VISRTX_USE_MDL_FOR_PHYSICALLY_BASED) endif() make_test(TestSamplerAlphaFill) make_test(TestTextureDataUpdate) +target_link_libraries(TestTextureDataUpdate PRIVATE CUDA::cudart) make_test(TestAlphaCutoffMode) make_test(TestRendererFog) make_test(TestRendererFogDiscovery) diff --git a/devices/rtx/apps/tests/api/TestArrayMapping.cpp b/devices/rtx/apps/tests/api/TestArrayMapping.cpp new file mode 100644 index 000000000..036bb3f87 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestArrayMapping.cpp @@ -0,0 +1,114 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: BSD-3-Clause + +#include +#include +#include + +#include +#include +#include +#include + +static void check(bool condition, const char *message) +{ + if (!condition) { + std::fprintf(stderr, "FAIL: %s\n", message); + std::exit(1); + } +} + +static void checkCUDA(cudaError_t result) +{ + check(result == cudaSuccess, cudaGetErrorString(result)); +} + +static void statusFunc(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + // Repeated successful map/unmap cycles must not warn about mapping state. + // Unrelated warnings (including device initialization) are not failures. + const bool mappingWarning = severity == ANARI_SEVERITY_WARNING + && (std::strstr(message, "array mapped again") + || std::strstr(message, "array unmapped again")); + check(severity != ANARI_SEVERITY_FATAL_ERROR + && severity != ANARI_SEVERITY_ERROR && !mappingWarning, + message); +} + +static void freeCUDA(void *ptr) +{ + checkCUDA(cudaFree(ptr)); +} + +static void capturedDeleter(const void *userData, const void *ptr) +{ + ++*static_cast(const_cast(userData)); + freeCUDA(const_cast(ptr)); +} + +static void exercise(ANARIDevice device, + void *memory, + bool cudaMemory, + ANARIMemoryDeleter deleter = nullptr, + const void *userData = nullptr) +{ + auto array = + anariNewArray1D(device, memory, deleter, userData, ANARI_FLOAT32, 4); + check(array != nullptr, "array creation failed"); + for (int iteration = 0; iteration < 2; ++iteration) { + void *mapped = anariMapArray(device, array); + check(mapped != nullptr, "mapping returned null"); + check(!memory || mapped == memory, "mapping changed application pointer"); + const float values[4] = {float(iteration), 1.f, 2.f, 3.f}; + if (cudaMemory) { + checkCUDA( + cudaMemcpy(mapped, values, sizeof(values), cudaMemcpyHostToDevice)); + checkCUDA(cudaDeviceSynchronize()); + } else { + auto *out = static_cast(mapped); + for (int i = 0; i < 4; ++i) + out[i] = values[i]; + } + anariUnmapArray(device, array); + } + anariRelease(device, array); +} + +int main() +{ + statusFunc(nullptr, + nullptr, + nullptr, + ANARI_UNKNOWN, + ANARI_SEVERITY_WARNING, + ANARI_STATUS_NO_ERROR, + "unrelated initialization warning"); + unsigned deleterCalls = 0; + auto device = makeVisRTXDevice(statusFunc); + check(device != nullptr, "device creation failed"); + + float host[4] = {}; + exercise(device, host, false); + exercise(device, nullptr, false); + + for (bool managed : {false, true}) { + void *ptr = nullptr; + checkCUDA(managed ? cudaMallocManaged(&ptr, sizeof(host)) + : cudaMalloc(&ptr, sizeof(host))); + std::unique_ptr allocation(ptr, freeCUDA); + exercise(device, ptr, true); + } + + void *captured = nullptr; + checkCUDA(cudaMalloc(&captured, sizeof(host))); + exercise(device, captured, true, capturedDeleter, &deleterCalls); + anariRelease(device, device); + check(deleterCalls == 1, "captured allocation must be deleted exactly once"); + return 0; +} diff --git a/devices/rtx/apps/tests/api/TestTextureDataUpdate.cpp b/devices/rtx/apps/tests/api/TestTextureDataUpdate.cpp index b3fdc563e..a82512ecd 100644 --- a/devices/rtx/apps/tests/api/TestTextureDataUpdate.cpp +++ b/devices/rtx/apps/tests/api/TestTextureDataUpdate.cpp @@ -31,6 +31,7 @@ #include #include +#include #include #include @@ -39,6 +40,7 @@ #include #include #include +#include #include #include @@ -381,6 +383,86 @@ static void checkAll( ok); } +static void testSharedHostMappingAfterRender(anari::Device d, bool &ok) +{ + TexturedScene s(d, 2, TexFormat::FLOAT_RGB, Ownership::SHARED); + check("shared-host-mapping/initial", renderMeanColor(s), GREEN, ok); + + // Rendering forces GPU consumption, though the sampler may use staging + // rather than retain a persistent linear device copy. + void *mapped = anariMapArray(d, s.image); + if (mapped != s.appMemory.data()) { + fprintf(stderr, "FAIL: shared host mapping changed application pointer\n"); + ok = false; + } + if (!mapped) + return; + + writeTexels(mapped, s.format, std::vector(s.texelCount, RED)); + anariUnmapArray(d, s.image); + check("shared-host-mapping/updated", renderMeanColor(s), RED, ok); +} + +static void requireCUDA(cudaError_t result) +{ + if (result != cudaSuccess) { + fprintf(stderr, "FAIL: CUDA: %s\n", cudaGetErrorString(result)); + std::exit(1); + } +} + +static void freeCUDA(void *ptr) +{ + requireCUDA(cudaFree(ptr)); +} + +static void testSharedCUDAUpdates( + anari::Device d, int dim, TexFormat format, bool &ok) +{ + constexpr size_t WIDTH = 2; + const size_t texelCount = WIDTH << (dim - 1); + void *ptr = nullptr; + const size_t bytes = texelCount * channels(format) + * (isFloat(format) ? sizeof(float) : sizeof(uint8_t)); + requireCUDA(cudaMalloc(&ptr, bytes)); + // Destroy the scene and its shared array before freeing application memory. + std::unique_ptr allocation(ptr, freeCUDA); + TexturedScene s(d, dim, format); + ANARIArray image = newImage(d, dim, anariFormat(format), WIDTH, ptr); + if (!image) { + fprintf(stderr, "FAIL: CUDA image creation failed\n"); + ok = false; + return; + } + anariRelease(d, s.image); + s.image = image; + setImage(d, s.samplers[0], "image", s.image, dim); + + // Bind once; subsequent renders must observe writes through unmap alone. + int iteration = 0; + for (const auto &color : {GREEN, RED, BLUE}) { + void *mapped = anariMapArray(d, s.image); + if (mapped != ptr) { + fprintf(stderr, "FAIL: CUDA mapping changed application pointer\n"); + ok = false; + } + if (!mapped) + return; + + std::vector texels((bytes + sizeof(float) - 1) / sizeof(float)); + writeTexels(texels.data(), format, std::vector(texelCount, color)); + requireCUDA( + cudaMemcpy(mapped, texels.data(), bytes, cudaMemcpyHostToDevice)); + requireCUDA(cudaDeviceSynchronize()); + anariUnmapArray(d, s.image); + check("shared-cuda-update/image" + std::to_string(dim) + "D/" + + formatName(format) + "/" + std::to_string(iteration++), + renderMeanColor(s), + color, + ok); + } +} + static void testWindows( anari::Device d, TexFormat format, Ownership ownership, bool &ok) { @@ -475,6 +557,46 @@ static void checkValid(anari::Device d, ok &= pass; } +static void testForeignCUDAInput(anari::Device d, bool &ok) +{ + int devices = 0; + requireCUDA(cudaGetDeviceCount(&devices)); + if (devices < 2) { + std::puts("SKIP: foreign CUDA input requires two GPUs"); + return; + } + int local = 0; + requireCUDA(cudaGetDevice(&local)); + const int foreign = (local + 1) % devices; + for (auto format : {TexFormat::FLOAT_RGB, TexFormat::FLOAT_RGBA}) { + void *ptr = nullptr; + requireCUDA(cudaSetDevice(foreign)); + requireCUDA(cudaMalloc(&ptr, 2 * channels(format) * sizeof(float))); + requireCUDA(cudaSetDevice(local)); + { + TexturedScene s(d, 1, format); + ANARIArray image = newImage(d, 1, anariFormat(format), 2, ptr); + anariRelease(d, s.image); + s.image = image; + setImage(d, s.samplers[0], "image", s.image, 1); + const unsigned before = uploadErrors; + expectUploadError = true; + renderMeanColor(s); + expectUploadError = false; + if (uploadErrors != before + 1) { + std::fprintf(stderr, "FAIL: foreign CUDA input was not rejected\n"); + ok = false; + } + checkValid(d, s.samplers[0], "foreign-cuda-input", false, ok); + // No kernel may touch the foreign pointer or poison the local context. + requireCUDA(cudaDeviceSynchronize()); + } + requireCUDA(cudaSetDevice(foreign)); + requireCUDA(cudaFree(ptr)); + requireCUDA(cudaSetDevice(local)); + } +} + static void testInvalidTransitions( anari::Device d, int dim, bool unset, bool &ok) { @@ -626,6 +748,14 @@ int main() setvbuf(stdout, nullptr, _IOLBF, 0); auto device = makeVisRTXDevice(statusFunc); bool ok = true; + testSharedHostMappingAfterRender(device, ok); + testForeignCUDAInput(device, ok); + for (int dim : {1, 2, 3}) + for (auto format : {TexFormat::FLOAT_RGB, + TexFormat::FLOAT_RGBA, + TexFormat::SRGB_RGB, + TexFormat::SRGB_RGBA}) + testSharedCUDAUpdates(device, dim, format, ok); for (auto format : {TexFormat::SRGB_RGBA, TexFormat::SRGB_RGB}) for (auto ownership : {Ownership::MANAGED, Ownership::SHARED}) testWindows(device, format, ownership, ok); diff --git a/devices/rtx/apps/tests/unit/CMakeLists.txt b/devices/rtx/apps/tests/unit/CMakeLists.txt index 405713910..65c58fd4f 100644 --- a/devices/rtx/apps/tests/unit/CMakeLists.txt +++ b/devices/rtx/apps/tests/unit/CMakeLists.txt @@ -1,6 +1,16 @@ # Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause +# GPU unit test using the same compiled RGB kernel as the device library. +add_executable(rtx_test_RGBExpansion test_RGBExpansion.cpp + $) +target_include_directories(rtx_test_RGBExpansion PRIVATE + ${CMAKE_CURRENT_LIST_DIR}/../../../device) +target_link_libraries(rtx_test_RGBExpansion PRIVATE CUDA::cudart) +target_compile_features(rtx_test_RGBExpansion PRIVATE cxx_std_17) +add_test(NAME rtx::RGBExpansion COMMAND rtx_test_RGBExpansion) +set_tests_properties(rtx::RGBExpansion PROPERTIES TIMEOUT 60) + # Host-only unit tests for the pure analytic primitive solvers. No CUDA/OptiX/GPU # — these run on CPU and exercise devices/rtx/device/gpu/intersectPrimitives.h # directly, so the intersection math is testable without a device. diff --git a/devices/rtx/apps/tests/unit/test_RGBExpansion.cpp b/devices/rtx/apps/tests/unit/test_RGBExpansion.cpp new file mode 100644 index 000000000..4f5eaec86 --- /dev/null +++ b/devices/rtx/apps/tests/unit/test_RGBExpansion.cpp @@ -0,0 +1,131 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: BSD-3-Clause + +#include "utility/CudaRGBExpansion.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +static void check(bool ok, const char *message) +{ + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", message); + std::exit(1); + } +} + +static void checkCUDA(cudaError_t error) +{ + check(error == cudaSuccess, cudaGetErrorString(error)); +} + +static void freeCUDA(void *ptr) +{ + checkCUDA(cudaFree(ptr)); +} + +static void freeArray(cudaArray *array) +{ + checkCUDA(cudaFreeArray(array)); +} + +template +static void exercise( + cudaExtent extent, T alpha, bool managed, bool half = false) +{ + // Offset input and non-block-aligned lengths exercise windowed RGB sources. + // Compare components bitwise, including -0.0f and raw FLOAT16 encodings. + const size_t width = extent.width; + const size_t height = extent.height ? extent.height : 1; + const size_t depth = extent.depth ? extent.depth : 1; + const size_t texels = width * height * depth; + constexpr size_t PREFIX = 3; + std::vector rgb((texels + PREFIX + 1) * 3); + for (size_t i = 0; i < rgb.size(); ++i) + rgb[i] = T(i % 251); + rgb[PREFIX * 3] = T(-0.0f); + std::vector expected(texels * 4); + for (size_t i = 0; i < texels; ++i) { + for (size_t c = 0; c < 3; ++c) + expected[4 * i + c] = rgb[(PREFIX + i) * 3 + c]; + expected[4 * i + 3] = alpha; + } + void *src = nullptr; + cudaArray_t dst = nullptr; + checkCUDA(managed ? cudaMallocManaged(&src, rgb.size() * sizeof(T)) + : cudaMalloc(&src, rgb.size() * sizeof(T))); + std::unique_ptr source(src, freeCUDA); + const int bits = int(sizeof(T) * 8); + const auto desc = cudaCreateChannelDesc(bits, + bits, + bits, + bits, + std::is_same_v || half ? cudaChannelFormatKindFloat + : cudaChannelFormatKindUnsigned); + checkCUDA(cudaMalloc3DArray(&dst, &desc, extent, cudaArraySurfaceLoadStore)); + std::unique_ptr destination(dst, freeArray); + checkCUDA(cudaMemcpy( + src, rgb.data(), rgb.size() * sizeof(T), cudaMemcpyHostToDevice)); + std::vector actual(expected.size(), T(17)); + // Repeat writes through newly created surfaces onto the same CUDA array. + for (int iteration = 0; iteration < 2; ++iteration) { + rgb[PREFIX * 3 + 1] = T(iteration + 19); + expected[1] = rgb[PREFIX * 3 + 1]; + checkCUDA(cudaMemcpy( + src, rgb.data(), rgb.size() * sizeof(T), cudaMemcpyHostToDevice)); + // A synchronous argument error must not be attributed to a later, + // successful expansion. Leave it in the thread's last-error slot. + cudaDeviceProp properties{}; + check(cudaGetDeviceProperties(&properties, -1) == cudaErrorInvalidDevice, + "failed to seed an unrelated CUDA error"); + checkCUDA(visrtx::expandRGBtoRGBADevice( + static_cast(src) + PREFIX * 3, dst, alpha)); + cudaGetLastError(); + cudaMemcpy3DParms copy{}; + copy.srcArray = dst; + copy.dstPtr = make_cudaPitchedPtr( + actual.data(), width * 4 * sizeof(T), width, height); + copy.extent = make_cudaExtent(width, height, depth); + copy.kind = cudaMemcpyDeviceToHost; + checkCUDA(cudaMemcpy3D(©)); + check(std::memcmp(actual.data(), expected.data(), actual.size() * sizeof(T)) + == 0, + "RGB surface expansion changed components or alpha"); + } +} + +int main() +{ + // Invalid destination flags return a CUDA status, not an exception. + cudaArray_t noSurface = nullptr; + const auto desc = cudaCreateChannelDesc(); + checkCUDA(cudaMallocArray(&noSurface, &desc, 1)); + std::unique_ptr destination( + noSurface, freeArray); + check(visrtx::expandRGBtoRGBADevice(nullptr, noSurface, 1.f) + == cudaErrorInvalidValue, + "array without surface support must be rejected"); + + for (bool managed : {false, true}) { + for (auto extent : {make_cudaExtent(1, 0, 0), + make_cudaExtent(257, 0, 0), + make_cudaExtent(257, 1, 0), + make_cudaExtent(17, 19, 0), + make_cudaExtent(7, 11, 5)}) { + exercise(extent, 1.f, managed); + exercise(extent, std::numeric_limits::max(), managed); + exercise(extent, std::numeric_limits::max(), managed); + exercise(extent, 0x3c00, managed, true); + exercise(extent, std::numeric_limits::max(), managed); + } + } + std::puts("RGB expansion passed for float32, float16 bits, and uint8/16/32"); +} diff --git a/devices/rtx/device/CMakeLists.txt b/devices/rtx/device/CMakeLists.txt index 6a490ddb8..7ff4e446f 100644 --- a/devices/rtx/device/CMakeLists.txt +++ b/devices/rtx/device/CMakeLists.txt @@ -243,7 +243,20 @@ if(VISRTX_ENABLE_MDL_SUPPORT) ) endif() -project_sources(PRIVATE ${SOURCES}) +# Share the production RGB kernel with its focused unit test without exporting +# private symbols from the device library or compiling the CUDA source twice. +add_library(visrtx_cuda_rgb_expansion OBJECT utility/CudaRGBExpansion.cu) +set_target_properties(visrtx_cuda_rgb_expansion PROPERTIES + POSITION_INDEPENDENT_CODE ON + CUDA_VISIBILITY_PRESET hidden + CUDA_STANDARD 17 CUDA_STANDARD_REQUIRED ON) +target_include_directories(visrtx_cuda_rgb_expansion PRIVATE + ${CMAKE_CURRENT_LIST_DIR}) +target_link_libraries(visrtx_cuda_rgb_expansion PRIVATE CUDA::cudart) +target_compile_options(visrtx_cuda_rgb_expansion PRIVATE + ${VISRTX_CUDA_COMPILE_OPTIONS}) +project_sources(PRIVATE ${SOURCES} + $) set(CUDA_SOURCES ${SOURCES}) list(FILTER CUDA_SOURCES INCLUDE REGEX ".*\\.cu$") diff --git a/devices/rtx/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index 5e543916e..74fc57da1 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -145,8 +145,11 @@ void *Array::map() reportMessage(ANARI_SEVERITY_WARNING, "array mapped again without being previously unmapped"); } - m_mapped = true; - return const_cast(data()); + void *ptr = appFacingPtr(); + + if (ptr) + m_mapped = true; + return ptr; } void Array::unmap() @@ -248,7 +251,11 @@ bool Array::isMapped() const const void *Array::dataGPU() const { uploadArrayData(); + return deviceData(); +} +const void *Array::deviceData() const +{ switch (ownership()) { case ArrayDataOwnership::SHARED: return m_data.shared.device.ptr(); @@ -269,20 +276,7 @@ const void *Array::dataGPU() const const void *Array::stagedDataGPU(DeviceBuffer &staging) const { const void *host = dataHost(); - const void *device = nullptr; - switch (ownership()) { - case ArrayDataOwnership::SHARED: - device = m_data.shared.device.ptr(); - break; - case ArrayDataOwnership::CAPTURED: - device = m_data.captured.device.ptr(); - break; - case ArrayDataOwnership::MANAGED: - device = m_data.managed.device.ptr(); - break; - default: - break; - } + const void *device = deviceData(); if (device && (!host || !needToUploadData())) return device; @@ -313,6 +307,16 @@ const void *Array::dataHost() const return nullptr; } +void *Array::appFacingPtr() const +{ + // Host-backed arrays may also have an internal GPU copy. Map the + // application-facing allocation, not that copy, without triggering uploads. + const void *ptr = dataHost(); + if (!ptr && ownership() != ArrayDataOwnership::MANAGED) + ptr = deviceData(); + return const_cast(ptr); +} + void Array::evictGPU() { if (m_data.shared.host) diff --git a/devices/rtx/device/array/Array.h b/devices/rtx/device/array/Array.h index e5c29789e..22e087649 100644 --- a/devices/rtx/device/array/Array.h +++ b/devices/rtx/device/array/Array.h @@ -114,6 +114,14 @@ struct Array : public UploadableArray void evictGPU(); private: + // Current device allocation, without uploading potentially modified host + // data. + const void *deviceData() const; + + // Map the application-facing allocation: host storage when present, otherwise + // the supplied CUDA pointer. Never upload or expose an internal GPU copy. + void *appFacingPtr() const; + void on_NoInternalReferences() override; void on_NoPublicReferences() override; diff --git a/devices/rtx/device/utility/CudaImageTexture.cpp b/devices/rtx/device/utility/CudaImageTexture.cpp index 4b7e9602d..65d99bba5 100644 --- a/devices/rtx/device/utility/CudaImageTexture.cpp +++ b/devices/rtx/device/utility/CudaImageTexture.cpp @@ -34,6 +34,7 @@ #include #include #include +#include "CudaRGBExpansion.h" #include "utility/AnariTypeHelpers.h" namespace visrtx { @@ -131,7 +132,21 @@ static cudaError_t buildNativeCudaArray( ? cudaChannelFormatKindFloat : cudaChannelFormatKindUnsigned; const int storedNc = (nc == 3) ? 4 : nc; - if (!array.data() || nc == 0 || size.x == 0 || size.y == 0 || size.z == 0) + if (nc == 0 || size.x == 0 || size.y == 0 || size.z == 0) + return cudaErrorInvalidValue; + + // Prefer host storage when present: its internal GPU copy may be stale. + const void *data = array.dataHost(); + cudaMemcpyKind copyKind = cudaMemcpyHostToDevice; + if (!data) { + data = array.dataGPU(); + // RGB expansion launches on this device; foreign pointers are unsafe + // without explicitly configured peer access. Reject them before any copy. + if (getPointerAddressSpace(data) == AddressSpace::FOREIGN) + return cudaErrorInvalidDevicePointer; + copyKind = cudaMemcpyDeviceToDevice; + } + if (!data) return cudaErrorInvalidValue; if (!cuArray) { @@ -142,39 +157,49 @@ static cudaError_t buildNativeCudaArray( kind); const auto error = cudaMalloc3DArray(&cuArray, &desc, - make_cudaExtent(size.x, size.y, size.z <= 1 ? 0 : size.z)); + make_cudaExtent(size.x, size.y, size.z <= 1 ? 0 : size.z), + nc == 3 && copyKind == cudaMemcpyDeviceToDevice + ? cudaArraySurfaceLoadStore + : cudaArrayDefault); if (error != cudaSuccess) return error; } - // Expand RGB->RGBA when needed; otherwise copy the host data straight in. + // Expand RGB in its source address space; CUDA inputs never need a download. std::vector staging; - const void *src = static_cast(array.data()) - + offset * anari::sizeOf(format); + const void *src = + static_cast(data) + offset * anari::sizeOf(format); size_t srcChannels = size_t(nc); if (nc == 3) { - staging.resize(array.totalSize() * 4 * compBytes); + const size_t texels = array.totalSize(); + const size_t bytes = texels * 4 * compBytes; + const bool onDevice = copyKind == cudaMemcpyDeviceToDevice; + // Surface writes fill the final array; only host input needs staging. + if (!onDevice) + staging.resize(bytes); + void *dst = staging.data(); + + const auto expand = [&](auto pad) { + using T = decltype(pad); + if (onDevice) + return expandRGBtoRGBADevice(static_cast(src), cuArray, pad); + expandRGBtoRGBA(src, texels, dst, pad); + return cudaSuccess; + }; + cudaError_t error; if (isFloat32(format)) - expandRGBtoRGBA(src, array.totalSize(), staging.data(), 1.0f); + error = expand(1.0f); else if (isFloat16(format)) - expandRGBtoRGBA( - src, array.totalSize(), staging.data(), kHalfOne); + error = expand(kHalfOne); else if (compBytes == 4) - expandRGBtoRGBA(src, - array.totalSize(), - staging.data(), - std::numeric_limits::max()); + error = expand(std::numeric_limits::max()); else if (compBytes == 2) - expandRGBtoRGBA(src, - array.totalSize(), - staging.data(), - std::numeric_limits::max()); + error = expand(std::numeric_limits::max()); else - expandRGBtoRGBA(src, - array.totalSize(), - staging.data(), - std::numeric_limits::max()); - src = staging.data(); + error = expand(std::numeric_limits::max()); + if (error != cudaSuccess || onDevice) + return error; + src = dst; srcChannels = 4; } @@ -186,7 +211,7 @@ static cudaError_t buildNativeCudaArray( size.x, size.y); p.extent = make_cudaExtent(size.x, size.y, size.z < 1 ? 1 : size.z); - p.kind = cudaMemcpyHostToDevice; + p.kind = copyKind; return cudaMemcpy3D(&p); } diff --git a/devices/rtx/device/utility/CudaRGBExpansion.cu b/devices/rtx/device/utility/CudaRGBExpansion.cu new file mode 100644 index 000000000..5b48d6f9b --- /dev/null +++ b/devices/rtx/device/utility/CudaRGBExpansion.cu @@ -0,0 +1,121 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: BSD-3-Clause + +#include "CudaRGBExpansion.h" +#include "gpu/gpu_decl.h" + +#include +#include +#include +#include +#include + +#include +#include + +namespace visrtx { + +namespace { + +struct Surface +{ + ~Surface(); + cudaSurfaceObject_t object{0}; +}; + +Surface::~Surface() +{ + if (object) + cudaDestroySurfaceObject(object); +} + +template +struct RGBTexel +{ + const T *src; + T pad; + cudaSurfaceObject_t surface; + cudaExtent extent; + + VISRTX_DEVICE void operator()(size_t texel) const; +}; + +template +VISRTX_DEVICE void RGBTexel::operator()(size_t texel) const +{ + using Pixel = std::conditional_t, + float4, + std::conditional_t>>; + const Pixel rgba{src[3 * texel], src[3 * texel + 1], src[3 * texel + 2], pad}; + // Surface x coordinates are in bytes, not texels. Use the actual CUDA array + // dimensions: VisRTX also represents a 1D image as a 2D array of height one. + const int x = int((texel % extent.width) * sizeof(Pixel)); + if (extent.height == 0) { + surf1Dwrite(rgba, surface, x); + } else { + const int y = int((texel / extent.width) % extent.height); + if (extent.depth == 0) + surf2Dwrite(rgba, surface, x, y); + else + surf3Dwrite( + rgba, surface, x, y, int(texel / (extent.width * extent.height))); + } +} + +} // namespace + +template +cudaError_t expandRGBtoRGBADevice(const T *src, cudaArray_t dst, T pad) +{ + cudaChannelFormatDesc desc{}; + cudaExtent extent{}; + unsigned int flags = 0; + auto error = cudaArrayGetInfo(&desc, &extent, &flags, dst); + if (error != cudaSuccess) + return error; + if (!(flags & cudaArraySurfaceLoadStore)) + return cudaErrorInvalidValue; + + cudaResourceDesc resource{}; + resource.resType = cudaResourceTypeArray; + resource.res.array.array = dst; + Surface surface; + error = cudaCreateSurfaceObject(&surface.object, &resource); + if (error != cudaSuccess) + return error; + + const size_t texels = extent.width * (extent.height ? extent.height : 1) + * (extent.depth ? extent.depth : 1); + const auto begin = thrust::make_counting_iterator(0); + // The synchronous policy finishes surface writes before the surface is + // destroyed and before the caller samples the updated texture. + // Thrust checks CUDA's last-error slot internally. Discard earlier, + // unrelated synchronous errors so only this operation determines its status. + cudaGetLastError(); + try { + thrust::for_each(thrust::device, + begin, + begin + texels, + RGBTexel{src, pad, surface.object, extent}); + } catch (const thrust::system_error &e) { + return e.code().category() == thrust::cuda_category() + ? static_cast(e.code().value()) + : cudaErrorUnknown; + } catch (...) { + return cudaErrorUnknown; + } + return cudaSuccess; +} + +template cudaError_t expandRGBtoRGBADevice( + const float *, cudaArray_t, float); +template cudaError_t expandRGBtoRGBADevice( + const uint8_t *, cudaArray_t, uint8_t); +template cudaError_t expandRGBtoRGBADevice( + const uint16_t *, cudaArray_t, uint16_t); +template cudaError_t expandRGBtoRGBADevice( + const uint32_t *, cudaArray_t, uint32_t); + +} // namespace visrtx diff --git a/devices/rtx/device/utility/CudaRGBExpansion.h b/devices/rtx/device/utility/CudaRGBExpansion.h new file mode 100644 index 000000000..9d8de7773 --- /dev/null +++ b/devices/rtx/device/utility/CudaRGBExpansion.h @@ -0,0 +1,19 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: BSD-3-Clause + +#pragma once + +#include +#include + +namespace visrtx { + +// Expand device RGB storage directly into an RGBA CUDA array, preserving +// component bits. dst must have cudaArraySurfaceLoadStore and four channels +// matching T's width; src must contain a texel for every destination element. +// Completes on the default stream before returning. Instantiated for float +// and uint8_t/uint16_t/uint32_t; pad supplies the opaque alpha encoding. +template +cudaError_t expandRGBtoRGBADevice(const T *src, cudaArray_t dst, T pad); + +} // namespace visrtx diff --git a/devices/rtx/shaders/visrtx/physically_based.mdl b/devices/rtx/shaders/visrtx/physically_based.mdl index 9c016a3f0..465e41b9d 100644 --- a/devices/rtx/shaders/visrtx/physically_based.mdl +++ b/devices/rtx/shaders/visrtx/physically_based.mdl @@ -165,42 +165,6 @@ float ResolveFloatInput(FloatInput input) return input.value; } -float2 ResolveFloat2Input(Float2Input input) -{ - if (tex::texture_isvalid(input.texture)) { - int textureSpace = input.textureSpace; - return tex::lookup_float2( - tex: input.texture, - coord: float2(state::texture_coordinate(textureSpace).x, state::texture_coordinate(textureSpace).y) - ); - } - return input.value; -} - -float3 ResolveFloat3Input(Float3Input input) -{ - if (tex::texture_isvalid(input.texture)) { - int textureSpace = input.textureSpace; - return tex::lookup_float3( - tex: input.texture, - coord: float2(state::texture_coordinate(textureSpace).x, state::texture_coordinate(textureSpace).y) - ); - } - return input.value; -} - -float4 ResolveFloat4Input(Float4Input input) -{ - if (tex::texture_isvalid(input.texture)) { - int textureSpace = input.textureSpace; - return tex::lookup_float4( - tex: input.texture, - coord: float2(state::texture_coordinate(textureSpace).x, state::texture_coordinate(textureSpace).y) - ); - } - return input.value; -} - float ResolveAlphaInput(AlphaMode alphaMode, float alphaCutoff, float alpha) { switch (alphaMode) {