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..89cd694f2 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestArrayMapping.cpp @@ -0,0 +1,103 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: BSD-3-Clause + +#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. + check(severity != ANARI_SEVERITY_FATAL_ERROR + && severity != ANARI_SEVERITY_ERROR + && severity != ANARI_SEVERITY_WARNING, + 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() +{ + 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..349815704 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) { @@ -626,6 +708,13 @@ int main() setvbuf(stdout, nullptr, _IOLBF, 0); auto device = makeVisRTXDevice(statusFunc); bool ok = true; + testSharedHostMappingAfterRender(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/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index 5e543916e..fae011021 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -145,8 +145,28 @@ void *Array::map() reportMessage(ANARI_SEVERITY_WARNING, "array mapped again without being previously unmapped"); } - m_mapped = true; - return const_cast(data()); + // Host-backed arrays may also have an internal GPU copy. Map the + // application-facing allocation, not that copy. + void *ptr = nullptr; + switch (ownership()) { + case ArrayDataOwnership::SHARED: + ptr = m_data.shared.host.isValid() ? m_data.shared.host.ptr() + : m_data.shared.device.ptr(); + break; + case ArrayDataOwnership::CAPTURED: + ptr = m_data.captured.host.isValid() ? m_data.captured.host.ptr() + : m_data.captured.device.ptr(); + break; + case ArrayDataOwnership::MANAGED: + ptr = m_data.managed.host.ptr(); + break; + default: + break; + } + + if (ptr) + m_mapped = true; + return ptr; } void Array::unmap() diff --git a/devices/rtx/device/utility/CudaImageTexture.cpp b/devices/rtx/device/utility/CudaImageTexture.cpp index 4b7e9602d..5cb993594 100644 --- a/devices/rtx/device/utility/CudaImageTexture.cpp +++ b/devices/rtx/device/utility/CudaImageTexture.cpp @@ -131,7 +131,17 @@ 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(); + copyKind = cudaMemcpyDeviceToDevice; + } + if (!data) return cudaErrorInvalidValue; if (!cuArray) { @@ -147,12 +157,24 @@ static cudaError_t buildNativeCudaArray( return error; } - // Expand RGB->RGBA when needed; otherwise copy the host data straight in. + // RGB expansion runs on the CPU. Download only that case; native CUDA + // formats can copy directly from application-provided device storage. + std::vector downloaded; 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) { + if (copyKind == cudaMemcpyDeviceToDevice) { + const size_t bytes = array.totalSize() * size_t(nc) * compBytes; + downloaded.resize((bytes + sizeof(uint32_t) - 1) / sizeof(uint32_t)); + const auto error = + cudaMemcpy(downloaded.data(), src, bytes, cudaMemcpyDeviceToHost); + if (error != cudaSuccess) + return error; + src = downloaded.data(); + copyKind = cudaMemcpyHostToDevice; + } staging.resize(array.totalSize() * 4 * compBytes); if (isFloat32(format)) expandRGBtoRGBA(src, array.totalSize(), staging.data(), 1.0f); @@ -186,7 +208,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); }