diff --git a/.agents/skills/benchmark-geometry-preprocessing/SKILL.md b/.agents/skills/benchmark-geometry-preprocessing/SKILL.md new file mode 100644 index 000000000..8cd3c0fc0 --- /dev/null +++ b/.agents/skills/benchmark-geometry-preprocessing/SKILL.md @@ -0,0 +1,87 @@ +--- +name: benchmark-geometry-preprocessing +description: Compare local before/after performance for RTX geometry preparation, preprocessing, BVH readiness or preparation-preserving updates. Use when assessing whether a development change improves end-to-end latency. +--- + +# Local geometry-preprocessing comparison + +Produce a terminal before/after comparison and a short assessment of whether the +change helps its intended workload. Results are local development feedback; +historical performance tracking is a separate CI concern. Run affected correctness +tests independently of timing. + +Repository paths below are relative to the checkout root. Timing definitions, +custom workload examples and optional profiling commands live in +`devices/rtx/docs/geometry-preprocessing-performance.md`; read it before choosing +workloads or interpreting numbers. + +## 1. Identify before and after + +Use the user's control revision; ask if unspecified. Keep the candidate intact +and create a separate control workspace using the checkout's VCS (`jj workspace +add` in a jj workspace, otherwise `git worktree add`). Record the control revision +and candidate revision/working-copy state in the local report. + +## 2. Build matched libraries + +Use identical compiler, CUDA, OptiX, architecture, build configuration, optional +components and library suffix on both sides. Prefer the host's existing build +recipe. A minimal single-configuration starting point, with dependencies already +available, is: + +```bash +cmake -S SOURCE -B BUILD -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DVISRTX_BUILD_GL_DEVICE=OFF -DVISRTX_ENABLE_MDL_SUPPORT=OFF \ + -DVISRTX_ENABLE_MATERIALX_SUPPORT=OFF -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared +``` + +Enable `VISRTX_BUILD_TESTS` in the candidate and build +`BenchmarkGeometryPreprocessing`; build `anari_library_visrtx` in the control. +One candidate executable runs against either ABI-compatible library, so the +control need not contain benchmark sources. If their ABIs differ, establish a +compatible harness/build pair before comparing. + +Locate the executable and directories containing the built shared libraries. +For multi-configuration builds include the configuration directory. Check both +loader resolutions, substituting each library directory: + +```bash +LD_LIBRARY_PATH=LIBRARY_DIR ldd BENCHMARK +``` + +Proceed only when each resolves the intended device library and a real CUDA +driver, not a toolkit link-time stub. Keep the remaining runtime environment the +same on both sides. + +## 3. Compare + +Start with the default cases, or a focused case when the user requests one: + +```bash +python3 devices/rtx/apps/tests/api/benchmark_preprocessing.py \ + BENCHMARK CONTROL_LIBRARY_DIR CANDIDATE_LIBRARY_DIR +``` + +Use `--help` for workload selection, geometry, device inputs and run budget. +The tool prints warm medians, trial ranges and candidate/control ratios. +A trailing JSON path before the options retains raw results in local scratch; +no output file is required. A nonzero exit or incomplete run is a failed +comparison. Resolve the failure rather than reporting its partial timing. + +## 4. Assess and stop + +Report the selected workloads, before/after medians, trial ranges and ratios. +Describe what improved, regressed or remains inconclusive, and the geometry/input +and rendering paths actually measured. Overlapping ranges warrant a focused +rerun with more trials if the distinction matters; they neither prove equality +nor establish a statistically significant effect. Avoid universal percentage +thresholds for noise on an uncontrolled host. + +For an apparent regression, rerun that case before drawing a conclusion. For a +claimed work-elimination speedup, use the optional trace recipe to check work +counts. Pair synchronization or memory-lifetime changes with relevant failure +and retirement tests; use Compute Sanitizer when those risks warrant it. + +Finish with a concise local assessment and any remaining uncertainty. Keep raw +results and captures outside the repository; this workflow does not create +versioned baselines, performance-history tables or CI acceptance thresholds. diff --git a/devices/rtx/AGENTS.md b/devices/rtx/AGENTS.md index e597deaa1..ad4d62ffd 100644 --- a/devices/rtx/AGENTS.md +++ b/devices/rtx/AGENTS.md @@ -12,6 +12,10 @@ The `devices/rtx/` subdirectory contains the OptiX-based GPU ray-tracing ANARI d - [`CONTEXT-MAP.md`](./CONTEXT-MAP.md) — bounded contexts and how they relate; each context has its own `CONTEXT.md` glossary ([Frontend](./device/CONTEXT.md), [Render Pipeline](./device/renderer/CONTEXT.md), [World](./device/world/CONTEXT.md), [MDL](./libmdl/CONTEXT.md)). Use these terms in code and docs. - [`docs/adr/`](./docs/adr/) — architecture decision records. Scan the directory and read the relevant one before "fixing" a design it locks in. +## Measuring geometry preparation + +Use the [`benchmark-geometry-preprocessing`](../../.agents/skills/benchmark-geometry-preprocessing/SKILL.md) skill for local before/after checks of geometry preparation or preparation-reuse performance. Timing contracts: [`docs/geometry-preprocessing-performance.md`](./docs/geometry-preprocessing-performance.md). Keep one-off results in local scratch; historical tracking belongs in a separate CI workflow. + ## Build Built as part of the repository build — see the repo-root [AGENTS.md](../../AGENTS.md). `CMAKE_PREFIX_PATH` must locate the ANARI-SDK and OptiX. @@ -53,6 +57,8 @@ Test sources: `apps/tests/api/` (e.g. `ctest -C Release -R TestSpheres`). Run vi - OptiX device context - All precompiled PTX modules (one per renderer type, one per material/sampler type) - `DeviceObjectArray` registries for materials, geometries, samplers, spatial fields +- `preparationStream`, the `PreparationStream` that geometry preparation, BVH builds, registry uploads and world-table uploads submit to +- `preparation`, the one `GeometryPreparation` that owns GPU geometry preparation (its queues, batch, results and input allocation cache); read `device/geometry/GeometryPreparation.h` for the lifecycle **Frame::renderFrame()** orchestrates each frame: @@ -117,6 +123,7 @@ After rebuild, `OptixTraversableHandle`s are stored in `WorldGPUData` and passed | `device/renderer/Renderer.h` | Base renderer: pipeline init, SBT construction | | `device/world/World.h/.cpp` | BVH (TLAS/BLAS) management | | `device/utility/DeviceObjectArray.h` | Thread-safe GPU slot allocator / registry | +| `device/geometry/GeometryPreparation.h` | Owner of GPU geometry preparation: one scene update as one commit/upload/submit/collect transaction | ### Renderer Types diff --git a/devices/rtx/apps/tests/api/BenchmarkCudaOrdering.cu b/devices/rtx/apps/tests/api/BenchmarkCudaOrdering.cu new file mode 100644 index 000000000..d0569f264 --- /dev/null +++ b/devices/rtx/apps/tests/api/BenchmarkCudaOrdering.cu @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// Manual semantics probe, not a timing assertion. Uses the same legacy-default +// stream compilation mode as the device. Never change production ordering based +// only on this probe: pageable copies and readbacks impose additional edges. +#include +#include +#include +#include +#include + +static void check(cudaError_t error) +{ + if (error != cudaSuccess) { + fprintf(stderr, "%s\n", cudaGetErrorString(error)); + std::exit(1); + } +} + +__global__ void delay(unsigned long long cycles) +{ + const auto start = clock64(); + while (clock64() - start < cycles) { + } +} + +int main() +{ + int clockRate = 0; + check(cudaDeviceGetAttribute(&clockRate, cudaDevAttrClockRate, 0)); + // clockRate is kHz: about 30 ms, not a precision timing source. + const auto cycles = 30ull * clockRate; + check(cudaFree(nullptr)); + for (unsigned flags : + {unsigned(cudaStreamDefault), unsigned(cudaStreamNonBlocking)}) { + cudaStream_t stream; + cudaEvent_t done; + check(cudaStreamCreateWithFlags(&stream, flags)); + check(cudaEventCreateWithFlags(&done, cudaEventDisableTiming)); + for (bool producerDefault : {true, false}) { + delay<<<1, 1, 0, producerDefault ? nullptr : stream>>>(cycles); + check(cudaGetLastError()); + // Record completion of an otherwise empty consumer stream. With legacy + // NULL-stream ordering this event cannot pass the blocking producer. + check(cudaEventRecord(done, producerDefault ? stream : nullptr)); + const auto start = std::chrono::steady_clock::now(); + check(cudaEventSynchronize(done)); + const double ms = std::chrono::duration( + std::chrono::steady_clock::now() - start) + .count(); + printf("flags=%s producer=%s consumer=%s consumer_wait_ms=%.3f\n", + flags == cudaStreamDefault ? "blocking" : "nonblocking", + producerDefault ? "default" : "work", + producerDefault ? "work" : "default", + ms); + check(cudaDeviceSynchronize()); + } + check(cudaEventDestroy(done)); + check(cudaStreamDestroy(stream)); + } +} diff --git a/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp b/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp new file mode 100644 index 000000000..5264cd91e --- /dev/null +++ b/devices/rtx/apps/tests/api/BenchmarkGeometryPreprocessing.cpp @@ -0,0 +1,345 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// Manual evidence tool, deliberately not a wall-clock CTest assertion. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" + +using vec3 = std::array; +using vec4 = std::array; +static int errors = 0; +static std::atomic completions{0}; +static void complete(const void *, ANARIDevice, ANARIFrame) +{ + ++completions; +} +static void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + fprintf(stderr, "%s\n", message); + } +} +int main(int argc, char **argv) +{ + if (argc < 5 || argc > 10) { + fprintf(stderr, + "usage: %s triangle|sphere|cone|cylinder|quad|curve|sdf count device repeats [shared-surfaces] [distinct-geometries] [recommit|replace|unchanged|overlap|update] [frames:0=bounds] [emissive:0|1]\n", + argv[0]); + return 2; + } + const std::string type = argv[1]; + const size_t n = std::stoull(argv[2]); + const bool device = std::atoi(argv[3]) != 0; + const int repeats = std::atoi(argv[4]); + const int sharedSurfaces = argc >= 6 ? std::atoi(argv[5]) : 1; + const int distinctGeometries = argc >= 7 ? std::atoi(argv[6]) : 1; + const std::string mode = argc >= 8 ? argv[7] : "recommit"; + const int numFrames = argc >= 9 ? std::atoi(argv[8]) : 0; + const bool emissive = argc >= 10 ? std::atoi(argv[9]) != 0 : true; + if (!n || repeats < 2 || sharedSurfaces < 1 || distinctGeometries < 1 + || numFrames < 0 + || (mode != "recommit" && mode != "replace" && mode != "unchanged" + && mode != "overlap" && mode != "update") + || (mode == "update" && (device || type == "sdf")) + || (mode == "overlap" && numFrames != 1) + || (type != "triangle" && type != "sphere" && type != "cone" + && type != "cylinder" && type != "quad" && type != "curve" + && type != "sdf")) + return 2; + auto d = makeVisRTXDevice(status); + const auto setupStart = std::chrono::steady_clock::now(); + std::vector geometries; + std::vector positionArrays; + std::vector positions; + std::vector radii; + std::vector sphereIndices; + std::vector> tubeIndices; + std::vector> triIndices; + std::vector> quadIndices; + std::vector sdf; + for (size_t i = 0; i < n; ++i) { + const float x = float(i % 256) * 0.04f, y = float(i / 256) * 0.04f; + const unsigned base = unsigned(positions.size()); + if (type == "triangle" || type == "quad") { + positions.push_back({x, y, 0}); + positions.push_back({x + 0.02f, y, 0}); + positions.push_back({x + 0.02f, y + 0.02f, 0}); + if (type == "quad") { + positions.push_back({x, y + 0.02f, 0}); + quadIndices.push_back({base, base + 1, base + 2, base + 3}); + } else + triIndices.push_back({base, base + 1, base + 2}); + } else if (type == "sphere") { + positions.push_back({x, y, 0}); + radii.push_back(0.01f); + sphereIndices.push_back(base); + } else if (type == "sdf") { + const size_t offset = sdf.size(); + sdf.resize(offset + 72); + const vec3 center = {x, y, 0}; + const float radius = 0.01f; + std::memcpy(sdf.data() + offset + 20, center.data(), sizeof(center)); + std::memcpy(sdf.data() + offset + 44, &radius, sizeof(radius)); + std::memcpy(sdf.data() + offset + 48, &radius, sizeof(radius)); + } else { + positions.push_back({x, y, 0}); + positions.push_back({x + 0.02f, y, 0}); + tubeIndices.push_back({base, base + 1}); + radii.push_back(0.01f); + if (type != "cylinder") + radii.push_back(0.005f); + } + } + auto setInputs = [&](anari::Geometry geometry) { + if (type == "sdf") + setTestArray(d, geometry, "primitive.sdf", sdf, device, 0); + else if (mode == "update") { + auto array = anari::newArray1D(d, ANARI_FLOAT32_VEC3, positions.size()); + std::copy(positions.begin(), positions.end(), anari::map(d, array)); + anari::unmap(d, array); + anari::setParameter(d, geometry, "vertex.position", array); + positionArrays.push_back(array); + } else + setTestArray(d, geometry, "vertex.position", positions, device, 0); + if (type == "triangle") + setTestArray(d, geometry, "primitive.index", triIndices, device, 0); + if (type == "quad") + setTestArray(d, geometry, "primitive.index", quadIndices, device, 0); + if (type == "sphere") + setTestArray(d, geometry, "primitive.index", sphereIndices, device, 0); + if (type == "cone" || type == "cylinder") + setTestArray(d, geometry, "primitive.index", tubeIndices, device, 0); + if (type != "curve" && !radii.empty()) + setTestArray(d, + geometry, + type == "cylinder" ? "primitive.radius" : "vertex.radius", + radii, + device, + 0); + if (type == "curve") + anari::setParameter(d, geometry, "radius", 0.01f); + anari::commitParameters(d, geometry); + }; + for (int i = 0; i < distinctGeometries; ++i) { + auto geometry = anari::newObject(d, type.c_str()); + setInputs(geometry); + geometries.push_back(geometry); + } + auto material = anari::newObject(d, "physicallyBased"); + anari::setParameter( + d, material, "emissive", emissive ? vec3{1, 1, 1} : vec3{0, 0, 0}); + anari::commitParameters(d, material); + std::vector surfaces; + for (auto geometry : geometries) + for (int i = 0; i < sharedSurfaces; ++i) { + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", geometry); + anari::setParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + surfaces.push_back(surface); + } + anari::release(d, material); + auto world = anari::newObject(d); + anari::setParameterArray1D( + d, world, "surface", surfaces.data(), surfaces.size()); + for (auto surface : surfaces) + anari::release(d, surface); + anari::commitParameters(d, world); + std::vector frames; + for (int i = 0; i < numFrames; ++i) { + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "interactive"); + anari::setParameter(d, renderer, "sampleLimit", 0); + anari::setParameter( + d, renderer, "pixelSamples", mode == "overlap" ? 32 : 1); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + const unsigned resolution = mode == "overlap" ? 1024 : 64; + anari::setParameter( + d, frame, "size", std::array{resolution, resolution}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setParameter(d, frame, "world", world); + ANARIFrameCompletionCallback callback = complete; + anari::setParameter(d, + frame, + "frameCompletionCallback", + ANARI_FRAME_COMPLETION_CALLBACK, + &callback); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::commitParameters(d, frame); + frames.push_back(frame); + } + // Bounds-only measures GPU-ready acceleration structures; render mode also + // includes registry publication and completed tracing. No pre-query in render + // mode: it would move update work outside the submission measurement. + double warm = 0; + for (int iteration = 0; iteration < repeats; ++iteration) { + const auto start = std::chrono::steady_clock::now(); + if (iteration > 0) { + for (size_t g = 0; g < geometries.size(); ++g) { + auto geometry = geometries[g]; + if (mode == "update") { + auto *mapped = anari::map(d, positionArrays[g]); + if (!mapped) + return 1; + std::copy(positions.begin(), positions.end(), mapped); + for (size_t i = 0; i < positions.size(); ++i) + mapped[i][2] += (iteration % 2) * 0.001f; + anari::unmap(d, positionArrays[g]); + } + if (mode == "replace") + setInputs(geometry); // Include allocation, staging, and H2D costs. + else if (mode == "recommit" || mode == "update") { + anari::setParameter( + d, geometry, "attribute0", vec4{float(iteration), 0, 0, 0}); + anari::commitParameters(d, geometry); + } + } + } + for (auto frame : frames) + anari::render(d, frame); + const auto submitted = std::chrono::steady_clock::now(); + if (mode == "overlap") { + for (auto geometry : geometries) { + anari::setParameter( + d, geometry, "attribute0", vec4{float(iteration), 0, 0, 0}); + anari::commitParameters(d, geometry); + } + std::array overlapBounds{}; + const auto queryStart = std::chrono::steady_clock::now(); + if (!anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + overlapBounds.data(), + sizeof(overlapBounds), + ANARI_WAIT)) + return 1; + const auto queryEnd = std::chrono::steady_clock::now(); + for (float value : overlapBounds) + if (!std::isfinite(value)) + return 1; + printf("overlap iteration=%d query_ms=%.6f\n", + iteration, + std::chrono::duration(queryEnd - queryStart) + .count()); + } + for (auto frame : frames) + anari::wait(d, frame); + std::array bounds{}; + const bool ok = anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT); + const auto completed = std::chrono::steady_clock::now(); + const double ms = + std::chrono::duration(completed - start).count(); + if (!ok || errors || completions != (iteration + 1) * numFrames) + return 1; + // Validation is outside the timed interval. Never accept a skipped frame + // or non-finite output as a faster completed render. + for (auto frame : frames) { + int samples = 0; + if (!anari::getProperty(d, frame, "numSamples", samples) || samples < 1) { + fprintf( + stderr, "unexpected samples=%d iteration=%d\n", samples, iteration); + return 1; + } + auto pixels = anari::map(d, frame, "channel.color"); + if (!pixels.data) + return 1; + for (size_t i = 0; i < size_t(pixels.width) * pixels.height; ++i) + for (float value : pixels.data[i]) + if (!std::isfinite(value)) + return 1; + anari::unmap(d, frame, "channel.color"); + } + for (float value : bounds) + if (!std::isfinite(value)) + return 1; + printf("sample iteration=%d ms=%.6f submit_ms=%.6f\n", + iteration, + ms, + std::chrono::duration(submitted - start).count()); + if (iteration == 0) { + printf("first_ms=%.6f setup_to_ready_ms=%.6f\n", + ms, + std::chrono::duration(completed - setupStart) + .count()); + } else + warm += ms; + } + printf("mode=%s geometries=%d shared_surfaces=%d frames=%d emissive=%d\n", + mode.c_str(), + distinctGeometries, + sharedSurfaces, + numFrames, + emissive); + printf("type=%s count=%zu device=%d warm_rebuild_ms=%.6f repeats=%d\n", + type.c_str(), + n, + device, + warm / (repeats - 1), + repeats); + for (auto frame : frames) + anari::release(d, frame); + anari::release(d, world); + for (auto geometry : geometries) + anari::release(d, geometry); + for (auto array : positionArrays) + anari::release(d, array); + anari::release(d, d); + return 0; +} diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 04d6bff2b..cccff8b56 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -46,6 +46,9 @@ make_test(TestQuadLightShaping) make_test(TestQuadLightFocus) make_test(TestQuadLightTexture) make_test(TestDenoiserReuse) +add_executable(TestPreparationQueue TestPreparationQueue.cpp) +target_link_libraries(TestPreparationQueue PRIVATE nonstd::scope-lite) +add_test(NAME TestPreparationQueue COMMAND TestPreparationQueue) if (WIN32) return() @@ -80,12 +83,121 @@ target_link_libraries(TestSampleAddressing PRIVATE CUDA::cudart) set_tests_properties(TestSampleAddressing PROPERTIES TIMEOUT 120) make_test(TestPowerLightPickEnv) make_test(TestEmissiveGeometryLight) +add_executable(BenchmarkCudaOrdering BenchmarkCudaOrdering.cu) +target_link_libraries(BenchmarkCudaOrdering PRIVATE CUDA::cudart) +set_target_properties(BenchmarkCudaOrdering PROPERTIES CUDA_ARCHITECTURES "${CMAKE_CUDA_ARCHITECTURES}") +add_executable(BenchmarkGeometryPreprocessing BenchmarkGeometryPreprocessing.cpp) +target_link_libraries(BenchmarkGeometryPreprocessing PRIVATE anari_library_visrtx anari::anari_static CUDA::cudart) +add_executable(TestPreparationStream TestPreparationStream.cpp) +target_link_libraries(TestPreparationStream PRIVATE CUDA::cudart Threads::Threads) +add_test(NAME TestPreparationStream COMMAND TestPreparationStream) +add_executable(TestRegistrySnapshot TestRegistrySnapshot.cpp + ../../../device/utility/MemoryAllocation.cpp) +target_include_directories(TestRegistrySnapshot PRIVATE + ../../../device ../../../external/nanovdb/include ${OptiX_ROOT_DIR}/include) +target_link_libraries(TestRegistrySnapshot PRIVATE + CUDA::cudart anari::anari_static visrtx::glm nonstd::scope-lite) +target_compile_definitions(TestRegistrySnapshot PRIVATE GLM_ENABLE_EXPERIMENTAL) +add_test(NAME TestRegistrySnapshot COMMAND TestRegistrySnapshot) +make_test(TestDeferredGeometryPreparation) +target_link_libraries(TestDeferredGeometryPreparation PRIVATE CUDA::cudart) +make_test(TestSmallGeometryBatch) +target_link_libraries(TestSmallGeometryBatch PRIVATE CUDA::cudart) +make_test(TestGeometryAreaCDF) +target_sources(TestGeometryAreaCDF PRIVATE ../../../device/utility/MemoryAllocation.cpp) +# Inspect published device records without adding a public debug property. +# Match private host layouts, including optional MDL fields, to the device. +target_compile_definitions(TestGeometryAreaCDF PRIVATE + $) +target_include_directories(TestGeometryAreaCDF PRIVATE + $) +target_link_libraries(TestGeometryAreaCDF PRIVATE + CUDA::cudart visrtx::glm nonstd::scope-lite) +# Private layouts also require the matching built library, not a stale install +# selected by the developer shell's LD_LIBRARY_PATH. +set_tests_properties(TestGeometryAreaCDF PROPERTIES ENVIRONMENT + "LD_LIBRARY_PATH=$:$ENV{LD_LIBRARY_PATH}") +make_test(TestGeometryPreparationReuse) +target_link_libraries(TestGeometryPreparationReuse PRIVATE CUDA::cudart) +make_test(TestSharedGeometryLifecycle) +target_link_libraries(TestSharedGeometryLifecycle PRIVATE CUDA::cudart) +make_test(TestGeometryPreprocessingFailure) +target_link_libraries(TestGeometryPreprocessingFailure PRIVATE CUDA::cudart) +add_test(NAME TestGeometryBoundsFailure COMMAND TestGeometryPreprocessingFailure --bounds) +# CUDA API interposition needs ELF dynamic symbols; static cudart calls cannot +# be intercepted. Configure with -DCMAKE_CUDA_RUNTIME_LIBRARY=Shared to run. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CUDA_RUNTIME_LIBRARY STREQUAL "Shared") + add_executable(TestDeviceAllocationCache TestDeviceAllocationCache.cpp + ../../../device/utility/MemoryAllocation.cpp) + target_link_libraries(TestDeviceAllocationCache PRIVATE CUDA::cudart anari::anari_static nonstd::scope-lite ${CMAKE_DL_LIBS} Threads::Threads) + set_target_properties(TestDeviceAllocationCache PROPERTIES ENABLE_EXPORTS ON) + add_test(NAME TestDeviceAllocationCache COMMAND TestDeviceAllocationCache) + target_link_libraries(TestSmallGeometryBatch PRIVATE ${CMAKE_DL_LIBS}) + target_compile_definitions(TestSmallGeometryBatch PRIVATE VISRTX_TEST_INTERPOSE_CUDA) + set_target_properties(TestSmallGeometryBatch PROPERTIES ENABLE_EXPORTS ON) + make_test(TestFramePublicationRecovery) + target_link_libraries(TestFramePublicationRecovery PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) + set_target_properties(TestFramePublicationRecovery PROPERTIES ENABLE_EXPORTS ON) + make_test(TestGeometryInputBatch) + target_link_libraries(TestGeometryInputBatch PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) + set_target_properties(TestGeometryInputBatch PROPERTIES ENABLE_EXPORTS ON) + add_executable(TestPreparationResults TestPreparationResults.cpp + ../../../device/geometry/PreparationResults.cpp) + target_link_libraries(TestPreparationResults PRIVATE CUDA::cudart ${CMAKE_DL_LIBS}) + set_target_properties(TestPreparationResults PROPERTIES ENABLE_EXPORTS ON) + add_test(NAME TestPreparationResults COMMAND TestPreparationResults) + make_test(TestCudaPreparationFailure) + target_link_libraries(TestCudaPreparationFailure PRIVATE CUDA::cudart ${CMAKE_DL_LIBS} Threads::Threads) + target_include_directories(TestCudaPreparationFailure PRIVATE ${OptiX_ROOT_DIR}/include) + set_target_properties(TestCudaPreparationFailure PROPERTIES ENABLE_EXPORTS ON) + add_test(NAME TestIsosurfacePreparationRecovery + COMMAND TestCudaPreparationFailure isosurface) + foreach(geometry sphere sphere-indexed sphere-completion sphere-dependency + sphere-undrained-completion + sphere-batch-small-copy sphere-batch-small-launch sphere-batch-small-readback + sphere-batch-small-result-allocation sphere-batch-small-pinned-allocation + sphere-readback-allocation sphere-result-allocation + sphere-batch-completion + sphere-batch-upload-completion sphere-batch-input-completion + sphere-upload-allocation sphere-upload-copy sphere-upload-completion + sphere-upload-partial sphere-upload-observer) + add_test(NAME TestSpherePreparationRecovery_${geometry} + COMMAND TestCudaPreparationFailure ${geometry}) + endforeach() + foreach(failure registry-copy registry-sync registry-partial + instance-allocation instance-copy instance-sync world-copy world-sync) + add_test(NAME TestSceneUploadRecovery_${failure} + COMMAND TestCudaPreparationFailure ${failure}) + endforeach() + foreach(failure bvh-copy bvh-sync tlas-sync bvh-pinned-allocation) + add_test(NAME TestBvhPreparationRecovery_${failure} + COMMAND TestCudaPreparationFailure ${failure}) + endforeach() + foreach(failure allocation copy work-sync copy-sync pending-retirement) + add_test(NAME TestArrayPrivatizationFailure_${failure} + COMMAND TestCudaPreparationFailure ${failure}) + endforeach() +endif() +make_test(TestDeviceGeometryVisibility) +target_link_libraries(TestDeviceGeometryVisibility PRIVATE CUDA::cudart) +add_test(NAME TestSharedGeometryInputs COMMAND TestDeviceGeometryVisibility --shared-inputs) +add_test(NAME TestDeviceArrayRetirement COMMAND TestDeviceGeometryVisibility --retire) +add_test(NAME TestDeviceSdfExpansion COMMAND TestDeviceGeometryVisibility sdf-expanded) +foreach(type triangle sphere curve sdf cone cylinder) + add_test(NAME TestDeviceGeometryVisibility_${type} COMMAND TestDeviceGeometryVisibility ${type}) +endforeach() make_test(TestQuadLightSide) make_test(TestVisibleAreaLight) make_test(TestEmissiveSphereLight) +target_link_libraries(TestEmissiveSphereLight PRIVATE CUDA::cudart) +# Sampling radiometry retains host anchors and all-device integration; +# individual input roles use deterministic bounds/visibility above. make_test(TestEmissiveInstanceScale) make_test(TestEmissiveSphereInstanceScale) make_test(TestEmissiveCylinderConeLight) +target_link_libraries(TestEmissiveCylinderConeLight PRIVATE CUDA::cudart) +# Each family keeps independent identity/nonuniform-transform references; +# cap residency is isolated at identity, with all-device coverage also scaled. # These interleave attribute-driven emission cases, and MDL does not support # attributes — native-PBR only. (Textured emission itself works on the MDL # wrapper too; TestEmissiveMaterialParity covers it in that config.) @@ -96,6 +208,8 @@ endif() make_test(TestPbrSpecularDefault) make_test(TestNormalMapDecode) make_test(TestGeneratedTangents) +target_link_libraries(TestGeneratedTangents PRIVATE CUDA::cudart) +add_test(NAME TestDeviceGeneratedTangents COMMAND TestGeneratedTangents --device) make_test(TestShadingNormalGrazing) if (VISRTX_USE_MDL_FOR_PHYSICALLY_BASED) # Its closed-form reference models the backend's diffuse lobe. diff --git a/devices/rtx/apps/tests/api/DeviceTestArray.h b/devices/rtx/apps/tests/api/DeviceTestArray.h new file mode 100644 index 000000000..a4ad3788b --- /dev/null +++ b/devices/rtx/apps/tests/api/DeviceTestArray.h @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include +#include +#include + +// Capture device allocations so early PUBLIC release exercises array ownership. +// Ordinary inputs use their full range. Tests of logical slicing opt into +// padding explicitly; residency alone does not imply a nonzero range. +template +static void setTestArray(ANARIDevice device, + anari::Geometry geometry, + const char *name, + const Container &values, + bool onDevice, + size_t offset = 0) +{ + using T = typename Container::value_type; + std::vector padded(values.size() + 2 * offset); + std::copy(values.begin(), values.end(), padded.begin() + offset); + anari::Array1D array; + if (onDevice) { + void *ptr = nullptr; + if (cudaMalloc(&ptr, padded.size() * sizeof(T)) != cudaSuccess + || cudaMemcpy(ptr, + padded.data(), + padded.size() * sizeof(T), + cudaMemcpyHostToDevice) + != cudaSuccess) + std::exit(2); + array = anariNewArray1D( + device, + ptr, + [](const void *, const void *memory) { + cudaFree(const_cast(memory)); + }, + nullptr, + anari::ANARITypeFor::value, + padded.size()); + } else { + array = + anari::newArray1D(device, anari::ANARITypeFor::value, padded.size()); + std::copy(padded.begin(), padded.end(), anari::map(device, array)); + anari::unmap(device, array); + } + anari::setParameter(device, array, "begin", uint64_t(offset)); + anari::setParameter(device, array, "end", uint64_t(offset + values.size())); + anari::commitParameters(device, array); + anari::setAndReleaseParameter(device, geometry, name, array); +} diff --git a/devices/rtx/apps/tests/api/ReceiverTestSupport.h b/devices/rtx/apps/tests/api/ReceiverTestSupport.h new file mode 100644 index 000000000..a9e189fab --- /dev/null +++ b/devices/rtx/apps/tests/api/ReceiverTestSupport.h @@ -0,0 +1,128 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: BSD-3-Clause + +#pragma once + +// Reuse the existing public-object ownership and checked mapping support. Fog +// scenes and receiver scenes otherwise keep their own independent fixtures. +#include "RendererFogSupport.h" + +#include + +namespace visrtx::test { + +using fogtest::exitOnErrorStatus; +using fogtest::FrameMapping; +using fogtest::ObjectOwner; +using Vec4 = std::array; +using Size = std::array; + +// Fixed diffuse XZ receiver at y=0. The caller owns the returned Surface. +inline anari::Surface receiverFloor( + anari::Device device, float reflectance = 0.6f) +{ + const std::array, 4> pos = { + std::array{-6.f, 0.f, -6.f}, + std::array{6.f, 0.f, -6.f}, + std::array{6.f, 0.f, 6.f}, + std::array{-6.f, 0.f, 6.f}}; + const std::array, 2> idx = { + std::array{0, 1, 2}, std::array{0, 2, 3}}; + + auto geom = anari::newObject(device, "triangle"); + anari::setParameterArray1D(device, geom, "vertex.position", pos.data(), 4); + anari::setParameterArray1D(device, geom, "primitive.index", idx.data(), 2); + anari::commitParameters(device, geom); + + auto mat = anari::newObject(device, "physicallyBased"); + anari::setParameter(device, + mat, + "baseColor", + std::array{reflectance, reflectance, reflectance}); + anari::setParameter(device, mat, "metallic", 0.f); + anari::setParameter(device, mat, "roughness", 1.f); + anari::commitParameters(device, mat); + + auto surface = anari::newObject(device); + anari::setAndReleaseParameter(device, surface, "geometry", geom); + anari::setAndReleaseParameter(device, surface, "material", mat); + anari::commitParameters(device, surface); + return surface; +} + +/* Fixed receiver view shared by the geometry-light radiometry tests. The + * caller keeps its World reference; the returned Frame owns camera/Renderer. + * This deliberately does not construct emitters, references or a scene graph. + */ +inline anari::Frame receiverFrame(anari::Device device, + anari::World world, + Size size, + const char *rendererSubtype, + int pixelSamples) +{ + auto camera = anari::newObject(device, "perspective"); + const ObjectOwner cameraOwner(device, camera); + anari::setParameter( + device, camera, "position", std::array{0.f, 0.5f, -3.f}); + anari::setParameter( + device, camera, "direction", std::array{0.f, -0.15f, 1.f}); + anari::setParameter( + device, camera, "up", std::array{0.f, 1.f, 0.f}); + anari::setParameter(device, camera, "aspect", size[0] / float(size[1])); + anari::commitParameters(device, camera); + + auto renderer = anari::newObject(device, rendererSubtype); + const ObjectOwner rendererOwner(device, renderer); + anari::setParameter(device, renderer, "background", Vec4{0.f, 0.f, 0.f, 1.f}); + anari::setParameter(device, renderer, "ambientRadiance", 0.f); + anari::setParameter(device, renderer, "pixelSamples", pixelSamples); + anari::setParameter(device, renderer, "fireflyFilterMode", "none"); + anari::commitParameters(device, renderer); + + auto frame = anari::newObject(device); + ObjectOwner frameOwner(device, frame); + anari::setParameter(device, frame, "size", size); + anari::setParameter(device, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setParameter(device, frame, "world", world); + anari::setParameter(device, frame, "camera", camera); + anari::setParameter(device, frame, "renderer", renderer); + anari::commitParameters(device, frame); + frameOwner.release(); + return frame; +} + +/* Half-open pixel bounds stay at the assertion site: they define the measured + * physical receiver, not a configurable scene or an implicit tolerance. + */ +struct PixelRegion +{ + unsigned xBegin, xEnd, yBegin, yEnd; +}; + +inline double meanLuminance(const Vec4 *pixels, Size size, PixelRegion region) +{ + if (region.xBegin >= region.xEnd || region.xEnd > size[0] + || region.yBegin >= region.yEnd || region.yEnd > size[1]) + throw std::runtime_error("Invalid receiver measurement region"); + double sum = 0.; + for (unsigned y = region.yBegin; y < region.yEnd; ++y) + for (unsigned x = region.xBegin; x < region.xEnd; ++x) { + const auto &p = pixels[std::size_t(y) * size[0] + x]; + sum += 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; + } + return sum + / (std::size_t(region.xEnd - region.xBegin) + * (region.yEnd - region.yBegin)); +} + +inline double receiverLuminance( + anari::Device device, anari::Frame frame, Size size, PixelRegion region) +{ + anari::render(device, frame); + anari::wait(device, frame); + const FrameMapping mapping(device, frame, "channel.color"); + return meanLuminance( + mapping.checkedData(size[0], size[1], ANARI_FLOAT32_VEC4), size, region); +} + +} // namespace visrtx::test diff --git a/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp new file mode 100644 index 000000000..278f66647 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestCudaPreparationFailure.cpp @@ -0,0 +1,861 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// ELF interposition injects recoverable CUDA API errors without poisoning the +// real CUDA context. This test requires a shared CUDA runtime, not production +// failure-injection switches in the device. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../../device/geometry/PreparationResults.h" + +namespace { +enum class Failure +{ + NONE, + ALLOCATION, + READBACK_ALLOCATION, + COPY, + WORK_SYNC, + COPY_SYNC, + PREPARATION_SYNC, + PREPARATION_EARLY_SYNC, + SMALL_DESCRIPTOR_COPY, + SMALL_LAUNCH, + SMALL_READBACK, + SMALL_PINNED_ALLOCATION, + PREPARATION_DEPENDENCY, + BVH_SYNC, + BVH_COPY, + BVH_PINNED_ALLOCATION, + UPLOAD_COPY, + UPLOAD_SYNC, + BATCH_COPY, + BATCH_SYNC +}; +bool smallDescriptorSubmitted = false; +bool trackBatch = false; +bool batchQueued = false; +int batchCopiesToSkip = 0; +int batchCopies = 0; +const void *uploadSource = nullptr; +int uploadCopies = 0; +bool uploadOnWrongStream = false; +bool uploadQueued = false; +cudaStream_t preparationStream = nullptr; +bool bvhReadback = false; +int bvhReadbacksToSkip = 0; +Failure failure = Failure::NONE; +size_t allocationBytes = 0; +int injections = 0; +int errors = 0; +int disableReports = 0; +std::vector disabledRefusals; +std::atomic completions{0}; + +struct PendingCompletion +{ + cudaEvent_t done{}; + const void *scratch{nullptr}; + bool queued{false}; + bool failed{false}; + bool drained{false}; + bool pendingAtFailure{false}; + bool pendingAtDrain{false}; + bool prematureFree{false}; + bool prematureReport{false}; + bool retired{false}; + std::atomic released{false}; + std::atomic timedOut{false}; + std::mutex mutex; + std::condition_variable condition; +} pendingCompletion; + +void releasePendingWork() +{ + { + std::lock_guard lock(pendingCompletion.mutex); + pendingCompletion.released = true; + } + pendingCompletion.condition.notify_one(); +} + +void CUDART_CB blockPreparation(void *) +{ + while (!pendingCompletion.released.load()) + std::this_thread::yield(); +} + +bool inject(Failure kind) +{ + if (failure != kind) + return false; + failure = Failure::NONE; + ++injections; + return true; +} + +template +T next(const char *name) +{ + auto result = reinterpret_cast(dlsym(RTLD_NEXT, name)); + if (!result) { + fprintf(stderr, "missing CUDA symbol %s\n", name); + std::abort(); + } + return result; +} + +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + pendingCompletion.prematureReport |= + pendingCompletion.failed && !pendingCompletion.drained; + ++errors; + fprintf(stderr, "%s\n", message); + if (std::strstr(message, "array privatization failed")) + ++disableReports; + else if (std::strstr(message, "device disabled")) + disabledRefusals.emplace_back(message); + } +} + +// The disable is reported once; each later call reports its own refusal. +bool refusedWhileDisabled(const char *call) +{ + for (const auto &message : disabledRefusals) + if (message.find(call) != std::string::npos) + return disableReports == 1; + return false; +} +void complete(const void *, ANARIDevice, ANARIFrame) +{ + ++completions; +} +} // namespace + +// Bytes of the first device or pinned allocation of geometry results. +constexpr size_t RESULTS_BYTES = + visrtx::PreparationResults::MIN_CAPACITY * sizeof(visrtx::GeometryResults); + +extern "C" cudaError_t cudaMallocHost(void **ptr, size_t bytes) +{ + // The BVH readback holds six bounds floats and a 64-bit compaction size. + constexpr size_t BVH_BYTES = 6 * sizeof(float) + sizeof(uint64_t); + if ((bytes == BVH_BYTES && inject(Failure::BVH_PINNED_ALLOCATION)) + || (bytes == RESULTS_BYTES + && (inject(Failure::READBACK_ALLOCATION) + || inject(Failure::SMALL_PINNED_ALLOCATION)))) { + *ptr = nullptr; + return next("cudaMallocHost")(ptr, size_t(-1)); + } + return next("cudaMallocHost")(ptr, bytes); +} + +extern "C" cudaError_t cudaMalloc(void **ptr, size_t bytes) +{ + if (bytes == allocationBytes && inject(Failure::ALLOCATION)) { + // Use the real runtime: returning an enum alone does not set CUDA + // last-error state, and misses contamination of the next preparation. + *ptr = nullptr; + return next("cudaMalloc")(ptr, size_t(-1)); + } + return next("cudaMalloc")(ptr, bytes); +} + +extern "C" cudaError_t cudaFree(void *ptr) +{ + if (ptr && ptr == pendingCompletion.scratch) { + pendingCompletion.retired = true; + pendingCompletion.prematureFree |= !pendingCompletion.drained; + } + return next("cudaFree")(ptr); +} + +extern "C" cudaError_t cudaMemcpy( + void *dst, const void *src, size_t bytes, cudaMemcpyKind kind) +{ + if (uploadSource && src == uploadSource && kind == cudaMemcpyHostToDevice) { + ++uploadCopies; + uploadOnWrongStream = true; + } + if (kind == cudaMemcpyDeviceToDevice && inject(Failure::COPY)) + return cudaErrorInvalidValue; + return next("cudaMemcpy")(dst, src, bytes, kind); +} + +extern "C" cudaError_t cudaStreamCreateWithFlags( + cudaStream_t *stream, unsigned flags) +{ + const auto result = next( + "cudaStreamCreateWithFlags")(stream, flags); + if (result == cudaSuccess && (flags & cudaStreamNonBlocking)) + preparationStream = *stream; + return result; +} + +extern "C" cudaError_t cudaStreamWaitEvent( + cudaStream_t stream, cudaEvent_t event, unsigned flags) +{ + if (stream == preparationStream && inject(Failure::PREPARATION_DEPENDENCY)) + return cudaErrorInvalidValue; + return next("cudaStreamWaitEvent")( + stream, event, flags); +} + +extern "C" cudaError_t cudaGetLastError() +{ + const auto error = next("cudaGetLastError")(); + // The launch-status check follows the descriptor upload. Inject a failed + // report after real dispatch so cleanup must still drain the queued kernel. + if (smallDescriptorSubmitted && inject(Failure::SMALL_LAUNCH)) { + smallDescriptorSubmitted = false; + return cudaErrorInvalidConfiguration; + } + return error; +} + +extern "C" cudaError_t cudaMemcpyAsync(void *dst, + const void *src, + size_t bytes, + cudaMemcpyKind kind, + cudaStream_t stream) +{ + // These cases use device-backed sphere inputs. The first preparation H2D + // transfer is the descriptor batch, not an authored-array upload. + if (stream == preparationStream + && ((kind == cudaMemcpyHostToDevice + && inject(Failure::SMALL_DESCRIPTOR_COPY)) + || (kind == cudaMemcpyDeviceToHost + && inject(Failure::SMALL_READBACK)))) + return cudaErrorInvalidValue; + if (uploadSource && src == uploadSource && kind == cudaMemcpyHostToDevice) { + ++uploadCopies; + uploadOnWrongStream |= stream != preparationStream; + if (inject(Failure::UPLOAD_COPY)) + return cudaErrorInvalidValue; + uploadQueued = true; + } + if (trackBatch && stream == preparationStream + && kind == cudaMemcpyHostToDevice) { + ++batchCopies; + if (batchCopiesToSkip) + --batchCopiesToSkip; + else { + if (inject(Failure::BATCH_COPY)) { + // Exercise real CUDA last-error state as well as the returned status. + return next("cudaMemcpyAsync")( + nullptr, src, bytes, kind, stream); + } + batchQueued = true; + } + } + if (stream == preparationStream && kind == cudaMemcpyDeviceToHost + && bytes == 6 * sizeof(float) + && (failure == Failure::BVH_COPY || failure == Failure::BVH_SYNC)) { + if (bvhReadbacksToSkip) + --bvhReadbacksToSkip; + else { + if (inject(Failure::BVH_COPY)) + return cudaErrorInvalidValue; + bvhReadback = true; + } + } + if (failure == Failure::PREPARATION_EARLY_SYNC && stream == preparationStream + && kind == cudaMemcpyDeviceToHost && bytes + && bytes % sizeof(visrtx::GeometryResults) == 0 + && !pendingCompletion.queued) { + // Gate the consolidated results readback after kernel submission. No + // subsequent allocation or pageable copy can supply a hidden wait. + auto error = cudaLaunchHostFunc(stream, blockPreparation, nullptr); + if (error != cudaSuccess) + return error; + pendingCompletion.queued = true; + pendingCompletion.scratch = src; + error = next("cudaMemcpyAsync")( + dst, src, bytes, kind, stream); + if (error == cudaSuccess) + error = cudaEventRecord(pendingCompletion.done, stream); + return error; + } + const auto error = next("cudaMemcpyAsync")( + dst, src, bytes, kind, stream); + if (error == cudaSuccess && failure == Failure::SMALL_LAUNCH + && kind == cudaMemcpyHostToDevice && stream == preparationStream) + smallDescriptorSubmitted = true; + return error; +} + +extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) +{ + if (stream == preparationStream && pendingCompletion.queued) { + if (inject(Failure::PREPARATION_EARLY_SYNC)) { + pendingCompletion.pendingAtFailure = + cudaEventQuery(pendingCompletion.done) == cudaErrorNotReady; + pendingCompletion.failed = true; + return cudaErrorUnknown; // Deliberately do NOT drain the real work. + } + if (pendingCompletion.failed && !pendingCompletion.drained) { + pendingCompletion.pendingAtDrain = + cudaEventQuery(pendingCompletion.done) == cudaErrorNotReady; + releasePendingWork(); // Only the fallback drain releases the producer. + const auto error = next( + "cudaStreamSynchronize")(stream); + pendingCompletion.drained = error == cudaSuccess + && cudaEventQuery(pendingCompletion.done) == cudaSuccess; + return error; + } + } + // Other cases simulate a failed completion report after draining real work. + const auto result = + next("cudaStreamSynchronize")(stream); + if ((stream && inject(Failure::WORK_SYNC)) + || (!stream && inject(Failure::COPY_SYNC)) + || (stream == preparationStream && inject(Failure::PREPARATION_SYNC)) + || (stream == preparationStream && uploadQueued + && inject(Failure::UPLOAD_SYNC)) + || (stream == preparationStream && bvhReadback + && inject(Failure::BVH_SYNC)) + || (stream == preparationStream && batchQueued + && inject(Failure::BATCH_SYNC))) + return cudaErrorUnknown; + return result; +} + +// Retirement synchronizes the render stream, and full preparation orders +// itself after it, only when a query finds it busy; it is idle whenever a test +// arms WORK_SYNC or PREPARATION_DEPENDENCY. Report it busy so the wait that +// carries the injected failure happens. +extern "C" cudaError_t cudaStreamQuery(cudaStream_t stream) +{ + if (stream && stream != preparationStream + && (failure == Failure::WORK_SYNC + || failure == Failure::PREPARATION_DEPENDENCY)) + return cudaErrorNotReady; + return next("cudaStreamQuery")(stream); +} + +int main(int argc, char **argv) +{ + const bool pendingRetirement = + argc > 1 && std::strcmp(argv[1], "pending-retirement") == 0; + const bool isosurfaceFailure = + argc > 1 && std::strcmp(argv[1], "isosurface") == 0; + const bool sphereFailure = + argc > 1 && std::strncmp(argv[1], "sphere", 6) == 0; + const bool earlyCompletion = + sphereFailure && std::strcmp(argv[1], "sphere-undrained-completion") == 0; + const bool batchCompletion = + sphereFailure && std::strncmp(argv[1], "sphere-batch-", 13) == 0; + // Over SmallGeometryBatch::MAX_PRIMITIVES: results are reserved at + // submission (general path), not at small-batch launch. + const bool generalResults = sphereFailure + && (std::strcmp(argv[1], "sphere-readback-allocation") == 0 + || std::strcmp(argv[1], "sphere-result-allocation") == 0); + const bool inputBatchCompletion = batchCompletion + && std::strcmp(argv[1], "sphere-batch-input-completion") == 0; + const bool batchUploadCompletion = batchCompletion + && (std::strcmp(argv[1], "sphere-batch-upload-completion") == 0 + || inputBatchCompletion); + const bool sphereUpload = inputBatchCompletion + || (argc > 1 && std::strncmp(argv[1], "sphere-upload-", 14) == 0); + const bool observerRecovery = + sphereUpload && std::strcmp(argv[1], "sphere-upload-observer") == 0; + const bool partialUpload = + sphereUpload && std::strcmp(argv[1], "sphere-upload-partial") == 0; + const bool bvhFailure = argc > 1 + && (std::strncmp(argv[1], "bvh-", 4) == 0 + || std::strcmp(argv[1], "tlas-sync") == 0); + const bool registryFailure = + argc > 1 && std::strncmp(argv[1], "registry-", 9) == 0; + const bool registryPartial = + registryFailure && std::strcmp(argv[1], "registry-partial") == 0; + const bool instanceFailure = argc > 1 + && (std::strncmp(argv[1], "instance-", 9) == 0 + || std::strncmp(argv[1], "world-", 6) == 0); + const bool worldRecords = + instanceFailure && std::strncmp(argv[1], "world-", 6) == 0; + const bool curveFailure = argc == 1 || isosurfaceFailure || sphereFailure; + auto d = makeVisRTXDevice(status); + using vec3 = std::array; + std::array vertices = { + {{-1, 0, 0}, {1, 0, 0}, {-1, 1, 0}, {1, 1, 0}, {-1, 2, 0}, {1, 2, 0}}}; + void *deviceVertices = nullptr; + if (cudaMalloc(&deviceVertices, sizeof(vertices)) != cudaSuccess + || cudaMemcpy(deviceVertices, + vertices.data(), + sizeof(vertices), + cudaMemcpyHostToDevice) + != cudaSuccess) + return 1; + if (sphereUpload) + uploadSource = vertices.data(); + auto array = anariNewArray1D(d, + sphereUpload ? static_cast(vertices.data()) : deviceVertices, + nullptr, + nullptr, + ANARI_FLOAT32_VEC3, + vertices.size()); + auto geometry = anari::newObject(d, + isosurfaceFailure ? "isosurface" + : (sphereFailure || pendingRetirement) ? "sphere" + : "curve"); + if (partialUpload) { + const std::array radii{0.1f, 0.1f, 0.1f, 0.1f, 0.1f, 0.1f}; + anari::setParameterArray1D( + d, geometry, "vertex.radius", radii.data(), radii.size()); + } + if (sphereFailure && std::strcmp(argv[1], "sphere-indexed") == 0) { + const std::array indices{5, 1, 3}; + anari::setParameterArray1D( + d, geometry, "primitive.index", indices.data(), indices.size()); + } + if (isosurfaceFailure) { + std::array values{}; + for (size_t i = 0; i < values.size(); ++i) + values[i] = float(i / 64); + auto field = anari::newObject(d, "structuredRegular"); + auto data = anari::newArray3D(d, values.data(), 8, 8, 8); + anari::setAndReleaseParameter(d, field, "data", data); + anari::setParameter(d, field, "origin", vec3{0, 0, 0}); + anari::setParameter(d, field, "spacing", vec3{1, 1, 1}); + anari::commitParameters(d, field); + anari::setAndReleaseParameter(d, geometry, "field", field); + anari::setParameter(d, geometry, "isovalue", 3.5f); + } else if (generalResults) { + std::vector positions(300); + for (size_t i = 0; i < positions.size(); ++i) + positions[i] = {float(i % 20) * 0.1f - 1.f, float(i / 20) * 0.1f, 0.f}; + anari::setParameterArray1D( + d, geometry, "vertex.position", positions.data(), positions.size()); + anari::setParameter(d, geometry, "radius", 0.1f); + } else { + anari::setParameter(d, geometry, "vertex.position", array); + anari::setParameter(d, geometry, "radius", observerRecovery ? 0.2f : 0.1f); + } + anari::commitParameters(d, geometry); + auto material = anari::newObject(d, "matte"); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", geometry); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + std::vector surfaces{surface}; + anari::Geometry sibling = nullptr; + if ((curveFailure && !isosurfaceFailure && !sphereFailure) + || batchCompletion) { + sibling = anari::newObject( + d, batchCompletion ? "sphere" : "curve"); + if (batchCompletion && !batchUploadCompletion) + anari::setParameter(d, sibling, "vertex.position", array); + else + anari::setParameterArray1D( + d, sibling, "vertex.position", vertices.data(), 4); + anari::setParameter(d, sibling, "radius", 0.1f); + anari::commitParameters(d, sibling); + auto siblingMaterial = anari::newObject(d, "matte"); + anari::commitParameters(d, siblingMaterial); + auto siblingSurface = anari::newObject(d); + anari::setParameter(d, siblingSurface, "geometry", sibling); + anari::setAndReleaseParameter( + d, siblingSurface, "material", siblingMaterial); + anari::commitParameters(d, siblingSurface); + surfaces.push_back(siblingSurface); + } + if (registryPartial) { + sibling = anari::newObject(d, "curve"); + anari::setParameter(d, sibling, "vertex.position", array); + anari::setParameter(d, sibling, "radius", 0.1f); + anari::commitParameters(d, sibling); + } + auto world = anari::newObject(d); + anari::setParameterArray1D( + d, world, "surface", surfaces.data(), surfaces.size()); + for (auto s : surfaces) + anari::release(d, s); + anari::commitParameters(d, world); + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject( + d, registryFailure ? "interactive" : "debug"); + if (registryFailure) + anari::setParameter(d, renderer, "sampleLimit", 0); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{8, 8}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::setParameter(d, frame, "world", world); + ANARIFrameCompletionCallback callback = complete; + anari::setParameter(d, + frame, + "frameCompletionCallback", + ANARI_FRAME_COMPLETION_CALLBACK, + &callback); + anari::commitParameters(d, frame); + std::array bounds{}; + auto haveBounds = [&]() { + return anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT) + != 0; + }; + bool ok = errors == 0; + if (pendingRetirement) { + uint8_t valid = 0; + ok = + anariGetProperty( + d, geometry, "valid", ANARI_BOOL, &valid, sizeof(valid), ANARI_WAIT) + && valid && ok; + failure = Failure::PREPARATION_SYNC; + anari::release(d, array); + ok = injections == 1 && errors > 0 && ok; + cudaFree(deviceVertices); + deviceVertices = nullptr; + ok = !haveBounds() && refusedWhileDisabled("anariGetProperty") && ok; + anari::render(d, frame); + ok = refusedWhileDisabled("anariRenderFrame") && ok; + anari::wait(d, frame); + ok = completions == 0 && ok; + } else if (registryFailure) { + ok = haveBounds() && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 1 && errors == 0 && ok; + for (auto g : {geometry, sibling}) { + if (!g) + continue; + anari::setParameter(d, g, "color", std::array{1, 0, 0, 1}); + anari::commitParameters(d, g); + } + trackBatch = true; + batchCopiesToSkip = registryPartial ? 1 : 0; + failure = std::strcmp(argv[1], "registry-sync") == 0 ? Failure::BATCH_SYNC + : Failure::BATCH_COPY; + anari::render(d, frame); + anari::wait(d, frame); + ok = injections == 1 && errors > 0 && completions == 1 && ok; + const int beforeErrors = errors; + // No recommit: failed upload must retain all dirty slots, including the + // first successful copy in the partial-batch case. + anari::render(d, frame); + anari::wait(d, frame); + ok = errors == beforeErrors && completions == 2 + && batchCopies == (registryPartial ? 4 : 2) && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = errors == beforeErrors && completions == 3 + && batchCopies == (registryPartial ? 4 : 2) && ok; + anari::release(d, array); + } else if (bvhFailure || instanceFailure) { + auto injected = std::strcmp(argv[1], "bvh-copy") == 0 ? Failure::BVH_COPY + : Failure::BVH_SYNC; + if (std::strcmp(argv[1], "bvh-pinned-allocation") == 0) + injected = Failure::BVH_PINNED_ALLOCATION; + if (instanceFailure) { + trackBatch = true; + batchCopiesToSkip = worldRecords ? 1 : 0; + injected = std::strstr(argv[1], "copy") ? Failure::BATCH_COPY + : Failure::BATCH_SYNC; + if (std::strcmp(argv[1], "instance-allocation") == 0) { + allocationBytes = sizeof(OptixInstance); + injected = Failure::ALLOCATION; + } + } + bvhReadbacksToSkip = std::strcmp(argv[1], "tlas-sync") == 0 ? 1 : 0; + failure = injected; + ok = !haveBounds() && injections == 1 && errors > 0 && ok; + ok = !anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_NO_WAIT) + && ok; + failure = injected; + bvhReadback = false; + bvhReadbacksToSkip = 0; + batchCopiesToSkip = worldRecords ? 1 : 0; + batchQueued = false; + anari::render(d, frame); + anari::wait(d, frame); + ok = injections == 2 && completions == 0 && ok; + const int beforeErrors = errors; + ok = haveBounds() && errors == beforeErrors && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 1 && errors == beforeErrors && ok; + anari::release(d, array); + } else if (curveFailure) { + if (isosurfaceFailure) { + ok = haveBounds() && ok; + anari::setParameter(d, geometry, "isovalue", 2.5f); + anari::commitParameters(d, geometry); + } + if (sibling) { + anari::setParameter(d, sibling, "radius", 0.15f); + anari::commitParameters(d, sibling); + } + // Sphere AABBs (two vec3s each), or generated curve indices. + allocationBytes = sphereFailure + ? (std::strcmp(argv[1], "sphere-indexed") == 0 ? 3 : vertices.size()) + * 2 * sizeof(vec3) + : 3 * sizeof(unsigned); + if (sphereUpload) + allocationBytes = + partialUpload ? vertices.size() * sizeof(float) : sizeof(vertices); + failure = isosurfaceFailure ? Failure::WORK_SYNC : Failure::ALLOCATION; + if (sphereUpload + && (std::strcmp(argv[1], "sphere-upload-copy") == 0 + || observerRecovery)) + failure = Failure::UPLOAD_COPY; + if (sphereUpload && std::strcmp(argv[1], "sphere-upload-completion") == 0) + failure = Failure::UPLOAD_SYNC; + if (sphereFailure + && std::strcmp(argv[1], "sphere-readback-allocation") == 0) + failure = Failure::READBACK_ALLOCATION; + if (sphereFailure + && std::strcmp(argv[1], "sphere-result-allocation") == 0) { + allocationBytes = RESULTS_BYTES; // Device side of the reservation. + failure = Failure::ALLOCATION; + } + if ((sphereFailure && std::strcmp(argv[1], "sphere-completion") == 0) + || batchCompletion) + failure = Failure::PREPARATION_SYNC; + if (sphereFailure && std::strcmp(argv[1], "sphere-dependency") == 0) + failure = Failure::PREPARATION_DEPENDENCY; + if (sphereFailure && std::strcmp(argv[1], "sphere-batch-small-copy") == 0) + failure = Failure::SMALL_DESCRIPTOR_COPY; + if (sphereFailure && std::strcmp(argv[1], "sphere-batch-small-launch") == 0) + failure = Failure::SMALL_LAUNCH; + if (sphereFailure + && std::strcmp(argv[1], "sphere-batch-small-readback") == 0) + failure = Failure::SMALL_READBACK; + if (sphereFailure + && std::strcmp(argv[1], "sphere-batch-small-result-allocation") == 0) { + allocationBytes = RESULTS_BYTES; // Device results of both geometries. + failure = Failure::ALLOCATION; + } + if (sphereFailure + && std::strcmp(argv[1], "sphere-batch-small-pinned-allocation") == 0) + failure = Failure::SMALL_PINNED_ALLOCATION; + std::thread watchdog; + if (earlyCompletion) { + if (cudaEventCreateWithFlags( + &pendingCompletion.done, cudaEventDisableTiming) + != cudaSuccess) + return 1; + failure = Failure::PREPARATION_EARLY_SYNC; + watchdog = std::thread([] { + std::unique_lock lock(pendingCompletion.mutex); + if (!pendingCompletion.condition.wait_for(lock, + std::chrono::seconds(5), + [] { return pendingCompletion.released.load(); })) { + pendingCompletion.timedOut = true; + pendingCompletion.released = true; + } + }); + } + ok = !haveBounds() && ok; + if (earlyCompletion) { + // Cleanup cannot conceal a missing fallback drain. Snapshot its outcome + // before unblocking the gate ourselves and destroying any resources. + ok = pendingCompletion.queued && pendingCompletion.pendingAtFailure + && pendingCompletion.pendingAtDrain && pendingCompletion.drained + && !pendingCompletion.timedOut && !pendingCompletion.prematureFree + && !pendingCompletion.prematureReport && ok; + releasePendingWork(); + watchdog.join(); + } + // The unaffected sibling must not inherit the first geometry's OOM. + // Recovery below must succeed without recommitting the sibling. + ok = injections == 1 && errors == 1 && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 0 && ok; + const int beforeErrors = errors; + if (observerRecovery) { + if (!anariMapArray(d, array)) + return 1; + anariUnmapArray(d, array); // New array version, no geometry recommit. + } else { + anari::setParameter( + d, geometry, isosurfaceFailure ? "isovalue" : "radius", 0.2f); + anari::commitParameters(d, geometry); + } + if (batchCompletion) { + // A completion error invalidates the whole pending batch, not just its + // first geometry. Repreparing only that geometry cannot publish a world. + ok = !haveBounds() && errors == beforeErrors && ok; + anari::setParameter(d, sibling, "radius", 0.25f); + anari::commitParameters(d, sibling); + } + ok = haveBounds() && errors == beforeErrors && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 1 && errors == beforeErrors && ok; + if (sphereUpload) { + const int expected = + std::strcmp(argv[1], "sphere-upload-allocation") == 0 ? 1 : 2; + ok = uploadCopies == expected && !uploadOnWrongStream && ok; + auto *mapped = static_cast(anariMapArray(d, array)); + if (!mapped) + return 1; + mapped[0][0] -= 0.2f; + anariUnmapArray(d, array); + anari::setParameter( + d, geometry, "attribute0", std::array{1, 0, 0, 1}); + anari::commitParameters(d, geometry); + ok = haveBounds() && errors == beforeErrors + && uploadCopies == expected + 1 && !uploadOnWrongStream + && std::fabs(bounds[0] - (-1.2f - (partialUpload ? 0.1f : 0.2f))) + < 1e-4f + && ok; + } + if (sphereFailure) { + // Preparation-preserving bounds queries must not drain the work stream. + // Leave the injection armed, then change radius to require the fence. + failure = Failure::WORK_SYNC; + anari::setParameter( + d, geometry, "color", std::array{1, 0, 0, 1}); + anari::commitParameters(d, geometry); + ok = haveBounds() && injections == 1 && errors == beforeErrors && ok; + anari::setParameter(d, geometry, "radius", 0.3f); + anari::commitParameters(d, geometry); + ok = !haveBounds() && injections == 2 && errors > beforeErrors && ok; + const int retirementErrors = errors; + // Change the value to force a retry through deferred commit processing. + anari::setParameter(d, geometry, "radius", 0.4f); + anari::commitParameters(d, geometry); + ok = haveBounds() && errors == retirementErrors && ok; + } + if (observerRecovery) { + // An observer-only update: no commit captures the dirty array, so the + // geometry's own finalize uploads it. A failed copy or completion there + // fails that finalize only; the next observer update retries without a + // geometry commit. + for (const auto kind : {Failure::UPLOAD_COPY, Failure::UPLOAD_SYNC}) { + const int errorsBefore = errors; + const int copiesBefore = uploadCopies; + const int injectionsBefore = injections; + uploadQueued = false; + failure = kind; + if (!anariMapArray(d, array)) + return 1; + anariUnmapArray(d, array); + ok = !haveBounds() && injections == injectionsBefore + 1 + && errors == errorsBefore + 1 && uploadCopies == copiesBefore + 1 + && ok; + if (!anariMapArray(d, array)) + return 1; + anariUnmapArray(d, array); + ok = haveBounds() && errors == errorsBefore + 1 + && uploadCopies == copiesBefore + 2 && !uploadOnWrongStream && ok; + } + } + anari::release(d, array); + } else { + ok = haveBounds() && ok; + anari::render(d, frame); + anari::wait(d, frame); + ok = completions == 1 && errors == 0 && ok; + allocationBytes = sizeof(vertices); + if (std::strcmp(argv[1], "allocation") == 0) + failure = Failure::ALLOCATION; + else if (std::strcmp(argv[1], "copy") == 0) + failure = Failure::COPY; + else if (std::strcmp(argv[1], "work-sync") == 0) + failure = Failure::WORK_SYNC; + else if (std::strcmp(argv[1], "copy-sync") == 0) + failure = Failure::COPY_SYNC; + else + return 2; + anari::release(d, array); + ok = injections == 1 && errors > 0 && ok; + cudaFree(deviceVertices); + deviceVertices = nullptr; + ok = !haveBounds() && refusedWhileDisabled("anariGetProperty") && ok; + anari::render(d, frame); + ok = refusedWhileDisabled("anariRenderFrame") && ok; + anari::wait(d, frame); + ok = completions == 1 && ok; + // No retry or device re-enable after the injected CUDA error is gone. + anari::setParameter(d, geometry, "radius", 0.3f); + anari::commitParameters(d, geometry); + ok = !haveBounds() && ok; + } + if (deviceVertices) + cudaFree(deviceVertices); + anari::release(d, frame); + anari::release(d, world); + anari::release(d, geometry); + if (sibling) + anari::release(d, sibling); + anari::release(d, d); + if (earlyCompletion) { + ok = pendingCompletion.retired && !pendingCompletion.prematureFree && ok; + cudaEventDestroy(pendingCompletion.done); + } + printf("%s injections=%d %s\n", + curveFailure ? "curve" : argv[1], + injections, + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp b/devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp new file mode 100644 index 000000000..7a1cab653 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestDeferredGeometryPreparation.cpp @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +int freed = 0; +int errors = 0; +int rejectedQueries = 0; +int refusedQueryReports = 0; +int refusedRenderReports = 0; +anari::World callbackWorld = nullptr; +anari::Frame callbackFrame = nullptr; + +void releaseDevice(const void *, const void *memory) +{ + cudaFree(const_cast(memory)); + ++freed; +} + +void status(const void *, + ANARIDevice d, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity == ANARI_SEVERITY_WARNING + && std::strstr(message, "geometry preparations are being collected")) { + refusedQueryReports += std::strstr(message, "anariGetProperty") != nullptr; + refusedRenderReports += std::strstr(message, "anariRenderFrame") != nullptr; + // Reentering from the refusal report itself must not recurse. + if (callbackFrame) + anariRenderFrame(d, callbackFrame); + return; + } + if (severity > ANARI_SEVERITY_ERROR) + return; + ++errors; + std::fprintf(stderr, "%s\n", message); + if (callbackFrame) + anariRenderFrame(d, callbackFrame); + if (callbackWorld) { + std::array bounds{}; + if (!anariGetProperty(d, + callbackWorld, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT)) + ++rejectedQueries; + } +} + +bool position(anari::Device d, anari::Geometry geometry, float x) +{ + const std::array center{x, 0, 0}; + void *device = nullptr; + if (cudaMalloc(&device, sizeof(center)) != cudaSuccess + || cudaMemcpy( + device, center.data(), sizeof(center), cudaMemcpyHostToDevice) + != cudaSuccess) + return false; + auto array = + anariNewArray1D(d, device, releaseDevice, nullptr, ANARI_FLOAT32_VEC3, 1); + anariSetParameter(d, geometry, "vertex.position", ANARI_ARRAY1D, &array); + anariRelease(d, array); + anari::setParameter(d, geometry, "radius", 1.f); + anari::commitParameters(d, geometry); + return true; +} + +bool flushGeometry(anari::Device d, anari::Geometry geometry) +{ + uint8_t valid = 0; + return anariGetProperty(d, + geometry, + "valid", + ANARI_BOOL, + &valid, + sizeof(valid), + ANARI_WAIT) + && valid; +} +} // namespace + +int main() +{ + auto d = makeVisRTXDevice(status); + auto geometry = anari::newObject(d, "sphere"); + if (!position(d, geometry, 0.f)) + return 1; + auto material = anari::newObject(d, "matte"); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", geometry); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto world = anari::newObject(d); + anari::setParameterArray1D(d, world, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, world); + + // Flush finalizers without requesting a BVH: readbacks remain queued. + bool ok = flushGeometry(d, geometry) && freed == 0; + ok = position(d, geometry, 4.f) && ok; + ok = flushGeometry(d, geometry) && freed == 1 && ok; + std::array bounds{}; + auto haveBounds = [&] { + return anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT) + != 0; + }; + ok = haveBounds() && std::fabs(bounds[0] - 3.f) < 1e-4f + && std::fabs(bounds[3] - 5.f) < 1e-4f && errors == 0 && ok; + + // A failed, unreferenced geometry must not poison an unrelated world. A + // status callback must not reenter collection and publish partial results. + auto invalid = anari::newObject(d, "sphere"); + ok = position(d, invalid, std::numeric_limits::quiet_NaN()) && ok; + ok = flushGeometry(d, invalid) && ok; + // Each refused reentrant call is reported, naming the call. + auto frame = anari::newObject(d); + callbackWorld = world; + callbackFrame = frame; + ok = haveBounds() && errors == 1 && rejectedQueries == 1 + && refusedQueryReports == 1 && refusedRenderReports == 1 && ok; + callbackWorld = nullptr; + callbackFrame = nullptr; + anari::release(d, frame); + anari::release(d, invalid); + + // The pending queue owns a last-reference geometry until device teardown. + auto orphan = anari::newObject(d, "sphere"); + ok = position(d, orphan, 8.f) && flushGeometry(d, orphan) && ok; + anari::release(d, orphan); + anari::release(d, world); + anari::release(d, geometry); + ok = freed == 3 && ok; + anari::release(d, d); + ok = freed == 4 && errors == 1 && ok; + std::printf("deferred geometry: freed=%d errors=%d %s\n", + freed, + errors, + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp b/devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp new file mode 100644 index 000000000..4a25bceaa --- /dev/null +++ b/devices/rtx/apps/tests/api/TestDeviceAllocationCache.cpp @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../../../device/utility/DeviceAllocationCache.h" +#include "../../../device/utility/DeviceBuffer.h" +#include "../../../device/utility/MemoryAllocation.h" + +namespace { +std::atomic allocations{0}, frees{0}, syncs{0}, attempts{0}; +size_t failBytes = 0; +bool failSync = false; +int capturedDeletes = 0; +std::atomic trackSync{false}, syncEntered{false}, gateReleased{false}, + cohortReturned{false}; +std::mutex gateMutex; +std::condition_variable gateCondition; +void CUDART_CB blockConsumer(void *) +{ + while (!gateReleased.load()) + std::this_thread::yield(); +} +template +T next(const char *name) +{ + auto result = reinterpret_cast(dlsym(RTLD_NEXT, name)); + if (!result) + std::abort(); + return result; +} +void capturedDelete(const void *, const void *pointer) +{ + ++capturedDeletes; + cudaFree(const_cast(pointer)); +} +} // namespace + +extern "C" cudaError_t cudaMalloc(void **pointer, size_t bytes) +{ + ++attempts; + if (failBytes && bytes == failBytes) { + failBytes = 0; + return next("cudaMalloc")( + pointer, std::numeric_limits::max()); + } + const auto error = next("cudaMalloc")(pointer, bytes); + if (error == cudaSuccess && *pointer) + ++allocations; + return error; +} +extern "C" cudaError_t cudaFree(void *pointer) +{ + if (pointer) + ++frees; + return next("cudaFree")(pointer); +} +extern "C" cudaError_t cudaDeviceSynchronize() +{ + ++syncs; + if (trackSync) { + { + std::lock_guard lock(gateMutex); + syncEntered = true; + } + gateCondition.notify_all(); + } + const auto error = + next("cudaDeviceSynchronize")(); + if (failSync) { + failSync = false; + return cudaErrorUnknown; + } + return error; +} + +int main() +{ + using visrtx::DeviceAllocationCache; + auto complete = [] { return cudaSuccess; }; + bool ok = true; + { + DeviceAllocationCache cache(128, 4); + void *a = nullptr, *b = nullptr, *c = nullptr; + ok = cache.allocate(32, &a) == cudaSuccess && ok; + cache.release(a, 32); + ok = cache.allocate(32, &b) == cudaSuccess && a != b && ok; + const int beforeSyncs = syncs; + // Deferred work must be submitted before the shared completion boundary. + cudaStream_t stream{}; + ok = + cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) == cudaSuccess + && ok; + ok = cache.reclaim([&] { return cudaMemsetAsync(a, 0x2a, 32, stream); }) + == cudaSuccess + && syncs == beforeSyncs + 1 && ok; + ok = cache.allocate(32, &c) == cudaSuccess && c == a && ok; + int value = 0; + ok = cudaMemcpy(&value, c, sizeof(value), cudaMemcpyDeviceToHost) + == cudaSuccess + && value == 0x2a2a2a2a && ok; + cudaStreamDestroy(stream); + cache.release(c, 32); + cache.release(b, 32); + const int beforeFailedFlush = syncs; + ok = cache.reclaim([] { return cudaErrorInvalidValue; }) + == cudaErrorInvalidValue + && syncs == beforeFailedFlush && ok; + failSync = true; + ok = cache.reclaim(complete) == cudaErrorUnknown && ok; + void *d = nullptr; + ok = cache.allocate(32, &d) == cudaSuccess && d != a && d != b && ok; + cache.release(d, 32); + ok = cache.reclaim(complete) == cudaSuccess && ok; + cache.close(); + const int afterClose = frees; + cache.close(); + ok = frees == afterClose && ok; + } + { + // A consumer outside the preparation stream must also complete before a + // returned block can be reused. The timeout only escapes a broken wait. + DeviceAllocationCache cache; + void *p = nullptr; + ok = cache.allocate(32, &p) == cudaSuccess && ok; + cudaStream_t consumer{}; + ok = cudaStreamCreateWithFlags(&consumer, cudaStreamNonBlocking) + == cudaSuccess + && ok; + ok = cudaLaunchHostFunc(consumer, blockConsumer, nullptr) == cudaSuccess + && ok; + ok = cudaMemsetAsync(p, 0x17, 32, consumer) == cudaSuccess && ok; + cache.release(p, 32); + int gpu = 0; + cudaGetDevice(&gpu); + cudaError_t completion = cudaErrorUnknown; + trackSync = true; + std::thread collector([&] { + cudaSetDevice(gpu); + completion = cache.reclaim(complete); + { + std::lock_guard lock(gateMutex); + cohortReturned = true; + } + gateCondition.notify_all(); + }); + { + std::unique_lock lock(gateMutex); + const bool entered = gateCondition.wait_for(lock, + std::chrono::seconds(5), + [] { return syncEntered.load() || cohortReturned.load(); }); + ok = entered && syncEntered && !cohortReturned && ok; + gateReleased = true; + } + collector.join(); + trackSync = false; + ok = completion == cudaSuccess && ok; + cudaStreamSynchronize(consumer); + void *reused = nullptr; + ok = cache.allocate(32, &reused) == cudaSuccess && reused == p && ok; + int value = 0; + ok = cudaMemcpy(&value, reused, sizeof(value), cudaMemcpyDeviceToHost) + == cudaSuccess + && value == 0x17171717 && ok; + cache.release(reused, 32); + cudaStreamDestroy(consumer); + } + { + DeviceAllocationCache cache(64, 2); + void *p[3]{}; + for (auto &pointer : p) + ok = cache.allocate(32, &pointer) == cudaSuccess && ok; + const int beforeFree = frees; + for (auto pointer : p) + cache.release(pointer, 32); + ok = + frees == beforeFree + 1 && ok; // Bound pending as well as ready blocks. + ok = cache.reclaim(complete) == cudaSuccess && ok; + void *large = nullptr; + ok = cache.allocate(65, &large) == cudaSuccess && ok; + cache.release(large, 65); + ok = frees == beforeFree + 2 && ok; + } + { + DeviceAllocationCache cache(1024, 1); + void *a = nullptr, *b = nullptr; + ok = cache.allocate(16, &a) == cudaSuccess && ok; + ok = cache.allocate(16, &b) == cudaSuccess && ok; + const int beforeFree = frees; + cache.release(a, 16); + cache.release(b, 16); + ok = + frees == beforeFree + 1 && ok; // Entry bound independent of byte bound. + } + { + DeviceAllocationCache cache(32, 1); + void *a = nullptr, *b = nullptr; + ok = cache.allocate(32, &a) == cudaSuccess && ok; + ok = cache.allocate(32, &b) == cudaSuccess && ok; + cache.release(a, 32); + const int beforeFree = frees; + ok = cache.reclaim([&] { + cache.release(b, 32); // Frozen blocks still consume the cache budget. + return cudaSuccess; + }) == cudaSuccess + && frees == beforeFree + 1 && ok; + } + { + DeviceAllocationCache cache(1024, 64); + std::array pointers{}; + for (auto &p : pointers) + ok = cache.allocate(8, &p) == cudaSuccess && ok; + const int beforeFree = frees; + std::vector workers; + for (int worker = 0; worker < 8; ++worker) + workers.emplace_back([&, worker] { + for (int i = worker; i < 64; i += 8) + cache.release(pointers[i], 8); + }); + for (auto &worker : workers) + worker.join(); + ok = frees == beforeFree && cache.reclaim(complete) == cudaSuccess && ok; + } + { + DeviceAllocationCache cache; + void *a = nullptr, *b = nullptr, *c = nullptr; + ok = cache.allocate(32, &a) == cudaSuccess && ok; + ok = cache.allocate(32, &b) == cudaSuccess && ok; + cache.release(a, 32); + ok = cache.reclaim([&] { + cache.release(b, 32); // Later returns cannot join this frozen cohort. + return cudaSuccess; + }) == cudaSuccess + && ok; + ok = cache.allocate(32, &c) == cudaSuccess && c == a && ok; + void *d = nullptr; + ok = cache.allocate(32, &d) == cudaSuccess && d != b && ok; + cache.release(c, 32); + cache.release(d, 32); + bool threw = false; + try { + cache.reclaim([]() -> cudaError_t { throw std::runtime_error("test"); }); + } catch (const std::runtime_error &) { + threw = true; + } + ok = threw && cache.reclaim(complete) == cudaSuccess && ok; + } + { + // Reusing a block while a cohort is frozen and a later return waits must + // leave each of the other two where it was. + DeviceAllocationCache cache; + void *ready = nullptr, *frozen = nullptr, *waiting = nullptr, *p = nullptr; + ok = cache.allocate(32, &ready) == cudaSuccess && ok; + ok = cache.allocate(48, &frozen) == cudaSuccess && ok; + ok = cache.allocate(64, &waiting) == cudaSuccess && ok; + cache.release(ready, 32); + ok = cache.reclaim(complete) == cudaSuccess && ok; + cache.release(frozen, 48); + ok = cache.reclaim([&] { + cache.release(waiting, 64); + ok = cache.allocate(32, &p) == cudaSuccess && p == ready && ok; + ok = cache.allocate(48, &p) == cudaSuccess && p != frozen && ok; + cache.release(p, 48); + return cudaSuccess; + }) == cudaSuccess + && ok; + ok = cache.allocate(48, &p) == cudaSuccess && p == frozen && ok; + void *other = nullptr; + ok = cache.allocate(64, &other) == cudaSuccess && other != waiting && ok; + ok = cache.reclaim(complete) == cudaSuccess && ok; + void *q = nullptr; + ok = cache.allocate(64, &q) == cudaSuccess && q == waiting && ok; + for (auto [pointer, bytes] : + {std::pair{ready, 32}, {p, 48}, {other, 64}, {q, 64}}) + cache.release(pointer, bytes); + } + { + DeviceAllocationCache cache; + void *p = nullptr; + ok = cache.allocate(32, &p) == cudaSuccess && ok; + cache.release(p, 32); + ok = cache.reclaim(complete) == cudaSuccess && ok; + const int beforeAttempts = attempts, beforeFrees = frees; + failBytes = 64; + ok = cache.allocate(64, &p) == cudaSuccess && attempts == beforeAttempts + 2 + && frees == beforeFrees + 1 && ok; + cache.release(p, 64); + // With no ready blocks to trim, preserve the original allocation error. + failBytes = 128; + ok = cache.allocate(128, &p) == cudaErrorMemoryAllocation && !p && ok; + cudaGetLastError(); + } + { + auto cache = std::make_shared(); + void *p = nullptr; + ok = cache->allocate(32, &p) == cudaSuccess && ok; + auto allocation = visrtx::CudaMemoryAllocation::fromCache(p, 32, cache); + auto moved = std::move(allocation); + ok = !allocation && moved.ptr() == p && moved.isOwner() && ok; + cache->close(); + cache.reset(); // A late return must free, not resurrect a closed cache. + const int beforeFree = frees; + moved = visrtx::CudaMemoryAllocation(); + ok = frees == beforeFree + 1 && ok; + ok = cudaMalloc(&p, 32) == cudaSuccess && ok; + { + visrtx::CudaMemoryAllocation captured(p, 32, capturedDelete); + } + ok = capturedDeletes == 1 && ok; + } + { + // A failed reservation leaves the buffer empty, consumes the runtime + // error, and lets the same size be retried. + visrtx::DeviceBuffer buffer; + failBytes = 96; + ok = buffer.tryReserve(96) == cudaErrorMemoryAllocation && !buffer + && buffer.bytes() == 0 && cudaGetLastError() == cudaSuccess && ok; + ok = buffer.tryReserve(96) == cudaSuccess && buffer && buffer.bytes() >= 96 + && ok; + const auto *storage = buffer.ptr(); + ok = buffer.tryReserve(48) == cudaSuccess && buffer.ptr() == storage + && buffer.tryReserve(0) == cudaSuccess && buffer.ptr() == storage && ok; + failBytes = 192; + ok = buffer.tryReserve(192) == cudaErrorMemoryAllocation && !buffer + && buffer.bytes() == 0 && cudaGetLastError() == cudaSuccess && ok; + ok = buffer.tryReserve(192) == cudaSuccess && buffer.bytes() >= 192 && ok; + } + ok = allocations == frees && ok; + std::printf("allocation cache allocations=%d frees=%d syncs=%d %s\n", + int(allocations), + int(frees), + int(syncs), + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestDeviceGeometryVisibility.cpp b/devices/rtx/apps/tests/api/TestDeviceGeometryVisibility.cpp new file mode 100644 index 000000000..633e283aa --- /dev/null +++ b/devices/rtx/apps/tests/api/TestDeviceGeometryVisibility.cpp @@ -0,0 +1,398 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" + +using vec3 = std::array; +using vec4 = std::array; +static int errors = 0; +static bool retireShared = false; +static bool expandedSdf = false; + +struct ResidencyCase +{ + const char *name; + int deviceInputs; +}; + +static constexpr std::array QUAD_CASES = {{{"host", 0}, + {"device-positions", 1}, + {"device-indices", 2}, + {"all-device", 3}}}; +static constexpr std::array CURVE_CASES = {{{"host", 0}, + {"device-positions", 1}, + {"device-indices", 2}, + {"device-vertex-radii", 4}, + {"all-device", 7}}}; +static constexpr auto CONE_CASES = CURVE_CASES; +static constexpr auto TRIANGLE_CASES = QUAD_CASES; +static constexpr std::array SPHERE_CASES = {{{"host", 0}, + {"device-positions", 1}, + {"device-indices", 2}, + {"device-vertex-radii", 4}, + {"all-device", 7}}}; +static constexpr std::array CYLINDER_CASES = {{{"host", 0}, + {"device-positions", 1}, + {"device-indices", 2}, + {"device-primitive-radii", 4}, + {"all-device", 7}}}; +static constexpr std::array SDF_CASES = { + {{"host", 0}, {"device-primitive-bytes", 1}}}; +static constexpr std::array EXPANDED_SDF_CASES = { + {{"host", 0}, + {"device-primitive-bytes", 1}, + {"device-neighbors", 2}, + {"all-device", 3}}}; +// Indices and radii always use shared GPU storage in retirement mode. +static constexpr std::array RETIREMENT_CASES = { + {{"host-positions-shared-device-indices-radii", 0}, + {"device-positions-shared-device-indices-radii", 1}}}; + +template +static std::pair sharedArray( + ANARIDevice d, anari::Geometry g, const char *name, const Container &values) +{ + using T = typename Container::value_type; + void *ptr = nullptr; + if (cudaMalloc(&ptr, values.size() * sizeof(T)) != cudaSuccess + || cudaMemcpy(ptr, + values.data(), + values.size() * sizeof(T), + cudaMemcpyHostToDevice) + != cudaSuccess) + std::exit(2); + auto array = anariNewArray1D( + d, ptr, nullptr, nullptr, anari::ANARITypeFor::value, values.size()); + anari::setParameter(d, g, name, array); + return {array, ptr}; +} +static void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + fprintf(stderr, "%s\n", message); + } +} + +struct Scene +{ + anari::World world; + anari::Frame frame; +}; +static Scene makeScene(ANARIDevice d, anari::Geometry g) +{ + auto material = anari::newObject(d, "matte"); + anari::setParameter(d, material, "color", vec3{1, 0, 0}); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", g); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto world = anari::newObject(d); + anari::setParameterArray1D(d, world, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, world); + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "debug"); + anari::setParameter(d, renderer, "method", "baseColor"); + anari::setParameter(d, renderer, "background", vec4{0, 0, 0, 1}); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{64, 64}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::setParameter(d, frame, "world", world); + anari::commitParameters(d, frame); + return {world, frame}; +} + +// Exact bounds and a visible/cleared center pixel are independent oracles. +static bool validate(ANARIDevice d, + Scene scene, + const std::array &expected, + bool visible) +{ + anari::wait(d, scene.frame); + std::array bounds{}; + bool ok = anariGetProperty(d, + scene.world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT); + for (size_t i = 0; i < bounds.size(); ++i) + ok = std::isfinite(bounds[i]) && std::abs(bounds[i] - expected[i]) < 1e-4f + && ok; + auto fb = anari::map(d, scene.frame, "channel.color"); + const float red = fb.data ? fb.data[32 * 64 + 32][0] : NAN; + ok = std::isfinite(red) && (visible ? red > 0.5f : red < 0.01f) && ok; + anari::unmap(d, scene.frame, "channel.color"); + printf("bounds=[%g %g %g %g %g %g] center=%g %s\n", + bounds[0], + bounds[1], + bounds[2], + bounds[3], + bounds[4], + bounds[5], + red, + ok ? "PASS" : "FAIL"); + return ok; +} + +// Public API seam: exact geometric bounds and a visible center pixel are +// independent controls. 1e-4 absolute bounds tolerance permits OptiX rounding; +// moving the input by +2 in X must move the bounds and clear the center pixel. +static bool check(ANARIDevice d, + const char *type, + const ResidencyCase &residency, + float shift) +{ + const int device = residency.deviceInputs; + const char *scenario = + retireShared ? "retirement" : (expandedSdf ? "sdf-expanded" : type); + fprintf(stderr, "[case] %s/%s shift=%g\n", scenario, residency.name, shift); + auto g = anari::newObject(d, type); + std::vector> shared; + float xExtent = 0.5f, yExtent = 0.5f, zExtent = 0.f; + if (std::strcmp(type, "sphere") == 0) { + // The unused large sphere makes ignoring the index observable. + const std::array vertices = { + {{shift + 4.f, 4.f, 0}, {shift, 0, 0}}}; + const std::array indices = {1}; + const std::array radii = {1.f, 0.5f}; + setTestArray(d, g, "vertex.position", vertices, device & 1, 1); + setTestArray(d, g, "primitive.index", indices, device & 2, 1); + setTestArray(d, g, "vertex.radius", radii, device & 4, 1); + zExtent = 0.5f; + } else if (std::strcmp(type, "triangle") == 0) { + const std::array vertices = {{{shift + 4.f, 4.f, 0}, + {shift - 0.5f, -0.5f, 0}, + {shift + 0.5f, -0.5f, 0}, + {shift, 0.5f, 0}}}; + const std::array, 1> indices = {{{1, 2, 3}}}; + setTestArray(d, g, "vertex.position", vertices, device & 1, 1); + setTestArray(d, g, "primitive.index", indices, device & 2, 1); + } else if (std::strcmp(type, "quad") == 0) { + const std::array vertices = {{{shift - 0.5f, -0.5f, 0}, + {shift + 0.5f, -0.5f, 0}, + {shift + 0.5f, 0.5f, 0}, + {shift - 0.5f, 0.5f, 0}}}; + const std::array, 1> indices = {{{0, 1, 2, 3}}}; + setTestArray(d, g, "vertex.position", vertices, device & 1, 1); + setTestArray(d, g, "primitive.index", indices, device & 2, 1); + } else if (std::strcmp(type, "cone") == 0 + || std::strcmp(type, "cylinder") == 0) { + const bool cone = std::strcmp(type, "cone") == 0; + // Vertex 0 is deliberately unused. Selecting it instead of logical + // vertices 2 and 1 must fail both the bounds and visibility controls. + const std::array vertices = { + {{shift + 4.f, 4.f, 0}, {shift + 0.5f, 0, 0}, {shift - 0.5f, 0, 0}}}; + const std::array, 1> indices = {{{2, 1}}}; + const std::array vertexRadii = {0.75f, 0.25f, 0.125f}; + const std::array primitiveRadii = {0.25f}; + setTestArray(d, g, "vertex.position", vertices, device & 1, 1); + setTestArray(d, g, "primitive.index", indices, device & 2, 1); + if (cone) + setTestArray(d, g, "vertex.radius", vertexRadii, device & 4, 1); + else + setTestArray(d, g, "primitive.radius", primitiveRadii, device & 4, 1); + anari::setParameter(d, g, "caps", "both"); + // Conservative tube bounds: endpoints [-0.5,0.5], largest radius 0.25. + // This literal oracle is independent of device bound-generation code. + xExtent = 0.75f; + yExtent = zExtent = 0.25f; + } else if (std::strcmp(type, "curve") == 0) { + const std::array vertices = { + {{shift - 0.5f, 0, 0}, {shift + 0.5f, 0, 0}}}; + const std::array indices = {0}; + const std::array radii = {0.125f, 0.125f}; + setTestArray(d, g, "vertex.position", vertices, device & 1, 1); + if (retireShared) { + shared.push_back(sharedArray(d, g, "primitive.index", indices)); + shared.push_back(sharedArray(d, g, "vertex.radius", radii)); + } else { + setTestArray(d, g, "primitive.index", indices, device & 2, 1); + setTestArray(d, g, "vertex.radius", radii, device & 4, 1); + } + xExtent = 0.625f; + yExtent = zExtent = 0.125f; + } else { + // VISRTX_GEOMETRY_SDF documents N*72 raw bytes. Pack a sphere, without + // depending on device classes or their private preprocessing buffers. + std::array bytes{}; + const vec3 center = {shift, 0, 0}; + const float radius = 0.5f; + std::memcpy(bytes.data() + 20, center.data(), sizeof(center)); + std::memcpy(bytes.data() + 44, &radius, sizeof(radius)); + std::memcpy(bytes.data() + 48, &radius, sizeof(radius)); + if (expandedSdf) { + bytes[64] = 1; + const std::array neighbours = {0}; + setTestArray(d, g, "primitive.neighbor", neighbours, device & 2, 1); + anari::setParameter(d, g, "blendFactor", 0.5f); + anari::setParameter(d, g, "noiseFactor", 0.5f); + // 0.5 base + 0.5*0.5 blend + 0.5*0.5*0.1 noise. + xExtent = yExtent = 0.775f; + } + setTestArray(d, g, "primitive.sdf", bytes, device & 1, 1); + zExtent = xExtent; + } + anari::commitParameters(d, g); + const auto scene = makeScene(d, g); + anari::release(d, g); + const auto frame = scene.frame; + anari::render(d, frame); + if (retireShared) { + // Last PUBLIC release must finish outstanding consumers and rebind any + // aliases before the application is allowed to retire its shared storage. + for (auto entry : shared) { + anari::release(d, entry.first); + cudaFree(entry.second); + } + fprintf(stderr, + "[case] %s/%s shift=%g after shared storage retirement\n", + scenario, + residency.name, + shift); + anari::setParameter(d, frame, "accumulationVersion", uint64_t(2)); + anari::commitParameters(d, frame); + anari::render(d, frame); + } + const std::array expected = { + shift - xExtent, -yExtent, -zExtent, shift + xExtent, yExtent, zExtent}; + const bool ok = validate(d, scene, expected, shift == 0.f); + anari::release(d, frame); + anari::release(d, scene.world); + return ok; +} +// One array observed by two distinct geometries/worlds. Detaching one consumer +// must not detach the other or hide observer-only unmap updates. +static bool sharedInputs(ANARIDevice d) +{ + auto positions = anari::newArray1D(d, ANARI_FLOAT32_VEC3, 2); + const auto update = [&](float y) { + auto *p = anari::map(d, positions); + p[0] = {-0.5f, y, 0}; + p[1] = {0.5f, y, 0}; + anari::unmap(d, positions); + }; + update(0); + std::array geometries; + std::array scenes; + for (size_t i = 0; i < scenes.size(); ++i) { + auto g = anari::newObject(d, "curve"); + anari::setParameter(d, g, "vertex.position", positions); + anari::setParameter(d, g, "radius", 0.125f); + anari::commitParameters(d, g); + geometries[i] = g; + scenes[i] = makeScene(d, g); + } + const auto check = [&](size_t consumer, float y) { + fprintf(stderr, "[case] shared-input consumer=%zu y=%g\n", consumer, y); + anari::render(d, scenes[consumer].frame); + return validate(d, + scenes[consumer], + {-0.625f, y - 0.125f, -0.125f, 0.625f, y + 0.125f, 0.125f}, + y == 0); + }; + bool ok = check(0, 0); + ok = check(1, 0) && ok; + update(1); // no geometry/world recommit + ok = check(0, 1) && ok; + ok = check(1, 1) && ok; + const std::array replacement = {{{-0.5f, 0, 0}, {0.5f, 0, 0}}}; + setTestArray(d, geometries[0], "vertex.position", replacement, true); + anari::commitParameters(d, geometries[0]); + ok = check(0, 0) && ok; + ok = check(1, 1) && ok; + for (size_t i = 0; i < scenes.size(); ++i) { + anari::release(d, scenes[i].frame); + anari::release(d, scenes[i].world); + anari::release(d, geometries[i]); + } + anari::release(d, positions); + return ok; +} +int main(int argc, char **argv) +{ + retireShared = argc > 1 && std::strcmp(argv[1], "--retire") == 0; + expandedSdf = argc > 1 && std::strcmp(argv[1], "sdf-expanded") == 0; + const char *type = retireShared + ? "curve" + : (expandedSdf ? "sdf" : (argc > 1 ? argv[1] : "quad")); + auto d = makeVisRTXDevice(status); + bool ok = true; + const auto runCases = [&](const auto &cases) { + for (const auto &residency : cases) + for (float shift : {0.f, 2.f}) + ok = check(d, type, residency, shift) && ok; + }; + if (std::strcmp(type, "--shared-inputs") == 0) + ok = sharedInputs(d); + else if (retireShared) + runCases(RETIREMENT_CASES); + else if (expandedSdf) + runCases(EXPANDED_SDF_CASES); + else if (std::strcmp(type, "triangle") == 0) + runCases(TRIANGLE_CASES); + else if (std::strcmp(type, "sphere") == 0) + runCases(SPHERE_CASES); + else if (std::strcmp(type, "quad") == 0) + runCases(QUAD_CASES); + else if (std::strcmp(type, "curve") == 0) + runCases(CURVE_CASES); + else if (std::strcmp(type, "cone") == 0) + runCases(CONE_CASES); + else if (std::strcmp(type, "cylinder") == 0) + runCases(CYLINDER_CASES); + else + runCases(SDF_CASES); + anari::release(d, d); + return ok && errors == 0 ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestEmissiveCylinderConeLight.cpp b/devices/rtx/apps/tests/api/TestEmissiveCylinderConeLight.cpp index c5f7269bb..fa6aaa1ad 100644 --- a/devices/rtx/apps/tests/api/TestEmissiveCylinderConeLight.cpp +++ b/devices/rtx/apps/tests/api/TestEmissiveCylinderConeLight.cpp @@ -64,31 +64,37 @@ #include #include #include +#include "DeviceTestArray.h" +#include "ReceiverTestSupport.h" + +struct ResidencyCase +{ + const char *name; + int deviceInputs; +}; + +// Bounds/visibility isolate positions, indices and radii. Caps affect +// sampling rather than conservative bounds, so retain their isolated oracle. +static constexpr std::array TUBE_CASES = { + {{"host-indexed", 0}, {"device-vertex-caps", 4}, {"all-device", 15}}}; using vec3 = std::array; using vec4 = std::array; using uvec3 = std::array; using mat4 = std::array; -static void statusFunc(const void *, - ANARIDevice, - ANARIObject source, - ANARIDataType, - ANARIStatusSeverity severity, - ANARIStatusCode, - const char *message) -{ - if (severity == ANARI_SEVERITY_FATAL_ERROR) { - fprintf(stderr, "[FATAL][%p] %s\n", source, message); - std::exit(1); - } else if (severity == ANARI_SEVERITY_ERROR) - fprintf(stderr, "[ERROR][%p] %s\n", source, message); -} - static constexpr std::array IMAGE_SIZE = {256, 256}; static constexpr int PIXEL_SAMPLES = 1024; static constexpr float EMISSIVE_RADIANCE = 8.f; -static constexpr int TESS = 128; // circumferential segments of the reference mesh +static constexpr double TOLERANCE = 0.03; +static bool equivalent(double actual, double reference) +{ + return std::isfinite(actual) && std::isfinite(reference) && actual > 0.0 + && reference > 0.0 + && std::abs(actual - reference) / reference <= TOLERANCE; +} +static constexpr int TESS = + 128; // circumferential segments of the reference mesh // One tapered tube (cylinder if r0==r1). Two parallel bars above the origin, // axes along X, offset in Z, so their walls face the floor. Above the top of @@ -169,35 +175,11 @@ static anari::Material makeEmissiveMaterial(ANARIDevice device) return mat; } -static anari::Surface makeFloor(ANARIDevice device) -{ - const std::array pos = {vec3{-6.f, 0.f, -6.f}, - vec3{6.f, 0.f, -6.f}, - vec3{6.f, 0.f, 6.f}, - vec3{-6.f, 0.f, 6.f}}; - const std::array idx = {uvec3{0, 1, 2}, uvec3{0, 2, 3}}; - - auto geom = anari::newObject(device, "triangle"); - anari::setParameterArray1D(device, geom, "vertex.position", pos.data(), 4); - anari::setParameterArray1D(device, geom, "primitive.index", idx.data(), 2); - anari::commitParameters(device, geom); - - auto mat = anari::newObject(device, "physicallyBased"); - anari::setParameter(device, mat, "baseColor", vec3{0.5f, 0.5f, 0.5f}); - anari::setParameter(device, mat, "roughness", 1.f); - anari::commitParameters(device, mat); - - auto surface = anari::newObject(device); - anari::setAndReleaseParameter(device, surface, "geometry", geom); - anari::setAndReleaseParameter(device, surface, "material", mat); - anari::commitParameters(device, surface); - return surface; -} - // Capped, tessellated emissive triangle mesh of the given tubes: two rings of // TESS points per tube plus a center vertex for each ENABLED cap. Winding does -// not matter (emission is double-sided); the closed shell absorbs its own inward -// emission so it lights the exterior floor like a single-sided primitive. +// not matter (emission is double-sided); the closed shell absorbs its own +// inward emission so it lights the exterior floor like a single-sided +// primitive. static anari::Surface makeEmissiveTubeMesh( ANARIDevice device, const std::array &tubes) { @@ -257,7 +239,8 @@ static anari::Surface makeEmissiveTubeMesh( // Per-endpoint vertex.cap (0/1) for a soup tube set: endpoints of tube k are // vertices (2k, 2k+1). -static std::vector tubeVertexCaps(const std::array &tubes) +static std::vector tubeVertexCaps( + const std::array &tubes) { std::vector caps; for (const auto &t : tubes) { @@ -267,7 +250,8 @@ static std::vector tubeVertexCaps(const std::array &tube return caps; } -static anari::Surface makeEmissiveCylinderPrim(ANARIDevice device) +static anari::Surface makeEmissiveCylinderPrim( + ANARIDevice device, int deviceInputs, bool indexed) { std::vector pos; std::vector radii; // per primitive @@ -279,12 +263,13 @@ static anari::Surface makeEmissiveCylinderPrim(ANARIDevice device) const auto caps = tubeVertexCaps(CYLINDERS); auto geom = anari::newObject(device, "cylinder"); - anari::setParameterArray1D( - device, geom, "vertex.position", pos.data(), pos.size()); - anari::setParameterArray1D( - device, geom, "primitive.radius", radii.data(), radii.size()); - anari::setParameterArray1D( - device, geom, "vertex.cap", caps.data(), caps.size()); + setTestArray(device, geom, "vertex.position", pos, deviceInputs & 1); + setTestArray(device, geom, "primitive.radius", radii, deviceInputs & 2); + setTestArray(device, geom, "vertex.cap", caps, deviceInputs & 4); + if (indexed) { + const std::array, 2> indices = {{{0, 1}, {2, 3}}}; + setTestArray(device, geom, "primitive.index", indices, deviceInputs & 8); + } anari::commitParameters(device, geom); auto surface = anari::newObject(device); @@ -295,7 +280,8 @@ static anari::Surface makeEmissiveCylinderPrim(ANARIDevice device) return surface; } -static anari::Surface makeEmissiveConePrim(ANARIDevice device) +static anari::Surface makeEmissiveConePrim( + ANARIDevice device, int deviceInputs, bool indexed) { std::vector pos; std::vector radii; // per vertex @@ -308,12 +294,13 @@ static anari::Surface makeEmissiveConePrim(ANARIDevice device) const auto caps = tubeVertexCaps(CONES); auto geom = anari::newObject(device, "cone"); - anari::setParameterArray1D( - device, geom, "vertex.position", pos.data(), pos.size()); - anari::setParameterArray1D( - device, geom, "vertex.radius", radii.data(), radii.size()); - anari::setParameterArray1D( - device, geom, "vertex.cap", caps.data(), caps.size()); + setTestArray(device, geom, "vertex.position", pos, deviceInputs & 1); + setTestArray(device, geom, "vertex.radius", radii, deviceInputs & 2); + setTestArray(device, geom, "vertex.cap", caps, deviceInputs & 4); + if (indexed) { + const std::array, 2> indices = {{{0, 1}, {2, 3}}}; + setTestArray(device, geom, "primitive.index", indices, deviceInputs & 8); + } anari::commitParameters(device, geom); auto surface = anari::newObject(device); @@ -342,128 +329,90 @@ static anari::Instance instanceOf( return inst; } -static std::vector render(ANARIDevice device, +static double render(ANARIDevice device, const std::function &emitter, bool scaled) { const std::array instances = { - instanceOf(device, makeFloor(device), false), + instanceOf(device, visrtx::test::receiverFloor(device, 0.5f), false), instanceOf(device, emitter(device), scaled)}; auto world = anari::newObject(device); + const visrtx::test::ObjectOwner worldOwner(device, world); anari::setParameterArray1D( device, world, "instance", instances.data(), instances.size()); for (auto i : instances) anari::release(device, i); anari::commitParameters(device, world); - auto camera = anari::newObject(device, "perspective"); - anari::setParameter(device, camera, "position", vec3{0.f, 0.5f, -3.f}); - anari::setParameter(device, camera, "direction", vec3{0.f, -0.15f, 1.f}); - anari::setParameter(device, camera, "up", vec3{0.f, 1.f, 0.f}); - anari::setParameter( - device, camera, "aspect", IMAGE_SIZE[0] / float(IMAGE_SIZE[1])); - anari::commitParameters(device, camera); - - auto renderer = anari::newObject(device, "quality"); - anari::setParameter(device, renderer, "background", vec4{0.f, 0.f, 0.f, 1.f}); - anari::setParameter(device, renderer, "ambientRadiance", 0.f); - anari::setParameter(device, renderer, "pixelSamples", PIXEL_SAMPLES); - anari::setParameter(device, renderer, "fireflyFilterMode", "none"); - anari::commitParameters(device, renderer); - - auto frame = anari::newObject(device); - anari::setParameter(device, frame, "size", IMAGE_SIZE); - anari::setParameter(device, frame, "channel.color", ANARI_FLOAT32_VEC4); - anari::setAndReleaseParameter(device, frame, "world", world); - anari::setAndReleaseParameter(device, frame, "camera", camera); - anari::setAndReleaseParameter(device, frame, "renderer", renderer); - anari::commitParameters(device, frame); - - anari::render(device, frame); - anari::wait(device, frame); - - auto fb = anari::map(device, frame, "channel.color"); - std::vector out(fb.data, fb.data + size_t(fb.width) * fb.height); - anari::unmap(device, frame, "channel.color"); - anari::release(device, frame); - return out; -} - -// Mean linear luminance over the lit floor region (lower-center of the frame, -// ANARI's bottom-left framebuffer origin). -static double poolMeanLuminance(const std::vector &fb) -{ - double sum = 0.0; - uint64_t n = 0; - for (uint32_t y = IMAGE_SIZE[1] / 8; y < IMAGE_SIZE[1] / 2; ++y) { - for (uint32_t x = 3 * IMAGE_SIZE[0] / 8; x < 5 * IMAGE_SIZE[0] / 8; ++x) { - const vec4 &p = fb[y * IMAGE_SIZE[0] + x]; - sum += 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; - ++n; - } - } - return n ? sum / double(n) : 0.0; + auto frame = visrtx::test::receiverFrame( + device, world, IMAGE_SIZE, "quality", PIXEL_SAMPLES); + const visrtx::test::ObjectOwner frameOwner(device, frame); + // Bottom-left origin; only the floor's cast pool, never the emitters. + return visrtx::test::receiverLuminance(device, + frame, + IMAGE_SIZE, + {3 * IMAGE_SIZE[0] / 8, + 5 * IMAGE_SIZE[0] / 8, + IMAGE_SIZE[1] / 8, + IMAGE_SIZE[1] / 2}); } -static bool checkEquivalent( - ANARIDevice device, const char *name, - const std::function &prim, - const std::function &mesh, +static bool checkFamily(ANARIDevice device, + const char *name, + const std::array &tubes, + const std::function &prim, bool scaled) { - const double p = poolMeanLuminance(render(device, prim, scaled)); - const double m = poolMeanLuminance(render(device, mesh, scaled)); - const double relErr = m > 0.0 ? std::abs(p - m) / m : (p > 0 ? 1.0 : 0.0); - printf("%s%s: primitive=%f mesh=%f relErr=%f\n", - name, - scaled ? " (scaled)" : "", - p, - m, - relErr); - if (p <= 0.0 || m <= 0.0) { - fprintf(stderr, "FAIL: %s floor pool unlit\n", name); - return false; + const char *transform = scaled ? "nonuniform-scale" : "identity"; + // Keep an independent tessellated reference for each family and transform. + fprintf(stderr, "[case] %s/%s/reference\n", name, transform); + const double mesh = render( + device, + [&](ANARIDevice d) { return makeEmissiveTubeMesh(d, tubes); }, + scaled); + bool ok = std::isfinite(mesh) && mesh > 0.0; + + const auto check = + [&](const char *residency, int deviceInputs, bool indexed) { + fprintf(stderr, "[case] %s/%s/%s\n", name, transform, residency); + const double actual = render( + device, + [&](ANARIDevice d) { return prim(d, deviceInputs, indexed); }, + scaled); + // Keep the original 3% MC/faceting allowance. + const bool matches = equivalent(actual, mesh); + printf("%s/%s/%s primitive=%f reference=%f relErr=%g tolerance=%g %s\n", + name, + transform, + residency, + actual, + mesh, + std::abs(actual - mesh) / mesh, + TOLERANCE, + matches ? "PASS" : "FAIL"); + ok = matches && ok; + }; + check("host-implicit-indices", 0, false); + for (const auto &residency : TUBE_CASES) { + // Residency roles are isolated at identity; the all-device case also + // witnesses their integration with the nonuniform area Jacobian. + if (!scaled || residency.deviceInputs == 15) + check(residency.name, residency.deviceInputs, true); } - // 3% absorbs MC noise at 1024 spp plus the reference mesh's small (<0.1% area) - // faceting; observed relErr is well under 1%. - constexpr double TOLERANCE = 0.03; - if (relErr > TOLERANCE) { - fprintf(stderr, - "FAIL: %s%s geometry light not equivalent to tessellated mesh (relErr=%f > %f)\n", - name, - scaled ? " (scaled)" : "", - relErr, - TOLERANCE); - return false; - } - return true; + return ok; } int main() { - auto device = makeVisRTXDevice(statusFunc); - - const auto cylMesh = [](ANARIDevice d) { - return makeEmissiveTubeMesh(d, CYLINDERS); - }; - const auto coneMesh = [](ANARIDevice d) { - return makeEmissiveTubeMesh(d, CONES); - }; - + auto device = makeVisRTXDevice(visrtx::test::exitOnErrorStatus); bool ok = true; for (bool scaled : {false, true}) { - ok = checkEquivalent( - device, "cylinder", makeEmissiveCylinderPrim, cylMesh, scaled) - && ok; - ok = checkEquivalent(device, "cone", makeEmissiveConePrim, coneMesh, scaled) + ok = checkFamily( + device, "cylinder", CYLINDERS, makeEmissiveCylinderPrim, scaled) && ok; + ok = checkFamily(device, "cone", CONES, makeEmissiveConePrim, scaled) && ok; } - anari::release(device, device); - - if (!ok) - return 1; - printf("emissive cylinder/cone geometry light equivalence passed\n"); - return 0; + return ok ? 0 : 1; } diff --git a/devices/rtx/apps/tests/api/TestEmissiveSphereLight.cpp b/devices/rtx/apps/tests/api/TestEmissiveSphereLight.cpp index 52d295e17..6f54d078a 100644 --- a/devices/rtx/apps/tests/api/TestEmissiveSphereLight.cpp +++ b/devices/rtx/apps/tests/api/TestEmissiveSphereLight.cpp @@ -33,11 +33,11 @@ // (PhysicallyBased, constant `emissive`) must illuminate a floor the same as an // ANARI sphere light (the "point" subtype with radius) of matching radiance, // radius, and placement. Validates the sphere sampler's radiometry and that -// hit-side MIS does not bias (NEE + BSDF-hit deposit sum to the analytic light's -// contribution). The emitter sits above the top of frame so only its cast pool -// on the floor is measured — the emissive sphere's own glow (which the analytic -// light has no counterpart for) never enters the region. Rendered with 'quality' -// into a linear float buffer, firefly filter off. +// hit-side MIS does not bias (NEE + BSDF-hit deposit sum to the analytic +// light's contribution). The emitter sits above the top of frame so only its +// cast pool on the floor is measured — the emissive sphere's own glow (which +// the analytic light has no counterpart for) never enters the region. Rendered +// with 'quality' into a linear float buffer, firefly filter off. // anari_cpp #define ANARI_EXTENSION_UTILITY_IMPL @@ -52,70 +52,58 @@ #include #include #include +#include "DeviceTestArray.h" +#include "ReceiverTestSupport.h" + +struct ResidencyCase +{ + const char *name; + int deviceInputs; +}; + +// Bounds/visibility isolate input roles; radiometry checks the sampler. +static constexpr std::array SPHERE_CASES = { + {{"host-indexed", 0}, {"all-device", 7}}}; using uvec2 = std::array; using vec3 = std::array; using vec4 = std::array; -static void statusFunc(const void *, - ANARIDevice, - ANARIObject source, - ANARIDataType, - ANARIStatusSeverity severity, - ANARIStatusCode, - const char *message) -{ - if (severity == ANARI_SEVERITY_FATAL_ERROR) { - fprintf(stderr, "[FATAL][%p] %s\n", source, message); - std::exit(1); - } else if (severity == ANARI_SEVERITY_ERROR) - fprintf(stderr, "[ERROR][%p] %s\n", source, message); -} - static constexpr uvec2 IMAGE_SIZE = {256, 256}; static constexpr int PIXEL_SAMPLES = 512; static constexpr float EMISSIVE_RADIANCE = 8.f; +static constexpr double TOLERANCE = 0.05; + +static bool equivalent(double actual, double reference) +{ + return std::isfinite(actual) && std::isfinite(reference) && actual > 0.0 + && reference > 0.0 + && std::abs(actual - reference) / reference <= TOLERANCE; +} // Emitter footprint: a small sphere centered above the origin, above frame. static constexpr vec3 SPHERE_CENTER = {0.f, 1.5f, 0.f}; static constexpr float SPHERE_RADIUS = 0.4f; -// Add a floor (large diffuse XZ quad at y=0) to the world. -static anari::Surface makeFloor(ANARIDevice device) -{ - const std::array pos = {vec3{-6.f, 0.f, -6.f}, - vec3{6.f, 0.f, -6.f}, - vec3{6.f, 0.f, 6.f}, - vec3{-6.f, 0.f, 6.f}}; - const std::array, 2> idx = { - std::array{0, 1, 2}, std::array{0, 2, 3}}; - - auto geom = anari::newObject(device, "triangle"); - anari::setParameterArray1D(device, geom, "vertex.position", pos.data(), 4); - anari::setParameterArray1D(device, geom, "primitive.index", idx.data(), 2); - anari::commitParameters(device, geom); - - auto mat = anari::newObject(device, "physicallyBased"); - anari::setParameter(device, mat, "baseColor", vec3{0.6f, 0.6f, 0.6f}); - anari::setParameter(device, mat, "metallic", 0.f); - anari::setParameter(device, mat, "roughness", 1.f); - anari::commitParameters(device, mat); - - auto surface = anari::newObject(device); - anari::setAndReleaseParameter(device, surface, "geometry", geom); - anari::setAndReleaseParameter(device, surface, "material", mat); - anari::commitParameters(device, surface); - return surface; -} - // Emissive sphere geometry at the emitter footprint. -static anari::Surface makeEmissiveSphere(ANARIDevice device) +static anari::Surface makeEmissiveSphere( + ANARIDevice device, int deviceInputs, bool indexed) { const std::array pos = {SPHERE_CENTER}; auto geom = anari::newObject(device, "sphere"); - anari::setParameterArray1D(device, geom, "vertex.position", pos.data(), 1); - anari::setParameter(device, geom, "radius", SPHERE_RADIUS); + if (indexed) { + const std::array positions = {vec3{0.f, 20.f, 0.f}, SPHERE_CENTER}; + const std::array radii = {0.01f, SPHERE_RADIUS}; + const std::array indices = {1}; + setTestArray(device, geom, "vertex.position", positions, deviceInputs & 1); + setTestArray(device, geom, "vertex.radius", radii, deviceInputs & 2); + setTestArray(device, geom, "primitive.index", indices, deviceInputs & 4); + anari::setParameter(device, geom, "radius", 0.01f); + } else { + anari::setParameterArray1D(device, geom, "vertex.position", pos.data(), 1); + anari::setParameter(device, geom, "radius", SPHERE_RADIUS); + } anari::commitParameters(device, geom); auto mat = anari::newObject(device, "physicallyBased"); @@ -149,17 +137,21 @@ static anari::Light makeSphereLight(ANARIDevice device) } // Render the floor lit by either the emissive sphere (useMesh) or the ANARI -// sphere light, and return the linear framebuffer. -static std::vector render(ANARIDevice device, bool useMesh) +// sphere light, measuring linear luminance without copying the framebuffer. +static double render(ANARIDevice device, + bool useMesh, + int deviceInputs = 0, + bool indexed = false) { - std::vector surfaces = {makeFloor(device)}; + std::vector surfaces = {visrtx::test::receiverFloor(device)}; std::vector lights; if (useMesh) - surfaces.push_back(makeEmissiveSphere(device)); + surfaces.push_back(makeEmissiveSphere(device, deviceInputs, indexed)); else lights.push_back(makeSphereLight(device)); auto world = anari::newObject(device); + const visrtx::test::ObjectOwner worldOwner(device, world); anari::setParameterArray1D( device, world, "surface", surfaces.data(), surfaces.size()); if (!lights.empty()) @@ -171,85 +163,45 @@ static std::vector render(ANARIDevice device, bool useMesh) anari::release(device, l); anari::commitParameters(device, world); - // Look across the floor toward +Z; the emitter at y=1.5 sits above the frame, - // so only its cast pool on the floor is visible. - auto camera = anari::newObject(device, "perspective"); - anari::setParameter(device, camera, "position", vec3{0.f, 0.5f, -3.f}); - anari::setParameter(device, camera, "direction", vec3{0.f, -0.15f, 1.f}); - anari::setParameter(device, camera, "up", vec3{0.f, 1.f, 0.f}); - anari::setParameter( - device, camera, "aspect", IMAGE_SIZE[0] / float(IMAGE_SIZE[1])); - anari::commitParameters(device, camera); - - auto renderer = anari::newObject(device, "quality"); - anari::setParameter(device, renderer, "background", vec4{0.f, 0.f, 0.f, 1.f}); - anari::setParameter(device, renderer, "ambientRadiance", 0.f); - anari::setParameter(device, renderer, "pixelSamples", PIXEL_SAMPLES); - anari::setParameter(device, renderer, "fireflyFilterMode", "none"); - anari::commitParameters(device, renderer); - - auto frame = anari::newObject(device); - anari::setParameter(device, frame, "size", IMAGE_SIZE); - anari::setParameter(device, frame, "channel.color", ANARI_FLOAT32_VEC4); - anari::setAndReleaseParameter(device, frame, "world", world); - anari::setAndReleaseParameter(device, frame, "camera", camera); - anari::setAndReleaseParameter(device, frame, "renderer", renderer); - anari::commitParameters(device, frame); - - anari::render(device, frame); - anari::wait(device, frame); - - auto fb = anari::map(device, frame, "channel.color"); - std::vector out(fb.data, fb.data + size_t(fb.width) * fb.height); - anari::unmap(device, frame, "channel.color"); - anari::release(device, frame); - return out; -} - -// Mean linear luminance over the lit floor region (lower-center of the frame, -// ANARI's bottom-left framebuffer origin). -static double poolMeanLuminance(const std::vector &fb) -{ - double sum = 0.0; - uint64_t n = 0; - for (uint32_t y = IMAGE_SIZE[1] / 8; y < IMAGE_SIZE[1] / 2; ++y) { - for (uint32_t x = 3 * IMAGE_SIZE[0] / 8; x < 5 * IMAGE_SIZE[0] / 8; ++x) { - const vec4 &p = fb[y * IMAGE_SIZE[0] + x]; - sum += 0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]; - ++n; - } - } - return n ? sum / double(n) : 0.0; + auto frame = visrtx::test::receiverFrame( + device, world, IMAGE_SIZE, "quality", PIXEL_SAMPLES); + const visrtx::test::ObjectOwner frameOwner(device, frame); + // Bottom-left origin; only the floor's cast pool, never the emitter. + return visrtx::test::receiverLuminance(device, + frame, + IMAGE_SIZE, + {3 * IMAGE_SIZE[0] / 8, + 5 * IMAGE_SIZE[0] / 8, + IMAGE_SIZE[1] / 8, + IMAGE_SIZE[1] / 2}); } int main() { - auto device = makeVisRTXDevice(statusFunc); - - const double mesh = poolMeanLuminance(render(device, true)); - const double light = poolMeanLuminance(render(device, false)); + auto device = makeVisRTXDevice(visrtx::test::exitOnErrorStatus); + + fprintf(stderr, "[case] sphere/reference\n"); + const double light = render(device, false); + bool ok = std::isfinite(light) && light > 0.0; + + const auto check = [&](const char *name, int deviceInputs, bool indexed) { + fprintf(stderr, "[case] sphere/%s\n", name); + const double mesh = render(device, true, deviceInputs, indexed); + // The unchanged 5% allowance covers MC noise at 512 spp. + const bool matches = equivalent(mesh, light); + printf("sphere/%s mesh=%f reference=%f relErr=%g tolerance=%g %s\n", + name, + mesh, + light, + std::abs(mesh - light) / light, + TOLERANCE, + matches ? "PASS" : "FAIL"); + ok = matches && ok; + }; + check("host-scalar-radius", 0, false); + for (const auto &residency : SPHERE_CASES) + check(residency.name, residency.deviceInputs, true); anari::release(device, device); - - const double relErr = - light > 0.0 ? std::abs(mesh - light) / light : (mesh > 0 ? 1.0 : 0.0); - printf("emissiveSphere=%f sphereLight=%f relErr=%f\n", mesh, light, relErr); - - // Both estimators must converge to the same floor irradiance. A generous 5% - // absorbs residual MC noise at 512 spp; a broken radiometry or double-count - // shifts it by far more. - if (mesh <= 0.0 || light <= 0.0) { - fprintf(stderr, "FAIL: floor pool unlit (mesh=%f light=%f)\n", mesh, light); - return 1; - } - constexpr double TOLERANCE = 0.05; - if (relErr > TOLERANCE) { - fprintf(stderr, - "FAIL: emissive sphere geometry light not equivalent to sphere light (relErr=%f > %f)\n", - relErr, - TOLERANCE); - return 1; - } - printf("emissive sphere geometry light equivalence passed\n"); - return 0; + return ok ? 0 : 1; } diff --git a/devices/rtx/apps/tests/api/TestFramePublicationRecovery.cpp b/devices/rtx/apps/tests/api/TestFramePublicationRecovery.cpp new file mode 100644 index 000000000..3e3fa43fc --- /dev/null +++ b/devices/rtx/apps/tests/api/TestFramePublicationRecovery.cpp @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +// Recoverable publication errors must not consume a checkerboard tile. ELF +// interposition requires the shared CUDA runtime, just like preparation tests. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using vec3 = std::array; +using vec4 = std::array; +bool failPublication = false; +int injections = 0; +int errors = 0; +int publicationErrors = 0; +std::atomic completions{0}; + +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + if (std::strstr(message, "GPU publication failure")) + ++publicationErrors; + std::fprintf(stderr, "%s\n", message); + } +} + +void complete(const void *, ANARIDevice, ANARIFrame) +{ + ++completions; +} + +bool run(bool checkerboard, bool reset) +{ + const int initialErrors = errors; + auto d = makeVisRTXDevice(status); + auto geometry = anari::newObject(d, "quad"); + const std::array vertices = { + vec3{-10, -10, 0}, vec3{10, -10, 0}, vec3{10, 10, 0}, vec3{-10, 10, 0}}; + anari::setParameterArray1D( + d, geometry, "vertex.position", vertices.data(), vertices.size()); + anari::setParameter(d, geometry, "color", vec4{0.8f, 0.4f, 0.2f, 1.f}); + anari::commitParameters(d, geometry); + auto material = anari::newObject(d, "matte"); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setAndReleaseParameter(d, surface, "geometry", geometry); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto world = anari::newObject(d); + anari::setParameterArray1D(d, world, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, world); + auto camera = anari::newObject(d, "orthographic"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + // Debug is deterministic and has a finite sample limit of one. Orthographic + // rays make facing modulation constant, so every tile must match exactly. + auto renderer = anari::newObject(d, "debug"); + anari::setParameter(d, renderer, "method", "geometry.color"); + anari::setParameter(d, renderer, "checkerboarding", checkerboard); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{8, 8}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, frame, "world", world); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::setParameter(d, frame, "accumulationVersion", uint64_t(1)); + ANARIFrameCompletionCallback callback = complete; + anari::setParameter(d, + frame, + "frameCompletionCallback", + ANARI_FRAME_COMPLETION_CALLBACK, + &callback); + anari::commitParameters(d, frame); + auto render = [&] { + anari::render(d, frame); + anari::wait(d, frame); + }; + auto samples = [&] { + int n = -1; + anariGetProperty( + d, frame, "numSamples", ANARI_INT32, &n, sizeof(n), ANARI_WAIT); + return n; + }; + auto pixels = [&] { + auto fb = anari::map(d, frame, "channel.color"); + std::vector result; + if (fb.data) + result.assign(fb.data, fb.data + 64); + anari::unmap(d, frame, "channel.color"); + return result; + }; + const int tiles = checkerboard ? 4 : 1; + // Resolve the frame's initial reset before the manual-version reset, then + // obtain a complete reference cycle (extra calls stop at the sample limit). + render(); + for (int i = 0; i < tiles; ++i) + render(); + const auto reference = pixels(); + bool ok = samples() == 1 && reference.size() == 64 && errors == initialErrors; + for (const auto &pixel : reference) + ok = pixel[0] > 0.7f && pixel[1] > 0.3f && ok; + if (!ok) + std::fprintf(stderr, + "reference failed: samples=%d pixels=%zu errors=%d\n", + samples(), + reference.size(), + errors - initialErrors); + + anari::setParameter(d, frame, "accumulationVersion", uint64_t(2)); + anari::commitParameters(d, frame); + if (!reset) + render(); // Start a checkerboard cycle, then reject its second tile. + const int before = completions; + const int beforeInjections = injections; + const int beforePublicationErrors = publicationErrors; + failPublication = true; + render(); + ok = injections == beforeInjections + 1 + && publicationErrors == beforePublicationErrors + 1 + && errors == initialErrors + 1 && completions == before && samples() == 0 + && ok; + // No recommit: recovery must restart every tile, not skip the rejected one. + for (int i = 0; i < tiles; ++i) { + render(); + const bool stepOk = + completions == before + i + 1 && samples() == (i + 1 == tiles ? 1 : 0); + if (!stepOk) + std::fprintf(stderr, + "retry %d: completions=%d samples=%d\n", + i, + int(completions) - before, + samples()); + ok = stepOk && ok; + } + const auto recovered = pixels(); + ok = recovered.size() == reference.size() && ok; + if (recovered.size() == reference.size()) + for (size_t i = 0; i < reference.size(); ++i) + for (int c = 0; c < 4; ++c) + ok = std::isfinite(recovered[i][c]) + && std::abs(recovered[i][c] - reference[i][c]) < 1e-5f && ok; + if (!ok) + std::fprintf(stderr, "recovery failed before sample-limit check\n"); + render(); // The finite sample limit must suppress only this extra call. + ok = completions == before + tiles && samples() == 1 + && errors == initialErrors + 1 && ok; + anari::release(d, frame); + anari::release(d, d); + std::printf("publication recovery checkerboard=%d reset=%d %s\n", + checkerboard, + reset, + ok ? "PASS" : "FAIL"); + return ok; +} +} // namespace + +extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) +{ + auto real = reinterpret_cast( + dlsym(RTLD_NEXT, "cudaStreamSynchronize")); + if (!real) + std::abort(); + const auto error = real(stream); + if (!stream && failPublication) { + failPublication = false; + ++injections; + return cudaErrorUnknown; + } + return error; +} + +int main() +{ + bool ok = run(true, false); + ok = run(true, true) && ok; + ok = run(false, true) && ok; + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestGeneratedTangents.cpp b/devices/rtx/apps/tests/api/TestGeneratedTangents.cpp index 28ff414c9..337cd841c 100644 --- a/devices/rtx/apps/tests/api/TestGeneratedTangents.cpp +++ b/devices/rtx/apps/tests/api/TestGeneratedTangents.cpp @@ -53,6 +53,9 @@ #include #include #include +#include "DeviceTestArray.h" + +static bool deviceInputs = false; using uvec2 = std::array; using uvec3 = std::array; @@ -69,11 +72,10 @@ static void statusFunc(const void *, ANARIStatusCode, const char *message) { - if (severity == ANARI_SEVERITY_FATAL_ERROR) { - fprintf(stderr, "[FATAL][%p] %s\n", source, message); - std::exit(1); - } else if (severity == ANARI_SEVERITY_ERROR) + if (severity <= ANARI_SEVERITY_ERROR) { fprintf(stderr, "[ERROR][%p] %s\n", source, message); + std::exit(1); + } } static constexpr uvec2 IMAGE_SIZE = {256, 256}; @@ -200,13 +202,10 @@ static anari::Geometry makeQuads(ANARIDevice device, Frame frame) } auto geom = anari::newObject(device, "quad"); - anari::setParameterArray1D( - device, geom, "vertex.position", pos.data(), pos.size()); - anari::setParameterArray1D( - device, geom, "primitive.index", idx.data(), idx.size()); + setTestArray(device, geom, "vertex.position", pos, deviceInputs); + setTestArray(device, geom, "primitive.index", idx, deviceInputs); anari::setParameterArray1D(device, geom, "vertex.normal", n.data(), n.size()); - anari::setParameterArray1D( - device, geom, "vertex.attribute0", uv.data(), uv.size()); + setTestArray(device, geom, "vertex.attribute0", uv, deviceInputs); if (frame == Frame::AUTHORED || frame == Frame::ROTATED) anari::setParameterArray1D( device, geom, "vertex.tangent", t.data(), t.size()); @@ -320,8 +319,9 @@ static double maxTileRelErr( return worst; } -int main() +int main(int argc, char **) { + deviceInputs = argc > 1; auto device = makeVisRTXDevice(statusFunc); const std::array subtypes = {"physicallyBased", diff --git a/devices/rtx/apps/tests/api/TestGeometryAreaCDF.cpp b/devices/rtx/apps/tests/api/TestGeometryAreaCDF.cpp new file mode 100644 index 000000000..35ae9021f --- /dev/null +++ b/devices/rtx/apps/tests/api/TestGeometryAreaCDF.cpp @@ -0,0 +1,345 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" +#include "geometry/Geometry.h" + +namespace { +using vec3 = std::array; +using uvec2 = std::array; +using uvec3 = std::array; +int errors = 0; +std::atomic completions{0}; +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + std::fprintf(stderr, "%s\n", message); + } +} +void complete(const void *, ANARIDevice, ANARIFrame) +{ + ++completions; +} + +struct Case +{ + std::string type; + size_t count; + bool indexed; + bool device; + anari::Geometry geometry; + std::vector areas; +}; + +float weight(size_t i, int generation) +{ + if (generation == 1) + return 0.f; + // Put zeros on both sides of warp and small/general boundaries, then move + // them on the recovery generation. Sharp positive weights also cross warps. + const bool zero = generation == 0 ? (i == 0 || i == 30 || i == 31 || i == 32 + || i == 254 || i == 255 || i == 256) + : (i % 13 == 0); + if (zero) + return 0.f; + const float value = float((17 * i + 3 + generation) % 23 + 1) / 8.f; + return (i == 29 || i == 33 || i == 253 || i == 255) ? 16.f * value : value; +} + +void author(anari::Device d, Case &c, int generation) +{ + std::vector vertices; + std::vector radii; + std::vector caps; + std::vector sphereIndices; + std::vector segmentIndices; + std::vector triangleIndices; + const auto n = c.count; + for (size_t i = 0; i < n; ++i) { + const float x = 100.f * i; + const float w = weight(i, generation); + const float length = float(i % 5 + 1) / 2.f; + if (c.type == "triangle") { + // Independent closed form: base 2*w, height 1, hence area w. + vertices.push_back({x, 0, 0}); + vertices.push_back({x + 2.f * w, 0, 0}); + vertices.push_back({x, 1, 0}); + } else if (c.type == "sphere") { + vertices.push_back({x, 0, 0}); + radii.push_back(w); + } else { + vertices.push_back({x, 0, 0}); + vertices.push_back({x, length, 0}); + caps.push_back(i % 3 == 0); + caps.push_back(i % 5 == 0); + if (c.type == "cone") { + radii.push_back(w / 2.f); + radii.push_back(w); + } else + radii.push_back(w); // Cylinder radius is per primitive, not per vertex. + } + const uint32_t source = uint32_t(c.indexed ? n - 1 - i : i); + sphereIndices.push_back(source); + segmentIndices.push_back({2 * source, 2 * source + 1}); + triangleIndices.push_back({3 * source, 3 * source + 1, 3 * source + 2}); + } + // Use independent analytic areas in double precision, not the production + // primitiveArea helper, scan implementation or published total as an oracle. + const double pi = std::acos(-1.0); + c.areas.clear(); + for (size_t i = 0; i < n; ++i) { + const size_t source = c.indexed ? n - 1 - i : i; + const double w = weight(source, generation); + const double length = double(source % 5 + 1) / 2.0; + double area = 0; + if (c.type == "triangle") + area = w; + else if (c.type == "sphere") + area = 4.0 * pi * w * w; + else { + const double r0 = c.type == "cone" ? w / 2.0 : weight(i, generation); + const double r1 = c.type == "cone" ? w : r0; + area = c.type == "cone" + ? pi * (r0 + r1) * std::sqrt(length * length + (r0 - r1) * (r0 - r1)) + : 2.0 * pi * r0 * length; + if (source % 3 == 0) + area += pi * r0 * r0; + if (source % 5 == 0) + area += pi * r1 * r1; + } + c.areas.push_back(area); + } + setTestArray(d, c.geometry, "vertex.position", vertices, c.device, 1); + if (c.type != "triangle") + setTestArray(d, + c.geometry, + c.type == "cylinder" ? "primitive.radius" : "vertex.radius", + radii, + c.device, + 1); + if (!caps.empty()) + setTestArray(d, c.geometry, "vertex.cap", caps, c.device, 1); + if (c.indexed) { + if (c.type == "triangle") + setTestArray( + d, c.geometry, "primitive.index", triangleIndices, c.device, 1); + else if (c.type == "sphere") + setTestArray( + d, c.geometry, "primitive.index", sphereIndices, c.device, 1); + else + setTestArray( + d, c.geometry, "primitive.index", segmentIndices, c.device, 1); + } + anari::commitParameters(d, c.geometry); +} + +bool checkPublished(const Case &c, int generation) +{ + // Native VisRTX handles are Geometry pointers. Inspect the actual published + // GPU record only after a completed frame. This internal test is compiled + // with the device's layout definitions (not a new public ANARI property). + auto *geometry = reinterpret_cast(c.geometry); + auto *state = static_cast( + geometry->helium::BaseObject::deviceState()); + const auto *registry = state->registry.geometries.devicePtr(); + visrtx::GeometryGPUData data{}; + if (!registry + || cudaMemcpy(&data, + registry + geometry->index(), + sizeof(data), + cudaMemcpyDeviceToHost) + != cudaSuccess) + return false; + const float *cdf = nullptr; + uint32_t count = 0; + float total = -1; + auto sampling = [&](const auto &record) { + cdf = record.primAreaCdf; + count = record.numPrimitives; + total = record.totalArea; + }; + if (c.type == "triangle" && data.type == visrtx::GeometryType::TRIANGLE) + sampling(data.tri); + else if (c.type == "sphere" && data.type == visrtx::GeometryType::SPHERE) + sampling(data.sphere); + else if (c.type == "cone" && data.type == visrtx::GeometryType::CONE) + sampling(data.cone); + else if (c.type == "cylinder" && data.type == visrtx::GeometryType::CYLINDER) + sampling(data.cylinder); + else + return false; + const double expectedTotal = + std::accumulate(c.areas.begin(), c.areas.end(), 0.0); + bool ok = std::isfinite(total); + if (expectedTotal == 0) + ok = total == 0.f && count == 0 && !cdf && ok; + else { + ok = cdf && count == c.count + && std::abs(double(total) - expectedTotal) <= 2e-6 * expectedTotal + && ok; + if (!cdf || count != c.count) + return false; + std::vector values(count); + if (cudaMemcpy( + values.data(), cdf, count * sizeof(float), cudaMemcpyDeviceToHost) + != cudaSuccess) + return false; + double prefix = 0; + float previous = 0; + for (size_t i = 0; i < count; ++i) { + prefix += c.areas[i]; + const double expected = prefix / expectedTotal; + const bool entryOk = std::isfinite(values[i]) && values[i] >= previous + && values[i] >= 0.f && values[i] <= 1.f + && std::abs(double(values[i]) - expected) <= 2e-6 + && (c.areas[i] != 0 || std::abs(values[i] - previous) <= 2e-6f); + if (!entryOk) { + std::fprintf(stderr, + "%s n=%zu indexed=%d device=%d gen=%d bin=%zu actual=%.9g expected=%.9g\n", + c.type.c_str(), + c.count, + c.indexed, + c.device, + generation, + i, + values[i], + expected); + ok = false; + break; + } + previous = values[i]; + } + ok = values.back() == 1.f && ok; + } + if (!ok) + std::fprintf(stderr, + "%s n=%zu indexed=%d device=%d gen=%d total=%.9g expected=%.9g\n", + c.type.c_str(), + c.count, + c.indexed, + c.device, + generation, + total, + expectedTotal); + return ok; +} +} // namespace + +int main() +{ + auto d = makeVisRTXDevice(status); + auto material = anari::newObject(d, "physicallyBased"); + anari::setParameter(d, material, "emissive", vec3{1, 1, 1}); + anari::commitParameters(d, material); + std::vector cases; + std::vector surfaces; + constexpr size_t boundary = visrtx::SmallGeometryBatch::MAX_PRIMITIVES; + for (const char *type : {"triangle", "sphere", "cone", "cylinder"}) + for (size_t n : {size_t(31), + size_t(32), + size_t(33), + boundary - 1, + boundary, + boundary + 1}) + for (bool indexed : {false, true}) + for (bool device : {false, true}) { + auto g = anari::newObject(d, type); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", g); + anari::setParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + surfaces.push_back(surface); + cases.push_back({type, n, indexed, device, g, {}}); + } + anari::release(d, material); + auto world = anari::newObject(d); + anari::setParameterArray1D( + d, world, "surface", surfaces.data(), surfaces.size()); + anari::commitParameters(d, world); + for (auto surface : surfaces) + anari::release(d, surface); + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -100}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "debug"); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{2, 2}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::setAndReleaseParameter(d, frame, "world", world); + ANARIFrameCompletionCallback callback = complete; + anari::setParameter(d, + frame, + "frameCompletionCallback", + ANARI_FRAME_COMPLETION_CALLBACK, + &callback); + anari::commitParameters(d, frame); + bool ok = true; + for (int generation = 0; generation < 3; ++generation) { + for (auto &c : cases) + author(d, c, generation); + anari::render(d, frame); + anari::wait(d, frame); + if (errors || completions != generation + 1) { + ok = false; + break; + } + for (const auto &c : cases) + ok = checkPublished(c, generation) && ok; + } + anari::release(d, frame); + for (const auto &c : cases) + anari::release(d, c.geometry); + anari::release(d, d); + ok = errors == 0 && ok; + std::printf("weighted geometry CDF: %zu cases x 3 generations %s\n", + cases.size(), + ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp b/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp new file mode 100644 index 000000000..11807ce7d --- /dev/null +++ b/devices/rtx/apps/tests/api/TestGeometryInputBatch.cpp @@ -0,0 +1,347 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using vec3 = std::array; +anari::Device device = nullptr; +ANARIArray retireArray = nullptr; +void **retireSource = nullptr; +void *sourceA = nullptr; +void *sourceB = nullptr; +const void *trackedA = nullptr; +const void *replacementSource = nullptr; +void *deviceA = nullptr; +bool watchReplacement = false; +bool oldDeviceFreed = false; +bool replacementAllocated = false; +bool cohortCompleted = false; +bool replacementReused = false; +bool failCohort = false; +cudaStream_t preparationStream = nullptr; +int copies = 0; +int firstSyncCopies = -1; +int preparationSyncs = 0; +int errors = 0; +bool wrongStream = false; +bool retireNext = false; +bool retired = false; + +template +T next(const char *name) +{ + auto function = reinterpret_cast(dlsym(RTLD_NEXT, name)); + if (!function) + std::abort(); + return function; +} + +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + std::fprintf(stderr, "%s\n", message); + } +} + +bool trackedSource(const void *src) +{ + return src && (src == trackedA || src == sourceB || src == replacementSource); +} + +void resetCounts() +{ + copies = 0; + firstSyncCopies = -1; + preparationSyncs = 0; + wrongStream = false; +} +} // namespace + +extern "C" cudaError_t cudaStreamCreateWithFlags( + cudaStream_t *stream, unsigned flags) +{ + const auto error = next( + "cudaStreamCreateWithFlags")(stream, flags); + if (error == cudaSuccess && (flags & cudaStreamNonBlocking)) + preparationStream = *stream; + return error; +} + +extern "C" cudaError_t cudaMalloc(void **ptr, size_t bytes) +{ + if (watchReplacement && bytes == sizeof(vec3)) + replacementAllocated = true; + return next("cudaMalloc")(ptr, bytes); +} + +extern "C" cudaError_t cudaFree(void *ptr) +{ + const auto error = next("cudaFree")(ptr); + if (error == cudaSuccess && watchReplacement && ptr == deviceA) + oldDeviceFreed = true; + return error; +} + +extern "C" cudaError_t cudaDeviceSynchronize() +{ + const auto error = + next("cudaDeviceSynchronize")(); + if (failCohort) { + failCohort = false; + return cudaErrorUnknown; + } + if (watchReplacement && error == cudaSuccess) + cohortCompleted = true; + return error; +} + +extern "C" cudaError_t cudaMemcpy( + void *dst, const void *src, size_t bytes, cudaMemcpyKind kind) +{ + if (kind == cudaMemcpyHostToDevice && trackedSource(src)) { + ++copies; + wrongStream = true; + } + return next("cudaMemcpy")(dst, src, bytes, kind); +} + +extern "C" cudaError_t cudaMemcpyAsync(void *dst, + const void *src, + size_t bytes, + cudaMemcpyKind kind, + cudaStream_t stream) +{ + const bool tracked = kind == cudaMemcpyHostToDevice && trackedSource(src); + if (kind == cudaMemcpyHostToDevice && src == trackedA) + deviceA = dst; + if (watchReplacement && src == replacementSource + && kind == cudaMemcpyHostToDevice) + replacementReused = dst == deviceA && cohortCompleted; + if (tracked) { + ++copies; + wrongStream |= stream != preparationStream; + } + const auto error = next("cudaMemcpyAsync")( + dst, src, bytes, kind, stream); + if (error == cudaSuccess && tracked && retireNext && src == *retireSource) { + retireNext = false; + // Reenter from the host submission path, not from a CUDA host callback. + // Public release must wait before the application frees a pinned source. + const int beforeRelease = preparationSyncs; + anariRelease(device, retireArray); + if (preparationSyncs == beforeRelease) { + ++errors; + std::fprintf(stderr, "host release omitted pending upload wait\n"); + } + retireArray = nullptr; + if (cudaFreeHost(*retireSource) != cudaSuccess) + ++errors; + *retireSource = nullptr; + retired = true; + } + return error; +} + +extern "C" cudaError_t cudaStreamSynchronize(cudaStream_t stream) +{ + if (stream == preparationStream) + ++preparationSyncs; + if (stream == preparationStream && copies && firstSyncCopies < 0) + firstSyncCopies = copies; + return next("cudaStreamSynchronize")( + stream); +} + +int main() +{ + device = makeVisRTXDevice(status); + if (cudaMallocHost(&sourceA, sizeof(vec3)) != cudaSuccess + || cudaMallocHost(&sourceB, sizeof(vec3)) != cudaSuccess) + return 1; + trackedA = sourceA; + *static_cast(sourceA) = {0, 0, 0}; + *static_cast(sourceB) = {2, 0, 0}; + auto a = + anariNewArray1D(device, sourceA, nullptr, nullptr, ANARI_FLOAT32_VEC3, 1); + auto b = + anariNewArray1D(device, sourceB, nullptr, nullptr, ANARI_FLOAT32_VEC3, 1); + auto material = anari::newObject(device, "matte"); + anari::commitParameters(device, material); + std::array geometries; + std::array surfaces; + for (size_t i = 0; i < geometries.size(); ++i) { + auto g = anari::newObject(device, "sphere"); + auto array = i == 1 ? b : a; + anariSetParameter(device, g, "vertex.position", ANARI_ARRAY1D, &array); + anari::setParameter(device, g, "radius", 0.25f); + anari::commitParameters(device, g); + geometries[i] = g; + auto s = anari::newObject(device); + anari::setParameter(device, s, "geometry", g); + anari::setParameter(device, s, "material", material); + anari::commitParameters(device, s); + surfaces[i] = s; + } + anari::release(device, material); + auto world = anari::newObject(device); + anari::setParameterArray1D( + device, world, "surface", surfaces.data(), surfaces.size()); + anari::commitParameters(device, world); + for (auto surface : surfaces) + anari::release(device, surface); + auto bounds = [&](float lo, float hi) { + std::array result{}; + return anariGetProperty(device, + world, + "bounds", + ANARI_FLOAT32_BOX3, + result.data(), + sizeof(result), + ANARI_WAIT) + && std::fabs(result[0] - lo) < 1e-4f + && std::fabs(result[3] - hi) < 1e-4f; + }; + auto commitGeometryWideAttributes = [&](float value) { + for (auto geometry : geometries) { + anari::setParameter( + device, geometry, "attribute0", std::array{value, 0, 0, 1}); + anari::commitParameters(device, geometry); + } + }; + auto change = [&](ANARIArray array, float x) { + auto *mapped = static_cast(anariMapArray(device, array)); + if (!mapped) + std::abort(); + *mapped = {x, 0, 0}; + anariUnmapArray(device, array); + }; + resetCounts(); + bool ok = bounds(-0.25f, 2.25f) && copies == 2 && firstSyncCopies == 2 + && !wrongStream; + resetCounts(); + commitGeometryWideAttributes(1.f); + ok = bounds(-0.25f, 2.25f) && copies == 0 && ok; + resetCounts(); + change(a, 1.f); // Observer-only fallback still uploads once for shared input. + ok = bounds(0.75f, 2.25f) && copies == 1 && !wrongStream && ok; + resetCounts(); + change(a, -1.f); + change(b, 3.f); + commitGeometryWideAttributes(2.f); + ok = bounds(-1.25f, 3.25f) && copies == 2 && firstSyncCopies == 2 + && !wrongStream && ok; + // Replacement must retire the obsolete snapshot cohort, then reuse its + // certified backend storage rather than allocating a second resident cohort. + void *replacement = nullptr; + if (cudaMallocHost(&replacement, sizeof(vec3)) != cudaSuccess) + return 1; + *static_cast(replacement) = {-1, 0, 0}; + replacementSource = replacement; + auto c = anariNewArray1D( + device, replacement, nullptr, nullptr, ANARI_FLOAT32_VEC3, 1); + auto replaceShared = [&](ANARIArray array) { + for (size_t i = 0; i < geometries.size(); ++i) { + if (i == 1) + continue; + anariSetParameter( + device, geometries[i], "vertex.position", ANARI_ARRAY1D, &array); + anari::commitParameters(device, geometries[i]); + } + }; + watchReplacement = true; + replaceShared(c); + ok = bounds(-1.25f, 3.25f) && replacementReused && !oldDeviceFreed + && !replacementAllocated && ok; + watchReplacement = false; + replaceShared(a); + ok = bounds(-1.25f, 3.25f) && ok; + // A failed shared retirement boundary cannot publish or reuse the cohort. + // Recommit the failed inputs to retry once the completion error is gone. + const int beforeFailureCopies = copies; + failCohort = true; + replaceShared(c); + ok = !bounds(-1.25f, 3.25f) && !failCohort && errors == 1 + && copies == beforeFailureCopies && ok; + commitGeometryWideAttributes(4.f); + ok = bounds(-1.25f, 3.25f) && errors == 1 && ok; + replaceShared(a); + ok = bounds(-1.25f, 3.25f) && ok; + anariRelease(device, c); + cudaFreeHost(replacement); + replacementSource = nullptr; + // An observer-only update has no commit to capture it: its geometry's + // finalizer uploads it. A release from inside that copy must wait too. + resetCounts(); + change(b, 4.f); + retireArray = b; + retireSource = &sourceB; + retireNext = true; + ok = bounds(-1.25f, 4.25f) && retired && copies == 1 && !wrongStream && ok; + retired = false; + resetCounts(); + change(a, -2.f); + commitGeometryWideAttributes(3.f); + retireArray = a; + retireSource = &sourceA; + retireNext = true; + ok = bounds(-2.25f, 4.25f) && retired && copies == 1 && !wrongStream && ok; + anari::release(device, world); + for (auto geometry : geometries) + anari::release(device, geometry); + if (sourceA) { + anariRelease(device, a); + cudaFreeHost(sourceA); + } + if (sourceB) { + anariRelease(device, b); + cudaFreeHost(sourceB); + } + anari::release(device, device); + ok = errors == 1 && ok; + std::printf("geometry input batches: %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestGeometryPreparationReuse.cpp b/devices/rtx/apps/tests/api/TestGeometryPreparationReuse.cpp new file mode 100644 index 000000000..46ebaa8c0 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestGeometryPreparationReuse.cpp @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using vec3 = std::array; +using vec4 = std::array; +static int errors = 0, preparations = 0, builds = 0; +static void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType type, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + fprintf(stderr, "%s\n", message); + } + // Diagnostic counts verify that metadata publication does not silently run + // the expensive path. Images/bounds independently verify observable results. + if (type == ANARI_GEOMETRY && std::strstr(message, "finalizing ")) + ++preparations; + if (std::strstr(message, "visrtx::Group building ") + || std::strstr(message, "visrtx::World building surface BVH")) + ++builds; +} + +static bool run(ANARIDevice d, const std::string &type, bool device) +{ + auto geometry = anari::newObject(d, type.c_str()); + std::vector positions; + if (type == "triangle") + positions = {{-1, -1, 0}, {1, -1, 0}, {0, 1, 0}}; + else if (type == "quad") + positions = {{-1, -1, 0}, {1, -1, 0}, {1, 1, 0}, {-1, 1, 0}}; + else if (type == "sphere") + positions = {{0, 0, 0}}; + else + positions = {{-0.5f, 0, 0}, {0.5f, 0, 0}}; + const bool sdf = type == "sdf"; + const size_t count = sdf ? 72 : positions.size(); + const auto elementType = sdf ? ANARI_UINT8 : ANARI_FLOAT32_VEC3; + const size_t bytes = sdf ? count : count * sizeof(vec3); + std::vector inputs(2 * bytes); + if (sdf) { + const float radius = 0.5f; + std::memcpy(inputs.data() + 44, &radius, sizeof(radius)); + std::memcpy(inputs.data() + 48, &radius, sizeof(radius)); + std::memcpy(inputs.data() + bytes, inputs.data(), bytes); + const float shift = 2.f; + std::memcpy(inputs.data() + bytes + 20, &shift, sizeof(shift)); + } else { + std::memcpy(inputs.data(), positions.data(), bytes); + for (auto &v : positions) + v[0] += 2.f; + std::memcpy(inputs.data() + bytes, positions.data(), bytes); + } + void *external = nullptr; + anari::Array1D array; + if (device) { + if (cudaMalloc(&external, inputs.size()) != cudaSuccess + || cudaMemcpy( + external, inputs.data(), inputs.size(), cudaMemcpyHostToDevice) + != cudaSuccess) + return false; + array = + anariNewArray1D(d, external, nullptr, nullptr, elementType, 2 * count); + } else { + array = anari::newArray1D(d, elementType, 2 * count); + std::memcpy(anariMapArray(d, array), inputs.data(), inputs.size()); + anariUnmapArray(d, array); + } + anari::setParameter(d, array, "end", uint64_t(count)); + anari::commitParameters(d, array); + const char *inputName = sdf ? "primitive.sdf" : "vertex.position"; + anari::setParameter(d, geometry, inputName, array); + anari::setParameter(d, geometry, "radius", 0.25f); + if (type == "cone") { + const std::array radii = {0.25f, 0.25f}; + anari::setParameterArray1D(d, geometry, "vertex.radius", radii.data(), 2); + } + anari::setParameter(d, geometry, "attribute0", vec4{0.2f, 0.4f, 0.8f, 1}); + anari::commitParameters(d, geometry); + auto material = anari::newObject(d, "physicallyBased"); + // Area-samplable types prepare their CDF as well as bounds on first use. + anari::setParameter(d, material, "emissive", vec3{1, 1, 1}); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", geometry); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto world = anari::newObject(d); + anari::setParameterArray1D(d, world, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, world); + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "debug"); + anari::setParameter(d, renderer, "method", "geometry.attribute0"); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{32, 32}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setParameter(d, frame, "world", world); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setParameter(d, frame, "renderer", renderer); + anari::commitParameters(d, frame); + auto render = [&]() { + anari::render(d, frame); + anari::wait(d, frame); + auto fb = anari::map(d, frame, "channel.color"); + vec3 result{}; + if (!fb.data) { + ++errors; + return result; + } + const auto pixel = fb.data[16 * 32 + 16]; + for (int i = 0; i < 3; ++i) + result[i] = pixel[i]; + anari::unmap(d, frame, "channel.color"); + return result; + }; + auto bounds = [&]() { + std::array result{}; + if (!anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + result.data(), + sizeof(result), + ANARI_WAIT)) + ++errors; + return result; + }; + auto close = [](vec3 actual, vec3 expected) { + for (int i = 0; i < 3; ++i) + if (!std::isfinite(actual[i]) + || std::abs(actual[i] - expected[i]) > 1e-4f) + return false; + return true; + }; + // Debug output includes geometric facing modulation. Obtain its reference + // from initial full preparation, then require identical + // preparation-preserving output. + const auto reference = render(); + const auto originalBounds = bounds(); + bool ok = errors == 0 && reference[0] > 0.1f && reference[2] > 0.6f; + anari::unsetParameter(d, geometry, "attribute0"); + anari::commitParameters(d, geometry); + ok = close(render(), {0, 0, 0}) && ok; + for (const char *attribute : + {"attribute0", "attribute1", "attribute2", "attribute3", "color"}) { + const std::string method = std::string("geometry.") + attribute; + anari::setParameter(d, renderer, "method", method.c_str()); + anari::commitParameters(d, renderer); + const int beforePrep = preparations, beforeBuild = builds; + anari::setParameter(d, geometry, attribute, vec4{0.2f, 0.4f, 0.8f, 1}); + anari::commitParameters(d, geometry); + // Staging a geometric edit after commit must not leak into its snapshot. + anari::unsetParameter(d, geometry, inputName); + const auto actual = render(); + const bool setOk = close(actual, reference) && bounds() == originalBounds + && preparations == beforePrep && builds == beforeBuild; + if (!setOk) + fprintf(stderr, + "%s %s set pixel=%g,%g,%g prep=%d build=%d\n", + type.c_str(), + attribute, + actual[0], + actual[1], + actual[2], + preparations - beforePrep, + builds - beforeBuild); + ok = setOk && ok; + anari::setParameter(d, geometry, inputName, array); + anari::unsetParameter(d, geometry, attribute); + anari::commitParameters(d, geometry); + const auto unset = render(); + const bool unsetOk = close(unset, {0, 0, 0}) && preparations == beforePrep + && builds == beforeBuild; + if (!unsetOk) + fprintf(stderr, + "%s %s unset pixel=%g,%g,%g prep=%d build=%d\n", + type.c_str(), + attribute, + unset[0], + unset[1], + unset[2], + preparations - beforePrep, + builds - beforeBuild); + ok = unsetOk && ok; + } + { + // Scalar/string parameters are part of the preparation identity too. + const int beforePrep = preparations, beforeBuild = builds; + const bool round = + type == "sphere" || type == "curve" || type == "cylinder"; + auto change = [&](bool changed) { + if (round) + anari::setParameter(d, geometry, "radius", changed ? 0.35f : 0.25f); + else if (type == "cone") + anari::setParameter(d, geometry, "caps", changed ? "both" : "none"); + else if (sdf) + anari::setParameter(d, geometry, "epsilon", changed ? 1e-4f : 1e-5f); + else + anari::setParameter(d, geometry, "cullBackfaces", changed); + anari::commitParameters(d, geometry); + }; + change(true); + const auto changedBounds = bounds(); + ok = preparations > beforePrep && builds > beforeBuild && ok; + if (round) + ok = changedBounds[0] < originalBounds[0] - 0.05f + && changedBounds[3] > originalBounds[3] + 0.05f && ok; + change(false); + const auto restored = bounds(); + for (int i = 0; i < 6; ++i) + ok = std::isfinite(restored[i]) + && std::abs(restored[i] - originalBounds[i]) < 1e-4f && ok; + } + if (!device) { + // An in-place unmap changes values without changing the handle or GPU + // address. Coalescing it with a geometry-wide attribute commit must still + // prepare. + const int beforePrep = preparations, beforeBuild = builds; + auto *mapped = static_cast(anariMapArray(d, array)); + if (sdf) { + const float shift = 0.25f; + std::memcpy(mapped + 20, &shift, sizeof(shift)); + } else { + for (size_t i = 0; i < count; ++i) { + vec3 position; + std::memcpy(position.data(), mapped + i * sizeof(vec3), sizeof(vec3)); + position[0] += 0.25f; + std::memcpy(mapped + i * sizeof(vec3), position.data(), sizeof(vec3)); + } + } + anariUnmapArray(d, array); + anari::setParameter(d, geometry, "attribute0", vec4{0.1f, 0.2f, 0.3f, 1}); + anari::commitParameters(d, geometry); + const auto moved = bounds(); + ok = preparations > beforePrep && builds > beforeBuild && ok; + for (int i = 0; i < 6; ++i) + ok = std::isfinite(moved[i]) + && std::abs(moved[i] - originalBounds[i] - (i % 3 == 0 ? 0.25f : 0.f)) + < 1e-4f + && ok; + std::memcpy(anariMapArray(d, array), inputs.data(), inputs.size()); + anariUnmapArray(d, array); + anari::setParameter(d, geometry, "attribute0", vec4{0, 0, 0, 1}); + anari::commitParameters(d, geometry); + ok = bounds() == originalBounds && ok; + } + // Coalesced range and geometry-wide attribute commits must prepare the new + // logical input. + int beforePrep = preparations, beforeBuild = builds; + anari::setParameter(d, array, "begin", uint64_t(count)); + anari::setParameter(d, array, "end", uint64_t(2 * count)); + anari::commitParameters(d, array); + anari::setParameter(d, geometry, "attribute0", vec4{1, 0, 0, 1}); + anari::commitParameters(d, geometry); + const auto shifted = bounds(); + ok = preparations > beforePrep && builds > beforeBuild && ok; + for (int i = 0; i < 6; ++i) + ok = std::isfinite(shifted[i]) + && std::abs(shifted[i] - originalBounds[i] - (i % 3 == 0 ? 2.f : 0.f)) + < 1e-4f + && ok; + // Last-public release changes backing pointers, but not values or ranges. + // Coalesce it with a geometry-wide attribute commit to exercise pointer-only + // invalidation. + beforePrep = preparations; + beforeBuild = builds; + anari::release(d, array); + if (external) + cudaFree(external); + anari::setParameter(d, geometry, "attribute0", vec4{0, 1, 0, 1}); + anari::commitParameters(d, geometry); + ok = bounds() == shifted && ok; + if (device) + ok = preparations > beforePrep && builds > beforeBuild && ok; + render(); + ok = errors == 0 && ok; + printf("preparation-preserving updates %s device=%d %s\n", + type.c_str(), + device, + ok ? "PASS" : "FAIL"); + anari::release(d, frame); + anari::release(d, renderer); + anari::release(d, world); + anari::release(d, geometry); + return ok; +} + +int main() +{ + auto d = makeVisRTXDevice(status); + bool ok = true; + for (const char *type : + {"triangle", "quad", "sphere", "curve", "cone", "cylinder", "sdf"}) + for (bool device : {false, true}) + ok = run(d, type, device) && ok; + anari::release(d, d); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp b/devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp new file mode 100644 index 000000000..9f3cab41b --- /dev/null +++ b/devices/rtx/apps/tests/api/TestGeometryPreprocessingFailure.cpp @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" + +using vec3 = std::array; +using vec4 = std::array; +static int errors = 0; +static void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + fprintf(stderr, "%s\n", message); + } +} +static std::atomic completions{0}; +static void complete(const void *, ANARIDevice, ANARIFrame) +{ + ++completions; +} + +// Numeric failure is recoverable without poisoning CUDA. Test first preparation +// and failure after a good generation, via public samples/callback/bounds APIs. +int main(int argc, char **argv) +{ + const bool boundsFailure = argc > 1; + auto d = makeVisRTXDevice(status); + auto geometry = anari::newObject( + d, boundsFailure ? "cylinder" : "sphere"); + const std::array positions = {{{-0.25f, 0, 0}, {0.25f, 0, 0}}}; + setTestArray(d, geometry, "vertex.position", positions, true); + auto material = anari::newObject(d, "physicallyBased"); + anari::setParameter(d, material, "emissive", vec3{1, 1, 1}); + anari::commitParameters(d, material); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", geometry); + anari::setAndReleaseParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto world = anari::newObject(d); + anari::setParameterArray1D(d, world, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, world); + auto camera = anari::newObject(d, "perspective"); + anari::setParameter(d, camera, "position", vec3{0, 0, -3}); + anari::setParameter(d, camera, "direction", vec3{0, 0, 1}); + anari::commitParameters(d, camera); + auto renderer = anari::newObject(d, "interactive"); + anari::commitParameters(d, renderer); + auto frame = anari::newObject(d); + anari::setParameter(d, frame, "size", std::array{32, 32}); + anari::setParameter(d, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, frame, "camera", camera); + anari::setAndReleaseParameter(d, frame, "renderer", renderer); + anari::setParameter(d, frame, "world", world); + ANARIFrameCompletionCallback callback = complete; + anari::setParameter(d, + frame, + "frameCompletionCallback", + ANARI_FRAME_COMPLETION_CALLBACK, + &callback); + anari::commitParameters(d, frame); + bool ok = true; + int previousSamples = 0; + for (int step = 0; step < 4; ++step) { + const bool invalid = step % 2 == 0; + const std::array radii = {invalid + ? (boundsFailure ? std::numeric_limits::infinity() : 1e20f) + : 0.25f, + 0.125f}; + setTestArray(d, + geometry, + boundsFailure ? "primitive.radius" : "vertex.radius", + radii, + true); + anari::commitParameters(d, geometry); + const int beforeErrors = errors; + const int beforeCompletions = completions; + anari::render(d, frame); + anari::wait(d, frame); + int samples = -1; + ok = anari::getProperty(d, frame, "numSamples", samples) && ok; + std::array bounds{}; + const bool haveBounds = anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT); + if (invalid) { + ok = ok && errors > beforeErrors && samples == previousSamples + && completions == beforeCompletions && !haveBounds; + // Geometry-wide attributes must not rehabilitate a failed generation. + anari::setParameter( + d, geometry, "attribute0", vec4{float(step), 0, 0, 1}); + anari::commitParameters(d, geometry); + ok = !anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + bounds.data(), + sizeof(bounds), + ANARI_WAIT) + && ok; + } else { + ok = ok && errors == beforeErrors && samples > 0 + && completions == beforeCompletions + 1 && haveBounds; + previousSamples = samples; + } + printf("%s step=%d samples=%d callbacks=%d errors=%d bounds=%d %s\n", + boundsFailure ? "bounds" : "area", + step, + samples, + int(completions), + errors, + haveBounds, + ok ? "PASS" : "FAIL"); + } + anari::release(d, frame); + anari::release(d, world); + anari::release(d, geometry); + anari::release(d, d); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestPreparationQueue.cpp b/devices/rtx/apps/tests/api/TestPreparationQueue.cpp new file mode 100644 index 000000000..f4bd6bc3d --- /dev/null +++ b/devices/rtx/apps/tests/api/TestPreparationQueue.cpp @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include "../../../device/utility/PreparationQueue.h" + +namespace { +struct Item +{ + explicit Item(int &destroyed); + ~Item(); + void publish(); + int &destroyed; + bool queued{true}; + bool failPublication{false}; + int publications{0}; + std::function onDestroy; +}; +Item::Item(int &counter) : destroyed(counter) {} +Item::~Item() +{ + ++destroyed; + if (onDestroy) + onDestroy(); +} +void Item::publish() +{ + if (failPublication) + throw std::bad_alloc(); + ++publications; +} +using Queue = visrtx::PreparationQueue>; + +auto retire = [](Item *item) noexcept { item->queued = false; }; + +// Batch work that throws before touching any object, like a descriptor +// reserve. Owners must survive, unwind must see them all, nothing is retired. +bool runFailure(bool retry) +{ + int destroyed = 0; + { + Queue queue; + std::vector deferred; + for (int i = 0; i < 2; ++i) { + auto item = std::make_shared(destroyed); + deferred.push_back(item.get()); + queue.enqueue(std::move(item)); // The queue is the only owner. + } + bool threw = false; + int unwound = 0; + try { + queue.collect([&](Item *) { throw std::bad_alloc(); }, + retire, + [&] { + if (queue.collecting()) + queue.forEach([&](Item *) { ++unwound; }); + }); + } catch (const std::bad_alloc &) { + threw = true; + } + if (!threw || unwound != 2 || destroyed || queue.size() != 2 + || queue.collecting()) + return false; + for (auto *item : deferred) + if (!item->queued || item->publications) + return false; + if (retry) { + bool refusedReentry = false; + bool unwoundAgain = false; + if (!queue.collect( + [&](Item *) { + refusedReentry = !queue.collect([](Item *) {}, retire, [] {}); + queue.forEach([](Item *item) { item->publish(); }); + }, + retire, + [&] { unwoundAgain = true; }) + || !refusedReentry || unwoundAgain || !queue.empty() + || queue.collecting() || destroyed != 2) + return false; + } + } + return destroyed == 2; // Also covers destruction after an unretried failure. +} + +// A later object's publication throws after an earlier one published. Both +// stay queued and unretired; a retry publishes both and retires both. +bool publicationFailure() +{ + int destroyed = 0; + Queue queue; + auto first = std::make_shared(destroyed); + auto second = std::make_shared(destroyed); + second->failPublication = true; + queue.enqueue(first); + queue.enqueue(second); + auto publishAll = [&](Item *) { + queue.forEach([](Item *item) { item->publish(); }); + }; + bool threw = false; + try { + queue.collect(publishAll, retire, [] {}); + } catch (const std::bad_alloc &) { + threw = true; + } + bool ok = threw && queue.size() == 2 && !queue.collecting() && first->queued + && second->queued && first->publications == 1 + && second->publications == 0; + second->failPublication = false; + ok = queue.collect(publishAll, retire, [] {}) && ok; + ok = queue.empty() && !first->queued && !second->queued + && first->publications == 2 && second->publications == 1 && ok; + ok = queue.collect(publishAll, retire, [] {}) && first->publications == 2 + && ok; + first.reset(); + second.reset(); + return destroyed == 2 && ok; +} + +// Retirement sees the object still queued. The last owner is released after +// membership is gone but while the queue is still collecting, so a destructor +// can neither see it nor collect again. +bool retirementReentry() +{ + int destroyed = 0; + Queue queue; + bool safe = false; + auto item = std::make_shared(destroyed); + Item *raw = item.get(); + item->onDestroy = [&] { + int visible = 0; + queue.forEach([&](Item *) { ++visible; }); + safe = queue.empty() && queue.collecting() && visible == 0 + && !queue.collect([](Item *) {}, retire, [] {}); + }; + bool retiredBeforeRelease = false; + queue.enqueue(std::move(item)); + const bool collected = queue.collect([](Item *) {}, + [&](Item *object) noexcept { + retiredBeforeRelease = object == raw && !destroyed && queue.size() == 1; + }, + [] {}); + return collected && retiredBeforeRelease && safe && destroyed == 1 + && !queue.collecting(); +} + +// Positions index the queue in enqueue order and restart after a collection; +// run() receives the oldest object. +bool positionsRestartAfterCollection() +{ + int destroyed = 0; + Queue queue; + auto oldest = std::make_shared(destroyed); + bool ok = queue.enqueue(oldest) == 0 + && queue.enqueue(std::make_shared(destroyed)) == 1; + Item *first = nullptr; + ok = queue.collect([&](Item *item) { first = item; }, retire, [] {}) && ok; + ok = first == oldest.get() && ok; + ok = queue.enqueue(std::make_shared(destroyed)) == 0 && ok; + return ok; +} +} // namespace + +int main() +{ + bool ok = runFailure(true); + ok = runFailure(false) && ok; + ok = publicationFailure() && ok; + ok = retirementReentry() && ok; + ok = positionsRestartAfterCollection() && ok; + std::printf( + "preparation queue exception ownership: %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestPreparationResults.cpp b/devices/rtx/apps/tests/api/TestPreparationResults.cpp new file mode 100644 index 000000000..fa5d8ff96 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestPreparationResults.cpp @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include "../../../device/geometry/PreparationResults.h" + +namespace { +bool failDevice = false; +bool failHost = false; + +template +T next(const char *name) +{ + auto function = reinterpret_cast(dlsym(RTLD_NEXT, name)); + if (!function) + std::abort(); + return function; +} + +using visrtx::GeometryResults; +using visrtx::PreparationResults; + +// Writes one geometry's results as a kernel would. +bool write(PreparationResults &results, + size_t position, + float value, + cudaStream_t stream) +{ + const GeometryResults written{ + {value, uint32_t(position)}, {-value, uint32_t(position) + 1}}; + return cudaMemcpyAsync(results.device(position), + &written, + sizeof(written), + cudaMemcpyHostToDevice, + stream) + == cudaSuccess + && cudaStreamSynchronize(stream) == cudaSuccess; +} + +bool holds(const PreparationResults &results, size_t position, float value) +{ + const auto &read = results.host(position); + return read.bounds.value == value && read.bounds.invalid == uint32_t(position) + && read.area.value == -value + && read.area.invalid == uint32_t(position) + 1; +} + +// Reads back and waits, as GeometryPreparation::flush() does. +bool readBackAndWait( + PreparationResults &results, size_t count, cudaStream_t stream) +{ + return results.readback(count, stream) == cudaSuccess + && cudaStreamSynchronize(stream) == cudaSuccess; +} +} // namespace + +// Real failed allocations, so CUDA last-error state is set as in production. +extern "C" cudaError_t cudaMalloc(void **ptr, size_t bytes) +{ + if (failDevice) { + failDevice = false; + *ptr = nullptr; + return next("cudaMalloc")(ptr, size_t(-1)); + } + return next("cudaMalloc")(ptr, bytes); +} + +extern "C" cudaError_t cudaMallocHost(void **ptr, size_t bytes) +{ + if (failHost) { + failHost = false; + *ptr = nullptr; + return next("cudaMallocHost")(ptr, size_t(-1)); + } + return next("cudaMallocHost")(ptr, bytes); +} + +int main() +{ + constexpr size_t INITIAL = PreparationResults::MIN_CAPACITY; + cudaStream_t stream{}; + if (cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking) != cudaSuccess) + return 1; + bool ok = true; + { + PreparationResults results; + + // Nothing reserved or written: readback transfers nothing. + ok = readBackAndWait(results, 1, stream) && ok; + + // A failed first allocation of either side is reported, leaves no stale + // error, and retries. + for (bool *fail : {&failHost, &failDevice}) { + *fail = true; + ok = results.reserve(1, stream) != cudaSuccess && ok; + ok = cudaGetLastError() == cudaSuccess && ok; + } + ok = results.reserve(1, stream) == cudaSuccess && ok; + + ok = write(results, 0, 1.f, stream) && ok; + ok = readBackAndWait(results, 1, stream) && holds(results, 0, 1.f) && ok; + + // Failed growth keeps the existing storage and its results. + ok = write(results, INITIAL - 1, 2.f, stream) && ok; + for (bool *fail : {&failHost, &failDevice}) { + *fail = true; + ok = results.reserve(INITIAL + 1, stream) != cudaSuccess && ok; + ok = cudaGetLastError() == cudaSuccess && ok; + } + ok = readBackAndWait(results, INITIAL, stream) && holds(results, 0, 1.f) + && holds(results, INITIAL - 1, 2.f) && ok; + + // Growth keeps device results written before it, including at the last + // position of the old capacity; never-written positions read back zero. + ok = write(results, 0, 3.f, stream) && ok; + ok = results.reserve(INITIAL + 1, stream) == cudaSuccess && ok; + ok = write(results, INITIAL, 4.f, stream) && ok; + ok = readBackAndWait(results, INITIAL + 1, stream) && ok; + ok = holds(results, 0, 3.f) && holds(results, INITIAL - 1, 2.f) + && holds(results, INITIAL, 4.f) && ok; + const auto &unwritten = results.host(1); + ok = unwritten.bounds.value == 0.f && unwritten.bounds.invalid == 0 + && unwritten.area.value == 0.f && unwritten.area.invalid == 0 && ok; + + // A rewrite after a readback reaches the host on the next readback, which + // also transfers the untouched positions again. + ok = write(results, 0, 5.f, stream) && ok; + ok = readBackAndWait(results, INITIAL + 1, stream) && ok; + ok = holds(results, 0, 5.f) && holds(results, INITIAL, 4.f) && ok; + + // Readback is limited to positions that have storage. + ok = write(results, 0, 6.f, stream) && ok; + ok = readBackAndWait(results, 4 * INITIAL, stream) && holds(results, 0, 6.f) + && ok; + } + cudaStreamDestroy(stream); + std::printf("preparation results %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestPreparationStream.cpp b/devices/rtx/apps/tests/api/TestPreparationStream.cpp new file mode 100644 index 000000000..fc207234f --- /dev/null +++ b/devices/rtx/apps/tests/api/TestPreparationStream.cpp @@ -0,0 +1,153 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "../../../device/utility/PreparationStream.h" + +namespace { +struct Gate +{ + std::atomic released{false}; + std::atomic timedOut{false}; + std::mutex mutex; + std::condition_variable condition; +}; + +void CUDART_CB block(void *data) +{ + auto &gate = *static_cast(data); + while (!gate.released.load()) + std::this_thread::yield(); +} + +bool check(cudaError_t error) +{ + if (error == cudaSuccess) + return true; + std::fprintf(stderr, "%s\n", cudaGetErrorString(error)); + return false; +} +} // namespace + +int main() +{ + visrtx::PreparationStream preparation; + cudaStream_t other{}; + cudaEvent_t done{}; + int *device = nullptr; + if (!check(preparation.initialize(nullptr)) + || !check(cudaStreamCreateWithFlags(&other, cudaStreamNonBlocking)) + || !check(cudaEventCreateWithFlags(&done, cudaEventDisableTiming)) + || !check( + cudaMalloc(reinterpret_cast(&device), 2 * sizeof(int)))) + return 1; + unsigned flags = 0; + bool ok = check(cudaStreamGetFlags(preparation.stream(), &flags)) + && (flags & cudaStreamNonBlocking); + + // Exercise both explicit and legacy-default producers, plus independence + // from an unrelated nonblocking stream. All allocations precede gated work. + for (int mode : {0, 1, 2}) { + const bool dependency = mode != 0; + const cudaStream_t producer = mode == 2 ? nullptr : other; + ok = + check(cudaMemsetAsync(device, 0, 2 * sizeof(int), preparation.stream())) + && check(preparation.sync()) && ok; + Gate gate; + // Watchdog is a deadlock escape, not a latency assertion. A stream-wide + // or device-wide accidental wait must fail rather than hang the suite. + std::thread watchdog([&] { + std::unique_lock lock(gate.mutex); + if (!gate.condition.wait_for(lock, std::chrono::seconds(5), [&] { + return gate.released.load(); + })) { + gate.timedOut = true; + gate.released = true; + } + }); + ok = check(cudaLaunchHostFunc(producer, block, &gate)) && ok; + int result = 0; + if (dependency) { + ok = check(cudaMemsetAsync(device, 0x2a, sizeof(int), producer)) && ok; + ok = check(preparation.orderAfter(producer)) && ok; + } else { + // Importing the default stream must not join an unrelated nonblocking + // stream. The mode above separately tests a pending default producer. + ok = check(preparation.orderAfter(nullptr)) && ok; + ok = check( + cudaMemsetAsync(device, 0x2a, sizeof(int), preparation.stream())) + && ok; + } + // A real consumer distinguishes importing producer data from merely + // waiting for the stream later during host readback. + ok = check(cudaMemcpyAsync(device + 1, + device, + sizeof(int), + cudaMemcpyDeviceToDevice, + preparation.stream())) + && ok; + // Keep readback after releasing the gate: a pageable D2H copy itself may + // block the host and would obscure what the stream dependency test proves. + ok = check(cudaEventRecord(done, preparation.stream())) && ok; + if (dependency) + ok = cudaEventQuery(done) == cudaErrorNotReady && ok; + else { + ok = check(preparation.sync()) && ok; + ok = cudaStreamQuery(other) == cudaErrorNotReady && ok; + } + { + std::lock_guard lock(gate.mutex); + gate.released = true; + } + gate.condition.notify_one(); + watchdog.join(); + ok = !gate.timedOut && check(preparation.sync()) && ok; + ok = check(cudaMemcpyAsync(&result, + device + 1, + sizeof(result), + cudaMemcpyDeviceToHost, + preparation.stream())) + && check(preparation.sync()) && result == 0x2a2a2a2a && ok; + ok = check(cudaStreamSynchronize(producer)) && ok; + } + cudaFree(device); + cudaEventDestroy(done); + cudaStreamDestroy(other); + preparation.reset(); + std::printf("preparation stream dependencies: %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp b/devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp new file mode 100644 index 000000000..ef9efc4e6 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestRegistrySnapshot.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "gpu/gpu_objects.h" +#include "utility/DeviceObjectArray.h" +#include "utility/PreparationStream.h" + +int main() +{ + visrtx::PreparationStream preparation; + if (preparation.initialize(nullptr) != cudaSuccess) + return 1; + visrtx::DeviceObjectArray registry; + int token = 0; + const auto first = registry.alloc(&token); + registry.set(first, 11); + if (preparation.upload(registry) != cudaSuccess) + return 1; + registry.markUploaded(); + bool ok = !registry.dirty(); + + registry.set(first, 22); + if (registry.enqueueUpload(preparation.stream()) != cudaSuccess) + return 1; + // Model object creation/finalization between submission and completion: + // growing the live host vector must not invalidate the copy's source, and + // acknowledging that copy must not erase newer edits. + registry.set(first, 33); + visrtx::DeviceObjectIndex last = first; + for (int i = 0; i < 1024; ++i) + last = registry.alloc(&token); + registry.set(last, 44); + if (preparation.sync() != cudaSuccess) + return 1; + registry.markUploaded(); + ok = registry.dirty() && ok; + int value = 0; + ok = cudaMemcpy( + &value, registry.devicePtr(), sizeof(value), cudaMemcpyDeviceToHost) + == cudaSuccess + && value == 22 && ok; + + if (preparation.upload(registry) != cudaSuccess) + return 1; + registry.markUploaded(); + ok = !registry.dirty() && ok; + ok = cudaMemcpy( + &value, registry.devicePtr(), sizeof(value), cudaMemcpyDeviceToHost) + == cudaSuccess + && value == 33 && ok; + ok = cudaMemcpy(&value, + registry.devicePtr() + last, + sizeof(value), + cudaMemcpyDeviceToHost) + == cudaSuccess + && value == 44 && ok; + + visrtx::DeviceObjectArray uncommitted; + uncommitted.alloc(&token); + uncommitted.alloc(&token); + if (preparation.upload(uncommitted) != cudaSuccess) + return 1; + uncommitted.markUploaded(); + uncommitted.set(0, 7); + if (preparation.upload(uncommitted) != cudaSuccess) + return 1; + uncommitted.markUploaded(); + int pair[2]{}; + ok = cudaMemcpy( + pair, uncommitted.devicePtr(), sizeof(pair), cudaMemcpyDeviceToHost) + == cudaSuccess + && pair[0] == 7 && pair[1] == 0 && !uncommitted.dirty() && ok; + std::printf("registry snapshot: %s\n", ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestSharedGeometryLifecycle.cpp b/devices/rtx/apps/tests/api/TestSharedGeometryLifecycle.cpp new file mode 100644 index 000000000..9ae529df8 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestSharedGeometryLifecycle.cpp @@ -0,0 +1,310 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" +#include "ReceiverTestSupport.h" + +using vec3 = std::array; +using vec4 = std::array; +using Pools = std::array; +static constexpr unsigned WIDTH = 128, HEIGHT = 128; +// Fixed before inspecting results: match the existing 512-spp triangle/quad +// oracle's 5% allowance. Omitting one light must fail this same threshold. +// Zero-area phases allow only 1e-6. +static constexpr double REL_TOL = 0.05, BLACK_TOL = 1e-6; + +static std::array vertices(float halfWidth) +{ + return {{{-halfWidth, 1.5f, -0.5f}, + {halfWidth, 1.5f, -0.5f}, + {halfWidth, 1.5f, 0.5f}, + {-halfWidth, 1.5f, 0.5f}, + {-halfWidth, 1.5f, -0.25f}}}; +} +static void setTriangles(ANARIDevice d, + anari::Geometry g, + float halfWidth, + bool device = true, + bool soup = false) +{ + const auto positions = vertices(halfWidth); + // Unequal areas plus a zero-area triangle exercise the area/CDF sampler. + const std::array, 4> indices = { + {{0, 1, 4}, {1, 2, 4}, {2, 3, 4}, {4, 4, 4}}}; + if (soup) { + std::array expanded; + for (size_t i = 0; i < indices.size(); ++i) + for (size_t c = 0; c < 3; ++c) + expanded[3 * i + c] = positions[indices[i][c]]; + setTestArray(d, g, "vertex.position", expanded, device); + anari::unsetParameter(d, g, "primitive.index"); + } else { + setTestArray(d, g, "vertex.position", positions, device); + setTestArray(d, g, "primitive.index", indices, device); + } + anari::commitParameters(d, g); +} +static anari::Geometry geometry(ANARIDevice d, float halfWidth) +{ + auto g = anari::newObject(d, "triangle"); + setTriangles(d, g, halfWidth); + return g; +} +static anari::Surface surface(ANARIDevice d, anari::Geometry g) +{ + auto m = anari::newObject(d, "physicallyBased"); + anari::setParameter(d, m, "baseColor", vec3{0, 0, 0}); + anari::setParameter(d, m, "emissive", vec3{8, 8, 8}); + anari::commitParameters(d, m); + auto s = anari::newObject(d); + anari::setParameter(d, s, "geometry", g); + anari::setAndReleaseParameter(d, s, "material", m); + anari::commitParameters(d, s); + return s; +} +static void translate(ANARIDevice d, anari::Instance instance, float x) +{ + const std::array matrix = { + 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, 0, 0, 1}; + anari::setParameter( + d, instance, "transform", ANARI_FLOAT32_MAT4, matrix.data()); + anari::commitParameters(d, instance); +} +static anari::Instance instanceOf(ANARIDevice d, anari::Surface s, float x) +{ + auto group = anari::newObject(d); + anari::setParameterArray1D(d, group, "surface", &s, 1); + anari::commitParameters(d, group); + auto instance = anari::newObject(d, "transform"); + anari::setAndReleaseParameter(d, instance, "group", group); + translate(d, instance, x); + return instance; +} +static anari::World worldWithFloor(ANARIDevice d) +{ + auto w = anari::newObject(d); + auto floor = visrtx::test::receiverFloor(d); + anari::setParameterArray1D(d, w, "surface", &floor, 1); + anari::release(d, floor); + return w; +} +static anari::Frame frame(ANARIDevice d, anari::World world) +{ + return visrtx::test::receiverFrame( + d, world, {WIDTH, HEIGHT}, "interactive", 512); +} +static Pools render(ANARIDevice d, anari::Frame f) +{ + anari::render(d, f); + anari::wait(d, f); + const visrtx::test::FrameMapping mapping(d, f, "channel.color"); + const auto *pixels = mapping.checkedData(WIDTH, HEIGHT, ANARI_FLOAT32_VEC4); + Pools pools{}; + for (unsigned side = 0; side < 2; ++side) + pools[side] = visrtx::test::meanLuminance(pixels, + {WIDTH, HEIGHT}, + {WIDTH / 4 + side * WIDTH / 4, + WIDTH / 2 + side * WIDTH / 4, + HEIGHT / 8, + HEIGHT / 2}); + return pools; +} +// Independent oracle: two authored analytic quads, not copies of the geometry +// preprocessing implementation. A missing light must fail the same comparator. +static Pools reference(ANARIDevice d, + const std::array &widths, + const std::array &offsets, + bool omitRight = false) +{ + auto w = worldWithFloor(d); + const visrtx::test::ObjectOwner worldOwner(d, w); + std::vector lights; + for (unsigned i = 0; i < 2; ++i) { + if (widths[i] == 0 || (omitRight && i == 1)) + continue; + auto light = anari::newObject(d, "quad"); + anari::setParameter( + d, light, "position", vec3{offsets[i] - widths[i], 1.5f, -0.5f}); + anari::setParameter(d, light, "edge1", vec3{2 * widths[i], 0, 0}); + anari::setParameter(d, light, "edge2", vec3{0, 0, 1}); + anari::setParameter(d, light, "color", vec3{1, 1, 1}); + anari::setParameter(d, light, "intensity", 8.f); + anari::setParameter(d, light, "side", "both"); + anari::commitParameters(d, light); + lights.push_back(light); + } + if (!lights.empty()) + anari::setParameterArray1D(d, w, "light", lights.data(), lights.size()); + for (auto light : lights) + anari::release(d, light); + anari::commitParameters(d, w); + auto f = frame(d, w); + const visrtx::test::ObjectOwner frameOwner(d, f); + return render(d, f); +} +static bool matches(const Pools &actual, const Pools &expected) +{ + for (unsigned i = 0; i < 2; ++i) { + if (!std::isfinite(actual[i]) || !std::isfinite(expected[i])) + return false; + if (expected[i] > BLACK_TOL) { + if (std::abs(actual[i] - expected[i]) / expected[i] > REL_TOL) + return false; + } else if (std::abs(actual[i]) > BLACK_TOL) + return false; + } + return true; +} +static bool phase(ANARIDevice d, + anari::Frame f, + anari::World world, + const char *name, + const std::array &widths, + const std::array &offsets) +{ + fprintf(stderr, "[case] %s\n", name); + const auto actual = render(d, f); + uint32_t lights = 0; + const uint32_t expectedLights = + uint32_t(widths[0] > 0) + uint32_t(widths[1] > 0); + const bool countMatches = + anari::getProperty(d, world, "numLightInstances", lights) + && lights == expectedLights; + const auto expected = reference(d, widths, offsets); + const bool lit = widths[0] > 0 || widths[1] > 0; + bool ok = countMatches && matches(actual, expected); + if (lit) + for (double value : expected) + ok = ok && std::isfinite(value) && value > BLACK_TOL; + printf("%s actual=[%g,%g] analytic=[%g,%g] lights=%u %s\n", + name, + actual[0], + actual[1], + expected[0], + expected[1], + lights, + ok ? "PASS" : "FAIL"); + return ok; +} +int main() +{ + auto d = makeVisRTXDevice(visrtx::test::exitOnErrorStatus); + auto g = geometry(d, 0.5f); + const std::array surfaces = {surface(d, g), surface(d, g)}; + std::array offsets = {-0.9f, 0.9f}; + const std::array instances = { + instanceOf(d, surfaces[0], offsets[0]), + instanceOf(d, surfaces[1], offsets[1])}; + auto w = worldWithFloor(d); + anari::setParameterArray1D( + d, w, "instance", instances.data(), instances.size()); + anari::commitParameters(d, w); + auto f = frame(d, w); + bool ok = true; + // Share the analytic oracle with lifecycle checks; finish with device-backed + // indexed triangles so the subsequent sequence exercises that path once. + for (bool device : {false, true}) + for (bool soup : {true, false}) { + setTriangles(d, g, 0.5f, device, soup); + const std::string name = std::string(device ? "device/" : "host/") + + (soup ? "triangle-soup" : "indexed-triangle"); + ok = phase(d, f, w, name.c_str(), {0.5f, 0.5f}, offsets) && ok; + } + const auto oracle = reference(d, {0.5f, 0.5f}, offsets); + const auto missing = reference(d, {0.5f, 0.5f}, offsets, true); + const bool validControl = std::isfinite(missing[0]) + && std::isfinite(missing[1]) && missing[0] > BLACK_TOL + && missing[1] > BLACK_TOL; + const bool controls = validControl && !matches(oracle, missing); + printf("missing-instance=[%g,%g] control=%s\n", + missing[0], + missing[1], + controls ? "PASS" : "FAIL"); + ok = controls && ok; + + // Shrink while the five-vertex/four-triangle area data is active. The same + // geometry keeps its buffer capacity, but must publish only two triangles. + // A changed footprint makes stale area weights/counts observable in both + // pools against independently authored analytic lights. + auto positions = anari::newArray1D(d, ANARI_FLOAT32_VEC3, 4); + auto update = [&](float halfWidth) { + const auto v = vertices(halfWidth); + std::copy_n(v.begin(), 4, anari::map(d, positions)); + anari::unmap(d, positions); + }; + update(0.375f); + const std::array, 2> indices = { + {{0, 1, 2}, {0, 2, 3}}}; + anari::setParameter(d, g, "vertex.position", positions); + setTestArray(d, g, "primitive.index", indices, true); + anari::commitParameters(d, g); + ok = phase(d, f, w, "shared active count shrink", {0.375f, 0.375f}, offsets) + && ok; + update(0.f); // no geometry/surface/group/instance recommit + ok = phase(d, f, w, "shared unmap to zero", {0, 0}, offsets) && ok; + update(0.5f); // recovery also requires no higher-object recommit + ok = phase(d, f, w, "shared unmap recovery", {0.5f, 0.5f}, offsets) && ok; + setTestArray(d, g, "vertex.position", vertices(0.25f), true); + anari::commitParameters(d, g); + ok = phase(d, f, w, "shared device replacement", {0.25f, 0.25f}, offsets) + && ok; + auto detached = geometry(d, 0.375f); + anari::setParameter(d, surfaces[1], "geometry", detached); + anari::commitParameters(d, surfaces[1]); + anari::release(d, detached); + ok = phase(d, f, w, "detach right surface", {0.25f, 0.375f}, offsets) && ok; + update(0.125f); + anari::setParameter(d, g, "vertex.position", positions); + anari::commitParameters(d, g); + ok = phase(d, f, w, "update remaining consumer", {0.125f, 0.375f}, offsets) + && ok; + offsets[1] = 1.25f; + translate(d, instances[1], offsets[1]); + ok = + phase(d, f, w, "move detached instance", {0.125f, 0.375f}, offsets) && ok; + anari::release(d, f); + anari::release(d, w); + for (auto i : instances) + anari::release(d, i); + for (auto s : surfaces) + anari::release(d, s); + anari::release(d, g); + anari::release(d, positions); + anari::release(d, d); + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp b/devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp new file mode 100644 index 000000000..a68be8eeb --- /dev/null +++ b/devices/rtx/apps/tests/api/TestSmallGeometryBatch.cpp @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "DeviceTestArray.h" +#ifdef VISRTX_TEST_INTERPOSE_CUDA +#include +#endif + +namespace { +#ifdef VISRTX_TEST_INTERPOSE_CUDA +bool trackSummaries = false; +int summaryCopies = 0; +#endif +using vec3 = std::array; +int errors = 0; +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity <= ANARI_SEVERITY_ERROR) { + ++errors; + std::fprintf(stderr, "%s\n", message); + } +} +struct Case +{ + std::string type; + size_t count; + anari::Geometry geometry; + anari::Group group; + std::array bounds; +}; + +bool run(bool device) +{ + auto d = makeVisRTXDevice(status); + auto material = anari::newObject(d, "physicallyBased"); + anari::setParameter(d, material, "emissive", vec3{1, 1, 1}); + anari::commitParameters(d, material); + std::vector cases; + std::vector instances; + for (const char *type : {"sphere", "cylinder", "cone", "triangle"}) + for (size_t n : {1, 31, 32, 33, 255, 256, 257}) { + auto g = anari::newObject(d, type); + auto surface = anari::newObject(d); + anari::setParameter(d, surface, "geometry", g); + anari::setParameter(d, surface, "material", material); + anari::commitParameters(d, surface); + auto group = anari::newObject(d); + anari::setParameterArray1D(d, group, "surface", &surface, 1); + anari::release(d, surface); + anari::commitParameters(d, group); + auto instance = anari::newObject(d, "transform"); + anari::setParameter(d, instance, "group", group); + anari::commitParameters(d, instance); + instances.push_back(instance); + cases.push_back({type, n, g, group, {}}); + } + anari::release(d, material); + auto world = anari::newObject(d); + anari::setParameterArray1D( + d, world, "instance", instances.data(), instances.size()); + anari::commitParameters(d, world); + for (auto instance : instances) + anari::release(d, instance); + bool ok = true; + for (int generation = 0; generation < 3; ++generation) { + for (auto &c : cases) { + // Reuse a batch's slots across degenerate results, then swap small and + // large paths to catch stale result pointers and scratch-growth errors. + const size_t n = generation == 2 ? (c.count <= 256 ? 257 : 32) : c.count; + const float r = generation == 1 ? 0.f : 0.25f; + const float h = generation == 1 ? 0.f : 0.5f; + std::vector vertices; + std::vector radii; + for (size_t i = 0; i < n; ++i) { + const float x = 2.f * i; + if (c.type == "sphere") + vertices.push_back({x, 0, 0}); + else if (c.type == "triangle") { + vertices.push_back({x - r, -h, 0}); + vertices.push_back({x + r, -h, 0}); + vertices.push_back({x, h, 0}); + } else { + vertices.push_back({x, -h, 0}); + vertices.push_back({x, h, 0}); + radii.push_back(r * 0.5f); + radii.push_back(r); + } + } + setTestArray(d, c.geometry, "vertex.position", vertices, device, 1); + if (c.type == "cone") + setTestArray(d, c.geometry, "vertex.radius", radii, device, 1); + anari::setParameter(d, c.geometry, "radius", r); + anari::setParameter(d, c.geometry, "caps", "both"); + anari::commitParameters(d, c.geometry); + const float y = c.type == "sphere" ? r : c.type == "triangle" ? h : h + r; + const float z = c.type == "triangle" ? 0.f : r; + c.bounds = {-r, -y, -z, 2.f * (n - 1) + r, y, z}; + } + // One world query flushes all geometries together, including lazy area + // requests on the first generation and bounds+area jobs on later ones. + std::array worldBounds{}; +#ifdef VISRTX_TEST_INTERPOSE_CUDA + summaryCopies = 0; + trackSummaries = true; +#endif + ok = anariGetProperty(d, + world, + "bounds", + ANARI_FLOAT32_BOX3, + worldBounds.data(), + sizeof(worldBounds), + ANARI_WAIT) + && ok; +#ifdef VISRTX_TEST_INTERPOSE_CUDA + trackSummaries = false; + // Initial bounds and lazy areas are separate collections. Once area data + // is wanted, finalization batches both together. Large-path scalar copies + // and OptiX's 8/24-byte readbacks are not batch summaries. + const int expectedCopies = generation == 0 ? 2 : 1; + if (summaryCopies != expectedCopies) + std::fprintf(stderr, + "generation=%d summary copies=%d expected=%d\n", + generation, + summaryCopies, + expectedCopies); + ok = summaryCopies == expectedCopies && ok; +#endif + uint32_t lights = 0; + ok = anariGetProperty(d, + world, + "numLightInstances", + ANARI_UINT32, + &lights, + sizeof(lights), + ANARI_WAIT) + && lights == (generation == 1 ? 0 : cases.size()) && ok; + for (const auto &c : cases) { + std::array actual{}; + bool valid = anariGetProperty(d, + c.group, + "bounds", + ANARI_FLOAT32_BOX3, + actual.data(), + sizeof(actual), + ANARI_WAIT); + if (generation == 1) { + // OptiX drops zero-extent primitives from its emitted BVH bounds. + for (int axis = 0; axis < 3; ++axis) + valid = actual[axis] > actual[axis + 3] && valid; + } else { + // OptiX conservatively pads bounds in proportion to coordinate scale. + const float tolerance = 1e-4f + 1e-6f * c.bounds[3]; + for (int i = 0; i < 6; ++i) + valid = std::isfinite(actual[i]) + && std::abs(actual[i] - c.bounds[i]) < tolerance && valid; + } + if (!valid) + std::fprintf(stderr, + "%s count=%zu generation=%d bounds actual=(%g,%g,%g;%g,%g,%g) expected=(%g,%g,%g;%g,%g,%g)\n", + c.type.c_str(), + c.count, + generation, + actual[0], + actual[1], + actual[2], + actual[3], + actual[4], + actual[5], + c.bounds[0], + c.bounds[1], + c.bounds[2], + c.bounds[3], + c.bounds[4], + c.bounds[5]); + ok = valid && ok; + } + ok = errors == 0 && ok; + } + anari::release(d, world); + for (const auto &c : cases) { + anari::release(d, c.group); + anari::release(d, c.geometry); + } + anari::release(d, d); + std::printf( + "small geometry batch device=%d %s\n", device, ok ? "PASS" : "FAIL"); + return ok; +} +} // namespace + +#ifdef VISRTX_TEST_INTERPOSE_CUDA +extern "C" cudaError_t cudaMemcpyAsync(void *dst, + const void *src, + size_t bytes, + cudaMemcpyKind kind, + cudaStream_t stream) +{ + constexpr size_t pairBytes = 2 * (sizeof(float) + sizeof(uint32_t)); + if (trackSummaries && kind == cudaMemcpyDeviceToHost && bytes + && bytes % pairBytes == 0) + ++summaryCopies; + using Copy = cudaError_t (*)( + void *, const void *, size_t, cudaMemcpyKind, cudaStream_t); + auto real = reinterpret_cast(dlsym(RTLD_NEXT, "cudaMemcpyAsync")); + if (!real) + std::abort(); + return real(dst, src, bytes, kind, stream); +} +#endif + +int main() +{ + bool ok = run(false); + ok = run(true) && ok; + return ok ? 0 : 1; +} diff --git a/devices/rtx/apps/tests/api/benchmark_preprocessing.py b/devices/rtx/apps/tests/api/benchmark_preprocessing.py new file mode 100644 index 000000000..4723648a7 --- /dev/null +++ b/devices/rtx/apps/tests/api/benchmark_preprocessing.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Compare local before/after geometry-preparation latency (not a CI assertion). + +Run one harness against two ABI-compatible device libraries. Only the device +library path is injected; the environment must resolve a real CUDA driver. +Each trial is a fresh process; iteration zero is excluded from warm statistics. +Optional JSON output is local scratch, not a versioned performance baseline. +""" +import argparse +import json +import math +import os +from pathlib import Path +import re +import statistics +import subprocess + +p = argparse.ArgumentParser(description=__doc__) +p.add_argument("executable") +p.add_argument("base_library_dir", help="before/control device library directory") +p.add_argument("branch_library_dir", help="after/candidate device library directory") +p.add_argument("output", type=Path, nargs="?", help="optional local JSON results path") +p.add_argument("--trials", type=int, default=3) +p.add_argument("--repeats", type=int, default=21) +p.add_argument("--geometry", default="cylinder", + choices=["triangle", "quad", "sphere", "curve", "cone", "cylinder", "sdf"]) +p.add_argument("--device", action="store_true", + help="use device-backed inputs; both libraries must support them") +p.add_argument("--case", action="append", default=[], metavar="NAME", + help="run only the named default case; repeatable") +p.add_argument("--extra-case", action="append", default=[], + metavar="NAME:COUNT:GEOMETRIES:MODE:FRAMES", + help="append a custom case; repeatable") +a = p.parse_args() +if a.trials < 2 or a.repeats < 3: + p.error("need at least two trials and three repetitions") +# name, primitive count per geometry, distinct geometries, update mode, frames +cases = [ + ("small-recommit", 32, 64, "recommit", 0), + ("small-replace", 32, 64, "replace", 0), + ("large-replace", 262144, 1, "replace", 0), + ("unchanged-frame", 32, 64, "unchanged", 1), + ("two-frames-replace", 32, 64, "replace", 2), +] +if a.case: + known = {c[0] for c in cases} + unknown = [n for n in a.case if n not in known] + if unknown: + p.error(f"unknown case(s) {unknown}; known: {sorted(known)}") + cases = [c for c in cases if c[0] in a.case] +for spec in a.extra_case: + try: + name, count, geometries, mode, frames = spec.split(":") + case = (name, int(count), int(geometries), mode, int(frames)) + if (not name or case[1] < 1 or case[2] < 1 or case[4] < 0 + or mode not in {"recommit", "replace", "unchanged", "update"} + or (mode == "update" and (a.device or a.geometry == "sdf")) + or name in {c[0] for c in cases}): + raise ValueError() + cases.append(case) + except ValueError: + p.error(f"bad --extra-case {spec!r}; use a unique NAME, positive COUNT/GEOMETRIES, " + "recommit|replace|unchanged|update, and nonnegative FRAMES; " + "update requires host inputs and non-SDF geometry") +records = [] + + +def save(): + if a.output: + a.output.write_text(json.dumps(records, indent=2) + "\n") + + +print("Warm latency (ms): median of trial medians [min..max trial median]. " + "After/before < 1 is faster; ranges are not confidence intervals.", flush=True) +for name, count, geometries, mode, frames in cases: + for trial in range(a.trials): + order = ["base", "branch"] if trial % 2 == 0 else ["branch", "base"] + for revision in order: + env = os.environ.copy() + lib = a.base_library_dir if revision == "base" else a.branch_library_dir + env["LD_LIBRARY_PATH"] = os.pathsep.join( + filter(None, [lib, env.get("LD_LIBRARY_PATH")])) + command = [a.executable, a.geometry, str(count), str(int(a.device)), + str(a.repeats), "1", str(geometries), mode, str(frames), "1"] + run = subprocess.run(command, env=env, capture_output=True, text=True) + samples = [(int(i), float(ms)) for i, ms in re.findall( + r"sample iteration=(\d+) ms=([\d.]+)", run.stdout)] + record = dict(case=name, trial=trial, revision=revision, + command=command, library_dir=lib, returncode=run.returncode, + stdout=run.stdout, stderr=run.stderr) + records.append(record) + save() + if (run.returncode or len(samples) != a.repeats + or {i for i, ms in samples} != set(range(a.repeats)) + or any(not math.isfinite(ms) or ms < 0 for i, ms in samples)): + raise SystemExit(f"failed {name} {revision} (exit {run.returncode}):\n" + f"{run.stderr}\n{run.stdout}") + record["warm_median_ms"] = statistics.median(ms for i, ms in samples if i) + save() + medians = {rev: [r["warm_median_ms"] for r in records + if r["case"] == name and r["revision"] == rev] + for rev in ["base", "branch"]} + before, after = (statistics.median(medians[rev]) for rev in ["base", "branch"]) + ratio = f"{after / before:.3f}" if before else "n/a" + ranges = [f"{statistics.median(values):.4f} [{min(values):.4f}..{max(values):.4f}]" + for values in medians.values()] + print(f"{name}: before={ranges[0]} after={ranges[1]} after/before={ratio}", flush=True) diff --git a/devices/rtx/device/CMakeLists.txt b/devices/rtx/device/CMakeLists.txt index 7ff4e446f..179f39289 100644 --- a/devices/rtx/device/CMakeLists.txt +++ b/devices/rtx/device/CMakeLists.txt @@ -137,6 +137,9 @@ set(SOURCES frame/Frame.cu geometry/ComputeTangent.cu + geometry/GeometryPreparation.cpp + geometry/PreparationResults.cpp + geometry/Preprocessing.cu geometry/Cone.cpp geometry/Curve.cpp geometry/Cylinder.cpp diff --git a/devices/rtx/device/RegisteredObject.h b/devices/rtx/device/RegisteredObject.h index 3e7ac7b6e..e623795a7 100644 --- a/devices/rtx/device/RegisteredObject.h +++ b/devices/rtx/device/RegisteredObject.h @@ -46,7 +46,9 @@ struct RegisteredObject : public Object virtual ~RegisteredObject(); void finalize() override; - void upload(); + // Publishes gpuData() to the registry slot. Subtypes may override to defer + // publication until their data is ready; virtual so finalize() honors that. + virtual void upload(); DeviceObjectIndex index() const; @@ -86,9 +88,7 @@ inline void RegisteredObject::finalize() template inline void RegisteredObject::upload() { - auto &data = m_registryArray->map(index()); - data = gpuData(); - m_registryArray->unmap(index()); + m_registryArray->set(index(), gpuData()); } template diff --git a/devices/rtx/device/VisRTXDevice.cpp b/devices/rtx/device/VisRTXDevice.cpp index 25d0429cb..b8f3148b9 100644 --- a/devices/rtx/device/VisRTXDevice.cpp +++ b/devices/rtx/device/VisRTXDevice.cpp @@ -117,7 +117,7 @@ const char **query_extensions(); void *VisRTXDevice::mapArray(ANARIArray a) { - if (!initDevice()) + if (!enter("anariMapArray")) return nullptr; CUDADeviceScope ds(this); return helium::BaseDevice::mapArray(a); @@ -125,7 +125,7 @@ void *VisRTXDevice::mapArray(ANARIArray a) void VisRTXDevice::unmapArray(ANARIArray a) { - if (!initDevice()) + if (!enter("anariUnmapArray")) return; CUDADeviceScope ds(this); helium::BaseDevice::unmapArray(a); @@ -139,7 +139,7 @@ ANARIArray1D VisRTXDevice::newArray1D(const void *appMemory, ANARIDataType type, uint64_t numItems) { - if (!initDevice()) + if (!enter("anariNewArray1D")) return {}; CUDADeviceScope ds(this); @@ -163,7 +163,7 @@ ANARIArray2D VisRTXDevice::newArray2D(const void *appMemory, uint64_t numItems1, uint64_t numItems2) { - if (!initDevice()) + if (!enter("anariNewArray2D")) return {}; CUDADeviceScope ds(this); @@ -186,7 +186,7 @@ ANARIArray3D VisRTXDevice::newArray3D(const void *appMemory, uint64_t numItems2, uint64_t numItems3) { - if (!initDevice()) + if (!enter("anariNewArray3D")) return {}; CUDADeviceScope ds(this); @@ -204,7 +204,7 @@ ANARIArray3D VisRTXDevice::newArray3D(const void *appMemory, ANARICamera VisRTXDevice::newCamera(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewCamera")) return {}; CUDADeviceScope ds(this); return (ANARICamera)Camera::createInstance(subtype, deviceState()); @@ -212,7 +212,7 @@ ANARICamera VisRTXDevice::newCamera(const char *subtype) ANARIFrame VisRTXDevice::newFrame() { - if (!initDevice()) + if (!enter("anariNewFrame")) return {}; CUDADeviceScope ds(this); return (ANARIFrame) new Frame(deviceState()); @@ -220,7 +220,7 @@ ANARIFrame VisRTXDevice::newFrame() ANARIGeometry VisRTXDevice::newGeometry(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewGeometry")) return {}; CUDADeviceScope ds(this); return (ANARIGeometry)Geometry::createInstance(subtype, deviceState()); @@ -228,7 +228,7 @@ ANARIGeometry VisRTXDevice::newGeometry(const char *subtype) ANARIGroup VisRTXDevice::newGroup() { - if (!initDevice()) + if (!enter("anariNewGroup")) return {}; CUDADeviceScope ds(this); return (ANARIGroup) new Group(deviceState()); @@ -236,7 +236,7 @@ ANARIGroup VisRTXDevice::newGroup() ANARIInstance VisRTXDevice::newInstance(const char *type) { - if (!initDevice()) + if (!enter("anariNewInstance")) return {}; CUDADeviceScope ds(this); return (ANARIInstance) new Instance(deviceState()); @@ -244,7 +244,7 @@ ANARIInstance VisRTXDevice::newInstance(const char *type) ANARILight VisRTXDevice::newLight(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewLight")) return {}; CUDADeviceScope ds(this); return (ANARILight)Light::createInstance(subtype, deviceState()); @@ -252,7 +252,7 @@ ANARILight VisRTXDevice::newLight(const char *subtype) ANARIMaterial VisRTXDevice::newMaterial(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewMaterial")) return {}; CUDADeviceScope ds(this); return (ANARIMaterial)Material::createInstance(subtype, deviceState()); @@ -260,7 +260,7 @@ ANARIMaterial VisRTXDevice::newMaterial(const char *subtype) ANARIRenderer VisRTXDevice::newRenderer(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewRenderer")) return {}; CUDADeviceScope ds(this); return (ANARIRenderer)Renderer::createInstance(subtype, deviceState()); @@ -268,7 +268,7 @@ ANARIRenderer VisRTXDevice::newRenderer(const char *subtype) ANARISampler VisRTXDevice::newSampler(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewSampler")) return {}; CUDADeviceScope ds(this); return (ANARISampler)Sampler::createInstance(subtype, deviceState()); @@ -276,7 +276,7 @@ ANARISampler VisRTXDevice::newSampler(const char *subtype) ANARISpatialField VisRTXDevice::newSpatialField(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewSpatialField")) return {}; CUDADeviceScope ds(this); return (ANARISpatialField)SpatialField::createInstance( @@ -285,7 +285,7 @@ ANARISpatialField VisRTXDevice::newSpatialField(const char *subtype) ANARISurface VisRTXDevice::newSurface() { - if (!initDevice()) + if (!enter("anariNewSurface")) return {}; CUDADeviceScope ds(this); return (ANARISurface) new Surface(deviceState()); @@ -293,7 +293,7 @@ ANARISurface VisRTXDevice::newSurface() ANARIVolume VisRTXDevice::newVolume(const char *subtype) { - if (!initDevice()) + if (!enter("anariNewVolume")) return {}; CUDADeviceScope ds(this); return (ANARIVolume)Volume::createInstance(subtype, deviceState()); @@ -301,7 +301,7 @@ ANARIVolume VisRTXDevice::newVolume(const char *subtype) ANARIWorld VisRTXDevice::newWorld() { - if (!initDevice()) + if (!enter("anariNewWorld")) return {}; CUDADeviceScope ds(this); return (ANARIWorld) new World(deviceState()); @@ -346,7 +346,7 @@ int VisRTXDevice::getProperty(ANARIObject object, uint64_t size, uint32_t mask) { - if (!initDevice()) + if (!enterOutsideCollection("anariGetProperty")) return 0; CUDADeviceScope ds(this); return helium::BaseDevice::getProperty(object, name, type, mem, size, mask); @@ -360,7 +360,7 @@ const void *VisRTXDevice::frameBufferMap(ANARIFrame f, uint32_t *height, ANARIDataType *pixelType) { - if (!initDevice()) { + if (!enter("anariMapFrame")) { *width = 0; *height = 0; *pixelType = ANARI_UNKNOWN; @@ -375,7 +375,7 @@ const void *VisRTXDevice::frameBufferMap(ANARIFrame f, void VisRTXDevice::renderFrame(ANARIFrame f) { - if (!initDevice()) + if (!enterOutsideCollection("anariRenderFrame")) return; CUDADeviceScope ds(this); helium::BaseDevice::renderFrame(f); @@ -383,7 +383,7 @@ void VisRTXDevice::renderFrame(ANARIFrame f) int VisRTXDevice::frameReady(ANARIFrame f, ANARIWaitMask m) { - if (!initDevice()) + if (!enter("anariFrameReady")) return 1; CUDADeviceScope ds(this); return helium::BaseDevice::frameReady(f, m); @@ -391,7 +391,7 @@ int VisRTXDevice::frameReady(ANARIFrame f, ANARIWaitMask m) void VisRTXDevice::discardFrame(ANARIFrame f) { - if (!initDevice()) + if (!enter("anariDiscardFrame")) return; CUDADeviceScope ds(this); return helium::BaseDevice::discardFrame(f); @@ -426,6 +426,7 @@ VisRTXDevice::~VisRTXDevice() // material dying here releases its samplers into the registry, so the MDL // teardown below must come after (also what empties the registry before its // "not empty on destruction" check). + state.preparation.collect(); state.commitBuffer.clear(); #ifdef USE_MDL @@ -448,11 +449,73 @@ VisRTXDevice::~VisRTXDevice() optixModuleDestroy(state.intersectionModules.customIntersectors); + state.preparation.shutdown(); + state.preparationStream.reset(); optixDeviceContextDestroy(state.optixContext); cudaStreamDestroy(state.stream); } +bool VisRTXDevice::enter(const char *call) +{ + // Refuse first, initialize second: a refused call initializes nothing. + return !refuseIfDisabled(call) && initDevice(); +} + +bool VisRTXDevice::enterOutsideCollection(const char *call) +{ + return !refuseDuringCollection(call) && enter(call); +} + +bool VisRTXDevice::refuseIfDisabled(const char *call) const +{ + // A failed last-reference array copy (Array::privatize) disables the device + // for good: cached GPU pointers may alias freed application memory. The + // failure itself is reported once there; each refused call says so here so + // a missing object or frame is never silent. + if (!deviceState()->arrayPrivatizationFailed) + return false; + reportRefusal(ANARI_SEVERITY_ERROR, + call, + "refused: device disabled after array privatization failure; " + "create a new device"); + return true; +} + +bool VisRTXDevice::refuseDuringCollection(const char *call) const +{ + // A status callback reported while geometry preparations are collected must + // not flush or re-finalize geometry whose readbacks and registry publication + // are still being resolved, so such reentrant calls do nothing. + if (!deviceState()->preparation.busy()) + return false; + reportRefusal(ANARI_SEVERITY_WARNING, + call, + "ignored: geometry preparations are being collected " + "(reentered from a status callback?)"); + return true; +} + +void VisRTXDevice::reportRefusal( + ANARIStatusSeverity severity, const char *call, const char *reason) const +{ + // The report runs the status callback, which may call back into a refused + // entry point. Only the outermost refusal on this thread is reported; + // refusals nested in its callback (on any device) are refused silently. + static thread_local bool reporting = false; + if (reporting) + return; + struct Reset + { + ~Reset() + { + reporting = false; // Also when the callback throws. + } + } reset; + reporting = true; + reportMessage(severity, "%s %s", call, reason); +} + bool VisRTXDevice::initDevice() { if (m_initStatus == DeviceInitStatus::SUCCESS) @@ -845,6 +908,14 @@ DeviceInitStatus VisRTXDevice::initOptix() &builtinISOptions, &state.intersectionModules.curveIntersector)); + const auto preparationStatus = + state.preparationStream.initialize(state.stream); + if (preparationStatus != cudaSuccess) { + reportMessage(ANARI_SEVERITY_FATAL_ERROR, + "could not initialize preparation stream: %s", + cudaGetErrorString(preparationStatus)); + return DeviceInitStatus::FAILURE; + } return DeviceInitStatus::SUCCESS; } diff --git a/devices/rtx/device/VisRTXDevice.h b/devices/rtx/device/VisRTXDevice.h index 8dbf6de58..778aee1f6 100644 --- a/devices/rtx/device/VisRTXDevice.h +++ b/devices/rtx/device/VisRTXDevice.h @@ -131,6 +131,22 @@ struct VisRTXDevice : public helium::BaseDevice bool initDevice(); // thread safe initialization private: + // The gate an API entry point that needs the initialized device passes + // first; call is the public ANARI function name. True when the call may + // proceed: the device is not disabled and is initialized. + // enterOutsideCollection() also refuses while geometry preparations are + // being collected. + bool enter(const char *call); + bool enterOutsideCollection(const char *call); + + // The refusals behind the gate. Each reports one message naming the + // refused call, except while another refusal is being reported on this + // thread (a status callback reentering the device must not recurse). + bool refuseIfDisabled(const char *call) const; + bool refuseDuringCollection(const char *call) const; + void reportRefusal( + ANARIStatusSeverity severity, const char *call, const char *reason) const; + struct CUDADeviceScope { CUDADeviceScope(VisRTXDevice *d); diff --git a/devices/rtx/device/array/Array.cpp b/devices/rtx/device/array/Array.cpp index 74fc57da1..e7a578d1a 100644 --- a/devices/rtx/device/array/Array.cpp +++ b/devices/rtx/device/array/Array.cpp @@ -30,8 +30,10 @@ */ #include "Array.h" +#include "optix_visrtx.h" // std #include +#include namespace visrtx { @@ -166,13 +168,34 @@ void Array::unmap() void Array::privatize() { + auto &state = *static_cast(deviceState()); + // Cleanup can release more public references after the original failure. + // Do not retry copies from application memory that may already be freed. + if (state.arrayPrivatizationFailed) + return; + // Disables the device. Set before reporting: callbacks must not resume + // rendering or query bounds using cached aliases to the application-owned + // allocation. + auto fail = [&](cudaError_t error) { + state.arrayPrivatizationFailed = true; + reportMessage(ANARI_SEVERITY_FATAL_ERROR, + "array privatization failed; device disabled: %s", + cudaGetErrorString(error)); + }; + bool changed = false; if (m_data.shared.host.isValid() && !m_data.shared.host.isOwner()) { + // A batched H2D copy may still use the application-owned host pointer. + // Draining does not release the queue's retained array references. + const auto completion = state.preparation.waitForHostReaders(); + if (completion != cudaSuccess) + return fail(completion); reportMessage(ANARI_SEVERITY_PERFORMANCE_WARNING, "making private copy of shared host array (type '%s') | refs: (%i:%i)", anari::toString(elementType()), this->useCount(helium::RefType::PUBLIC), this->useCount(helium::RefType::INTERNAL)); m_data.shared.host.privatize(); + changed = true; } if (m_data.shared.device.isValid() && !m_data.shared.device.isOwner()) { reportMessage(ANARI_SEVERITY_PERFORMANCE_WARNING, @@ -180,8 +203,21 @@ void Array::privatize() anari::toString(elementType()), this->useCount(helium::RefType::PUBLIC), this->useCount(helium::RefType::INTERNAL)); - m_data.shared.device.privatize(); + // Existing frames may still read the shared pointer. The application may + // free it as soon as this last PUBLIC release returns. + // Deferred preprocessing can still read this external allocation even + // when no frame is in flight. Retain it through that stream's completion. + auto completion = state.preparation.waitForDeviceReaders(); + if (completion == cudaSuccess) + completion = m_data.shared.device.privatize(); + if (completion != cudaSuccess) + return fail(completion); + changed = true; } + // Geometry may alias authored arrays directly: a new backing allocation is + // an observable pointer change even though the array's values did not change. + if (changed) + notifyChangeObservers(); } void Array::uploadArrayData() const @@ -189,16 +225,61 @@ void Array::uploadArrayData() const if (!needToUploadData()) return; - if (m_data.shared.host.isValid()) - m_data.shared.device = m_data.shared.host; - else if (m_data.captured.host.isValid()) - m_data.captured.device = m_data.captured.host; - else if (m_data.managed.host.isValid()) - m_data.managed.device = m_data.managed.host; + if (const auto backing = hostBacking(); backing.host) + *backing.device = *backing.host; markDataUploaded(); } +Array::HostBacking Array::hostBacking() const +{ + if (m_data.shared.host.isValid()) + return {&m_data.shared.host, &m_data.shared.device}; + if (m_data.captured.host.isValid()) + return {&m_data.captured.host, &m_data.captured.device}; + if (m_data.managed.host.isValid()) + return {&m_data.managed.host, &m_data.managed.device}; + return {}; +} + +cudaError_t Array::enqueueUpload(cudaStream_t stream) const +{ + if (anari::isObject(elementType())) + return cudaErrorInvalidValue; // ObjectArray has its own handle translation. + if (!needToUploadData()) + return cudaSuccess; + + const auto [host, device] = hostBacking(); + if (!host) + return cudaSuccess; // Application-owned device inputs are already resident. + + if (!device->isValid()) { + auto cache = static_cast(deviceState()) + ->preparation.inputAllocations(); + void *memory = nullptr; + const auto allocationError = cache->allocate(host->bytes(), &memory); + // Read on every path: this also clears the error a failed allocation left. + const auto lastError = cudaGetLastError(); + if (allocationError != cudaSuccess) + return allocationError; + // From here the owner returns the block to the cache on any early return. + auto allocation = CudaMemoryAllocation::fromCache( + memory, host->bytes(), std::move(cache)); + if (lastError != cudaSuccess) + return lastError; + if (!allocation) + return cudaErrorMemoryAllocation; + *device = std::move(allocation); + } + if (device->bytes() != host->bytes()) + return cudaErrorInvalidValue; + return cudaMemcpyAsync(device->ptr(), + host->ptr(), + host->bytes(), + cudaMemcpyHostToDevice, + stream); +} + ANARIDataType Array::elementType() const { return m_elementType; diff --git a/devices/rtx/device/array/Array.h b/devices/rtx/device/array/Array.h index 22e087649..61c171a65 100644 --- a/devices/rtx/device/array/Array.h +++ b/devices/rtx/device/array/Array.h @@ -82,6 +82,11 @@ struct Array : public UploadableArray void uploadArrayData() const override; + // Queue a pending host upload without marking it complete. Caller retains + // the array and orders prior GPU readers before this stream, then waits for + // completion before markDataUploaded() or exposing the pointer to consumers. + cudaError_t enqueueUpload(cudaStream_t stream) const; + // VisRTX interface // ANARIDataType elementType() const; @@ -122,6 +127,15 @@ struct Array : public UploadableArray // the supplied CUDA pointer. Never upload or expose an internal GPU copy. void *appFacingPtr() const; + // The active host allocation and the device copy uploads fill; both null + // when the array has no host storage (application-owned device memory). + struct HostBacking + { + const HostMemoryAllocation *host{nullptr}; + CudaMemoryAllocation *device{nullptr}; + }; + HostBacking hostBacking() const; + void on_NoInternalReferences() override; void on_NoPublicReferences() override; diff --git a/devices/rtx/device/frame/Frame.cu b/devices/rtx/device/frame/Frame.cu index 702aee870..499b4c31a 100644 --- a/devices/rtx/device/frame/Frame.cu +++ b/devices/rtx/device/frame/Frame.cu @@ -425,6 +425,8 @@ __global__ void resolveVec3Channel(const vec3 *__restrict__ accum, Frame::Frame(DeviceGlobalState *d) : helium::BaseFrame(d), m_denoiser(d) { + // Preparation can reject the first render before newFrame() initializes it. + data().fb.frameID = 0; data().mdlAnimationTime = 0.f; cudaEventCreate(&m_eventStart); cudaEventCreate(&m_eventEnd); @@ -679,6 +681,12 @@ void Frame::renderFrame() instrument::rangePop(); // rebuild BVHs instrument::rangePop(); // update scene + if (m_world->preparationFailed()) { + reportMessage(ANARI_SEVERITY_ERROR, + "skipping render after geometry preprocessing failure"); + return; + } + bool wasDenoising = m_denoise; bool wasDenoisingUsingAlbedo = m_denoiseUsingAlbedo; bool wasDenoisingUsingNormal = m_denoiseUsingNormal; @@ -722,6 +730,16 @@ void Frame::renderFrame() hd.fb.buffers.trimTopK = nullptr; } + const auto registryUpload = state.registry.upload(state.preparationStream); + if (registryUpload != cudaSuccess) { + reportMessage(ANARI_SEVERITY_ERROR, + "skipping render after registry upload failure: %s", + cudaGetErrorString(registryUpload)); + instrument::rangePop(); // frame setup + instrument::rangePop(); // Frame::renderFrame() + instrument::rangePop(); // frame + map + return; + } hd.registry.samplers = state.registry.samplers.devicePtr(); hd.registry.geometries = state.registry.geometries.devicePtr(); hd.registry.materials = state.registry.materials.devicePtr(); @@ -741,6 +759,24 @@ void Frame::renderFrame() upload(); instrument::rangePop(); // Frame::upload() + // Frame/renderer uploads still use legacy default-stream copies. Registries + // are already complete on the preparation stream; finish the remaining + // producers before tracing. + const auto publication = cudaStreamSynchronize(nullptr); + if (publication != cudaSuccess) { + // newFrame() already advanced the checkerboard phase and may have cleared + // accumulation buffers. Restart rather than consuming an unrendered tile + // or restoring counters over buffers whose previous contents are gone. + m_nextFrameReset = true; + reportMessage(ANARI_SEVERITY_ERROR, + "skipping render after GPU publication failure: %s", + cudaGetErrorString(publication)); + instrument::rangePop(); // render all frames + instrument::rangePop(); // Frame::renderFrame() + instrument::rangePop(); // frame + map + return; + } + instrument::rangePush("optixLaunch()"); OPTIX_CHECK(optixLaunch(m_renderer->pipeline(), state.stream, diff --git a/devices/rtx/device/geometry/Cone.cpp b/devices/rtx/device/geometry/Cone.cpp index 678d6c8b6..f5bbee02e 100644 --- a/devices/rtx/device/geometry/Cone.cpp +++ b/devices/rtx/device/geometry/Cone.cpp @@ -53,7 +53,13 @@ Cone::Cone(DeviceGlobalState *d) m_radius(this), m_vertex(this), m_vertexCaps(this) -{} +{ + declarePreparationParameters({"primitive.index", + "vertex.position", + "vertex.radius", + "vertex.cap", + "caps"}); +} Cone::~Cone() = default; @@ -68,153 +74,48 @@ void Cone::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } -void Cone::finalize() +size_t Cone::primitiveCount() const +{ + return m_index ? m_index->size() : m_vertex->size() / 2; +} + +PrimitiveInput Cone::primitiveInput() const +{ + ConeInput input{}; + input.segments = segmentInput( + *m_vertex, m_index.get(), m_vertexCaps.get(), m_defaultCapFlags); + input.radii = + m_radius ? m_radius->beginAs(AddressSpace::GPU) : nullptr; + return {primitiveCount(), input}; +} + +bool Cone::prepare() { if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on cone geometry"); - return; + return false; } if (!m_radius) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.radius' on cone geometry"); - return; + return false; } reportMessage(ANARI_SEVERITY_DEBUG, "finalizing %s cone geometry", m_index ? "indexed" : "soup"); - std::vector implicitIndices; - Span indices; - - if (!m_index) { - implicitIndices.resize(m_vertex->size() / 2); - uvec2 idx(0, 1); - std::for_each( - implicitIndices.begin(), implicitIndices.end(), [&](uvec2 &i) { - i = idx; - idx += 2; - }); - indices = make_Span(implicitIndices.data(), implicitIndices.size()); - } else { - indices = make_Span(m_index->beginAs(), m_index->size()); - } - - const float *radius = m_radius->beginAs(); - - m_aabbs.resize(indices.size()); - - const auto *posBegin = m_vertex->beginAs(); - std::transform( - indices.begin(), indices.end(), m_aabbs.begin(), [&](const uvec2 &c) { - const vec3 &v0 = posBegin[c.x]; - const vec3 &v1 = posBegin[c.y]; - const float r = glm::max(std::abs(radius[c.x]), std::abs(radius[c.y])); - return box3(glm::min(v0, v1) - r, glm::max(v0, v1) + r); - }); - - m_aabbs.upload(); - m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.dataDevice(); - - // Coordinate scale of the intersector's arithmetic; floors hit.epsilon so - // secondary rays clear the solve's fp noise band (see - // GeometryGPUData::epsilonScale). - m_epsilonScale = 0.f; - for (auto it = m_aabbs.begin(); it != m_aabbs.end(); ++it) { - const vec3 m = glm::max(glm::abs(it->lower), glm::abs(it->upper)); - m_epsilonScale = - std::max(m_epsilonScale, std::max(m.x, std::max(m.y, m.z))); - } - - // Vertices/radii/caps may have changed. Rebuild the Geometry Light CDF if a - // surface has ever requested it (order-independent of the surface commit), - // else drop stale data. Mirrors Triangle/Sphere. - m_areaDataValid = false; - if (m_areaDataWanted) - buildAreaData(); - else { - m_totalArea = 0.f; - m_primAreaCdf.clear(); - } - - upload(); -} - -void Cone::buildAreaData() -{ - std::vector implicitIndices; - Span indices; - if (!m_index) { - implicitIndices.resize(m_vertex->size() / 2); - uvec2 idx(0, 1); - for (auto &i : implicitIndices) { - i = idx; - idx += 2; - } - indices = make_Span(implicitIndices.data(), implicitIndices.size()); - } else - indices = make_Span(m_index->beginAs(), m_index->size()); - - const float *radius = m_radius->beginAs(); - const vec3 *pos = m_vertex->beginAs(); - const uint8_t *vcaps = m_vertexCaps ? m_vertexCaps->beginAs() : nullptr; - - const size_t n = indices.size(); - m_primAreaCdf.resize(n); - auto *cdf = m_primAreaCdf.dataHost(); - - double cumulative = 0.0; - for (size_t i = 0; i < n; ++i) { - const uvec2 c = indices[i]; - const double r0 = double(std::abs(radius[c.x])); - const double r1 = double(std::abs(radius[c.y])); - const double len = double(glm::length(pos[c.y] - pos[c.x])); - const bool cap0 = vcaps ? (vcaps[c.x] != 0) : (m_defaultCapFlags & CAP_FIRST); - const bool cap1 = vcaps ? (vcaps[c.y] != 0) : (m_defaultCapFlags & CAP_SECOND); - // A degenerate (zero-length) cone gets no pick mass; the sampler - // early-returns on it, so any mass here would be a wasted sample. - double area = 0.0; - if (len > 0.0) { - const double slant = std::sqrt(len * len + (r0 - r1) * (r0 - r1)); - area = double(kPi) * (r0 + r1) * slant; // lateral (frustum) - if (cap0) - area += double(kPi) * r0 * r0; - if (cap1) - area += double(kPi) * r1 * r1; - } - cumulative += area; - cdf[i] = float(cumulative); - } - m_totalArea = float(cumulative); - - if (m_totalArea > 0.f) { - for (size_t i = 0; i < n; ++i) - cdf[i] /= m_totalArea; - } - - m_primAreaCdf.upload(); - m_areaDataValid = true; -} - -bool Cone::isAreaSamplingSupported() const -{ + if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs)) + return false; + m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); return true; } -void Cone::ensureAreaData() -{ - m_areaDataWanted = true; - if (m_areaDataValid) - return; - buildAreaData(); - upload(); // republish gpuData() so the CDF pointers reach the device -} - -float Cone::totalArea() const +std::optional Cone::areaInput() const { - return m_totalArea; + return isValid() ? primitiveInput() : PrimitiveInput{}; } bool Cone::isValid() const @@ -227,7 +128,7 @@ void Cone::populateBuildInput(OptixBuildInput &buildInput) const buildInput.type = OPTIX_BUILD_INPUT_TYPE_CUSTOM_PRIMITIVES; buildInput.customPrimitiveArray.aabbBuffers = &m_aabbsBufferPtr; - buildInput.customPrimitiveArray.numPrimitives = m_aabbs.size(); + buildInput.customPrimitiveArray.numPrimitives = primitiveCount(); static uint32_t buildInputFlags[1] = {OPTIX_GEOMETRY_FLAG_NONE}; @@ -255,10 +156,7 @@ GeometryGPUData Cone::gpuData() const : nullptr; populateAttributeDataSet(m_vertexAttributes, cone.vertexAttr); - // Geometry Light sampling data; null/zero until ensureAreaData() runs. - cone.primAreaCdf = m_primAreaCdf.dataDevice(); - cone.numPrimitives = uint32_t(m_primAreaCdf.size()); - cone.totalArea = m_totalArea; + populateAreaData(cone, primitiveCount()); return retval; } diff --git a/devices/rtx/device/geometry/Cone.h b/devices/rtx/device/geometry/Cone.h index c04b8fe5f..7f867ba4d 100644 --- a/devices/rtx/device/geometry/Cone.h +++ b/devices/rtx/device/geometry/Cone.h @@ -33,7 +33,7 @@ #include "Geometry.h" #include "array/Array1D.h" -#include "utility/HostDeviceArray.h" +#include "utility/DeviceBuffer.h" namespace visrtx { @@ -43,23 +43,19 @@ struct Cone : public Geometry ~Cone() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; - // Build the per-primitive area CDF and object-space total area (lateral + - // enabled caps) used to sample this geometry as a Geometry Light. Lazy: only - // Emissive Surfaces call it. Mirrors Triangle/Sphere. - bool isAreaSamplingSupported() const override; - void ensureAreaData() override; - float totalArea() const override; - private: + bool prepare() override; GeometryGPUData gpuData() const override; - void buildAreaData(); + // Geometry Light sampling: the object-space area is lateral + enabled caps. + std::optional areaInput() const override; + PrimitiveInput primitiveInput() const; + size_t primitiveCount() const; helium::ChangeObserverPtr m_index; helium::ChangeObserverPtr m_radius; @@ -67,16 +63,10 @@ struct Cone : public Geometry helium::ChangeObserverPtr m_vertexCaps; GeometryAttributes m_vertexAttributes; - HostDeviceArray m_aabbs; + DeviceBuffer m_aabbs; CUdeviceptr m_aabbsBufferPtr{}; uint8_t m_defaultCapFlags{0}; - - // Geometry Light sampling data, built lazily by ensureAreaData(); see Triangle. - HostDeviceArray m_primAreaCdf; - float m_totalArea{0.f}; - bool m_areaDataValid{false}; - bool m_areaDataWanted{false}; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/Curve.cpp b/devices/rtx/device/geometry/Curve.cpp index bdb865014..8a614498a 100644 --- a/devices/rtx/device/geometry/Curve.cpp +++ b/devices/rtx/device/geometry/Curve.cpp @@ -37,7 +37,10 @@ namespace visrtx { Curve::Curve(DeviceGlobalState *d) : Geometry(d), m_index(this), m_vertexPosition(this), m_vertexRadius(this) -{} +{ + declarePreparationParameters( + {"primitive.index", "vertex.position", "vertex.radius", "radius"}); +} Curve::~Curve() = default; @@ -51,25 +54,26 @@ void Curve::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } -void Curve::finalize() +bool Curve::prepare() { if (!m_vertexPosition) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on curve geometry"); - return; + return false; } reportMessage(ANARI_SEVERITY_DEBUG, "finalizing %s curve geometry", m_index ? "indexed" : "soup"); - computeIndices(); - computeRadii(); + if (!computeIndices() || !computeRadii() + || !deviceState()->preparation.finish(this)) + return false; m_vertexBufferPtr = (CUdeviceptr)m_vertexPosition->begin(AddressSpace::GPU); - m_radiusBufferPtr = (CUdeviceptr)m_generatedRadii.dataDevice(); + m_radiusBufferPtr = (CUdeviceptr)m_radii; - upload(); + return true; } void Curve::populateBuildInput(OptixBuildInput &buildInput) const @@ -88,8 +92,8 @@ void Curve::populateBuildInput(OptixBuildInput &buildInput) const curveArray.widthBuffers = &m_radiusBufferPtr; curveArray.indexStrideInBytes = sizeof(uint32_t); - curveArray.numPrimitives = m_generatedIndices.size(); - curveArray.indexBuffer = (CUdeviceptr)m_generatedIndices.dataDevice(); + curveArray.numPrimitives = m_numPrimitives; + curveArray.indexBuffer = (CUdeviceptr)m_indices; curveArray.normalBuffers = 0; curveArray.normalStrideInBytes = 0; @@ -105,32 +109,30 @@ bool Curve::isValid() const return m_vertexPosition; } -void Curve::computeIndices() +bool Curve::computeIndices() { + m_numPrimitives = m_index ? m_index->size() : m_vertexPosition->size() / 2; if (m_index) { - m_generatedIndices.resize(m_index->size()); - std::copy(m_index->beginAs(), - m_index->endAs(), - m_generatedIndices.begin()); - } else { - m_generatedIndices.resize(m_vertexPosition->size() / 2); - std::iota(m_generatedIndices.begin(), m_generatedIndices.end(), 0); + m_indices = m_index->beginAs(AddressSpace::GPU); + return true; } - m_generatedIndices.upload(); + if (!generateCurveIndices(this, m_numPrimitives, m_generatedIndices)) + return false; + m_indices = m_generatedIndices.ptrAs(); + return true; } -void Curve::computeRadii() +bool Curve::computeRadii() { if (m_vertexRadius) { - m_generatedRadii.resize(m_vertexRadius->totalCapacity()); - std::copy(m_vertexRadius->dataAs(), - m_vertexRadius->dataAs() + m_vertexRadius->totalCapacity(), - m_generatedRadii.begin()); - } else { - m_generatedRadii.resize(m_vertexPosition->size()); - std::fill(m_generatedRadii.begin(), m_generatedRadii.end(), m_globalRadius); + m_radii = m_vertexRadius->beginAs(AddressSpace::GPU); + return true; } - m_generatedRadii.upload(); + if (!generateCurveRadii( + this, m_vertexPosition->size(), m_globalRadius, m_generatedRadii)) + return false; + m_radii = m_generatedRadii.ptrAs(); + return true; } GeometryGPUData Curve::gpuData() const @@ -140,8 +142,8 @@ GeometryGPUData Curve::gpuData() const auto &curve = retval.curve; curve.vertices = m_vertexPosition->beginAs(AddressSpace::GPU); - curve.indices = m_generatedIndices.dataDevice(); - curve.radii = m_generatedRadii.dataDevice(); + curve.indices = m_indices; + curve.radii = m_radii; populateAttributeDataSet(m_vertexAttributes, curve.vertexAttr); return retval; diff --git a/devices/rtx/device/geometry/Curve.h b/devices/rtx/device/geometry/Curve.h index 5683cf308..180b5d89d 100644 --- a/devices/rtx/device/geometry/Curve.h +++ b/devices/rtx/device/geometry/Curve.h @@ -33,7 +33,7 @@ #include "Geometry.h" #include "array/Array1D.h" -#include "utility/HostDeviceArray.h" +#include "utility/DeviceBuffer.h" namespace visrtx { @@ -43,7 +43,6 @@ struct Curve : public Geometry ~Curve() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; @@ -51,8 +50,9 @@ struct Curve : public Geometry int optixGeometryType() const override; private: - void computeIndices(); - void computeRadii(); + bool prepare() override; + bool computeIndices(); + bool computeRadii(); GeometryGPUData gpuData() const override; helium::ChangeObserverPtr m_index; @@ -62,8 +62,11 @@ struct Curve : public Geometry float m_globalRadius; - HostDeviceArray m_generatedIndices; - HostDeviceArray m_generatedRadii; + DeviceBuffer m_generatedIndices; + DeviceBuffer m_generatedRadii; + const uint32_t *m_indices{nullptr}; + const float *m_radii{nullptr}; + size_t m_numPrimitives{0}; CUdeviceptr m_vertexBufferPtr{}; CUdeviceptr m_radiusBufferPtr{}; diff --git a/devices/rtx/device/geometry/Cylinder.cpp b/devices/rtx/device/geometry/Cylinder.cpp index a703f1654..5ad18d15a 100644 --- a/devices/rtx/device/geometry/Cylinder.cpp +++ b/devices/rtx/device/geometry/Cylinder.cpp @@ -53,7 +53,14 @@ Cylinder::Cylinder(DeviceGlobalState *d) m_radius(this), m_vertex(this), m_vertexCaps(this) -{} +{ + declarePreparationParameters({"primitive.index", + "vertex.position", + "primitive.radius", + "vertex.cap", + "caps", + "radius"}); +} Cylinder::~Cylinder() = default; @@ -69,150 +76,43 @@ void Cylinder::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } -void Cylinder::finalize() +size_t Cylinder::primitiveCount() const +{ + return m_index ? m_index->size() : m_vertex->size() / 2; +} + +PrimitiveInput Cylinder::primitiveInput() const +{ + CylinderInput input{}; + input.segments = segmentInput( + *m_vertex, m_index.get(), m_vertexCaps.get(), m_defaultCapFlags); + input.radii = + m_radius ? m_radius->beginAs(AddressSpace::GPU) : nullptr; + input.radius = m_globalRadius; + return {primitiveCount(), input}; +} + +bool Cylinder::prepare() { if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on cylinders geometry"); - return; + return false; } reportMessage(ANARI_SEVERITY_DEBUG, "finalizing %s cylinder geometry", m_index ? "indexed" : "soup"); - std::vector implicitIndices; - Span indices; - - if (!m_index) { - implicitIndices.resize(m_vertex->size() / 2); - uvec2 idx(0, 1); - std::for_each( - implicitIndices.begin(), implicitIndices.end(), [&](uvec2 &i) { - i = idx; - idx += 2; - }); - indices = make_Span(implicitIndices.data(), implicitIndices.size()); - } else { - indices = make_Span(m_index->beginAs(), m_index->size()); - } - - const float *radius = nullptr; - if (m_radius) - radius = m_radius->beginAs(); - - m_aabbs.resize(indices.size()); - - const auto *posBegin = m_vertex->beginAs(); - size_t cylinderID = 0; - std::transform( - indices.begin(), indices.end(), m_aabbs.begin(), [&](const uvec2 &c) { - const float r = - std::abs(radius ? radius[cylinderID++] : m_globalRadius); - const vec3 &v0 = posBegin[c.x]; - const vec3 &v1 = posBegin[c.y]; - return box3(glm::min(v0, v1) - r, glm::max(v0, v1) + r); - }); - - m_aabbs.upload(); - m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.dataDevice(); - - // Coordinate scale of the intersector's arithmetic; floors hit.epsilon so - // secondary rays clear the solve's fp noise band (see - // GeometryGPUData::epsilonScale). - m_epsilonScale = 0.f; - for (auto it = m_aabbs.begin(); it != m_aabbs.end(); ++it) { - const vec3 m = glm::max(glm::abs(it->lower), glm::abs(it->upper)); - m_epsilonScale = - std::max(m_epsilonScale, std::max(m.x, std::max(m.y, m.z))); - } - - // Vertices/radii/caps may have changed. Rebuild the Geometry Light CDF if a - // surface has ever requested it (order-independent of the surface commit), - // else drop stale data. Mirrors Triangle/Sphere. - m_areaDataValid = false; - if (m_areaDataWanted) - buildAreaData(); - else { - m_totalArea = 0.f; - m_primAreaCdf.clear(); - } - - upload(); -} - -void Cylinder::buildAreaData() -{ - std::vector implicitIndices; - Span indices; - if (!m_index) { - implicitIndices.resize(m_vertex->size() / 2); - uvec2 idx(0, 1); - for (auto &i : implicitIndices) { - i = idx; - idx += 2; - } - indices = make_Span(implicitIndices.data(), implicitIndices.size()); - } else - indices = make_Span(m_index->beginAs(), m_index->size()); - - const float *radius = m_radius ? m_radius->beginAs() : nullptr; - const vec3 *pos = m_vertex->beginAs(); - const uint8_t *vcaps = m_vertexCaps ? m_vertexCaps->beginAs() : nullptr; - - const size_t n = indices.size(); - m_primAreaCdf.resize(n); - auto *cdf = m_primAreaCdf.dataHost(); - - double cumulative = 0.0; - for (size_t i = 0; i < n; ++i) { - const uvec2 c = indices[i]; - const float r = std::abs(radius ? radius[i] : m_globalRadius); - const double len = double(glm::length(pos[c.y] - pos[c.x])); - const bool cap0 = vcaps ? (vcaps[c.x] != 0) : (m_defaultCapFlags & CAP_FIRST); - const bool cap1 = vcaps ? (vcaps[c.y] != 0) : (m_defaultCapFlags & CAP_SECOND); - // A degenerate (zero-length or zero-radius) cylinder gets no pick mass; the - // sampler early-returns on it, so any mass here would be a wasted sample. - double area = 0.0; - if (len > 0.0 && r > 0.0f) { - area = 2.0 * double(kPi) * double(r) * len; // lateral - const double capArea = double(kPi) * double(r) * double(r); - if (cap0) - area += capArea; - if (cap1) - area += capArea; - } - cumulative += area; - cdf[i] = float(cumulative); - } - m_totalArea = float(cumulative); - - if (m_totalArea > 0.f) { - for (size_t i = 0; i < n; ++i) - cdf[i] /= m_totalArea; - } - - m_primAreaCdf.upload(); - m_areaDataValid = true; -} - -bool Cylinder::isAreaSamplingSupported() const -{ + if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs)) + return false; + m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); return true; } -void Cylinder::ensureAreaData() -{ - m_areaDataWanted = true; - if (m_areaDataValid) - return; - buildAreaData(); - upload(); // republish gpuData() so the CDF pointers reach the device -} - -float Cylinder::totalArea() const +std::optional Cylinder::areaInput() const { - return m_totalArea; + return isValid() ? primitiveInput() : PrimitiveInput{}; } bool Cylinder::isValid() const @@ -225,7 +125,7 @@ void Cylinder::populateBuildInput(OptixBuildInput &buildInput) const buildInput.type = OPTIX_BUILD_INPUT_TYPE_CUSTOM_PRIMITIVES; buildInput.customPrimitiveArray.aabbBuffers = &m_aabbsBufferPtr; - buildInput.customPrimitiveArray.numPrimitives = m_aabbs.size(); + buildInput.customPrimitiveArray.numPrimitives = primitiveCount(); static uint32_t buildInputFlags[1] = {OPTIX_GEOMETRY_FLAG_NONE}; @@ -251,10 +151,7 @@ GeometryGPUData Cylinder::gpuData() const : nullptr; populateAttributeDataSet(m_vertexAttributes, cylinder.vertexAttr); - // Geometry Light sampling data; null/zero until ensureAreaData() runs. - cylinder.primAreaCdf = m_primAreaCdf.dataDevice(); - cylinder.numPrimitives = uint32_t(m_primAreaCdf.size()); - cylinder.totalArea = m_totalArea; + populateAreaData(cylinder, primitiveCount()); return retval; } diff --git a/devices/rtx/device/geometry/Cylinder.h b/devices/rtx/device/geometry/Cylinder.h index 2b66e29e1..bad035da2 100644 --- a/devices/rtx/device/geometry/Cylinder.h +++ b/devices/rtx/device/geometry/Cylinder.h @@ -33,7 +33,7 @@ #include "Geometry.h" #include "array/Array1D.h" -#include "utility/HostDeviceArray.h" +#include "utility/DeviceBuffer.h" namespace visrtx { @@ -43,23 +43,19 @@ struct Cylinder : public Geometry ~Cylinder() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; - // Build the per-primitive area CDF and object-space total area (lateral + - // enabled caps) used to sample this geometry as a Geometry Light. Lazy: only - // Emissive Surfaces call it. Mirrors Triangle/Sphere. - bool isAreaSamplingSupported() const override; - void ensureAreaData() override; - float totalArea() const override; - private: + bool prepare() override; GeometryGPUData gpuData() const override; - void buildAreaData(); + // Geometry Light sampling: the object-space area is lateral + enabled caps. + std::optional areaInput() const override; + PrimitiveInput primitiveInput() const; + size_t primitiveCount() const; helium::ChangeObserverPtr m_index; helium::ChangeObserverPtr m_radius; @@ -67,18 +63,12 @@ struct Cylinder : public Geometry helium::ChangeObserverPtr m_vertexCaps; GeometryAttributes m_vertexAttributes; - HostDeviceArray m_aabbs; + DeviceBuffer m_aabbs; CUdeviceptr m_aabbsBufferPtr{}; float m_globalRadius{1.f}; uint8_t m_defaultCapFlags{0}; - - // Geometry Light sampling data, built lazily by ensureAreaData(); see Triangle. - HostDeviceArray m_primAreaCdf; - float m_totalArea{0.f}; - bool m_areaDataValid{false}; - bool m_areaDataWanted{false}; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index a00502c1f..9717341de 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -47,6 +47,7 @@ // std #include #include +#include // helium #include @@ -113,6 +114,25 @@ Geometry *Geometry::createInstance( void Geometry::commitParameters() { + if (m_inputBatch != InputBatch::None) + deviceState()->preparation.uploadInputs(); + // A parameter commit retries every failure. + if (m_inputBatch == InputBatch::Failed) + m_inputBatch = InputBatch::Queued; + if (preparationFailed()) + m_retry = Retry::Finalize; + if (m_preparationPosition) + deviceState()->preparation.collect(); + // Array observers can re-finalize without a parameter commit, but parameter + // replacement can release the last reference to an aliased device array. + // Complete earlier consumers before subclasses replace those references. + const bool retain = canRetainPreparationInputs(); + const bool retired = retain + || deviceState()->preparation.check(this, + deviceState()->preparation.retireRender(), + "retiring previous geometry inputs"); + if (!retired) + markPreparationFailed(Retry::Commit); commitAttributes("primitive.", m_primitiveAttributes); auto getUniformAttribute = @@ -130,24 +150,313 @@ void Geometry::commitParameters() m_uniformAttributes.attribute3 = getUniformAttribute("attribute3"); m_uniformAttributes.color = getUniformAttribute("color"); m_primitiveId = getParamObject("primitive.id"); + if (!retain && retired) + stageInputUploads(); } void Geometry::markFinalized() { Object::markFinalized(); - deviceState()->objectUpdates.lastSurfaceBLASChange = helium::newTimeStamp(); + if (!m_preparationReused) + deviceState()->objectUpdates.lastSurfaceBLASChange = helium::newTimeStamp(); +} + +bool Geometry::PreparationParameter::sameInput( + const PreparationParameter &other) const +{ + return parameterIndex == other.parameterIndex && value == other.value + && updated == other.updated && finalized == other.finalized + && modified == other.modified; +} + +bool Geometry::PreparationParameter::operator==( + const PreparationParameter &other) const +{ + return sameInput(other) && devicePointer == other.devicePointer; +} + +bool Geometry::canRetainPreparationInputs() const +{ + if (m_preparationState != PreparationState::Prepared + || m_preparationParameterNames.empty()) + return false; + + // Inspect committed values only, before subclasses replace their references. + // Do not call dataGPU(): it can upload/replace storage. Pointer validation + // remains in beginPreparation(), after references have been retained safely. + size_t present = 0; + const bool same = forEachPreparationParameter( + [&](PreparationParameter &¶meter, Array *) { + return present < m_preparedParameters.size() + && m_preparedParameters[present++].sameInput(parameter); + }); + return same && present == m_preparedParameters.size(); +} + +void Geometry::completePreparation() +{ + // complete() fails the geometry whenever it returns false. + if (m_preprocessing.complete(this)) + upload(); +} + +void Geometry::markPreparationCollected() noexcept +{ + m_preparationPosition.reset(); +} + +void Geometry::upload() +{ + if (m_preprocessing.pending()) { + deviceState()->preparation.defer(this); + return; + } + RegisteredObject::upload(); + if (preparationFailed()) + return; + if (isValid()) + m_preparationState = PreparationState::Prepared; + else { + m_preparationState = PreparationState::Unprepared; + m_preparationReused = false; + } +} + +void Geometry::declarePreparationParameters( + std::initializer_list parameters) +{ + for (const char *name : {"primitive.attribute0", + "primitive.attribute1", + "primitive.attribute2", + "primitive.attribute3", + "primitive.color", + "primitive.id", + "vertex.attribute0", + "vertex.attribute1", + "vertex.attribute2", + "vertex.attribute3", + "vertex.color"}) + m_preparationParameterNames.emplace_back(name); + for (const char *name : parameters) + m_preparationParameterNames.emplace_back(name); +} + +static bool needsInputUpload(const Array *array) +{ + return array && array->needToUploadData() && array->dataHost(); +} + +void Geometry::stageInputUploads() +{ + m_inputUploads.clear(); + forEachPreparationParameter( + [&](PreparationParameter &¶meter, Array *array) { + if (needsInputUpload(array)) + m_inputUploads.push_back({array, parameter.modified, false}); + return true; + }); + if (m_inputUploads.empty()) + return; + deviceState()->preparation.stageInputs(this); + m_inputBatch = InputBatch::Queued; +} + +void Geometry::retirePreparationSnapshot() +{ + // Only queued by a commit whose render-consumer retirement check succeeded. + // Discard obsolete references before allocating a multi-geometry cohort. + // Until beginPreparation establishes the new generation, old GPU records + // must not be usable if a host exception aborts finalization. + markPreparationFailed(); + m_preparedParameters.clear(); +} + +void Geometry::submitInputUploads() +{ + if (m_inputBatch == InputBatch::Failed) + return; + auto &state = *deviceState(); + auto fail = [&](cudaError_t error, const char *operation) { + if (error == cudaSuccess) + return false; + failInputUploads(); + state.preparation.fail(this, error, operation); + return true; + }; + for (auto &upload : m_inputUploads) { + upload.modified = upload.array->lastDataModified(); + const auto error = + state.preparation.stageArray(upload.array.ptr, upload.modified); + upload.submitted = error == cudaSuccess; + if (fail(error, "geometry array upload")) + return; + } +} + +void Geometry::failInputUploads() +{ + m_inputBatch = InputBatch::Failed; + markPreparationFailed(Retry::Update); +} + +void Geometry::completeInputUploads() noexcept +{ + for (const auto &upload : m_inputUploads) + if (!upload.submitted) + failInputUploads(); + const bool failed = m_inputBatch == InputBatch::Failed; + m_inputBatch = InputBatch::None; + if (failed) + m_failedInputUpdate = lastUpdated(); + else { + for (const auto &upload : m_inputUploads) { + // Array finalization or a coalesced unmap may have changed the version + // since submission. Leave that array dirty for the conservative path. + if (upload.array->lastDataModified() == upload.modified) + upload.array->markDataUploaded(); + } + } + m_inputUploads.clear(); +} + +void Geometry::finalize() +{ + if (beginPreparation() != PreparationStart::Prepare) + return; + if (prepare() && refreshAreaData()) + upload(); +} + +Geometry::PreparationStart Geometry::beginPreparation() +{ + if (!deviceState()->preparation.uploadInputs()) + return PreparationStart::Blocked; + // Observer-only finalization can arrive before a prior submission is + // collected. + if (m_preparationPosition) + deviceState()->preparation.collect(); + m_preparationReused = false; + // A later observer update is a new generation too; it may retry a failed + // input batch without requiring a parameter commit on the geometry. + if (preparationFailed() && m_retry == Retry::Update + && lastUpdated() > m_failedInputUpdate) + m_retry = Retry::Finalize; + if (retryBlocked()) + return PreparationStart::Blocked; + + std::vector current; + if (!m_preparationParameterNames.empty()) { + current.reserve(m_preparedParameters.capacity()); + // Indices remain valid if current grows; its AnariAny values retain every + // source array until the batch completes (including on failure). + std::vector> pendingUploads; + forEachPreparationParameter( + [&](PreparationParameter &¶meter, Array *array) { + // Privatization can change backing pointers without changing values + // or the array timestamp. Never reuse cached aliases in that case. + if (needsInputUpload(array)) + pendingUploads.emplace_back(current.size(), array); + else if (array) + parameter.devicePointer = array->dataGPU(); + current.push_back(std::move(parameter)); + return true; + }); + + if (!pendingUploads.empty()) { + // No commit captured these: an observer-only update, or an array + // modified after its batch was submitted. Upload them the same way, as + // a batch of this geometry alone. Its failure is this finalize's, so + // the next one retries. + stageInputUploads(); + deviceState()->preparation.uploadInputs(); + if (retryBlocked()) { + m_retry = Retry::Finalize; + return PreparationStart::Blocked; + } + for (const auto &[index, array] : pendingUploads) + current[index].devicePointer = array->dataGPU(); + } + + // Observer-only updates always take the preparation path. A geometry-wide + // attribute edit coalesced with an array change cannot hide that change; + // the versions/pointers above still invalidate preparation reuse. + if (m_preparationState == PreparationState::Prepared && isValid() + && lastCommitted() > lastFinalized() + && current == m_preparedParameters) { + m_preparationReused = true; + upload(); + return PreparationStart::Reused; + } + } + m_preparedParameters = std::move(current); + m_preparationState = PreparationState::Unprepared; + // Full preparation can overwrite derived buffers read by earlier frames. + // Keep that dependency on the GPU; parameter-reference retirement above + // still requires a host wait before releasing old application storage. + return deviceState()->preparation.check(this, + deviceState()->preparationStream.orderAfterRender(), + "previous geometry consumers") + ? PreparationStart::Prepare + : PreparationStart::Blocked; +} + +bool Geometry::preparationFailed() const +{ + return m_preparationState == PreparationState::Failed; +} + +bool Geometry::retryBlocked() const +{ + return preparationFailed() && m_retry != Retry::Finalize; +} + +void Geometry::markPreparationFailed(Retry retry) +{ + if (!preparationFailed() || retry > m_retry) + m_retry = retry; + m_preparationState = PreparationState::Failed; + m_preparationReused = false; +} + +std::optional Geometry::areaInput() const +{ + return {}; } bool Geometry::isAreaSamplingSupported() const { - return false; + return areaInput().has_value(); } -void Geometry::ensureAreaData() {} +void Geometry::ensureAreaData() +{ + if (m_areaDataValid) + return; + const auto input = areaInput(); + if (!input) + return; + m_areaDataWanted = true; + m_areaDataValid = m_preprocessing.areas(this, *input); + if (m_areaDataValid) + upload(); // republish only successfully prepared sampling data +} + +bool Geometry::refreshAreaData() +{ + // prepare() may have changed what the CDF was computed from. + m_areaDataValid = false; + if (!m_areaDataWanted) { + m_preprocessing.releaseAreas(); + return true; + } + // Wanted implies that the subtype has an area input. + m_areaDataValid = m_preprocessing.areas(this, *areaInput()); + return m_areaDataValid; +} float Geometry::totalArea() const { - return 0.f; + return m_preprocessing.totalArea(); } GeometryGPUData Geometry::gpuData() const @@ -168,7 +477,7 @@ GeometryGPUData Geometry::gpuData() const populateAttributeDataSet(m_primitiveAttributes, retval.attr); retval.primitiveId = (const uint32_t *)(m_primitiveId ? m_primitiveId->dataGPU() : nullptr); - retval.epsilonScale = m_epsilonScale; + retval.epsilonScale = m_preprocessing.epsilonScale(); return retval; } diff --git a/devices/rtx/device/geometry/Geometry.h b/devices/rtx/device/geometry/Geometry.h index c0a0f7a47..9d1e9055b 100644 --- a/devices/rtx/device/geometry/Geometry.h +++ b/devices/rtx/device/geometry/Geometry.h @@ -31,11 +31,16 @@ #pragma once +#include "Preprocessing.h" #include "RegisteredObject.h" #include "array/Array1D.h" #include "gpu/gpu_objects.h" // std +#include #include +#include +#include +#include namespace visrtx { @@ -71,21 +76,56 @@ struct Geometry : public RegisteredObject std::string_view subtype, DeviceGlobalState *d); void commitParameters() override; + // Final so that no subtype can skip the preparation protocol; subtypes + // implement prepare() instead. + void finalize() final; void markFinalized() override; + // Defers registry publication while preprocessing results are pending. + void upload() override; virtual void populateBuildInput(OptixBuildInput &) const = 0; virtual int optixGeometryType() const = 0; - // Geometry Light area sampling. Only types that can be sampled by area as an - // Emissive Surface override these (Stage 1: Triangle). ensureAreaData() builds - // the per-primitive area CDF; totalArea() is the object-space emitting area. - virtual bool isAreaSamplingSupported() const; - virtual void ensureAreaData(); - virtual float totalArea() const; + // Geometry Light area sampling, for the subtypes that implement areaInput(). + // ensureAreaData() submits the per-primitive area CDF if it is not current, + // and republishes the geometry. Lazy: only Emissive Surfaces call it, so + // ordinary geometry never pays for it. The request persists, so every later + // finalize rebuilds the CDF whatever the order of surface and geometry + // commits. Collect device geometry preparations before reading totalArea(), + // the object-space emitting area, or publishing a registry. + bool isAreaSamplingSupported() const; + void ensureAreaData(); + float totalArea() const; + + // True from a failure until a finalize prepares the geometry again. + bool preparationFailed() const; protected: + // Declare once in the subtype constructor, before the first commit. List + // every consumed parameter except geometry-wide attributes; the base adds + // primitive and vertex arrays. These inputs determine preparation reuse. + void declarePreparationParameters( + std::initializer_list parameters); + + // Builds the subtype's device data for a new generation; finalize() calls + // it only when one is needed, and uploads when it returns true. Return false + // for every reason not to upload: a missing required parameter, or a step + // that failed the geometry. finalize() does not ask preparationFailed() + // afterwards, so a failed step's result must not be discarded. Never call + // upload() here. + virtual bool prepare() = 0; GeometryGPUData gpuData() const override = 0; + // The input of the per-primitive area CDF, or nothing when the subtype + // cannot be sampled as a Geometry Light. Asked in any state: return an empty + // input while !isValid(). + virtual std::optional areaInput() const; + // Fills the Geometry Light fields of the subtype's GPU record: the CDF is + // null and the other two zero until ensureAreaData() ran and was collected. + // `count` is the subtype's primitive count, the length of the CDF. + template + void populateAreaData(RECORD_T &record, size_t count) const; + void commitAttributes(const char *prefix, GeometryAttributes &attrs); void populateAttributeDataSet( const GeometryAttributes &hostAttrs, AttributeDataSet &gpuAttrs) const; @@ -93,11 +133,167 @@ struct Geometry : public RegisteredObject GeometryAttributes m_primitiveAttributes; UniformAttributes m_uniformAttributes; helium::IntrusivePtr m_primitiveId; - // Set by analytic-primitive subtypes in finalize(); see - // GeometryGPUData::epsilonScale. - float m_epsilonScale{0.f}; + Preprocessing m_preprocessing; + + private: + // The device's GeometryPreparation drives the steps below; see its header + // for the order. + friend struct GeometryPreparation; + void completePreparation(); + void markPreparationCollected() noexcept; + void retirePreparationSnapshot(); + void submitInputUploads(); + void completeInputUploads() noexcept; + void failInputUploads(); + // What retries a failed preparation, weakest first. Until it arrives, + // beginPreparation() returns Blocked for the two stronger ones. + enum class Retry + { + Finalize, // The next finalize: every CUDA or numeric failure, a retired + // snapshot, and an input batch that a finalize queued itself. + Update, // A parameter commit, or an observer update newer than + // m_failedInputUpdate: an input batch queued by a commit failed. + Commit, // Only a parameter commit: retiring the previous inputs failed. + }; + // Fails the current generation. Never weakens the retry already recorded. + void markPreparationFailed(Retry retry = Retry::Finalize); + + // After prepare(): resubmits the area CDF if a surface ever asked for it, + // else drops it. False means the geometry failed. + bool refreshAreaData(); + + enum class PreparationStart + { + Prepare, // finalize() runs prepare() and uploads the new generation. + Reused, // Inputs are unchanged; the registry is already republished. + Blocked, // Failed, an earlier failure awaits retry, or an input + // collection is in progress. Nothing is prepared or uploaded. + }; + PreparationStart beginPreparation(); + + struct PreparationParameter + { + size_t parameterIndex{0}; + helium::AnariAny value; + helium::TimeStamp updated{0}; + helium::TimeStamp finalized{0}; + helium::TimeStamp modified{0}; + const void *devicePointer{nullptr}; + + // Equal in everything a commit can read. The device pointer is not: it is + // known only once the uploads finished. + bool sameInput(const PreparationParameter &other) const; + bool operator==(const PreparationParameter &other) const; + }; + // The one walk over the declared parameters. Calls fcn(PreparationParameter + // &&, Array *) for each one that is set, with the committed value, its + // versions and no device pointer; the array is null unless the value is one. + // Never calls dataGPU(), which can upload or replace storage. Stops, and + // returns false, when fcn does. + template + bool forEachPreparationParameter(FCN_T &&fcn) const; + bool canRetainPreparationInputs() const; + // Queues every declared array with host data newer than its device copy as + // this geometry's input batch. + void stageInputUploads(); + + struct InputUpload + { + helium::IntrusivePtr array; + helium::TimeStamp modified{0}; + bool submitted{false}; + }; + std::vector m_inputUploads; + std::vector m_preparedParameters; + std::vector m_preparationParameterNames; + + // Preparation state of the current generation. + // + // Unprepared Nothing published for the current inputs: initial, + // preparing, or published while !isValid(). + // Prepared Published; a commit may retain its inputs. + // Failed Nothing is prepared or published until m_retry arrives. + // + // Event To + // beginPreparation(), full preparation Unprepared + // upload(), unless Failed Prepared if isValid(), else + // Unprepared + // markPreparationFailed(retry) Failed + // + // When its retry arrives a failure only drops to Retry::Finalize; the full + // preparation of that or the next finalize is what leaves Failed. + enum class PreparationState + { + Unprepared, + Prepared, + Failed, + }; + PreparationState m_preparationState{PreparationState::Unprepared}; + // Meaningful while Failed. + Retry m_retry{Retry::Finalize}; + // lastUpdated() when the latest input upload batch failed (Retry::Update). + helium::TimeStamp m_failedInputUpdate{0}; + // The latest finalize reused the preparation, so markFinalized() leaves the + // BLAS change stamp alone. Only ever set while Prepared. + bool m_preparationReused{false}; + + bool retryBlocked() const; + + // Queue membership, independent of the state above. + enum class InputBatch + { + None, // Not queued for input uploads. + Queued, + Failed, // Queued; the batch failed, so submit nothing and mark no array + // uploaded. A commit retries it. Kept apart from Retry::Update + // because a batch can fail under Retry::Commit too. + }; + InputBatch m_inputBatch{InputBatch::None}; + // Position in the device's preparation queue while queued. + std::optional m_preparationPosition; + + // Geometry Light area data. Valid: the submitted CDF matches the current + // generation. Wanted: set by the first ensureAreaData() and kept across + // recommits. + bool m_areaDataValid{false}; + bool m_areaDataWanted{false}; }; +// Inlined definitions //////////////////////////////////////////////////////// + +template +inline bool Geometry::forEachPreparationParameter(FCN_T &&fcn) const +{ + for (size_t i = 0; i < m_preparationParameterNames.size(); ++i) { + // The committed value, not staging. + PreparationParameter parameter{ + i, getParamDirect(m_preparationParameterNames[i])}; + if (!parameter.value.valid()) + continue; // Keep only present values, retaining their parameter identity. + Array *array = nullptr; + if (anari::isObject(parameter.value.type())) { + if (auto *object = parameter.value.getObject()) { + parameter.updated = object->lastUpdated(); + parameter.finalized = object->lastFinalized(); + array = dynamic_cast(object); + if (array) + parameter.modified = array->lastDataModified(); + } + } + if (!fcn(std::move(parameter), array)) + return false; + } + return true; +} + +template +inline void Geometry::populateAreaData(RECORD_T &record, size_t count) const +{ + record.primAreaCdf = m_preprocessing.areaCdf(); + record.numPrimitives = record.primAreaCdf ? uint32_t(count) : 0; + record.totalArea = m_preprocessing.totalArea(); +} + } // namespace visrtx VISRTX_ANARI_TYPEFOR_SPECIALIZATION(visrtx::Geometry *, ANARI_GEOMETRY); diff --git a/devices/rtx/device/geometry/GeometryPreparation.cpp b/devices/rtx/device/geometry/GeometryPreparation.cpp new file mode 100644 index 000000000..5a68959f5 --- /dev/null +++ b/devices/rtx/device/geometry/GeometryPreparation.cpp @@ -0,0 +1,279 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "GeometryPreparation.h" +#include "Geometry.h" +#include "array/Array.h" + +namespace visrtx { + +GeometryPreparation::GeometryPreparation(PreparationStream &stream) + : m_stream(stream) +{} + +GeometryPreparation::~GeometryPreparation() = default; + +void GeometryPreparation::shutdown() +{ + // Disable cached returns and free idle/pending blocks before the device + // destroys its streams. Any allocation outliving the device falls back to + // ordinary free. + m_inputAllocations->close(); +} + +bool GeometryPreparation::busy() const +{ + return m_preparations.collecting() || m_inputUploads.collecting(); +} + +bool GeometryPreparation::collect() +{ + if (!uploadInputs()) + return false; + // Owners remain queued if descriptor allocation or registry publication + // throws. CUDA failure still invalidates the pending batch before reporting, + // so callbacks cannot see a partially valid generation. Numeric failures + // remain local to their geometries during publication. Every publication + // must succeed before any geometry leaves the queue. + return m_preparations.collect( + [&](Geometry *first) { + const auto error = flush(); + if (error != cudaSuccess) + fail(first, error, "batch completion"); + m_preparations.forEach( + [](Geometry *geometry) { geometry->completePreparation(); }); + }, + [](Geometry *geometry) noexcept { geometry->markPreparationCollected(); }, + [] {}); +} + +cudaError_t GeometryPreparation::waitForHostReaders() +{ + // Only an input-upload collection has copies in flight. Draining does not + // release the queue's retained array references. + return uploadingInputs() ? flush() : cudaSuccess; +} + +cudaError_t GeometryPreparation::waitForDeviceReaders() +{ + auto completion = retireRender(); + if (completion == cudaSuccess && pending()) + completion = flush(); + return completion; +} + +std::shared_ptr GeometryPreparation::inputAllocations() + const +{ + return m_inputAllocations; +} + +void GeometryPreparation::stageInputs(Geometry *geometry) +{ + m_inputUploads.enqueue(helium::IntrusivePtr(geometry)); +} + +bool GeometryPreparation::uploadInputs() +{ + return m_inputUploads.collect( + [&](Geometry *first) { + // The only route by which a geometry's host inputs reach the device. + // Commits capture sources; the first geometry finalizer submits every + // input batch before waiting. No legacy finalizer sees partially + // uploaded arrays. A finalizer then queues what no commit captured + // as a batch of its own. Retire obsolete cached copies before + // allocating a whole replacement cohort. A single geometry retains + // the existing allocation/retirement order. + if (m_inputUploads.size() > 1) + m_inputUploads.forEach([](Geometry *geometry) { + geometry->retirePreparationSnapshot(); + }); + auto error = m_inputAllocations->reclaim([&] { return flush(); }); + if (error == cudaSuccess) + error = m_stream.orderAfterRender(); + if (error == cudaSuccess) { + m_inputUploads.forEach( + [](Geometry *geometry) { geometry->submitInputUploads(); }); + error = flush(); + } + if (error != cudaSuccess) { + failInputUploads(); + fail(first, error, "geometry input batch completion"); + } + m_inputVersions.clear(); + }, + [](Geometry *geometry) noexcept { geometry->completeInputUploads(); }, + [&] { + // A host allocation or callback can unwind after copies were + // submitted. Keep sources alive and drain before permitting public + // release again. + failInputUploads(); + flush(); + m_inputVersions.clear(); + }); +} + +cudaError_t GeometryPreparation::stageArray( + Array *array, helium::TimeStamp modified) +{ + const auto found = m_inputVersions.find(array); + if (found != m_inputVersions.end() && found->second == modified) + return cudaSuccess; + const auto error = array->enqueueUpload(m_stream.stream()); + if (error == cudaSuccess) + m_inputVersions.insert_or_assign(array, modified); + return error; +} + +void GeometryPreparation::defer(Geometry *geometry) +{ + if (!geometry->m_preparationPosition) + geometry->m_preparationPosition = + m_preparations.enqueue(helium::IntrusivePtr(geometry)); +} + +void GeometryPreparation::deferSmall(Geometry *geometry, Preprocessing *job) +{ + m_smallBatch.enqueue(job, position(geometry)); +} + +GeometryResults *GeometryPreparation::deviceResults(Geometry *geometry) +{ + const size_t at = position(geometry); + if (!check(geometry, + m_results.reserve(at + 1, m_stream.stream()), + "allocating preparation results")) + return nullptr; + return m_results.device(at); +} + +const GeometryResults &GeometryPreparation::hostResults( + const Geometry *geometry) const +{ + return m_results.host(position(geometry)); +} + +size_t GeometryPreparation::position(const Geometry *geometry) const +{ + return *geometry->m_preparationPosition; +} + +cudaError_t GeometryPreparation::flush() +{ + // Flush deferred small jobs even at intervening upload/retirement waits: + // their input pointers must be consumed before a backing allocation changes. + // Then read back every queued result in one transfer. + const auto stream = m_stream.stream(); + auto error = m_smallBatch.launch(m_results, stream); + if (error == cudaSuccess) + error = m_results.readback(m_preparations.size(), stream); + const auto completion = cudaStreamSynchronize(stream); + if (error == cudaSuccess) + error = completion; + if (error != cudaSuccess) { + cudaGetLastError(); + // An intervening upload/legacy consumer may wait before the collection + // point. Its stream-completion error affects all already queued results. + m_preparations.forEach( + [](Geometry *geometry) { geometry->markPreparationFailed(); }); + failInputUploads(); + } + return error; +} + +void GeometryPreparation::fail( + Geometry *geometry, cudaError_t error, const char *operation) +{ + geometry->markPreparationFailed(); + // A failed dispatch/readback can follow successful queued kernels. Drain + // preparation before retrying or freeing scratch. Keep the render-stream + // drain on this error path too: this also handles input retirement and + // dependency failures, which may precede a successful producer edge. + flush(); + cudaStreamSynchronize(m_stream.renderStream()); + geometry->reportMessage(ANARI_SEVERITY_ERROR, + "geometry preprocessing failed during %s: %s", + operation, + cudaGetErrorString(error)); +} + +bool GeometryPreparation::check( + Geometry *geometry, cudaError_t error, const char *operation) +{ + if (error == cudaSuccess) + return true; + fail(geometry, error, operation); + return false; +} + +void GeometryPreparation::reject(Geometry *geometry, const char *reason) +{ + geometry->markPreparationFailed(); + geometry->reportMessage(ANARI_SEVERITY_ERROR, + "geometry preprocessing rejected input: %s", + reason); +} + +bool GeometryPreparation::finish(Geometry *geometry) +{ + // Also establishes an explicit boundary for legacy default-stream consumers. + return check(geometry, cudaGetLastError(), "launch") + && check(geometry, flush(), "execution completion"); +} + +cudaError_t GeometryPreparation::retireRender() +{ + // Anything but success, a failed query included, takes the wait: only a + // completed stream permits releasing what its work reads. + const auto renderStream = m_stream.renderStream(); + return cudaStreamQuery(renderStream) == cudaSuccess + ? cudaSuccess + : cudaStreamSynchronize(renderStream); +} + +bool GeometryPreparation::uploadingInputs() const +{ + return m_inputUploads.collecting(); +} + +bool GeometryPreparation::pending() const +{ + return m_preparations.collecting() || !m_preparations.empty() + || m_inputUploads.collecting(); +} + +void GeometryPreparation::failInputUploads() +{ + m_inputUploads.forEach( + [](Geometry *geometry) { geometry->failInputUploads(); }); +} + +} // namespace visrtx diff --git a/devices/rtx/device/geometry/GeometryPreparation.h b/devices/rtx/device/geometry/GeometryPreparation.h new file mode 100644 index 000000000..52be96d4d --- /dev/null +++ b/devices/rtx/device/geometry/GeometryPreparation.h @@ -0,0 +1,154 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include "Preprocessing.h" +#include "utility/DeviceAllocationCache.h" +#include "utility/PreparationQueue.h" +#include "utility/PreparationStream.h" +// helium +#include +#include +// std +#include +#include + +namespace visrtx { + +struct Array; +struct Geometry; + +/* + * Owns everything that prepares geometry on the GPU: the two collection + * queues, the small-geometry batch, the scalar results and the input + * allocation cache. The work runs on the device's PreparationStream, which + * BVH builds and scene-table uploads use directly. + * + * One scene update is one transaction: + * + * commit Geometry::commitParameters() captures its dirty host arrays and + * queues itself (stageInputs). + * upload The first finalizer uploads every queued geometry's inputs and + * waits once (uploadInputs). A finalizer whose arrays no commit + * captured queues and uploads them the same way. + * submit Each finalizer queues bounds/area work; nothing is published + * (defer). Small geometries are held for one batched launch. + * collect collect() launches the batch, reads all results back in one + * transfer, waits once, then publishes each geometry. + * + * A CUDA failure fails every queued geometry; a numeric failure fails its own. + * Calls are serialized by the device's scene-update path; nothing here locks. + */ +struct GeometryPreparation +{ + explicit GeometryPreparation(PreparationStream &stream); + ~GeometryPreparation(); + GeometryPreparation(const GeometryPreparation &) = delete; + GeometryPreparation &operator=(const GeometryPreparation &) = delete; + + // Closes the allocation cache. Call collect() first, while objects may + // still be released, and reset the stream afterwards. + void shutdown(); + + // True while input uploads or results are being collected. Reentrant + // property queries and rendering are refused meanwhile. + bool busy() const; + + // Completes the transaction: publishes every queued geometry. Returns + // false, doing nothing, when reentered from a collection. + bool collect(); + + // For a caller about to hand memory back to the application. The first + // waits for a host-to-device input copy in flight; the second for rendering + // and queued preparation that read an application-owned device array. + cudaError_t waitForHostReaders(); + cudaError_t waitForDeviceReaders(); + + // Backs device copies of authored host arrays. + std::shared_ptr inputAllocations() const; + + // For geometry code. fail() marks the geometry failed, drains both streams + // so no queued work still targets its storage, and reports. check() returns + // true on cudaSuccess, otherwise fail()s. finish() waits for the geometry's + // submitted work, failing it on error. + void fail(Geometry *geometry, cudaError_t error, const char *operation); + bool check(Geometry *geometry, cudaError_t error, const char *operation); + bool finish(Geometry *geometry); + // For input the device cannot prepare, with no CUDA error behind it: marks + // the geometry failed and reports. Touches no stream and no other geometry. + void reject(Geometry *geometry, const char *reason); + + // For Preprocessing. Each addresses the geometry's place in the queue; the + // position and the storage it indexes stay in here. + // Queues the geometry for collect(), once. + void defer(Geometry *geometry); + // Holds a deferred geometry's small job for the one batched launch. + void deferSmall(Geometry *geometry, Preprocessing *job); + // Device results a deferred geometry's kernels write; null after failing + // the geometry when they cannot be allocated. + GeometryResults *deviceResults(Geometry *geometry); + // The same results read back; only while the geometry is being collected. + const GeometryResults &hostResults(const Geometry *geometry) const; + + private: + friend struct Geometry; + + // Geometry protocol, in transaction order. + void stageInputs(Geometry *geometry); + bool uploadInputs(); + cudaError_t stageArray(Array *array, helium::TimeStamp modified); + // Indexes m_results. Only between a geometry's defer() and its collection. + size_t position(const Geometry *geometry) const; + // Launches the small batch, reads back, waits. Fails all queued on error. + cudaError_t flush(); + // A host-blocking wait for rendering (skipped when the render stream is + // idle), for callers about to release memory that render work may still + // read. PreparationStream::orderAfterRender() is the GPU-side dependency. + cudaError_t retireRender(); + + bool uploadingInputs() const; + bool pending() const; + void failInputUploads(); + + PreparationStream &m_stream; + std::shared_ptr m_inputAllocations{ + std::make_shared()}; + // Scalar results of queued geometry preparations, by queue position. + PreparationResults m_results; + SmallGeometryBatch m_smallBatch; + std::unordered_map m_inputVersions; + // Last, so queued geometries are released before the storage above. + PreparationQueue> m_inputUploads; + PreparationQueue> m_preparations; +}; + +} // namespace visrtx diff --git a/devices/rtx/device/geometry/Intersectors_ptx.cu b/devices/rtx/device/geometry/Intersectors_ptx.cu index 3f342da19..c5caf2bf3 100644 --- a/devices/rtx/device/geometry/Intersectors_ptx.cu +++ b/devices/rtx/device/geometry/Intersectors_ptx.cu @@ -1008,7 +1008,7 @@ VISRTX_DEVICE void marchVoxelsMacrocellSkip(const IsosurfaceGeometryData &iso, // cubic (linearCrossing). The fixed-step ray march below is no longer reached // by built-in fields. This generic form is the ray-march fallback for fields // without analytic voxel boundaries (e.g. custom fields); built-in fields are -// gated to require a space-skipping grid in Isosurface::finalize. +// gated to require a space-skipping grid in Isosurface::prepare. template VISRTX_DEVICE void marchIsosurfaceVoxels(const IsosurfaceGeometryData &iso, const SpatialFieldGPUData &field, diff --git a/devices/rtx/device/geometry/Isosurface.cpp b/devices/rtx/device/geometry/Isosurface.cpp index 725703155..ba3194b2b 100644 --- a/devices/rtx/device/geometry/Isosurface.cpp +++ b/devices/rtx/device/geometry/Isosurface.cpp @@ -54,7 +54,7 @@ void Isosurface::commitParameters() getParam("isovalue", ANARI_FLOAT32, &m_isovalueScalar); } -void Isosurface::finalize() +bool Isosurface::prepare() { m_numBricks = 0; m_isovaluesDev = nullptr; @@ -63,7 +63,7 @@ void Isosurface::finalize() if (!m_field) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'field' on isosurface geometry"); - return; + return false; } if (m_field->m_uniformGrid.m_valueRanges == nullptr) { // The field's space-skipping grid isn't built yet; a field committed before @@ -72,25 +72,25 @@ void Isosurface::finalize() reportMessage(ANARI_SEVERITY_WARNING, "isosurface 'field' space-skipping grid not ready; nothing will render " "yet"); - return; + return false; } if (!m_isovalueArray && !m_hasScalarIsovalue) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'isovalue' on isosurface geometry"); - return; + return false; } if (m_isovalueArray && m_isovalueArray->size() == 0) { reportMessage(ANARI_SEVERITY_WARNING, "empty 'isovalue' array on isosurface geometry; one or more values are " "required, nothing will render"); - return; + return false; } if (m_isovalueArray && m_isovalueArray->elementType() != ANARI_FLOAT32) { // beginAs() only asserts the element type, so under NDEBUG a non- // FLOAT32 array would be silently reinterpreted as float garbage. Reject it. reportMessage(ANARI_SEVERITY_WARNING, "isosurface 'isovalue' array must be ANARI_FLOAT32; nothing will render"); - return; + return false; } // Resolve the device isovalue array (array form preferred). @@ -129,7 +129,7 @@ void Isosurface::finalize() m_numIsovalues, m_numBricks); - upload(); + return true; } void Isosurface::dropUndersizedPrimitiveArrays() diff --git a/devices/rtx/device/geometry/Isosurface.h b/devices/rtx/device/geometry/Isosurface.h index d12a1e742..d0f1574f0 100644 --- a/devices/rtx/device/geometry/Isosurface.h +++ b/devices/rtx/device/geometry/Isosurface.h @@ -44,13 +44,13 @@ struct Isosurface : public Geometry ~Isosurface() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; private: + bool prepare() override; GeometryGPUData gpuData() const override; // Drops any per-primitive array shorter than m_numIsovalues (warns), so the diff --git a/devices/rtx/device/geometry/Neural.cpp b/devices/rtx/device/geometry/Neural.cpp index 114a0a0fd..46c615e14 100644 --- a/devices/rtx/device/geometry/Neural.cpp +++ b/devices/rtx/device/geometry/Neural.cpp @@ -27,13 +27,13 @@ void Neural::commitParameters() } } -void Neural::finalize() +bool Neural::prepare() { - Geometry::finalize(); m_aabbs.resize(1); m_aabbs.dataHost()[0] = m_aabb; m_aabbs.upload(); m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.dataDevice(); + return true; } bool Neural::isValid() const diff --git a/devices/rtx/device/geometry/Neural.h b/devices/rtx/device/geometry/Neural.h index c36008475..369c0b1bc 100644 --- a/devices/rtx/device/geometry/Neural.h +++ b/devices/rtx/device/geometry/Neural.h @@ -14,7 +14,6 @@ struct Neural : public Geometry ~Neural() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; @@ -22,6 +21,7 @@ struct Neural : public Geometry int optixGeometryType() const override; private: + bool prepare() override; GeometryGPUData gpuData() const override; mutable std::vector> m_layers; diff --git a/devices/rtx/device/geometry/PreparationResults.cpp b/devices/rtx/device/geometry/PreparationResults.cpp new file mode 100644 index 000000000..da76d78d2 --- /dev/null +++ b/devices/rtx/device/geometry/PreparationResults.cpp @@ -0,0 +1,142 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "PreparationResults.h" + +#include +#include +#include + +namespace visrtx { +namespace { + +// Returns 0 when `count` geometries cannot be addressed. +size_t grownCapacity(size_t current, size_t count) +{ + constexpr size_t LIMIT = + std::numeric_limits::max() / sizeof(GeometryResults); + if (count > LIMIT) + return 0; + const size_t doubled = current <= LIMIT / 2 ? 2 * current : LIMIT; + return std::max({PreparationResults::MIN_CAPACITY, doubled, count}); +} + +// Returns `error`, or the stream's completion error if `error` is success. +cudaError_t completeStream(cudaError_t error, cudaStream_t stream) +{ + const auto completion = cudaStreamSynchronize(stream); + return error == cudaSuccess ? completion : error; +} + +} // namespace + +void PinnedDeleter::operator()(void *memory) const +{ + cudaFreeHost(memory); +} + +void PreparationResults::DeviceDeleter::operator()(void *memory) const +{ + cudaFree(memory); +} + +const GeometryResults &PreparationResults::host(size_t position) const +{ + assert(position < m_capacity); + return m_host.get()[position]; +} + +cudaError_t PreparationResults::reserve(size_t count, cudaStream_t stream) +{ + if (count <= m_capacity) + return cudaSuccess; + const size_t capacity = grownCapacity(m_capacity, count); + if (capacity == 0) + return cudaErrorInvalidValue; + const size_t bytes = capacity * sizeof(GeometryResults); + void *memory = nullptr; + auto error = cudaMallocHost(&memory, bytes); + std::unique_ptr host( + static_cast(memory)); + memory = nullptr; + if (error == cudaSuccess) + error = cudaMalloc(&memory, bytes); + std::unique_ptr device( + static_cast(memory)); + // Readback transfers every position below the queue length, including ones + // no kernel has written yet: never transfer uninitialized bytes. + if (error == cudaSuccess) + error = cudaMemsetAsync(device.get(), 0, bytes, stream); + if (error == cudaSuccess && m_device) + error = cudaMemcpyAsync(device.get(), + m_device.get(), + m_capacity * sizeof(GeometryResults), + cudaMemcpyDeviceToDevice, + stream); + // Earlier kernels may still write the old device storage, and the copy + // reads it: free neither buffer before the stream completes. The first + // allocation needs no wait; later kernels on `stream` follow its memset. + // Every earlier readback completed in its own finish, and the next one + // transfers the whole queued range, so the old host storage is free to go. + if (device && (m_device || error != cudaSuccess)) + error = completeStream(error, stream); + if (error != cudaSuccess) { + cudaGetLastError(); // A failed growth must not poison a retry. + return error; + } + m_device = std::move(device); + m_host = std::move(host); + m_capacity = capacity; + return cudaSuccess; +} + +GeometryResults *PreparationResults::device(size_t position) +{ + assert(position < m_capacity); + m_unread = true; + return m_device.get() + position; +} + +cudaError_t PreparationResults::readback(size_t count, cudaStream_t stream) +{ + // Positions past the capacity were never written. + count = std::min(count, m_capacity); + if (!m_unread || count == 0) + return cudaSuccess; + m_unread = false; + return cudaMemcpyAsync(m_host.get(), + m_device.get(), + count * sizeof(GeometryResults), + cudaMemcpyDeviceToHost, + stream); +} + +} // namespace visrtx diff --git a/devices/rtx/device/geometry/PreparationResults.h b/devices/rtx/device/geometry/PreparationResults.h new file mode 100644 index 000000000..27b5b2035 --- /dev/null +++ b/devices/rtx/device/geometry/PreparationResults.h @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include +#include + +namespace visrtx { + +struct PreparationResult +{ + float value; + uint32_t invalid; +}; + +// One geometry's scalar preparation results. +struct GeometryResults +{ + PreparationResult bounds; // Epsilon scale and validity. + PreparationResult area; // Total area; NaN when invalid. +}; + +// Frees pinned host memory from cudaMallocHost(). +struct PinnedDeleter +{ + void operator()(void *memory) const; +}; + +// Scalar preparation results of the queued geometries, indexed by position in +// the device's preparation queue. Kernels write device storage; readback() +// copies the queued range to pinned host storage in one transfer. Device and +// host storage grow together to their high-water size and live until device +// teardown. +struct PreparationResults +{ + // Geometries; the first allocation holds this many. + static constexpr size_t MIN_CAPACITY = 256; + + PreparationResults() = default; + PreparationResults(const PreparationResults &) = delete; + PreparationResults &operator=(const PreparationResults &) = delete; + PreparationResults(PreparationResults &&) = delete; + PreparationResults &operator=(PreparationResults &&) = delete; + + // Valid after a completed readback() covering `position`. + const GeometryResults &host(size_t position) const; + + // Grows storage to hold `count` geometries, keeping earlier device results. + // Growth after the first allocation synchronizes `stream`, the only stream + // that writes results. Readback itself never allocates. + cudaError_t reserve(size_t count, cudaStream_t stream); + // Device results for a reserved position; marks them for the next readback. + GeometryResults *device(size_t position); + // Copies the first `count` geometries' results to the host if any were + // written since the last readback. The caller synchronizes `stream` before + // reading host() and before the next readback. + cudaError_t readback(size_t count, cudaStream_t stream); + + private: + struct DeviceDeleter + { + void operator()(void *memory) const; + }; + std::unique_ptr m_device; + std::unique_ptr m_host; + size_t m_capacity{0}; // Geometries, on both sides. + bool m_unread{false}; // Device results written since the last readback. +}; + +} // namespace visrtx diff --git a/devices/rtx/device/geometry/Preprocessing.cu b/devices/rtx/device/geometry/Preprocessing.cu new file mode 100644 index 000000000..d4689c25b --- /dev/null +++ b/devices/rtx/device/geometry/Preprocessing.cu @@ -0,0 +1,615 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "Geometry.h" +#include "Preprocessing.h" +#include "gpu/intersectPrimitives.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace visrtx { +namespace { +using Result = PreparationResult; + +VISRTX_DEVICE double triangleArea(const TriangleInput &in, size_t i) +{ + const uvec3 t = in.indices ? in.indices[i] : uvec3(0, 1, 2) + uint32_t(3 * i); + const vec3 a = in.vertices[t.x], b = in.vertices[t.y], c = in.vertices[t.z]; + return 0.5 * glm::length(glm::cross(b - a, c - a)); +} + +VISRTX_DEVICE double sphereArea(const SphereInput &in, size_t i) +{ + const uint32_t v = in.indices ? in.indices[i] : uint32_t(i); + const double r = glm::abs(in.radii ? in.radii[v] : in.radius); + return 4.0 * double(kPi) * r * r; +} + +VISRTX_DEVICE uvec2 segmentEndpoints(const SegmentInput &in, size_t i) +{ + return in.indices ? in.indices[i] : uvec2(2 * i, 2 * i + 1); +} + +VISRTX_DEVICE double segmentLength(const SegmentInput &in, uvec2 c) +{ + return double(glm::length(in.vertices[c.y] - in.vertices[c.x])); +} + +// Adds the disk areas of a segment's capped ends, of radii r0 and r1, to its +// side area. +VISRTX_DEVICE double addCapAreas( + double side, const SegmentInput &in, uvec2 c, double r0, double r1) +{ + const bool cap0 = in.caps ? in.caps[c.x] != 0 : in.capFlags & CAP_FIRST; + const bool cap1 = in.caps ? in.caps[c.y] != 0 : in.capFlags & CAP_SECOND; + double area = side; + if (cap0) + area += double(kPi) * r0 * r0; + if (cap1) + area += double(kPi) * r1 * r1; + return area; +} + +VISRTX_DEVICE double coneArea(const ConeInput &in, size_t i) +{ + const uvec2 c = segmentEndpoints(in.segments, i); + const double r0 = glm::abs(in.radii[c.x]); + const double r1 = glm::abs(in.radii[c.y]); + const double len = segmentLength(in.segments, c); + if (!(len > 0.0)) + return 0.0; + const double slant = sqrt(len * len + (r0 - r1) * (r0 - r1)); + return addCapAreas(double(kPi) * (r0 + r1) * slant, in.segments, c, r0, r1); +} + +VISRTX_DEVICE double cylinderArea(const CylinderInput &in, size_t i) +{ + const uvec2 c = segmentEndpoints(in.segments, i); + const double r = glm::abs(in.radii ? in.radii[i] : in.radius); + const double len = segmentLength(in.segments, c); + if (!(len > 0.0 && r > 0.0)) + return 0.0; + return addCapAreas(2.0 * double(kPi) * r * len, in.segments, c, r, r); +} + +VISRTX_DEVICE double primitiveArea(const PrimitiveInput &in, size_t i) +{ + switch (in.type) { + case GeometryType::TRIANGLE: + return triangleArea(in.triangle, i); + case GeometryType::SPHERE: + return sphereArea(in.sphere, i); + case GeometryType::CONE: + return coneArea(in.cone, i); + case GeometryType::CYLINDER: + return cylinderArea(in.cylinder, i); + default: + return NAN; // No area sampling; fails the area validation. + } +} + +VISRTX_GLOBAL void primitiveAreas( + const PrimitiveInput in, double *areas, Result *result) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= in.count) + return; + const double area = primitiveArea(in, i); + if (!isfinite(area) || area < 0.0) + atomicOr(&result->invalid, 1u); + areas[i] = area; +} + +VISRTX_GLOBAL void normalizeAreas( + const double *prefix, size_t n, float *cdf, Result *result) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= n) + return; + const double total = prefix[n - 1]; + const float area = float(total); + if (!isfinite(prefix[i]) || prefix[i] < 0.0 || !isfinite(area) + || (total > 0.0 && area == 0.f)) + atomicOr(&result->invalid, 1u); + cdf[i] = total > 0.0 ? (i + 1 == n ? 1.f : float(prefix[i] / total)) : 0.f; + if (i == 0) + result->value = area; +} +// Encode numeric failure in the scalar readback; cone/cylinder bounds have +// have a separate status readback for this generation. +VISRTX_GLOBAL void publishArea(Result *result) +{ + if (result->invalid) + result->value = __int_as_float(0x7fffffff); +} + +VISRTX_DEVICE box3 computeSDFPrimitiveAABB(const SDFPrimitive &g) +{ + const float disp = g.userParams.x; // displacement amplitude padding + const float r0 = glm::max(0.f, g.r0); + const float r1 = glm::max(0.f, g.r1); + + switch (static_cast(g.type)) { + case SDFType::SPHERE: + case SDFType::CUT_SPHERE: + return box3(g.p0 - (r0 + disp), g.p0 + (r0 + disp)); + + case SDFType::TORUS: + return box3(g.p0 - (r0 + r1 + disp), g.p0 + (r0 + r1 + disp)); + + case SDFType::ELLIPSOID: + // p1 stores radii vector for the ellipsoid + return box3(g.p0 - (g.p1 + disp), g.p0 + (g.p1 + disp)); + + case SDFType::PILL: + case SDFType::CONE_PILL: + case SDFType::CONE_PILL_SIGMOID: + case SDFType::CONE: + case SDFType::VESICA: + default: { + const float maxR = glm::max(r0, r1) + disp; + return box3(glm::min(g.p0, g.p1) - maxR, glm::max(g.p0, g.p1) + maxR); + } + } +} + +VISRTX_DEVICE Result sdfBound(const SDFInput &in, size_t i, box3 &bound) +{ + const SDFPrimitive &g = in.primitives[i]; + box3 b = computeSDFPrimitiveAABB(g); + float padding = in.noiseFactor * glm::max(0.f, g.r0) * 0.1f; + if (g.numNeighbours > 0) { + const float r0 = glm::max(0.f, g.r0); + const float r1 = glm::max(0.f, g.r1 >= 0.f ? g.r1 : g.r0); + padding += glm::mix(glm::min(r0, r1), glm::max(r0, r1), in.blendLerpFactor) + * in.blendFactor; + } + b.lower -= padding; + b.upper += padding; + bound = b; + Result result{}; + for (int axis = 0; axis < 3; ++axis) { + if (!isfinite(b.lower[axis]) || !isfinite(b.upper[axis])) + result.invalid = 1u; + } + return result; // SDF bounds carry no epsilon scale. +} + +// Bounds of the sphere of radius r swept from v0 to v1, with the largest +// coordinate magnitude as the epsilon scale. +VISRTX_DEVICE Result sweptSphereBound(vec3 v0, vec3 v1, float r, box3 &bound) +{ + const box3 b(glm::min(v0, v1) - r, glm::max(v0, v1) + r); + bound = b; + const vec3 m = glm::max(glm::abs(b.lower), glm::abs(b.upper)); + const float scale = glm::max(m.x, glm::max(m.y, m.z)); + Result result{}; + if (!isfinite(r) || !isfinite(v0.x) || !isfinite(v0.y) || !isfinite(v0.z) + || !isfinite(v1.x) || !isfinite(v1.y) || !isfinite(v1.z) + || !isfinite(scale)) + result.invalid = 1u; + else + result.value = scale; + return result; +} + +VISRTX_DEVICE Result sphereBound(const SphereInput &in, size_t i, box3 &bound) +{ + const size_t v = in.indices ? in.indices[i] : i; + const float r = glm::abs(in.radii ? in.radii[v] : in.radius); + return sweptSphereBound(in.vertices[v], in.vertices[v], r, bound); +} + +VISRTX_DEVICE Result coneBound(const ConeInput &in, size_t i, box3 &bound) +{ + const uvec2 c = segmentEndpoints(in.segments, i); + const float r = glm::max(glm::abs(in.radii[c.x]), glm::abs(in.radii[c.y])); + const vec3 *v = in.segments.vertices; + return sweptSphereBound(v[c.x], v[c.y], r, bound); +} + +VISRTX_DEVICE Result cylinderBound( + const CylinderInput &in, size_t i, box3 &bound) +{ + const uvec2 c = segmentEndpoints(in.segments, i); + const float r = glm::abs(in.radii ? in.radii[i] : in.radius); + const vec3 *v = in.segments.vertices; + return sweptSphereBound(v[c.x], v[c.y], r, bound); +} + +VISRTX_DEVICE Result primitiveBound( + const PrimitiveInput &in, size_t i, box3 &bound) +{ + switch (in.type) { + case GeometryType::SPHERE: + return sphereBound(in.sphere, i, bound); + case GeometryType::CONE: + return coneBound(in.cone, i, bound); + case GeometryType::CYLINDER: + return cylinderBound(in.cylinder, i, bound); + case GeometryType::SDF: + return sdfBound(in.sdf, i, bound); + default: + return {0.f, 1u}; // No custom-primitive bounds. + } +} + +VISRTX_GLOBAL void primitiveBounds( + const PrimitiveInput in, box3 *bounds, Result *result) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= in.count) + return; + const auto summary = primitiveBound(in, i, bounds[i]); + if (summary.invalid) + atomicOr(&result->invalid, 1u); + else + atomicMax(reinterpret_cast(&result->value), + __float_as_uint(summary.value)); +} + +// A batch is one launch, with independent block-local reductions/scans. The +// general multi-block/CUB path remains available above MAX_PRIMITIVES. +VISRTX_GLOBAL void smallGeometry(const SmallGeometryJob *jobs) +{ + constexpr int threads = SmallGeometryBatch::MAX_PRIMITIVES; + using FloatReduce = cub::BlockReduce; + using StatusReduce = cub::BlockReduce; + using Scan = cub::BlockScan; + __shared__ typename FloatReduce::TempStorage scaleStorage; + __shared__ typename StatusReduce::TempStorage statusStorage; + __shared__ typename Scan::TempStorage scanStorage; + const auto &job = jobs[blockIdx.x]; + const unsigned i = threadIdx.x; + // Write only the requested results: an earlier launch in this collection + // may have written the other one. + if (job.bounds) { + Result local{}; + if (i < job.boundsInput.count) + local = primitiveBound(job.boundsInput, i, job.bounds[i]); + const float scale = + FloatReduce(scaleStorage) + .Reduce(local.value, + [] __device__(float a, float b) { return glm::max(a, b); }); + const unsigned invalid = StatusReduce(statusStorage).Sum(local.invalid); + if (i == 0) + job.results->bounds = {scale, invalid}; + __syncthreads(); // statusStorage is reused for the area validation. + } + if (job.cdf) { + const auto n = job.areaInput.count; + const double area = i < n ? primitiveArea(job.areaInput, i) : 0.0; + double prefix, total; + Scan(scanStorage).InclusiveSum(area, prefix, total); + const float value = float(total); + const unsigned localInvalid = !isfinite(area) || area < 0.0 + || !isfinite(prefix) || prefix < 0.0 || !isfinite(value) + || (total > 0.0 && value == 0.f); + if (i < n) + job.cdf[i] = + total > 0.0 ? (i + 1 == n ? 1.f : float(prefix / total)) : 0.f; + const unsigned invalid = StatusReduce(statusStorage).Sum(localInvalid); + if (i == 0) + job.results->area = { + invalid ? __int_as_float(0x7fffffff) : value, invalid}; + } +} + +VISRTX_GLOBAL void quadIndices(const uvec4 *indices, size_t n, uvec3 *out) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= n) + return; + const uvec4 q = indices ? indices[i] : uvec4(4 * i) + uvec4(0, 1, 2, 3); + out[2 * i] = uvec3(q.x, q.y, q.w); + out[2 * i + 1] = uvec3(q.z, q.w, q.y); +} + +VISRTX_GLOBAL void curveIndices(size_t n, uint32_t *out) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) + out[i] = uint32_t(i); +} + +VISRTX_GLOBAL void curveRadii(size_t n, float radius, float *out) +{ + const size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < n) + out[i] = radius; +} +} // namespace + +SegmentInput segmentInput(const Array1D &vertices, + const Array1D *indices, + const Array1D *caps, + uint8_t capFlags) +{ + SegmentInput input{}; + input.vertices = vertices.beginAs(AddressSpace::GPU); + input.indices = + indices ? indices->beginAs(AddressSpace::GPU) : nullptr; + input.caps = caps ? caps->beginAs(AddressSpace::GPU) : nullptr; + input.capFlags = capFlags; + return input; +} + +bool generateQuadIndices( + Geometry *g, const uvec4 *indices, size_t n, DeviceBuffer &out) +{ + if (!reservePreparation(g, out, 2 * n * sizeof(uvec3))) + return false; + if (n) + quadIndices<<<(n + 255) / 256, + 256, + 0, + g->deviceState()->preparationStream.stream()>>>( + indices, n, out.ptrAs()); + return g->deviceState()->preparation.finish(g); +} + +bool generateCurveIndices(Geometry *g, size_t n, DeviceBuffer &out) +{ + if (!reservePreparation(g, out, n * sizeof(uint32_t))) + return false; + if (n) + curveIndices<<<(n + 255) / 256, + 256, + 0, + g->deviceState()->preparationStream.stream()>>>( + n, out.ptrAs()); + return g->deviceState()->preparation.check( + g, cudaGetLastError(), "curve indices"); +} + +bool generateCurveRadii(Geometry *g, size_t n, float radius, DeviceBuffer &out) +{ + if (!reservePreparation(g, out, n * sizeof(float))) + return false; + if (n) + curveRadii<<<(n + 255) / 256, + 256, + 0, + g->deviceState()->preparationStream.stream()>>>( + n, radius, out.ptrAs()); + return g->deviceState()->preparation.check( + g, cudaGetLastError(), "curve radii"); +} + +bool reservePreparation(Geometry *g, DeviceBuffer &buffer, size_t bytes) +{ + return g->deviceState()->preparation.check( + g, buffer.tryReserve(bytes), "allocating device storage"); +} + +void SmallGeometryBatch::enqueue(Preprocessing *preprocessing, size_t position) +{ + m_pending.push_back({preprocessing, position}); +} + +cudaError_t SmallGeometryBatch::launch( + PreparationResults &results, cudaStream_t stream) +{ + cudaError_t error = cudaSuccess; + if (!m_pending.empty()) { + size_t positions = 0; + for (const auto &p : m_pending) + positions = std::max(positions, p.position + 1); + // No host allocations after submission: descriptors remain stable even + // when an error requires a subsequent fallback drain. + m_jobs.clear(); + m_jobs.reserve(m_pending.size()); + if (m_pending.size() > size_t(std::numeric_limits::max())) + error = cudaErrorInvalidValue; + else + error = results.reserve(positions, stream); + if (error == cudaSuccess) { + for (const auto &p : m_pending) { + m_jobs.push_back(p.preprocessing->m_small); + m_jobs.back().results = results.device(p.position); + } + error = m_descriptors.enqueueUpload(m_jobs.data(), m_jobs.size(), stream); + } + if (error == cudaSuccess) { + smallGeometry<<>>( + m_descriptors.ptrAs()); + error = cudaGetLastError(); + } + } + for (const auto &p : m_pending) { + p.preprocessing->m_smallQueued = false; + p.preprocessing->m_small = {}; + } + m_pending.clear(); + return error; +} + +void Preprocessing::enqueueSmall(Geometry *g) +{ + if (!m_smallQueued) { + g->deviceState()->preparation.deferSmall(g, this); + m_smallQueued = true; + } +} + +Preprocessing::~Preprocessing() = default; + +bool Preprocessing::pending() const +{ + return m_boundsSubmitted || m_areasSubmitted; +} + +float Preprocessing::epsilonScale() const +{ + return m_epsilonScale; +} + +float Preprocessing::totalArea() const +{ + return m_totalArea; +} + +const float *Preprocessing::areaCdf() const +{ + return m_totalArea > 0.f ? m_areaCdf.ptrAs() : nullptr; +} + +void Preprocessing::releaseAreas() +{ + m_areasSubmitted = false; + m_totalArea = 0.f; + m_areaCdf.reset(); +} + +bool Preprocessing::complete(Geometry *g) +{ + const bool bounds = std::exchange(m_boundsSubmitted, false); + const bool areas = std::exchange(m_areasSubmitted, false); + if (g->preparationFailed()) + return false; + if (!bounds && !areas) + return true; + auto &preparation = g->deviceState()->preparation; + const auto &results = preparation.hostResults(g); + if (bounds && results.bounds.invalid) { + preparation.reject(g, "non-finite bounds"); + return false; + } + if (areas && !std::isfinite(results.area.value)) { + preparation.reject(g, "non-publishable primitive area"); + return false; + } + if (bounds) + m_epsilonScale = m_boundsHaveEpsilonScale ? results.bounds.value : 0.f; + if (areas) { + m_totalArea = results.area.value; + if (m_totalArea == 0.f) + m_areaCdf.reset(); + } + return true; +} + +bool Preprocessing::bounds( + Geometry *g, const PrimitiveInput &in, DeviceBuffer &aabbs) +{ + auto &preparation = g->deviceState()->preparation; + const auto stream = g->deviceState()->preparationStream.stream(); + m_epsilonScale = 0.f; + preparation.defer(g); + m_boundsSubmitted = true; + m_boundsHaveEpsilonScale = in.type != GeometryType::SDF; + if (!reservePreparation(g, aabbs, in.count * sizeof(box3))) + return false; + if (in.count > 0 && in.count <= SmallGeometryBatch::MAX_PRIMITIVES) { + m_small.boundsInput = in; + m_small.bounds = aabbs.ptrAs(); + enqueueSmall(g); + return true; + } + auto *results = preparation.deviceResults(g); + auto *result = results ? &results->bounds : nullptr; + if (!result + || !preparation.check(g, + cudaMemsetAsync(result, 0, sizeof(Result), stream), + "clearing bounds status")) + return false; + if (in.count) + primitiveBounds<<<(in.count + 255) / 256, 256, 0, stream>>>( + in, aabbs.ptrAs(), result); + return preparation.check(g, cudaGetLastError(), "bounds evaluation"); +} + +bool Preprocessing::areas(Geometry *g, const PrimitiveInput &in) +{ + m_totalArea = 0.f; + if (in.count == 0) { + m_areaCdf.reset(); + return true; + } + auto &preparation = g->deviceState()->preparation; + if (in.count > size_t(std::numeric_limits::max())) { + preparation.reject(g, "too many primitives for area sampling"); + return false; + } + preparation.defer(g); + m_areasSubmitted = true; + if (in.count <= SmallGeometryBatch::MAX_PRIMITIVES) { + if (!reservePreparation(g, m_areaCdf, in.count * sizeof(float))) + return false; + m_small.areaInput = in; + m_small.cdf = m_areaCdf.ptrAs(); + enqueueSmall(g); + return true; + } + const auto stream = g->deviceState()->preparationStream.stream(); + size_t scratchBytes = 0; + if (!reservePreparation(g, m_prefix, in.count * sizeof(double)) + || !reservePreparation(g, m_areaCdf, in.count * sizeof(float))) + return false; + auto *results = preparation.deviceResults(g); + auto *result = results ? &results->area : nullptr; + if (!result + || !preparation.check(g, + cudaMemsetAsync(result, 0, sizeof(Result), stream), + "clearing area status")) + return false; + auto *prefix = m_prefix.ptrAs(); + primitiveAreas<<<(in.count + 255) / 256, 256, 0, stream>>>( + in, prefix, result); + if (!preparation.check(g, cudaGetLastError(), "area evaluation") + || !preparation.check(g, + cub::DeviceScan::InclusiveSum( + nullptr, scratchBytes, prefix, prefix, int(in.count), stream), + "scan workspace query") + || !reservePreparation(g, m_scratch, scratchBytes) + || !preparation.check(g, + cub::DeviceScan::InclusiveSum(m_scratch.ptr(), + scratchBytes, + prefix, + prefix, + int(in.count), + stream), + "area scan")) + return false; + normalizeAreas<<<(in.count + 255) / 256, 256, 0, stream>>>( + prefix, in.count, m_areaCdf.ptrAs(), result); + if (!preparation.check(g, cudaGetLastError(), "CDF normalization")) + return false; + publishArea<<<1, 1, 0, stream>>>(result); + return preparation.check(g, cudaGetLastError(), "area publication"); +} +} // namespace visrtx diff --git a/devices/rtx/device/geometry/Preprocessing.h b/devices/rtx/device/geometry/Preprocessing.h new file mode 100644 index 000000000..9ea0cc40a --- /dev/null +++ b/devices/rtx/device/geometry/Preprocessing.h @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include "PreparationResults.h" +#include "gpu/gpu_objects.h" +#include "utility/DeviceBuffer.h" + +namespace visrtx { +struct Array1D; +struct Geometry; + +// Per-type preprocessing inputs. GPU views use logical array beginnings, never +// application allocation bases. Geometry::beginPreparation() completes +// authored host-array uploads before these views are consumed; kernels need no +// legacy default-stream dependency. A null `indices` means unindexed input. + +struct TriangleInput +{ + const vec3 *vertices; + const uvec3 *indices; // Else consecutive vertex triples. +}; + +struct SphereInput +{ + const vec3 *vertices; + const uint32_t *indices; // Else one sphere per vertex. + const float *radii; // Per vertex; else `radius`. + float radius; +}; + +// The endpoints and caps cones and cylinders share. +struct SegmentInput +{ + const vec3 *vertices; + const uvec2 *indices; // Else consecutive vertex pairs. + const uint8_t *caps; // Per vertex; else `capFlags`. + uint8_t capFlags; +}; + +struct ConeInput +{ + SegmentInput segments; + const float *radii; // Per vertex; required. +}; + +struct CylinderInput +{ + SegmentInput segments; + const float *radii; // Per primitive; else `radius`. + float radius; +}; + +struct SDFInput +{ + const SDFPrimitive *primitives; + float blendFactor; + float blendLerpFactor; + float noiseFactor; +}; + +// One geometry's preprocessing input: its primitive count and the input of +// its type. A tagged union rather than a per-type kernel so that the small +// geometry batch can mix types in one launch. +struct PrimitiveInput +{ + GeometryType type{GeometryType::TRIANGLE}; + size_t count{0}; + union + { + TriangleInput triangle; + SphereInput sphere; + ConeInput cone; + CylinderInput cylinder; + SDFInput sdf; + }; + + PrimitiveInput() : triangle{} {} + PrimitiveInput(size_t n, const TriangleInput &in) + : type(GeometryType::TRIANGLE), count(n), triangle(in) + {} + PrimitiveInput(size_t n, const SphereInput &in) + : type(GeometryType::SPHERE), count(n), sphere(in) + {} + PrimitiveInput(size_t n, const ConeInput &in) + : type(GeometryType::CONE), count(n), cone(in) + {} + PrimitiveInput(size_t n, const CylinderInput &in) + : type(GeometryType::CYLINDER), count(n), cylinder(in) + {} + PrimitiveInput(size_t n, const SDFInput &in) + : type(GeometryType::SDF), count(n), sdf(in) + {} +}; + +// Cone and cylinder endpoints: `indices` pairs vertices, else consecutive +// vertices pair up. +SegmentInput segmentInput(const Array1D &vertices, + const Array1D *indices, + const Array1D *caps, + uint8_t capFlags); + +// One block handles one small geometry. bounds() and areas() fill their halves +// independently; a half left at zero count is skipped. +struct SmallGeometryJob +{ + PrimitiveInput boundsInput; + PrimitiveInput areaInput; + box3 *bounds{nullptr}; + float *cdf{nullptr}; + GeometryResults *results{nullptr}; +}; + +struct Preprocessing; + +// Device-owned, single-flight batch. The geometry collection queue retains +// owners until the stream completes every queued descriptor and kernel. +struct SmallGeometryBatch +{ + static constexpr size_t MAX_PRIMITIVES = 256; + // `position` is the owning geometry's preparation-queue position; it holds + // until the geometry is collected, which is after the launch. + void enqueue(Preprocessing *preprocessing, size_t position); + // Launches every queued job, writing each geometry's results at its queue + // position in `results`. Always empties the batch; the caller synchronizes + // `stream`. + cudaError_t launch(PreparationResults &results, cudaStream_t stream); + + private: + struct Pending + { + Preprocessing *preprocessing; + size_t position; + }; + std::vector m_pending; + std::vector m_jobs; + DeviceBuffer m_descriptors; +}; + +// Per-geometry reusable workspace and the owner of its scalar results. +// Submission writes the device's PreparationResults at the geometry's queue +// position; complete() publishes the epsilon scale, total area and area CDF +// from their readback after the device's collection barrier. +struct Preprocessing +{ + Preprocessing() = default; + ~Preprocessing(); + Preprocessing(const Preprocessing &) = delete; + Preprocessing &operator=(const Preprocessing &) = delete; + Preprocessing(Preprocessing &&) = delete; + Preprocessing &operator=(Preprocessing &&) = delete; + + // True while a bounds or area submission awaits complete(). + bool pending() const; + // Published results. The CDF is null when the total area is zero. + float epsilonScale() const; + float totalArea() const; + const float *areaCdf() const; + + // Success means queued, not published. Small jobs defer GPU submission to + // the next preparation completion boundary. Submission zeroes the result it + // replaces until complete() publishes the new one. + bool areas(Geometry *geometry, const PrimitiveInput &input); + bool bounds( + Geometry *geometry, const PrimitiveInput &input, DeviceBuffer &aabbs); + // Drops the published area distribution and its storage, and cancels the + // publication of an area submission still awaiting complete(). + void releaseAreas(); + bool complete(Geometry *geometry); + + private: + friend struct SmallGeometryBatch; + void enqueueSmall(Geometry *geometry); + SmallGeometryJob m_small; + bool m_smallQueued{false}; + bool m_boundsSubmitted{false}; + bool m_areasSubmitted{false}; + // SDF bounds are padded per primitive and carry no epsilon scale. + bool m_boundsHaveEpsilonScale{false}; + float m_epsilonScale{0.f}; + float m_totalArea{0.f}; + DeviceBuffer m_areaCdf; + DeviceBuffer m_prefix; + DeviceBuffer m_scratch; +}; + +// CUDA failures go through GeometryPreparation::fail() / check() / finish(); +// rejected input through reject(). +bool reservePreparation(Geometry *geometry, DeviceBuffer &buffer, size_t bytes); +bool generateQuadIndices(Geometry *geometry, + const uvec4 *indices, + size_t count, + DeviceBuffer &output); +bool generateCurveIndices( + Geometry *geometry, size_t count, DeviceBuffer &output); +bool generateCurveRadii( + Geometry *geometry, size_t count, float radius, DeviceBuffer &output); + +} // namespace visrtx diff --git a/devices/rtx/device/geometry/Quad.cpp b/devices/rtx/device/geometry/Quad.cpp index 515227e95..93d950af1 100644 --- a/devices/rtx/device/geometry/Quad.cpp +++ b/devices/rtx/device/geometry/Quad.cpp @@ -34,7 +34,14 @@ namespace visrtx { -Quad::Quad(DeviceGlobalState *d) : Geometry(d), m_index(this), m_vertex(this) {} +Quad::Quad(DeviceGlobalState *d) : Geometry(d), m_index(this), m_vertex(this) +{ + declarePreparationParameters({"primitive.index", + "vertex.position", + "vertex.normal", + "vertex.tangent", + "cullBackfaces"}); +} Quad::~Quad() = default; @@ -49,26 +56,27 @@ void Quad::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } -void Quad::finalize() +bool Quad::prepare() { if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on quad geometry"); - return; + return false; } if (!m_index && m_vertex->size() % 4 != 0) { reportMessage(ANARI_SEVERITY_ERROR, "'vertex.position' on quad geometry is a non-multiple of 4" " without 'primitive.index' present"); - return; + return false; } reportMessage(ANARI_SEVERITY_DEBUG, "finalizing %s quad geometry", m_index ? "indexed" : "soup"); - generateIndices(); + if (!generateIndices()) + return false; if (m_vertexTangent && m_vertex->size() != m_vertexTangent->size()) { reportMessage(ANARI_SEVERITY_WARNING, @@ -83,7 +91,7 @@ void Quad::finalize() m_vertexBufferPtr = (CUdeviceptr)m_vertex->beginAs(AddressSpace::GPU); - upload(); + return true; } bool Quad::isValid() const @@ -102,8 +110,8 @@ void Quad::populateBuildInput(OptixBuildInput &buildInput) const buildInput.triangleArray.indexFormat = OPTIX_INDICES_FORMAT_UNSIGNED_INT3; buildInput.triangleArray.indexStrideInBytes = sizeof(uvec3); - buildInput.triangleArray.numIndexTriplets = m_indices.size(); - buildInput.triangleArray.indexBuffer = (CUdeviceptr)m_indices.dataDevice(); + buildInput.triangleArray.numIndexTriplets = m_numTriangles; + buildInput.triangleArray.indexBuffer = (CUdeviceptr)m_indices.ptrAs(); static uint32_t buildInputFlags[1] = {0}; @@ -123,7 +131,7 @@ GeometryGPUData Quad::gpuData() const auto &quad = retval.quad; quad.vertices = m_vertex->beginAs(AddressSpace::GPU); - quad.indices = m_indices.dataDevice(); + quad.indices = m_indices.ptrAs(); quad.vertexNormals = m_vertexNormal ? m_vertexNormal->beginAs(AddressSpace::GPU) : nullptr; @@ -135,29 +143,14 @@ GeometryGPUData Quad::gpuData() const return retval; } -void Quad::generateIndices() +bool Quad::generateIndices() { - if (m_index) { - size_t numIndices = 2 * m_index->size(); - m_indices.resize(numIndices); - auto *indicesIn = (const uvec4 *)m_index->dataAs(AddressSpace::HOST); - auto *indicesOut = m_indices.dataHost(); - for (size_t i = 0; i < m_index->size(); i++) { - auto idx = indicesIn[i]; - indicesOut[2 * i + 0] = uvec3(idx.x, idx.y, idx.w); - indicesOut[2 * i + 1] = uvec3(idx.z, idx.w, idx.y); - } - } else { - size_t numQuad = m_vertex->size() / 4; - m_indices.resize(2 * numQuad); - auto *indicesOut = m_indices.dataHost(); - for (size_t i = 0; i < numQuad; i++) { - indicesOut[2 * i + 0] = uvec3(4 * i) + uvec3(0, 1, 3); - indicesOut[2 * i + 1] = uvec3(4 * i) + uvec3(2, 3, 1); - } - } - - m_indices.upload(); + const size_t n = m_index ? m_index->size() : m_vertex->size() / 4; + m_numTriangles = 2 * n; + return generateQuadIndices(this, + m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr, + n, + m_indices); } void Quad::generateTangents() @@ -169,8 +162,8 @@ void Quad::generateTangents() // is always per vertex. TangentGenerationInput input; input.positions = m_vertex.get(); - input.indices = m_indices.dataDevice(); - input.numTriangles = m_indices.size(); + input.indices = m_indices.ptrAs(); + input.numTriangles = m_numTriangles; input.normals = m_vertexNormal.ptr; input.uvs = uvs; diff --git a/devices/rtx/device/geometry/Quad.h b/devices/rtx/device/geometry/Quad.h index 85dc950ec..17b6acb39 100644 --- a/devices/rtx/device/geometry/Quad.h +++ b/devices/rtx/device/geometry/Quad.h @@ -43,7 +43,6 @@ struct Quad : public Geometry ~Quad() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; @@ -51,11 +50,13 @@ struct Quad : public Geometry int optixGeometryType() const override; private: + bool prepare() override; GeometryGPUData gpuData() const override; - void generateIndices(); + bool generateIndices(); void generateTangents(); - HostDeviceArray m_indices; + DeviceBuffer m_indices; + size_t m_numTriangles{0}; helium::ChangeObserverPtr m_index; helium::ChangeObserverPtr m_vertex; diff --git a/devices/rtx/device/geometry/SDF.cpp b/devices/rtx/device/geometry/SDF.cpp index a7bdd2493..dbb2816dd 100644 --- a/devices/rtx/device/geometry/SDF.cpp +++ b/devices/rtx/device/geometry/SDF.cpp @@ -42,39 +42,19 @@ static_assert(offsetof(visrtx::SDFPrimitive, neighboursIndex) == 56, namespace visrtx { -// Compute a conservative AABB for an SDF primitive on the host (CPU). -static box3 computeSDFPrimitiveAABB(const SDFPrimitive &g) +SDF::SDF(DeviceGlobalState *d) : Geometry(d), m_sdf(this), m_neighbour(this) { - const float disp = g.userParams.x; // displacement amplitude padding - const float r0 = glm::max(0.f, g.r0); - const float r1 = glm::max(0.f, g.r1); - - switch (static_cast(g.type)) { - case SDFType::SPHERE: - case SDFType::CUT_SPHERE: - return box3(g.p0 - (r0 + disp), g.p0 + (r0 + disp)); - - case SDFType::TORUS: - return box3(g.p0 - (r0 + r1 + disp), g.p0 + (r0 + r1 + disp)); - - case SDFType::ELLIPSOID: - // p1 stores radii vector for the ellipsoid - return box3(g.p0 - (g.p1 + disp), g.p0 + (g.p1 + disp)); - - case SDFType::PILL: - case SDFType::CONE_PILL: - case SDFType::CONE_PILL_SIGMOID: - case SDFType::CONE: - case SDFType::VESICA: - default: { - const float maxR = glm::max(r0, r1) + disp; - return box3(glm::min(g.p0, g.p1) - maxR, glm::max(g.p0, g.p1) + maxR); - } - } + declarePreparationParameters({"primitive.sdf", + "primitive.neighbor", + "epsilon", + "nbMarchIterations", + "blendFactor", + "blendLerpFactor", + "omega", + "distanceFromCamera", + "noiseFactor"}); } -SDF::SDF(DeviceGlobalState *d) : Geometry(d), m_sdf(this), m_neighbour(this) {} - SDF::~SDF() = default; void SDF::commitParameters() @@ -92,12 +72,12 @@ void SDF::commitParameters() m_noiseFactor = glm::clamp(getParam("noiseFactor", 0.f), 0.f, 1.f); } -void SDF::finalize() +bool SDF::prepare() { if (!m_sdf) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'primitive.sdf' on sdf geometry"); - return; + return false; } // primitive.sdf must be an ANARI_UINT8 array of N * sizeof(SDFPrimitive) @@ -108,43 +88,31 @@ void SDF::finalize() "finalizing sdf geometry with %zu primitives", m_numPrimitives); - const auto *geometries = - reinterpret_cast(m_sdf->data()); - - m_aabbs.resize(m_numPrimitives); - auto *aabbsHost = m_aabbs.dataHost(); - for (size_t i = 0; i < m_numPrimitives; i++) { - aabbsHost[i] = computeSDFPrimitiveAABB(geometries[i]); - - // Expand AABB by the smooth-min blend radius so OptiX fires the - // intersection test for rays passing through the blending zone at - // junctions between adjacent primitives. Without this, blend zones that - // lie outside the tight per-primitive AABB produce holes in the geometry. - if (geometries[i].numNeighbours > 0) { - const float r0 = glm::max(0.f, geometries[i].r0); - const float r1 = glm::max( - 0.f, geometries[i].r1 >= 0.f ? geometries[i].r1 : geometries[i].r0); - const float k = - glm::mix(glm::min(r0, r1), glm::max(r0, r1), m_blendLerpFactor) - * m_blendFactor; - aabbsHost[i].lower -= k; - aabbsHost[i].upper += k; - } - - // Expand AABB for noise displacement. The noise can pull the surface - // outward by up to amplitude = noiseFactor * r0 * 0.1. - if (m_noiseFactor > 0.f) { - const float noiseAmplitude = - m_noiseFactor * glm::max(0.f, geometries[i].r0) * 0.1f; - aabbsHost[i].lower -= noiseAmplitude; - aabbsHost[i].upper += noiseAmplitude; - } - } - - m_aabbs.upload(); - m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.dataDevice(); - - upload(); + const void *source = m_sdf->begin(AddressSpace::GPU); + if (reinterpret_cast(source) % alignof(SDFPrimitive) != 0) { + const size_t bytes = m_numPrimitives * sizeof(SDFPrimitive); + if (!reservePreparation(this, m_alignedPrimitives, bytes) + || !deviceState()->preparation.check(this, + cudaMemcpyAsync(m_alignedPrimitives.ptr(), + source, + bytes, + cudaMemcpyDeviceToDevice, + deviceState()->preparationStream.stream()), + "aligning SDF input")) + return false; + m_primitives = m_alignedPrimitives.ptrAs(); + } else + m_primitives = static_cast(source); + SDFInput input{}; + input.primitives = m_primitives; + input.blendFactor = m_blendFactor; + input.blendLerpFactor = m_blendLerpFactor; + input.noiseFactor = m_noiseFactor; + if (!m_preprocessing.bounds(this, {m_numPrimitives, input}, m_aabbs)) + return false; + m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); + + return true; } bool SDF::isValid() const @@ -175,8 +143,7 @@ GeometryGPUData SDF::gpuData() const retval.type = GeometryType::SDF; auto &sdf = retval.sdf; - sdf.geometries = - reinterpret_cast(m_sdf->data(AddressSpace::GPU)); + sdf.geometries = m_primitives; sdf.neighbours = m_neighbour ? m_neighbour->beginAs(AddressSpace::GPU) : nullptr; sdf.numGeometries = static_cast(m_numPrimitives); diff --git a/devices/rtx/device/geometry/SDF.h b/devices/rtx/device/geometry/SDF.h index d5ee1bc10..5487eaebd 100644 --- a/devices/rtx/device/geometry/SDF.h +++ b/devices/rtx/device/geometry/SDF.h @@ -33,7 +33,7 @@ #include "Geometry.h" #include "array/Array1D.h" -#include "utility/HostDeviceArray.h" +#include "utility/DeviceBuffer.h" namespace visrtx { @@ -58,13 +58,13 @@ struct SDF : public Geometry ~SDF() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; private: + bool prepare() override; GeometryGPUData gpuData() const override; helium::ChangeObserverPtr m_sdf; @@ -78,7 +78,9 @@ struct SDF : public Geometry float m_distanceFromCamera{100.f}; float m_noiseFactor{0.f}; - HostDeviceArray m_aabbs; + DeviceBuffer m_alignedPrimitives; + const SDFPrimitive *m_primitives{nullptr}; + DeviceBuffer m_aabbs; CUdeviceptr m_aabbsBufferPtr{}; size_t m_numPrimitives{0}; }; diff --git a/devices/rtx/device/geometry/Sphere.cu b/devices/rtx/device/geometry/Sphere.cu index 66f5db3a3..5892204e7 100644 --- a/devices/rtx/device/geometry/Sphere.cu +++ b/devices/rtx/device/geometry/Sphere.cu @@ -30,18 +30,15 @@ */ #include "Sphere.h" -// thrust -#include -#include -#include -#include -#include namespace visrtx { Sphere::Sphere(DeviceGlobalState *d) : Geometry(d), m_index(this), m_vertex(this), m_vertexRadius(this) -{} +{ + declarePreparationParameters( + {"primitive.index", "vertex.position", "vertex.radius", "radius"}); +} Sphere::~Sphere() = default; @@ -55,12 +52,27 @@ void Sphere::commitParameters() commitAttributes("vertex.", m_vertexAttributes); } -void Sphere::finalize() +PrimitiveInput Sphere::primitiveInput() const +{ + SphereInput input{}; + // Area sampling reads no positions and may run without them. + input.vertices = + m_vertex ? m_vertex->beginAs(AddressSpace::GPU) : nullptr; + input.indices = + m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; + input.radii = m_vertexRadius + ? m_vertexRadius->beginAs(AddressSpace::GPU) + : nullptr; + input.radius = m_globalRadius; + return {m_numSpheres, input}; +} + +bool Sphere::prepare() { if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on sphere geometry"); - return; + return false; } reportMessage(ANARI_SEVERITY_DEBUG, @@ -70,124 +82,15 @@ void Sphere::finalize() // Calculate bounds // m_numSpheres = m_index ? m_index->size() : m_vertex->size(); - m_aabbs.reserve(m_numSpheres * sizeof(box3)); - - const float globalRadius = m_globalRadius; - const float *radii = nullptr; - if (m_vertexRadius) - radii = m_vertexRadius->beginAs(AddressSpace::GPU); - - const auto *vertices = m_vertex->beginAs(AddressSpace::GPU); - - auto &state = *deviceState(); - - if (m_index) { - auto *begin = m_index->beginAs(AddressSpace::GPU); - auto *end = m_index->endAs(AddressSpace::GPU); - thrust::transform(thrust::cuda::par.on(state.stream), - begin, - end, - thrust::device_pointer_cast((box3 *)m_aabbs.ptr()), - [=] __device__(uint32_t i) { - const auto &v = vertices[i]; - const float r = glm::abs(radii ? radii[i] : globalRadius); - return box3(v - r, v + r); - }); - } else { - DeviceBuffer index; - index.reserve(m_numSpheres * sizeof(uint32_t)); - auto idx_begin = - thrust::device_pointer_cast((uint32_t *)index.ptr()); - auto idx_end = idx_begin + m_numSpheres; - thrust::sequence(thrust::cuda::par.on(state.stream), idx_begin, idx_end); - thrust::transform(thrust::cuda::par.on(state.stream), - idx_begin, - idx_end, - thrust::device_pointer_cast((box3 *)m_aabbs.ptr()), - [=] __device__(uint32_t i) { - const auto &v = vertices[i]; - const float r = glm::abs(radii ? radii[i] : globalRadius); - return box3(v - r, v + r); - }); - } - + if (!m_preprocessing.bounds(this, primitiveInput(), m_aabbs)) + return false; m_aabbsBufferPtr = (CUdeviceptr)m_aabbs.ptr(); - - // Coordinate scale of the intersector's arithmetic; floors hit.epsilon so - // secondary rays clear the solve's fp noise band (see - // GeometryGPUData::epsilonScale). - auto aabbsBegin = thrust::device_pointer_cast((box3 *)m_aabbs.ptr()); - m_epsilonScale = thrust::transform_reduce( - thrust::cuda::par.on(state.stream), - aabbsBegin, - aabbsBegin + m_numSpheres, - [] __device__(const box3 &b) -> float { - const vec3 m = glm::max(glm::abs(b.lower), glm::abs(b.upper)); - return glm::max(m.x, glm::max(m.y, m.z)); - }, - 0.f, - thrust::maximum()); - - // Radii may have changed. Rebuild the Geometry Light CDF if a surface has ever - // requested it (order-independent of the surface commit), else drop stale data. - m_areaDataValid = false; - if (m_areaDataWanted) - buildAreaData(); - else { - m_totalArea = 0.f; - m_primAreaCdf.clear(); - } - - upload(); -} - -void Sphere::buildAreaData() -{ - const float *radii = - m_vertexRadius ? m_vertexRadius->beginAs(AddressSpace::HOST) : nullptr; - const uint32_t *indices = - m_index ? m_index->beginAs(AddressSpace::HOST) : nullptr; - - m_primAreaCdf.resize(m_numSpheres); - auto *cdf = m_primAreaCdf.dataHost(); - - double cumulative = 0.0; - for (size_t i = 0; i < m_numSpheres; ++i) { - const uint32_t vi = indices ? indices[i] : uint32_t(i); - const float r = glm::abs(radii ? radii[vi] : m_globalRadius); - cumulative += 4.0 * double(kPi) * double(r) * double(r); - cdf[i] = float(cumulative); - } - m_totalArea = float(cumulative); - - // Normalize to a cumulative CDF ending at 1. A degenerate (zero-area) set - // leaves totalArea 0; callers gate on that. - if (m_totalArea > 0.f) { - for (size_t i = 0; i < m_numSpheres; ++i) - cdf[i] /= m_totalArea; - } - - m_primAreaCdf.upload(); - m_areaDataValid = true; -} - -bool Sphere::isAreaSamplingSupported() const -{ return true; } -void Sphere::ensureAreaData() -{ - m_areaDataWanted = true; - if (m_areaDataValid) - return; - buildAreaData(); - upload(); // republish gpuData() so the CDF pointers reach the device -} - -float Sphere::totalArea() const +std::optional Sphere::areaInput() const { - return m_totalArea; + return isValid() ? primitiveInput() : PrimitiveInput{}; } bool Sphere::isValid() const @@ -224,10 +127,7 @@ GeometryGPUData Sphere::gpuData() const sphere.radius = m_globalRadius; populateAttributeDataSet(m_vertexAttributes, sphere.vertexAttr); - // Geometry Light sampling data; null/zero until ensureAreaData() runs. - sphere.primAreaCdf = m_primAreaCdf.dataDevice(); - sphere.numPrimitives = uint32_t(m_primAreaCdf.size()); - sphere.totalArea = m_totalArea; + populateAreaData(sphere, m_numSpheres); return retval; } diff --git a/devices/rtx/device/geometry/Sphere.h b/devices/rtx/device/geometry/Sphere.h index 0d00ddca2..622fad43f 100644 --- a/devices/rtx/device/geometry/Sphere.h +++ b/devices/rtx/device/geometry/Sphere.h @@ -33,7 +33,7 @@ #include "Geometry.h" #include "array/Array1D.h" -#include "utility/HostDeviceArray.h" +#include "utility/DeviceBuffer.h" namespace visrtx { @@ -43,24 +43,19 @@ struct Sphere : public Geometry ~Sphere() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; - // Build the per-primitive area CDF and object-space total area (Σ 4πr²) used - // to sample this sphere set as a Geometry Light. Lazy: only Emissive Surfaces - // call it, so ordinary sphere sets never pay for it. Mirrors Triangle. - bool isAreaSamplingSupported() const override; - void ensureAreaData() override; - float totalArea() const override; - private: + bool prepare() override; GeometryGPUData gpuData() const override; void cleanup(); - void buildAreaData(); + // Geometry Light sampling: the object-space area is Σ 4πr². + std::optional areaInput() const override; + PrimitiveInput primitiveInput() const; helium::ChangeObserverPtr m_index; helium::ChangeObserverPtr m_vertex; @@ -72,14 +67,6 @@ struct Sphere : public Geometry size_t m_numSpheres{0}; float m_globalRadius{1.f}; - - // Geometry Light sampling data, built lazily by ensureAreaData(). The CDF is - // the normalized cumulative object-space area over primitives. m_areaDataWanted - // persists across recommits so a re-finalize rebuilds it order-independently. - HostDeviceArray m_primAreaCdf; - float m_totalArea{0.f}; - bool m_areaDataValid{false}; - bool m_areaDataWanted{false}; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/Triangle.cpp b/devices/rtx/device/geometry/Triangle.cpp index 8b25db02f..ff887eddd 100644 --- a/devices/rtx/device/geometry/Triangle.cpp +++ b/devices/rtx/device/geometry/Triangle.cpp @@ -37,7 +37,20 @@ namespace visrtx { Triangle::Triangle(DeviceGlobalState *d) : Geometry(d), m_index(this), m_vertex(this) -{} +{ + declarePreparationParameters({"primitive.index", + "vertex.position", + "vertex.normal", + "faceVarying.normal", + "vertex.tangent", + "faceVarying.tangent", + "cullBackfaces", + "faceVarying.attribute0", + "faceVarying.attribute1", + "faceVarying.attribute2", + "faceVarying.attribute3", + "faceVarying.color"}); +} Triangle::~Triangle() = default; @@ -50,7 +63,7 @@ void Triangle::generateTangents() input.positions = m_vertex.get(); input.indices = m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; - input.numTriangles = m_index ? m_index->size() : m_vertex->size() / 3; + input.numTriangles = primitiveCount(); input.normals = m_vertexNormal.ptr; input.normalsFV = m_vertexNormalFV.ptr; input.uvs = uvs; @@ -74,19 +87,19 @@ void Triangle::commitParameters() commitAttributes("faceVarying.", m_vertexAttributesFV); } -void Triangle::finalize() +bool Triangle::prepare() { if (!m_vertex) { reportMessage(ANARI_SEVERITY_WARNING, "missing required parameter 'vertex.position' on triangle geometry"); - return; + return false; } if (!m_index && m_vertex->size() % 3 != 0) { reportMessage(ANARI_SEVERITY_ERROR, "'vertex.position' on triangle geometry is a non-multiple of 3" " without 'primitive.index' present"); - return; + return false; } if (m_vertexNormal && m_vertex->size() != m_vertexNormal->size()) { @@ -97,7 +110,7 @@ void Triangle::finalize() m_vertex->size()); } - const size_t numTriangles = m_index ? m_index->size() : m_vertex->size() / 3; + const size_t numTriangles = primitiveCount(); if (m_vertexNormalFV && 3 * numTriangles != m_vertexNormalFV->size()) { reportMessage(ANARI_SEVERITY_WARNING, @@ -137,70 +150,23 @@ void Triangle::finalize() m_index ? "indexed" : "soup"); m_vertexBufferPtr = (CUdeviceptr)m_vertex->beginAs(AddressSpace::GPU); - - // Vertices/indices may have changed. Rebuild the Geometry Light CDF if a - // surface has ever requested it (order-independent of the surface commit), - // else drop any stale data. - m_areaDataValid = false; - if (m_areaDataWanted) - buildAreaData(); - else { - m_totalArea = 0.f; - m_primAreaCdf.clear(); - } - - upload(); -} - -void Triangle::buildAreaData() -{ - const size_t numTriangles = m_index ? m_index->size() : m_vertex->size() / 3; - const vec3 *vertices = m_vertex->beginAs(AddressSpace::HOST); - const uvec3 *indices = - m_index ? m_index->beginAs(AddressSpace::HOST) : nullptr; - - m_primAreaCdf.resize(numTriangles); - auto *cdf = m_primAreaCdf.dataHost(); - - double cumulative = 0.0; - for (size_t i = 0; i < numTriangles; ++i) { - const uvec3 tri = indices ? indices[i] : uvec3(0, 1, 2) + uint32_t(3 * i); - const vec3 &v0 = vertices[tri.x]; - const vec3 &v1 = vertices[tri.y]; - const vec3 &v2 = vertices[tri.z]; - cumulative += 0.5 * glm::length(glm::cross(v1 - v0, v2 - v0)); - cdf[i] = float(cumulative); - } - m_totalArea = float(cumulative); - - // Normalize to a cumulative CDF ending at 1. A degenerate (zero-area) mesh - // leaves totalArea 0; callers gate on that. - if (m_totalArea > 0.f) { - for (size_t i = 0; i < numTriangles; ++i) - cdf[i] /= m_totalArea; - } - - m_primAreaCdf.upload(); - m_areaDataValid = true; -} - -bool Triangle::isAreaSamplingSupported() const -{ return true; } -void Triangle::ensureAreaData() +size_t Triangle::primitiveCount() const { - m_areaDataWanted = true; - if (m_areaDataValid) - return; - buildAreaData(); - upload(); // republish gpuData() so the CDF pointers reach the device + return m_index ? m_index->size() : m_vertex->size() / 3; } -float Triangle::totalArea() const +std::optional Triangle::areaInput() const { - return m_totalArea; + if (!isValid()) + return PrimitiveInput{}; + TriangleInput input{}; + input.vertices = m_vertex->beginAs(AddressSpace::GPU); + input.indices = + m_index ? m_index->beginAs(AddressSpace::GPU) : nullptr; + return PrimitiveInput{primitiveCount(), input}; } void Triangle::populateBuildInput(OptixBuildInput &buildInput) const @@ -263,10 +229,7 @@ GeometryGPUData Triangle::gpuData() const resolveTangentPtr(m_vertexTangentFV, m_vertexTangentFVFinalized); tri.cullBackfaces = m_cullBackfaces; - // Geometry Light sampling data; null/zero until ensureAreaData() runs. - tri.primAreaCdf = m_primAreaCdf.dataDevice(); - tri.numPrimitives = uint32_t(m_primAreaCdf.size()); - tri.totalArea = m_totalArea; + populateAreaData(tri, primitiveCount()); return retval; } diff --git a/devices/rtx/device/geometry/Triangle.h b/devices/rtx/device/geometry/Triangle.h index 9ef1161b8..9e2783b6b 100644 --- a/devices/rtx/device/geometry/Triangle.h +++ b/devices/rtx/device/geometry/Triangle.h @@ -35,7 +35,6 @@ #include "Geometry.h" #include "array/Array1D.h" #include "utility/DeviceBuffer.h" -#include "utility/HostDeviceArray.h" namespace visrtx { @@ -45,24 +44,20 @@ struct Triangle : public Geometry ~Triangle() override; void commitParameters() override; - void finalize() override; bool isValid() const override; void populateBuildInput(OptixBuildInput &) const override; int optixGeometryType() const override; - // Build the per-primitive area CDF and object-space total area used to sample - // this geometry as a Geometry Light. Lazy: only Emissive Surfaces call it, so - // ordinary meshes never pay for it. Re-uploads GPU data to publish the CDF. - bool isAreaSamplingSupported() const override; - void ensureAreaData() override; - float totalArea() const override; - private: + bool prepare() override; GeometryGPUData gpuData() const override; void cleanup(); - void buildAreaData(); + // Geometry Light sampling: the normalized cumulative object-space area over + // triangles. + std::optional areaInput() const override; + size_t primitiveCount() const; // Generate tangents that follow attribute0 when none were authored, into // the per-vertex or per-corner finalized buffer (see ComputeTangent.h). @@ -90,14 +85,6 @@ struct Triangle : public Geometry CUdeviceptr m_vertexBufferPtr{}; bool m_cullBackfaces{false}; - - // Geometry Light sampling data, built lazily by ensureAreaData(). The CDF is - // the normalized cumulative object-space area over primitives. m_areaDataWanted - // persists across recommits so a re-finalize rebuilds it order-independently. - HostDeviceArray m_primAreaCdf; - float m_totalArea{0.f}; - bool m_areaDataValid{false}; - bool m_areaDataWanted{false}; }; } // namespace visrtx diff --git a/devices/rtx/device/geometry/UnknownGeometry.cpp b/devices/rtx/device/geometry/UnknownGeometry.cpp index 2681f353e..154f5c2a1 100644 --- a/devices/rtx/device/geometry/UnknownGeometry.cpp +++ b/devices/rtx/device/geometry/UnknownGeometry.cpp @@ -46,6 +46,11 @@ void UnknownGeometry::populateBuildInput(OptixBuildInput &) const // no-op } +bool UnknownGeometry::prepare() +{ + return true; +} + GeometryGPUData UnknownGeometry::gpuData() const { return {}; diff --git a/devices/rtx/device/geometry/UnknownGeometry.h b/devices/rtx/device/geometry/UnknownGeometry.h index af024b876..e3388998d 100644 --- a/devices/rtx/device/geometry/UnknownGeometry.h +++ b/devices/rtx/device/geometry/UnknownGeometry.h @@ -47,6 +47,7 @@ struct UnknownGeometry : public Geometry bool isValid() const override; private: + bool prepare() override; GeometryGPUData gpuData() const override; }; diff --git a/devices/rtx/device/optix_visrtx.cpp b/devices/rtx/device/optix_visrtx.cpp index 8bba46cfd..c582f601e 100644 --- a/devices/rtx/device/optix_visrtx.cpp +++ b/devices/rtx/device/optix_visrtx.cpp @@ -31,6 +31,7 @@ #include "optix_visrtx.h" #include "Object.h" +#include "geometry/Geometry.h" #ifdef USE_MDL #include @@ -40,7 +41,7 @@ namespace visrtx { -void buildOptixBVH(std::vector buildInput, +bool buildOptixBVH(std::vector buildInput, DeviceBuffer &bvh, OptixTraversableHandle &traversable, box3 &bounds, @@ -48,82 +49,133 @@ void buildOptixBVH(std::vector buildInput, { traversable = {}; bounds = {}; - if (buildInput.empty()) { obj->reportMessage(ANARI_SEVERITY_DEBUG, "skipping BVH build"); - return; + return true; } auto &state = *obj->deviceState(); - - // TLAS setup // - - OptixAccelBuildOptions accelOptions{}; - accelOptions.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION; - accelOptions.operation = OPTIX_BUILD_OPERATION_BUILD; - - OptixAccelBufferSizes tlasBufferSizes; - OPTIX_CHECK_OBJECT(optixAccelComputeMemoryUsage(state.optixContext, - &accelOptions, - buildInput.data(), - buildInput.size(), - &tlasBufferSizes), - obj); - - // Prepare compaction // - - DeviceBuffer compactedSizeBuffer; - compactedSizeBuffer.reserve(sizeof(uint64_t)); - - OptixAccelEmitDesc emitDesc[2]; - emitDesc[0].type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE; - emitDesc[0].result = (CUdeviceptr)compactedSizeBuffer.ptr(); - - DeviceBuffer aabbBuffer; - aabbBuffer.reserve(sizeof(box3)); - - emitDesc[1].type = OPTIX_PROPERTY_TYPE_AABBS; - emitDesc[1].result = (CUdeviceptr)aabbBuffer.ptr(); - - // Execute BVH build // - - DeviceBuffer tempBuffer; - tempBuffer.reserve(tlasBufferSizes.tempSizeInBytes); - - DeviceBuffer outputBuffer; - outputBuffer.reserve(tlasBufferSizes.outputSizeInBytes); - - OPTIX_CHECK_OBJECT(optixAccelBuild(state.optixContext, - state.stream, - &accelOptions, - buildInput.data(), - buildInput.size(), - (CUdeviceptr)tempBuffer.ptr(), - tempBuffer.bytes(), - (CUdeviceptr)outputBuffer.ptr(), - outputBuffer.bytes(), - &traversable, - emitDesc, - 2), - obj); - CUDA_SYNC_CHECK_OBJECT(obj); - - aabbBuffer.download(&bounds); - - // Perform compaction // - - uint64_t compactedSize; - compactedSizeBuffer.download(&compactedSize, 1); - - bvh.reserve(compactedSize); - OPTIX_CHECK_OBJECT(optixAccelCompact(state.optixContext, - state.stream, - traversable, + auto &preparationStream = state.preparationStream; + const auto stream = preparationStream.stream(); + auto check = [&](cudaError_t error, const char *operation) { + if (error == cudaSuccess) + return true; + preparationStream.sync(); // Drain queued consumers before scratch is freed. + cudaGetLastError(); + obj->reportMessage(ANARI_SEVERITY_ERROR, + "BVH preparation failed during %s: %s", + operation, + cudaGetErrorString(error)); + return false; + }; + auto checkOptix = [&](OptixResult result, const char *operation) { + if (result == OPTIX_SUCCESS) + return true; + preparationStream.sync(); + obj->reportMessage(ANARI_SEVERITY_ERROR, + "BVH preparation failed during %s: %s", + operation, + optixGetErrorName(result)); + return false; + }; + auto reserve = [&](DeviceBuffer &buffer, size_t bytes) { + return check(buffer.tryReserve(bytes), "allocating device storage"); + }; + + // Legacy producers include field/isosurface work on the render stream and + // authored arrays/instance uploads on the default stream. Previous rendering + // must also finish before the existing BVH storage can be reused. + if (!check(preparationStream.orderAfterRender(), "previous BVH consumers") + || !check( + preparationStream.orderAfter(nullptr), "input upload dependency")) + return false; + + OptixAccelBuildOptions options{}; + options.buildFlags = OPTIX_BUILD_FLAG_ALLOW_COMPACTION; + options.operation = OPTIX_BUILD_OPERATION_BUILD; + OptixAccelBufferSizes sizes{}; + if (!checkOptix(optixAccelComputeMemoryUsage(state.optixContext, + &options, + buildInput.data(), + buildInput.size(), + &sizes), + "memory requirements")) + return false; + + // Allocate before submitting GPU work. Every earlier build completed, so + // no transfer still targets the readback. + struct Readback + { + box3 bounds; + uint64_t compactedSize; + }; + cudaError_t readbackError = cudaSuccess; + auto *readback = static_cast( + preparationStream.readback(sizeof(Readback), readbackError)); + if (!check(readbackError, "allocating BVH readback")) + return false; + + DeviceBuffer compactedSizeBuffer, aabbBuffer, tempBuffer, outputBuffer; + if (!reserve(compactedSizeBuffer, sizeof(uint64_t)) + || !reserve(aabbBuffer, sizeof(box3)) + || !reserve(tempBuffer, sizes.tempSizeInBytes) + || !reserve(outputBuffer, sizes.outputSizeInBytes)) + return false; + + OptixAccelEmitDesc emit[2]{}; + emit[0].type = OPTIX_PROPERTY_TYPE_COMPACTED_SIZE; + emit[0].result = (CUdeviceptr)compactedSizeBuffer.ptr(); + emit[1].type = OPTIX_PROPERTY_TYPE_AABBS; + emit[1].result = (CUdeviceptr)aabbBuffer.ptr(); + OptixTraversableHandle built{}; + if (!checkOptix(optixAccelBuild(state.optixContext, + stream, + &options, + buildInput.data(), + buildInput.size(), + (CUdeviceptr)tempBuffer.ptr(), + tempBuffer.bytes(), + (CUdeviceptr)outputBuffer.ptr(), + outputBuffer.bytes(), + &built, + emit, + 2), + "build")) + return false; + + auto &builtBounds = readback->bounds; + auto &compactedSize = readback->compactedSize; + if (!check(cudaMemcpyAsync(&builtBounds, + aabbBuffer.ptr(), + sizeof(box3), + cudaMemcpyDeviceToHost, + stream), + "bounds readback") + || !check(cudaMemcpyAsync(&compactedSize, + compactedSizeBuffer.ptr(), + sizeof(compactedSize), + cudaMemcpyDeviceToHost, + stream), + "compaction size readback") + || !check(preparationStream.sync(), "build completion")) + return false; + + if (!reserve(bvh, compactedSize) + || !checkOptix(optixAccelCompact(state.optixContext, + stream, + built, (CUdeviceptr)bvh.ptr(), bvh.bytes(), - &traversable), - obj); - CUDA_SYNC_CHECK_OBJECT(obj); + &built), + "compaction") + || !check(preparationStream.sync(), "compaction completion")) + return false; + + // Publication and scratch destruction happen only after this stream's work + // completes. Subsequent tracing needs no device-wide barrier. + traversable = built; + bounds = builtBounds; + return true; } /////////////////////////////////////////////////////////////////////////////// @@ -136,6 +188,27 @@ DeviceGlobalState::DeviceGlobalState(ANARIDevice d) DeviceGlobalState::~DeviceGlobalState() = default; +cudaError_t DeviceGlobalState::DeviceObjectRegistry::upload( + PreparationStream &stream) +{ + if (!(samplers.dirty() || geometries.dirty() || materials.dirty() + || surfaces.dirty() || lights.dirty() || fields.dirty() + || volumes.dirty())) + return cudaSuccess; + const auto error = stream.upload( + samplers, geometries, materials, surfaces, lights, fields, volumes); + if (error != cudaSuccess) + return error; + samplers.markUploaded(); + geometries.markUploaded(); + materials.markUploaded(); + surfaces.markUploaded(); + lights.markUploaded(); + fields.markUploaded(); + volumes.markUploaded(); + return cudaSuccess; +} + #ifdef USE_MDL namespace { diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index ffeaf323b..9b3426131 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -31,6 +31,7 @@ #pragma once +#include "geometry/GeometryPreparation.h" #include "gpu/gpu_objects.h" #include "utility/DeviceObjectArray.h" @@ -39,6 +40,7 @@ // anari #include // optix +#include #include #include #include @@ -52,11 +54,13 @@ #include "utility/TaskExecutor.h" #endif // defined(USE_MDL) // std +#include #include #include #include #include #include +#include #include #ifdef OPAQUE @@ -154,6 +158,8 @@ VISRTX_ANARI_TYPEFOR_SPECIALIZATION(visrtx::box3, ANARI_FLOAT32_BOX3); namespace visrtx { struct Object; +struct Geometry; +struct Array; struct MDL; struct ptx_blob @@ -166,6 +172,10 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState { anari::Device anariDevice{nullptr}; + // A failed last-public-release copy leaves application memory unavailable. + // Cached GPU pointers cannot be repaired safely: only cleanup is permitted. + std::atomic arrayPrivatizationFailed{false}; + CUcontext cudaContext; CUstream stream; cudaDeviceProp deviceProps; @@ -223,6 +233,8 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState DeviceObjectArray lights; DeviceObjectArray fields; DeviceObjectArray volumes; + + cudaError_t upload(PreparationStream &stream); } registry; // MDL @@ -262,9 +274,16 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState DeviceGlobalState(ANARIDevice d); ~DeviceGlobalState() override; + + // The scene-update stream: geometry preparation, BVH builds, registry and + // world-table uploads. + PreparationStream preparationStream; + // Declared last so it is destroyed first: the geometries it still holds are + // released while the registry and the stream above are alive. + GeometryPreparation preparation{preparationStream}; }; -void buildOptixBVH(std::vector buildInput, +bool buildOptixBVH(std::vector buildInput, DeviceBuffer &bvh, OptixTraversableHandle &traversable, box3 &bounds, diff --git a/devices/rtx/device/utility/DeviceAllocationCache.h b/devices/rtx/device/utility/DeviceAllocationCache.h new file mode 100644 index 000000000..4a716d3e4 --- /dev/null +++ b/devices/rtx/device/utility/DeviceAllocationCache.h @@ -0,0 +1,214 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace visrtx { + +// Device-local cache for backend-owned authored-array uploads only. Returning +// storage NEVER makes it reusable immediately: reclaim() freezes the blocks +// returned so far, and they become reusable only after deferred CPU +// submissions and all GPU consumers complete. Call allocate/reclaim in the +// owning device's CUDA context; scene updates and reclaim calls are +// serialized. No mutex is held across CUDA calls or callbacks. +struct DeviceAllocationCache +{ + static constexpr size_t MAX_BLOCKS = 256; + static constexpr size_t MAX_BYTES = 64 * 1024 * 1024; + explicit DeviceAllocationCache( + size_t byteLimit = MAX_BYTES, size_t blockLimit = MAX_BLOCKS); + ~DeviceAllocationCache(); + DeviceAllocationCache(const DeviceAllocationCache &) = delete; + DeviceAllocationCache &operator=(const DeviceAllocationCache &) = delete; + + cudaError_t allocate(size_t bytes, void **pointer); + void release(void *pointer, size_t bytes); + template + cudaError_t reclaim(CompleteDeferred completeDeferred); + void close(); + + private: + struct Block + { + void *pointer{nullptr}; + size_t bytes{0}; + }; + void *remove(size_t index); + bool freeBlocks(bool readyOnly); + const size_t m_byteLimit; + const size_t m_blockLimit; + std::mutex m_mutex; + bool m_enabled{true}; + size_t m_cachedBytes{0}; + // m_blocks holds three runs: [0, m_readyEnd) is reusable, [m_readyEnd, + // m_frozenEnd) is the cohort a reclaim() in progress froze, and + // [m_frozenEnd, m_count) was returned since and waits for the next one. + size_t m_readyEnd{0}; + size_t m_frozenEnd{0}; + size_t m_count{0}; + std::array m_blocks; +}; + +inline DeviceAllocationCache::DeviceAllocationCache( + size_t byteLimit, size_t blockLimit) + : m_byteLimit(byteLimit), m_blockLimit(std::min(blockLimit, MAX_BLOCKS)) +{} + +inline DeviceAllocationCache::~DeviceAllocationCache() +{ + close(); +} + +inline cudaError_t DeviceAllocationCache::allocate(size_t bytes, void **pointer) +{ + *pointer = nullptr; + if (!bytes) + return cudaSuccess; + { + std::lock_guard lock(m_mutex); + for (size_t i = 0; i < m_readyEnd; ++i) { + if (m_blocks[i].bytes == bytes) { + *pointer = remove(i); + return cudaSuccess; + } + } + } + auto error = cudaMalloc(pointer, bytes); + if (error == cudaErrorMemoryAllocation && freeBlocks(true)) { + // Release only certified idle blocks. Pending blocks are not safe to hand + // back without a completion boundary, and are never borrowed on failure. + cudaGetLastError(); + *pointer = nullptr; + error = cudaMalloc(pointer, bytes); + } + return error; +} + +inline void DeviceAllocationCache::release(void *pointer, size_t bytes) +{ + if (!pointer) + return; + { + std::lock_guard lock(m_mutex); + if (m_enabled && m_count < m_blockLimit + && bytes <= m_byteLimit - m_cachedBytes) { + m_blocks[m_count++] = {pointer, bytes}; + m_cachedBytes += bytes; + return; + } + } + // Overflow and late returns preserve ordinary cudaFree retirement semantics. + cudaFree(pointer); +} + +template +inline cudaError_t DeviceAllocationCache::reclaim( + CompleteDeferred completeDeferred) +{ + { + std::lock_guard lock(m_mutex); + if (m_frozenEnd == m_count) + return cudaSuccess; + m_frozenEnd = m_count; + } + bool reusable = false; + // Runs on host exceptions too: a cohort that was not certified idle goes + // back to waiting. + auto finish = nonstd::make_scope_exit([&] { + std::lock_guard lock(m_mutex); + if (reusable) + m_readyEnd = m_frozenEnd; + else + m_frozenEnd = m_readyEnd; + }); + auto error = completeDeferred(); + // These blocks used to be retired by cudaFree, which waits for the whole + // context. One wait of the same reach covers the cohort without a list of + // the streams that may have read it; later returns wait for the next + // reclaim(). + if (error == cudaSuccess) + error = cudaDeviceSynchronize(); + reusable = error == cudaSuccess; + return error; +} + +// Call with the mutex held. The hole is filled from the end of the block's own +// run, then from the end of each later run, so the three stay contiguous. +inline void *DeviceAllocationCache::remove(size_t index) +{ + const auto block = m_blocks[index]; + if (index < m_readyEnd) { + m_blocks[index] = m_blocks[--m_readyEnd]; + index = m_readyEnd; + } + if (index < m_frozenEnd) { + m_blocks[index] = m_blocks[--m_frozenEnd]; + index = m_frozenEnd; + } + m_blocks[index] = m_blocks[--m_count]; + m_cachedBytes -= block.bytes; + return block.pointer; +} + +// Frees the reusable blocks, or every block. Returns whether any was freed. +inline bool DeviceAllocationCache::freeBlocks(bool readyOnly) +{ + bool freed = false; + for (;;) { + void *pointer = nullptr; + { + std::lock_guard lock(m_mutex); + if ((readyOnly ? m_readyEnd : m_count) == 0) + return freed; + pointer = remove(0); + } + cudaFree(pointer); + freed = true; + } +} + +inline void DeviceAllocationCache::close() +{ + { + std::lock_guard lock(m_mutex); + m_enabled = false; + } + freeBlocks(false); +} + +} // namespace visrtx diff --git a/devices/rtx/device/utility/DeviceBuffer.h b/devices/rtx/device/utility/DeviceBuffer.h index bb9dca153..85049819b 100644 --- a/devices/rtx/device/utility/DeviceBuffer.h +++ b/devices/rtx/device/utility/DeviceBuffer.h @@ -33,6 +33,7 @@ #include "MemoryAllocation.h" // std +#include #include #include #include @@ -50,10 +51,20 @@ struct DeviceBuffer template void upload(const std::vector &v); + // Caller orders previous readers and retains src through stream completion. + template + cudaError_t enqueueUpload(const T *src, + size_t numElements, + cudaStream_t stream, + size_t byteOffsetStart = 0); + template void download(T *dst, size_t numElements = 1, size_t byteOffsetStart = 0); - HostMemoryAllocation hostCopy() const { return m_mem; } + HostMemoryAllocation hostCopy() const + { + return m_mem; + } template T *ptrAs() const; @@ -62,6 +73,9 @@ struct DeviceBuffer void reset(); void reserve(size_t bytes); + // Grows storage to at least `bytes` and consumes the CUDA error the attempt + // leaves pending. On failure the buffer is empty, so a retry allocates. + cudaError_t tryReserve(size_t bytes); operator bool() const; @@ -103,6 +117,30 @@ inline void DeviceBuffer::upload(const std::vector &v) upload(v.data(), v.size()); } +template +inline cudaError_t DeviceBuffer::enqueueUpload(const T *src, + size_t numElements, + cudaStream_t stream, + size_t byteOffsetStart) +{ + static_assert(std::is_trivially_copyable::value); + if (numElements == 0) + return cudaSuccess; + if (!src + || numElements + > (std::numeric_limits::max() - byteOffsetStart) / sizeof(T)) + return cudaErrorInvalidValue; + const auto copyBytes = bytesof(numElements); + const auto error = tryReserve(copyBytes + byteOffsetStart); + if (error != cudaSuccess) + return error; + return cudaMemcpyAsync(static_cast(ptr()) + byteOffsetStart, + src, + copyBytes, + cudaMemcpyHostToDevice, + stream); +} + template inline void DeviceBuffer::download( T *dst, size_t numElements, size_t byteOffsetStart) @@ -150,6 +188,23 @@ inline void DeviceBuffer::reserve(size_t numBytes) alloc(numBytes); } +inline cudaError_t DeviceBuffer::tryReserve(size_t numBytes) +{ + if (!ptr()) + reset(); // reserve()/upload() failures retain capacity without storage. + if (numBytes <= bytes()) + return cudaSuccess; + alloc(numBytes); + // Consume the runtime error even when missing storage identifies the + // failure. Otherwise the next successful CUDA call inherits it. + auto error = cudaGetLastError(); + if (error == cudaSuccess && !ptr()) + error = cudaErrorMemoryAllocation; + if (error != cudaSuccess) + reset(); + return error; +} + inline DeviceBuffer::operator bool() const { return ptr() != nullptr; diff --git a/devices/rtx/device/utility/DeviceObjectArray.h b/devices/rtx/device/utility/DeviceObjectArray.h index 01a2e5d5f..438f2500b 100644 --- a/devices/rtx/device/utility/DeviceObjectArray.h +++ b/devices/rtx/device/utility/DeviceObjectArray.h @@ -52,14 +52,15 @@ struct DeviceObjectArray size_t size() const; bool empty() const; - T &map(DeviceObjectIndex idx); - void unmap(DeviceObjectIndex idx); + void set(DeviceObjectIndex idx, const T &value); void *hostObject(DeviceObjectIndex idx) const; - void upload(); + bool dirty() const; + cudaError_t enqueueUpload(cudaStream_t stream); + void markUploaded(); - const T *devicePtr(); + const T *devicePtr() const; private: bool m_fullReupload{true}; @@ -70,7 +71,13 @@ struct DeviceObjectArray std::stack> m_freeIndices; std::vector m_objectsToUpload; - std::mutex m_allocationMutex; + // Stable sources for asynchronous copies even if unrelated objects are + // created or finalized while the batch is in flight. + std::vector m_uploadSnapshot; + std::vector m_uploadIndices; + size_t m_updateVersion{0}; + size_t m_uploadVersion{0}; + mutable std::mutex m_allocationMutex; }; // Inlined definitions //////////////////////////////////////////////////////// @@ -96,6 +103,7 @@ inline DeviceObjectIndex DeviceObjectArray::alloc(void *hostObj) m_fullReupload = true; } + ++m_updateVersion; return i; } @@ -126,44 +134,74 @@ inline bool DeviceObjectArray::empty() const } template -inline T &DeviceObjectArray::map(DeviceObjectIndex idx) +inline void DeviceObjectArray::set(DeviceObjectIndex idx, const T &value) { - return *(m_objects.dataHost() + idx); + std::scoped_lock lock(m_allocationMutex); + m_objects.dataHost()[idx] = value; + m_objectsToUpload.push_back(idx); + ++m_updateVersion; } template -inline void DeviceObjectArray::unmap(DeviceObjectIndex idx) +inline void *DeviceObjectArray::hostObject(DeviceObjectIndex idx) const { - m_objectsToUpload.push_back(idx); + return m_hostObjects[idx]; } template -inline void *DeviceObjectArray::hostObject(DeviceObjectIndex idx) const +inline bool DeviceObjectArray::dirty() const { - return m_hostObjects[idx]; + std::scoped_lock lock(m_allocationMutex); + return !m_objectsToUpload.empty(); } template -inline void DeviceObjectArray::upload() +inline cudaError_t DeviceObjectArray::enqueueUpload(cudaStream_t stream) { - if (m_objectsToUpload.empty()) - return; - - if (m_fullReupload) - m_objects.upload(); - else { - for (auto i : m_objectsToUpload) - m_objects.upload(i, i + 1); + bool full = false; + { + std::scoped_lock lock(m_allocationMutex); + m_uploadVersion = m_updateVersion; + m_uploadIndices = m_objectsToUpload; + if (m_uploadIndices.empty()) + return cudaSuccess; + full = m_fullReupload; + if (full) + m_uploadSnapshot.assign(m_objects.begin(), m_objects.end()); + else { + m_uploadSnapshot.clear(); + m_uploadSnapshot.reserve(m_uploadIndices.size()); + for (auto i : m_uploadIndices) + m_uploadSnapshot.push_back(m_objects.dataHost()[i]); + } + } + // Do not hold the registry lock during CUDA calls/waits: completion + // callbacks may create objects. The snapshot outlives the entire batch. + if (full) + return m_objects.enqueueUploadFrom( + m_uploadSnapshot.data(), m_uploadSnapshot.size(), 0, stream); + for (size_t i = 0; i < m_uploadIndices.size(); ++i) { + const auto error = m_objects.enqueueUploadFrom( + &m_uploadSnapshot[i], 1, m_uploadIndices[i], stream); + if (error != cudaSuccess) + return error; } + return cudaSuccess; +} +template +inline void DeviceObjectArray::markUploaded() +{ + std::scoped_lock lock(m_allocationMutex); + if (m_uploadIndices.empty() || m_uploadVersion != m_updateVersion) + return; // Retain edits made after the snapshot for the next batch. m_objectsToUpload.clear(); m_fullReupload = false; } template -inline const T *DeviceObjectArray::devicePtr() +inline const T *DeviceObjectArray::devicePtr() const { - upload(); return m_objects.dataDevice(); } diff --git a/devices/rtx/device/utility/HostDeviceArray.h b/devices/rtx/device/utility/HostDeviceArray.h index 626bb0de0..7ca68dc54 100644 --- a/devices/rtx/device/utility/HostDeviceArray.h +++ b/devices/rtx/device/utility/HostDeviceArray.h @@ -56,6 +56,12 @@ struct HostDeviceArray void upload(); void download(); + cudaError_t enqueueUpload(cudaStream_t stream); + cudaError_t enqueueUploadFrom( + const T *source, size_t count, size_t startIndex, cudaStream_t stream); + cudaError_t enqueueUpload( + cudaStream_t stream, size_t startIndex, size_t endIndex); + Span hostSpan() const; Span deviceSpan() const; @@ -121,6 +127,34 @@ inline void HostDeviceArray::upload(size_t startIndex, size_t endIndex) } } +template +inline cudaError_t HostDeviceArray::enqueueUpload( + cudaStream_t stream, size_t startIndex, size_t endIndex) +{ + if (startIndex > endIndex || endIndex > size()) + return cudaErrorInvalidValue; + if (startIndex == endIndex) + return cudaSuccess; + return m_deviceBuffer.enqueueUpload(&m_hostArray[startIndex], + endIndex - startIndex, + stream, + startIndex * sizeof(T)); +} + +template +inline cudaError_t HostDeviceArray::enqueueUploadFrom( + const T *source, size_t count, size_t startIndex, cudaStream_t stream) +{ + return m_deviceBuffer.enqueueUpload( + source, count, stream, startIndex * sizeof(T)); +} + +template +inline cudaError_t HostDeviceArray::enqueueUpload(cudaStream_t stream) +{ + return enqueueUpload(stream, 0, size()); +} + template inline void HostDeviceArray::download(size_t startIndex, size_t endIndex) { diff --git a/devices/rtx/device/utility/MemoryAllocation.cpp b/devices/rtx/device/utility/MemoryAllocation.cpp index d10aba51e..10474cc3d 100644 --- a/devices/rtx/device/utility/MemoryAllocation.cpp +++ b/devices/rtx/device/utility/MemoryAllocation.cpp @@ -30,6 +30,8 @@ */ #include "MemoryAllocation.h" +#include +#include "DeviceAllocationCache.h" // cuda #include // std @@ -100,7 +102,8 @@ HostMemoryAllocation &HostMemoryAllocation::operator=( return *this; } -HostMemoryAllocation::HostMemoryAllocation(const CudaMemoryAllocation &o) { +HostMemoryAllocation::HostMemoryAllocation(const CudaMemoryAllocation &o) +{ (*this) = o; } @@ -181,6 +184,15 @@ CudaMemoryAllocation::~CudaMemoryAllocation() freeMemory(); } +CudaMemoryAllocation CudaMemoryAllocation::fromCache( + void *memory, size_t bytes, std::shared_ptr cache) +{ + CudaMemoryAllocation allocation(memory, bytes); + allocation.m_owner = true; + allocation.m_cache = std::move(cache); + return allocation; +} + void *CudaMemoryAllocation::ptr() const { return m_ptr; @@ -219,20 +231,30 @@ CudaMemoryAllocation &CudaMemoryAllocation::operator=( return *this; } -CudaMemoryAllocation::CudaMemoryAllocation(const HostMemoryAllocation &o) { +CudaMemoryAllocation::CudaMemoryAllocation(const HostMemoryAllocation &o) +{ (*this) = o; } -void CudaMemoryAllocation::privatize() +cudaError_t CudaMemoryAllocation::privatize() { if (!isValid() || isOwner()) - return; + return cudaSuccess; void *dst = nullptr; - cudaMalloc(&dst, bytes()); - cudaMemcpy(dst, ptr(), bytes(), cudaMemcpyDeviceToDevice); + auto error = cudaMalloc(&dst, bytes()); + if (error != cudaSuccess) + return error; + error = cudaMemcpy(dst, ptr(), bytes(), cudaMemcpyDeviceToDevice); + if (error == cudaSuccess) + error = cudaStreamSynchronize(nullptr); + if (error != cudaSuccess) { + cudaFree(dst); + return error; + } freeMemory(); m_ptr = dst; m_owner = true; + return cudaSuccess; } CudaMemoryAllocation::CudaMemoryAllocation(CudaMemoryAllocation &&o) @@ -243,6 +265,7 @@ CudaMemoryAllocation::CudaMemoryAllocation(CudaMemoryAllocation &&o) m_deleter = o.m_deleter; m_deleterPtr = o.m_deleterPtr; m_owner = o.m_owner; + m_cache = std::move(o.m_cache); o.clearPointers(); } @@ -254,6 +277,7 @@ CudaMemoryAllocation &CudaMemoryAllocation::operator=(CudaMemoryAllocation &&o) m_deleter = o.m_deleter; m_deleterPtr = o.m_deleterPtr; m_owner = o.m_owner; + m_cache = std::move(o.m_cache); o.clearPointers(); return *this; } @@ -261,7 +285,9 @@ CudaMemoryAllocation &CudaMemoryAllocation::operator=(CudaMemoryAllocation &&o) void CudaMemoryAllocation::freeMemory() { if (isValid()) { - if (isOwner()) + if (isOwner() && m_cache) + m_cache->release(m_ptr, m_bytes); + else if (isOwner()) cudaFree(m_ptr); else if (m_deleter) m_deleter(m_deleterPtr, m_ptr); @@ -274,6 +300,7 @@ void CudaMemoryAllocation::clearPointers() m_ptr = nullptr; m_deleter = nullptr; m_deleterPtr = nullptr; + m_cache.reset(); } } // namespace visrtx \ No newline at end of file diff --git a/devices/rtx/device/utility/MemoryAllocation.h b/devices/rtx/device/utility/MemoryAllocation.h index 8bcad0891..7add396c0 100644 --- a/devices/rtx/device/utility/MemoryAllocation.h +++ b/devices/rtx/device/utility/MemoryAllocation.h @@ -33,11 +33,15 @@ // anari #include +// CUDA +#include +#include namespace visrtx { struct HostMemoryAllocation; struct CudaMemoryAllocation; +struct DeviceAllocationCache; struct HostMemoryAllocation { @@ -88,6 +92,8 @@ struct CudaMemoryAllocation CudaMemoryAllocation(size_t bytes); CudaMemoryAllocation() = default; ~CudaMemoryAllocation(); + static CudaMemoryAllocation fromCache( + void *memory, size_t bytes, std::shared_ptr cache); void *ptr() const; size_t bytes() const; @@ -99,7 +105,7 @@ struct CudaMemoryAllocation CudaMemoryAllocation &operator=(const HostMemoryAllocation &o); CudaMemoryAllocation(const HostMemoryAllocation &o); - void privatize(); // if !isOwner(), then make internal copy + cudaError_t privatize(); // publish an internal copy only after completion // Movable, not copyable // CudaMemoryAllocation(CudaMemoryAllocation &&); @@ -117,6 +123,7 @@ struct CudaMemoryAllocation anari::MemoryDeleter m_deleter{nullptr}; const void *m_deleterPtr{nullptr}; bool m_owner{false}; + std::shared_ptr m_cache; }; } // namespace visrtx diff --git a/devices/rtx/device/utility/PreparationQueue.h b/devices/rtx/device/utility/PreparationQueue.h new file mode 100644 index 000000000..9b2b8746d --- /dev/null +++ b/devices/rtx/device/utility/PreparationQueue.h @@ -0,0 +1,143 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +#include +#include +#include + +namespace visrtx { + +// Owners of objects waiting for one stage of batched preparation (input +// uploads, deferred preparation results). Pointer is an owning pointer. +// collect() runs the stage as one transaction: +// +// run(first) Batch-wide work, including any per-object publication. +// first is the oldest queued object. May throw. +// retire(object) Per object, after run() returned. Must be noexcept. +// unwind() Only if run() throws, while every owner is still queued. +// Runs during stack unwinding, so it must not throw. +// +// Membership is released only after every object is retired, so a throw +// leaves all owners queued for the next collection. Objects are released while +// collecting() is still true, so their destructors cannot start another +// collection. enqueue() is not allowed during a collection. +template +class PreparationQueue +{ + public: + // Returns the object's position, stable until a collection retires it. + size_t enqueue(Pointer object); + bool empty() const; + size_t size() const; + bool collecting() const; + template + void forEach(Function function); + // Returns false, doing nothing, if a collection is already running. + template + bool collect(Run run, Retire retire, Unwind unwind); + + private: + std::vector m_pending; + bool m_collecting{false}; +}; + +template +inline size_t PreparationQueue::enqueue(Pointer object) +{ + assert(!m_collecting); + m_pending.push_back(std::move(object)); + return m_pending.size() - 1; +} + +template +inline bool PreparationQueue::empty() const +{ + return m_pending.empty(); +} + +template +inline size_t PreparationQueue::size() const +{ + return m_pending.size(); +} + +template +inline bool PreparationQueue::collecting() const +{ + return m_collecting; +} + +template +template +inline void PreparationQueue::forEach(Function function) +{ + for (auto &object : m_pending) + function(object.operator->()); +} + +template +template +inline bool PreparationQueue::collect( + Run run, Retire retire, Unwind unwind) +{ + if (m_collecting) + return false; + if (m_pending.empty()) + return true; + m_collecting = true; + bool ran = false; + // unwind() runs from this guard during stack unwinding, so a throw from it + // terminates instead of replacing the original error. + auto collecting = nonstd::make_scope_exit([&] { + if (!ran) + unwind(); + m_collecting = false; + }); + run(m_pending.front().operator->()); + ran = true; + for (auto &object : m_pending) { + auto *pointer = object.operator->(); + static_assert(noexcept(retire(pointer)), + "PreparationQueue retire() must be noexcept: a throw would leave " + "some objects retired and others not"); + retire(pointer); + } + // Release owners only now, and keep the capacity for the next collection. + auto retired = std::move(m_pending); + retired.clear(); + m_pending.swap(retired); + return true; +} + +} // namespace visrtx diff --git a/devices/rtx/device/utility/PreparationStream.h b/devices/rtx/device/utility/PreparationStream.h new file mode 100644 index 000000000..4f008eaa2 --- /dev/null +++ b/devices/rtx/device/utility/PreparationStream.h @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: BSD-3-Clause + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include +// std +#include +#include + +namespace visrtx { + +/* + * The device's scene-update stream: a nonblocking CUDA stream beside the + * render stream. Geometry preparation, BVH builds and scene-table uploads + * submit to it, ordered after the work they depend on by event rather than by + * blocking the host. Calls are serialized by the device's scene-update path; + * nothing here locks. + */ +struct PreparationStream +{ + PreparationStream() = default; + ~PreparationStream(); + PreparationStream(const PreparationStream &) = delete; + PreparationStream &operator=(const PreparationStream &) = delete; + + // Device lifetime. `renderStream` is the stream frames render on. + cudaError_t initialize(cudaStream_t renderStream); + void reset(); + cudaStream_t stream() const; + cudaStream_t renderStream() const; + + // GPU-side ordering; neither blocks the host. The first asks CUDA whether + // the render stream is idle, so no submission site has to announce itself, + // and is skipped when it is: an event recorded on an idle stream is already + // complete and orders nothing. + cudaError_t orderAfterRender(); + cudaError_t orderAfter(cudaStream_t producer); + // Waits for this stream's submitted work. + cudaError_t sync(); + + // Orders after rendering, copies, waits. All sources must remain stable + // until this returns. A partial batch is drained on failure; callers + // acknowledge dirty state only after success. + template + cudaError_t upload(Arrays &...arrays); + + // Pinned host memory of at least `bytes` for a readback that completes + // before its caller returns (the BVH build's), so one block serves every + // caller. Allocated by the first call. Null with `error` set on failure. + void *readback(size_t bytes, cudaError_t &error); + + private: + cudaStream_t m_stream{nullptr}; + cudaStream_t m_renderStream{nullptr}; + struct PinnedDeleter + { + void operator()(void *memory) const + { + cudaFreeHost(memory); + } + }; + cudaEvent_t m_dependency{nullptr}; + std::unique_ptr m_readback; + size_t m_readbackBytes{0}; +}; + +// Inlined definitions //////////////////////////////////////////////////////// + +inline PreparationStream::~PreparationStream() +{ + reset(); +} + +inline cudaError_t PreparationStream::initialize(cudaStream_t renderStream) +{ + m_renderStream = renderStream; + if (m_stream) + return cudaSuccess; + auto error = cudaStreamCreateWithFlags(&m_stream, cudaStreamNonBlocking); + if (error == cudaSuccess) + error = cudaEventCreateWithFlags(&m_dependency, cudaEventDisableTiming); + if (error != cudaSuccess) + reset(); + return error; +} + +inline void PreparationStream::reset() +{ + if (m_stream) + cudaStreamSynchronize(m_stream); + if (m_dependency) + cudaEventDestroy(m_dependency); + if (m_stream) + cudaStreamDestroy(m_stream); + m_dependency = nullptr; + m_stream = nullptr; +} + +inline cudaStream_t PreparationStream::stream() const +{ + return m_stream; +} + +inline cudaStream_t PreparationStream::renderStream() const +{ + return m_renderStream; +} + +inline cudaError_t PreparationStream::orderAfterRender() +{ + return cudaStreamQuery(m_renderStream) == cudaSuccess + ? cudaSuccess + : orderAfter(m_renderStream); +} + +inline cudaError_t PreparationStream::orderAfter(cudaStream_t producer) +{ + auto error = cudaEventRecord(m_dependency, producer); + if (error == cudaSuccess) + error = cudaStreamWaitEvent(m_stream, m_dependency, 0); + return error; +} + +inline cudaError_t PreparationStream::sync() +{ + return cudaStreamSynchronize(m_stream); +} + +template +inline cudaError_t PreparationStream::upload(Arrays &...arrays) +{ + // Unlike orderAfterRender(), a registry or world-table upload records and + // waits on the event even when the render stream is idle. Kept as it was: + // dropping the wait there has not been decided. + auto error = orderAfter(m_renderStream); + auto enqueue = [&](auto &array) { + if (error == cudaSuccess) + error = array.enqueueUpload(m_stream); + }; + (enqueue(arrays), ...); + const auto completion = sync(); + if (error != cudaSuccess || completion != cudaSuccess) + cudaGetLastError(); // Keep a recoverable API error out of the next batch. + return error == cudaSuccess ? completion : error; +} + +inline void *PreparationStream::readback(size_t bytes, cudaError_t &error) +{ + error = cudaSuccess; + if (bytes > m_readbackBytes) { + m_readback.reset(); + m_readbackBytes = 0; + void *memory = nullptr; + error = cudaMallocHost(&memory, bytes); + if (error == cudaSuccess) { + m_readback.reset(memory); + m_readbackBytes = bytes; + } + } + return m_readback.get(); +} + +} // namespace visrtx diff --git a/devices/rtx/device/world/Group.cpp b/devices/rtx/device/world/Group.cpp index 0f991a0a7..b4fb8b817 100644 --- a/devices/rtx/device/world/Group.cpp +++ b/devices/rtx/device/world/Group.cpp @@ -71,8 +71,14 @@ bool Group::getProperty(const std::string_view &name, if (name == "bounds" && type == ANARI_FLOAT32_BOX3) { if (flags & ANARI_WAIT) { deviceState()->commitBuffer.flush(); - rebuildSurfaceBVHs(); - rebuildVolumeBVH(); + // Not short-circuited: a surface failure leaves the volume BVH current. + const bool surfacesBuilt = rebuildSurfaceBVHs(); + const bool volumesBuilt = rebuildVolumeBVH(); + if (!surfacesBuilt || !volumesBuilt) + return false; + } else if (preparationFailed()) { + // No step ran to report a result, so ask. + return false; } auto bounds = m_triangleBounds; bounds.extend(m_curveBounds); @@ -205,13 +211,40 @@ const std::vector &Group::surfacesUser() const return m_surfacesUser; } -void Group::rebuildSurfaceBVHs() +bool Group::preparationFailed() const { + return m_surfaceBuildFailed || m_volumeBuildFailed + || geometryPreparationFailed(); +} + +bool Group::geometryPreparationFailed() const +{ + if (!m_surfaceData) + return false; + auto surfaces = make_Span( + (Surface **)m_surfaceData->handlesBegin(), m_surfaceData->totalSize()); + for (auto *s : surfaces) { + if (s && s->isVisible() && s->geometry() + && s->geometry()->preparationFailed()) + return true; + } + return false; +} + +bool Group::rebuildSurfaceBVHs() +{ + const bool collected = deviceState()->preparation.collect(); + if (geometryPreparationFailed()) + return false; + // Nothing to rebuild, or a refused collection (reentered from one): the + // BVHs stay as the last attempt left them. const auto &state = *deviceState(); - if (state.objectUpdates.lastSurfaceBLASChange - < m_objectUpdates.lastSurfaceBVHBuilt) - return; + if (!collected + || state.objectUpdates.lastSurfaceBLASChange + < m_objectUpdates.lastSurfaceBVHBuilt) + return !m_surfaceBuildFailed; + m_surfaceBuildFailed = false; partitionValidGeometriesByType(); m_triangleBounds = box3(); @@ -221,54 +254,64 @@ void Group::rebuildSurfaceBVHs() m_traversableCurve = {}; m_traversableUser = {}; - if (!m_surfacesTriangle.empty()) { - reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building triangle BVH"); - buildOptixBVH(createOBI(m_surfacesTriangle), - m_bvhTriangle, - m_traversableTriangle, - m_triangleBounds, - this); - } else { - reportMessage( - ANARI_SEVERITY_DEBUG, "visrtx::Group skipping triangle BVH build"); - } - - if (!m_surfacesCurve.empty()) { - reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building curve BVH"); - buildOptixBVH(createOBI(m_surfacesCurve), - m_bvhCurve, - m_traversableCurve, - m_curveBounds, - this); - } else { - reportMessage( - ANARI_SEVERITY_DEBUG, "visrtx::Group skipping curve BVH build"); - } - - if (!m_surfacesUser.empty()) { - reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building user BVH"); - buildOptixBVH(createOBI(m_surfacesUser), - m_bvhUser, - m_traversableUser, - m_userBounds, - this); - } else { + // populateBuildInput can upload authored indices. The BVH builder imports + // those default-stream producers before submitting the build. Every + // partition's input is created before the first build. + struct Partition + { + const char *name; + std::vector input; + DeviceBuffer &bvh; + OptixTraversableHandle &traversable; + box3 &bounds; + }; + Partition partitions[] = { + {"triangle", + createOBI(m_surfacesTriangle), + m_bvhTriangle, + m_traversableTriangle, + m_triangleBounds}, + {"curve", + createOBI(m_surfacesCurve), + m_bvhCurve, + m_traversableCurve, + m_curveBounds}, + {"user", + createOBI(m_surfacesUser), + m_bvhUser, + m_traversableUser, + m_userBounds}, + }; + + for (auto &p : partitions) { + if (p.input.empty()) { + reportMessage( + ANARI_SEVERITY_DEBUG, "visrtx::Group skipping %s BVH build", p.name); + continue; + } reportMessage( - ANARI_SEVERITY_DEBUG, "visrtx::Group skipping user BVH build"); + ANARI_SEVERITY_DEBUG, "visrtx::Group building %s BVH", p.name); + if (!buildOptixBVH( + std::move(p.input), p.bvh, p.traversable, p.bounds, this)) { + m_surfaceBuildFailed = true; + return false; + } } buildSurfaceGPUData(); m_objectUpdates.lastSurfaceBVHBuilt = helium::newTimeStamp(); + return true; } -void Group::rebuildVolumeBVH() +bool Group::rebuildVolumeBVH() { const auto &state = *deviceState(); if (state.objectUpdates.lastVolumeBLASChange < m_objectUpdates.lastVolumeBVHBuilt) - return; + return !m_volumeBuildFailed; + m_volumeBuildFailed = false; partitionValidVolumes(); if (m_volumes.empty()) { m_volumeBounds = box3(); @@ -276,19 +319,23 @@ void Group::rebuildVolumeBVH() m_objectUpdates.lastVolumeBVHBuilt = helium::newTimeStamp(); reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::Group skipping volume BVH build"); - return; + return true; } reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::Group building volume BVH"); - buildOptixBVH(createOBI(m_volumes), - m_bvhVolume, - m_traversableVolume, - m_volumeBounds, - this); + if (!buildOptixBVH(createOBI(m_volumes), + m_bvhVolume, + m_traversableVolume, + m_volumeBounds, + this)) { + m_volumeBuildFailed = true; + return false; + } buildVolumeGPUData(); m_objectUpdates.lastVolumeBVHBuilt = helium::newTimeStamp(); + return true; } void Group::rebuildLights() diff --git a/devices/rtx/device/world/Group.h b/devices/rtx/device/world/Group.h index 3dc6073e6..9d65a4b46 100644 --- a/devices/rtx/device/world/Group.h +++ b/devices/rtx/device/world/Group.h @@ -76,15 +76,22 @@ struct Group : public Object // Triangle surfaces, the Stage 1 candidates for Geometry Light synthesis. const std::vector &surfacesTriangle() const; - // Custom-primitive surfaces (spheres, cylinders, cones, …); the area-samplable - // ones (Stage 1.5: Sphere) are also Geometry Light candidates. + // Custom-primitive surfaces (spheres, cylinders, cones, …); the + // area-samplable ones (Stage 1.5: Sphere) are also Geometry Light candidates. const std::vector &surfacesUser() const; - void rebuildSurfaceBVHs(); - void rebuildVolumeBVH(); + // For a caller with no build step's result in hand: one publishing bounds + // or a frame. It walks every surface. + bool preparationFailed() const; + // Each returns false when this group's BVHs of that kind cannot be used: a + // surface's geometry failed preparation, or a build failed now or in the + // last attempt. + bool rebuildSurfaceBVHs(); + bool rebuildVolumeBVH(); void rebuildLights(); private: + bool geometryPreparationFailed() const; void partitionValidGeometriesByType(); void partitionValidVolumes(); void partitionValidLights(); @@ -121,6 +128,9 @@ struct Group : public Object // BVH // + bool m_surfaceBuildFailed{false}; + bool m_volumeBuildFailed{false}; + struct ObjectUpdates { helium::TimeStamp lastSurfaceBVHBuilt{0}; diff --git a/devices/rtx/device/world/World.cpp b/devices/rtx/device/world/World.cpp index b89950378..753b7785e 100644 --- a/devices/rtx/device/world/World.cpp +++ b/devices/rtx/device/world/World.cpp @@ -42,9 +42,10 @@ #include "utility/AnariTypeHelpers.h" #include "world/Group.h" -#include +#include #include #include +#include #include #ifdef USE_MDL @@ -125,6 +126,8 @@ bool World::getProperty(const std::string_view &name, deviceState()->commitBuffer.flush(); rebuildWorld(); } + if (preparationFailed()) + return false; auto bounds = m_surfaceBounds; bounds.extend(m_volumeBounds); std::memcpy(ptr, &bounds, sizeof(bounds)); @@ -140,6 +143,8 @@ bool World::getProperty(const std::string_view &name, deviceState()->commitBuffer.flush(); rebuildWorld(); } + if (preparationFailed()) + return false; const auto count = uint32_t(m_instanceLightGPUData.size()); std::memcpy(ptr, &count, sizeof(count)); return true; @@ -247,8 +252,24 @@ WorldGPUData World::gpuData() const return retval; } +bool World::preparationFailed() const +{ + if (m_bvhBuildFailed) + return true; + for (auto *instance : m_instances) { + if (instance->group()->preparationFailed()) + return true; + } + return false; +} + void World::rebuildWorld() { + if (!deviceState()->preparation.collect()) + return; + if (m_bvhBuildFailed) + m_objectUpdates.lastTLASBuild = 0; + m_bvhBuildFailed = false; const auto &state = *deviceState(); const auto &updates = state.objectUpdates; @@ -257,7 +278,13 @@ void World::rebuildWorld() || updates.lastVolumeBLASChange >= lastCheck || updates.lastLightSetChange >= lastCheck) { m_objectUpdates.lastTLASBuild = 0; // BLAS changed, so need to build TLAS - rebuildBLASs(); + if (!rebuildBLASs()) + return; + } else if (preparationFailed()) { + // No step ran to report a result, so ask. A failure can outlast the BLAS + // check: area data collected for a Geometry Light fails its geometry after + // the check advanced, and a group shared with another owner can fail there. + return; } if (m_objectUpdates.lastTLASBuild <= state.objectUpdates.lastTLASChange) { @@ -271,18 +298,20 @@ void World::rebuildWorld() // populated: the proxy BLAS is instanced into that TLAS. Their Pick Power // is deliberately NOT computed here -- it is scaled by the scene radius, // which only exists once the TLAS has been built. See buildLightPickCdf(). - buildInstanceLightGPUData(); - buildLightProxies(); - - populateOptixInstances(); + if (!buildInstanceLightGPUData() || !buildLightProxies() + || !populateOptixInstances()) + return; reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World building surface BVH over %zu instances", m_optixSurfaceInstances.size()); - buildOptixBVH(createOBI(m_optixSurfaceInstances), - m_bvhSurfaces, - m_traversableSurfaces, - m_surfaceBounds, - this); + if (!buildOptixBVH(createOBI(m_optixSurfaceInstances), + m_bvhSurfaces, + m_traversableSurfaces, + m_surfaceBounds, + this)) { + m_bvhBuildFailed = true; + return; + } reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::World building surface gpu data"); buildInstanceSurfaceGPUData(); @@ -290,19 +319,33 @@ void World::rebuildWorld() reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World building volume BVH over %zu instances", m_optixVolumeInstances.size()); - buildOptixBVH(createOBI(m_optixVolumeInstances), - m_bvhVolumes, - m_traversableVolumes, - m_volumeBounds, - this); + if (!buildOptixBVH(createOBI(m_optixVolumeInstances), + m_bvhVolumes, + m_traversableVolumes, + m_volumeBounds, + this)) { + m_bvhBuildFailed = true; + return; + } reportMessage( ANARI_SEVERITY_DEBUG, "visrtx::World building volume gpu data"); buildInstanceVolumeGPUData(); // Both TLASs have reported their bounds, so the extent of the illuminated // scene can be resolved and the infinite lights weighted against it. - buildIlluminatedBounds(); + if (!buildIlluminatedBounds()) + return; buildLightPickCdf(); + // These records are consumed only by tracing, not by the intervening BVH + // builds. Upload their final values together, including proxy flag edits. + if (!uploadArrays(m_instanceSurfaceGPUData, + m_instanceVolumeGPUData, + m_instanceLightGPUData, + m_instanceHdriLightGPUData, + m_lightProxyGPUData, + m_lightPickCdf, + m_lightPickDelta)) + return; reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World finished building world over %zu instances", @@ -312,7 +355,7 @@ void World::rebuildWorld() } } -void World::populateOptixInstances() +bool World::populateOptixInstances() { m_numTriangleInstances = 0; m_numCurveInstances = 0; @@ -342,8 +385,8 @@ void World::populateOptixInstances() m_numTriangleInstances + m_numCurveInstances + m_numUserInstances; m_optixSurfaceInstances.resize( - m_numGeometrySurfaceInstances + (hasLightProxies ? 1 : 0)); - m_optixVolumeInstances.resize(m_numVolumeInstances); + m_numGeometrySurfaceInstances + (hasLightProxies ? 1 : 0), false); + m_optixVolumeInstances.resize(m_numVolumeInstances, false); auto prepInstance = [](auto &i, int instID, @@ -422,28 +465,36 @@ void World::populateOptixInstances() instID++; } - m_optixSurfaceInstances.upload(); - m_optixVolumeInstances.upload(); + return uploadArrays(m_optixSurfaceInstances, m_optixVolumeInstances); } -void World::rebuildBLASs() +bool World::rebuildBLASs() { reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World rebuilding BLASs"); + // A failure does not stop the rest: the next attempt then finds every other + // group already built. + bool rebuilt = true; std::for_each(m_instances.begin(), m_instances.end(), [&](auto *inst) { auto *group = inst->group(); - group->rebuildSurfaceBVHs(); - group->rebuildVolumeBVH(); + const bool surfacesBuilt = group->rebuildSurfaceBVHs(); + const bool volumesBuilt = group->rebuildVolumeBVH(); group->rebuildLights(); + if (!surfacesBuilt || !volumesBuilt) + rebuilt = false; }); - m_objectUpdates.lastBLASCheck = helium::newTimeStamp(); + // Only a check that found nothing failed is remembered, so the next + // rebuildWorld() comes back here until every group builds. + if (rebuilt) + m_objectUpdates.lastBLASCheck = helium::newTimeStamp(); + return rebuilt; } void World::buildInstanceSurfaceGPUData() { m_instanceSurfaceGPUData.resize( - m_numTriangleInstances + m_numCurveInstances + m_numUserInstances); + m_numTriangleInstances + m_numCurveInstances + m_numUserInstances, false); auto makeInstanceGPUData = [](const DeviceObjectIndex *s, const UniformAttributes &ua, @@ -501,8 +552,7 @@ void World::buildInstanceSurfaceGPUData() const mat4 o2wMat4 = mat4(inst->xfm(t)); const mat3x4 o2w = glm::transpose(mat4x3(o2wMat4)); - const mat3x4 w2o = - glm::transpose(mat4x3(glm::affineInverse(o2wMat4))); + const mat3x4 w2o = glm::transpose(mat4x3(glm::affineInverse(o2wMat4))); auto assignXfm = [&](InstanceSurfaceGPUData &g) { g.objectToWorld = o2w; @@ -519,32 +569,30 @@ void World::buildInstanceSurfaceGPUData() ++instID; } if (group->containsCurveGeometry()) { - sd[instID] = - makeInstanceGPUData(group->surfaceCurveGPUIndices().data(), - inst->uniformAttributes(), - id, - t); + sd[instID] = makeInstanceGPUData(group->surfaceCurveGPUIndices().data(), + inst->uniformAttributes(), + id, + t); assignXfm(sd[instID]); ++instID; } if (group->containsUserGeometry()) { - sd[instID] = - makeInstanceGPUData(group->surfaceUserGPUIndices().data(), - inst->uniformAttributes(), - id, - t); + sd[instID] = makeInstanceGPUData(group->surfaceUserGPUIndices().data(), + inst->uniformAttributes(), + id, + t); assignXfm(sd[instID]); ++instID; } } }); - m_instanceSurfaceGPUData.upload(); + // Published with the other tracing records at the end of rebuildWorld(). } void World::buildInstanceVolumeGPUData() { - m_instanceVolumeGPUData.resize(m_numVolumeInstances); + m_instanceVolumeGPUData.resize(m_numVolumeInstances, false); int instID = 0; std::for_each(m_instances.begin(), m_instances.end(), [&](auto *inst) { @@ -557,8 +605,7 @@ void World::buildInstanceVolumeGPUData() const mat4 o2wMat4 = mat4(inst->xfm(t)); const mat3x4 o2w = glm::transpose(mat4x3(o2wMat4)); - const mat3x4 w2o = - glm::transpose(mat4x3(glm::affineInverse(o2wMat4))); + const mat3x4 w2o = glm::transpose(mat4x3(glm::affineInverse(o2wMat4))); InstanceVolumeGPUData g; g.objectToWorld = o2w; @@ -569,7 +616,7 @@ void World::buildInstanceVolumeGPUData() } }); - m_instanceVolumeGPUData.upload(); + // Published with the other tracing records at the end of rebuildWorld(). } size_t World::countGeometryLights(Group *group) const @@ -584,46 +631,74 @@ size_t World::countGeometryLights(Group *group) const return n; } -void World::synthesizeGeometryLights() +bool World::synthesizeGeometryLights() { // Configure or drop each candidate surface's Geometry Light from current // material + geometry state. Runs over triangle and user (custom-primitive, - // e.g. sphere) surfaces; isSampleableEmitter gates out non-area-samplable ones. - // Object-space, so done once per group; the fill pass instances it per + // e.g. sphere) surfaces; isSampleableEmitter gates out non-area-samplable + // ones. Object-space, so done once per group; the fill pass instances it per // transform like an authored light. The light carries the material's mean // radiance (Pick Power); the sampler evaluates the material at the sampled // point when its emission is not constant. - auto configure = [](Surface *surface) { + // + // ensureAreaData() and collect() report an area that could not be computed + // on its geometry, so that is where each candidate's result is read. + auto areaFailed = [](Surface *surface) { + return surface->isSampleableEmitter() + && surface->geometry()->preparationFailed(); + }; + auto configure = [&](Surface *surface) { + if (areaFailed(surface)) + return false; if (surface->isSampleableEmitter()) { auto *geometry = surface->geometry(); - geometry->ensureAreaData(); const float area = geometry->totalArea(); if (area > 0.0f) { surface->ensureGeometryLight()->configure(geometry->index(), surface->material()->index(), surface->material()->emissionAverage(), area); - return; + return true; } } surface->clearGeometryLight(); + return true; }; std::set visited; + std::vector candidates; for (auto *inst : m_instances) { auto *group = inst->group(); if (!visited.insert(group).second) continue; for (auto *surface : group->surfacesTriangle()) - configure(surface); + candidates.push_back(surface); for (auto *surface : group->surfacesUser()) - configure(surface); + candidates.push_back(surface); } + // Submit every newly requested CDF before collecting scalar areas. Shared + // geometry's validity flag prevents duplicate submissions across surfaces. + for (auto *surface : candidates) + if (surface->isSampleableEmitter()) + surface->geometry()->ensureAreaData(); + // A refused collection (reentered from one) configures nothing: the lights + // keep their previous configuration, and the build goes on unless a request + // above already failed. + if (!deviceState()->preparation.collect()) + return std::none_of(candidates.begin(), candidates.end(), areaFailed); + // A failure does not stop the rest: the other lights are still configured. + bool synthesized = true; + for (auto *surface : candidates) { + if (!configure(surface)) + synthesized = false; + } + return synthesized; } -void World::buildInstanceLightGPUData() +bool World::buildInstanceLightGPUData() { - synthesizeGeometryLights(); + if (!synthesizeGeometryLights()) + return false; // Calculate total lights (authored + synthesized Geometry Lights) size_t totalLights = 0; @@ -657,20 +732,20 @@ void World::buildInstanceLightGPUData() totalHdriLights); // Allocate the instance-data, HDRI, and pick arrays. - m_instanceLightGPUData.resize(totalLights); - m_instanceHdriLightGPUData.resize(totalHdriLights); - m_lightPickCdf.resize(totalLights); - m_lightPickDelta.resize(totalLights); + m_instanceLightGPUData.resize(totalLights, false); + m_instanceHdriLightGPUData.resize(totalHdriLights, false); + m_lightPickCdf.resize(totalLights, false); + m_lightPickDelta.resize(totalLights, false); m_lightInstanceObjects.clear(); m_lightInstanceObjects.resize(totalLights, nullptr); size_t lightIndex = 0; size_t hdriIndex = 0; - // Mirrors buildInstanceSurfaceGPUData's instID: surface instances are laid out - // per (instance, transform) as [triangle?][curve?][user?]. Tracking the same - // cursor here recovers each Geometry Light's surface-instance index without a - // side table. + // Mirrors buildInstanceSurfaceGPUData's instID: surface instances are laid + // out per (instance, transform) as [triangle?][curve?][user?]. Tracking the + // same cursor here recovers each Geometry Light's surface-instance index + // without a side table. size_t surfaceInstanceCursor = 0; std::for_each(m_instances.begin(), m_instances.end(), [&](auto *inst) { @@ -730,11 +805,11 @@ void World::buildInstanceLightGPUData() // surface instance and emit silently wrong radiance — catch it here. assert(surfaceInstanceCursor == m_instanceSurfaceGPUData.size()); - m_instanceLightGPUData.upload(); - m_instanceHdriLightGPUData.upload(); + // Keep records host-side until proxy flags and Light Pick are finalized. + return true; } -void World::buildIlluminatedBounds() +bool World::buildIlluminatedBounds() { // What a DIRECTIONAL or HDRI light shines on. Both estimate their Pick Power // as irradiance times the cross-section of the scene, so the extent they are @@ -759,7 +834,7 @@ void World::buildIlluminatedBounds() // No proxy instance: the TLAS already covers geometry only. m_illuminatedBounds = m_surfaceBounds; m_illuminatedBounds.extend(m_volumeBounds); - return; + return true; } reportMessage(ANARI_SEVERITY_DEBUG, @@ -771,15 +846,19 @@ void World::buildIlluminatedBounds() DeviceBuffer geometryBvh; OptixTraversableHandle geometryTraversable{}; box3 geometryBounds; - buildOptixBVH( - createOBI(m_optixSurfaceInstances, m_numGeometrySurfaceInstances), - geometryBvh, - geometryTraversable, - geometryBounds, - this); + if (!buildOptixBVH( + createOBI(m_optixSurfaceInstances, m_numGeometrySurfaceInstances), + geometryBvh, + geometryTraversable, + geometryBounds, + this)) { + m_bvhBuildFailed = true; + return false; + } m_illuminatedBounds = geometryBounds; m_illuminatedBounds.extend(m_volumeBounds); + return true; } void World::buildLightPickCdf() @@ -798,9 +877,8 @@ void World::buildLightPickCdf() // // Fall back to unit radius so an empty scene still weights the infinite // lights nonzero. - m_sceneRadius = empty(m_illuminatedBounds) - ? 1.0f - : 0.5f + m_sceneRadius = empty(m_illuminatedBounds) ? 1.0f + : 0.5f * glm::length(m_illuminatedBounds.upper - m_illuminatedBounds.lower); if (!(m_sceneRadius > 0.0f) || !std::isfinite(m_sceneRadius)) m_sceneRadius = 1.0f; @@ -855,8 +933,7 @@ void World::buildLightPickCdf() } } - m_lightPickCdf.upload(); - m_lightPickDelta.upload(); + // Published with the other tracing records at the end of rebuildWorld(). } // An area light is flat, so its world AABB is degenerate along one axis @@ -867,7 +944,7 @@ void World::buildLightPickCdf() constexpr float LIGHT_PROXY_AABB_RELATIVE_PAD = 1.0e-4f; constexpr float LIGHT_PROXY_AABB_MINIMUM_PAD = 1.0e-6f; -void World::buildLightProxies() +bool World::buildLightProxies() { // Traceable stand-ins for the analytic AREA lights (ADR 0009), so a camera or // BSDF-continuation ray can hit them. Deliberately derived from the ALREADY @@ -967,23 +1044,21 @@ void World::buildLightProxies() "instances) -- area lights will not be directly visible", lightInstanceCursor, m_instanceLightGPUData.size()); - return; + return true; } if (proxies.empty()) - return; - - // Re-upload: the hasAreaProxy flags were written after - // buildInstanceLightGPUData's own upload. - m_instanceLightGPUData.upload(); + return true; - m_lightProxyGPUData.resize(proxies.size()); + // Tracing records (including hasAreaProxy) are uploaded once after the TLAS + // build; only the proxy AABBs are needed by the BLAS below. + m_lightProxyGPUData.resize(proxies.size(), false); std::copy(proxies.begin(), proxies.end(), m_lightProxyGPUData.dataHost()); - m_lightProxyGPUData.upload(); - m_lightProxyAabbs.resize(aabbs.size()); + m_lightProxyAabbs.resize(aabbs.size(), false); std::copy(aabbs.begin(), aabbs.end(), m_lightProxyAabbs.dataHost()); - m_lightProxyAabbs.upload(); + if (!uploadArrays(m_lightProxyAabbs)) + return false; reportMessage(ANARI_SEVERITY_DEBUG, "visrtx::World building light-proxy BLAS over %zu proxies", @@ -999,11 +1074,15 @@ void World::buildLightProxies() buildInput.customPrimitiveArray.numSbtRecords = 1; box3 proxyBounds; - buildOptixBVH({buildInput}, - m_bvhLightProxies, - m_traversableLightProxies, - proxyBounds, - this); + if (!buildOptixBVH({buildInput}, + m_bvhLightProxies, + m_traversableLightProxies, + proxyBounds, + this)) { + m_bvhBuildFailed = true; + return false; + } + return true; } } // namespace visrtx diff --git a/devices/rtx/device/world/World.h b/devices/rtx/device/world/World.h index 4f96cc9d7..d456dde6f 100644 --- a/devices/rtx/device/world/World.h +++ b/devices/rtx/device/world/World.h @@ -57,14 +57,22 @@ struct World : public Object WorldGPUData gpuData() const; + // For a caller with no build step's result in hand: one publishing a frame + // or a property. It walks every surface of every instance. + bool preparationFailed() const; void rebuildWorld(); private: - void populateOptixInstances(); - void rebuildBLASs(); + // The build steps that can fail return false when they did; rebuildWorld() + // stops at the first. A failed BVH build or upload also sets + // m_bvhBuildFailed, which is what preparationFailed() reports afterwards. + template + bool uploadArrays(Arrays &...arrays); + bool populateOptixInstances(); + bool rebuildBLASs(); void buildInstanceSurfaceGPUData(); void buildInstanceVolumeGPUData(); - void buildInstanceLightGPUData(); + bool buildInstanceLightGPUData(); // Power-proportional Light Pick over the light instances buildInstanceLight- // GPUData laid out. Split from it because the Pick Power of an infinite light // is scaled by the scene radius, which is an OUTPUT of the TLAS build, while @@ -74,12 +82,13 @@ struct World : public Object // World bounds of the ILLUMINATED scene: geometry and volumes, with the // light-proxy instance excluded. See the definition for why this is a second // acceleration-structure build rather than a subtraction. - void buildIlluminatedBounds(); + bool buildIlluminatedBounds(); // Builds the analytic area-light proxy records, their AABBs and their BLAS // (ADR 0009). Must run after buildInstanceLightGPUData: proxies reference // light-instance slots by index. - void buildLightProxies(); - void synthesizeGeometryLights(); + bool buildLightProxies(); + // False when a geometry whose emitting area it asked for failed. + bool synthesizeGeometryLights(); size_t countGeometryLights(Group *group) const; void cleanup(); @@ -98,6 +107,7 @@ struct World : public Object size_t m_numUserInstances{0}; size_t m_numVolumeInstances{0}; + bool m_bvhBuildFailed{false}; box3 m_surfaceBounds; box3 m_volumeBounds; // m_surfaceBounds minus the light-proxy instance, unioned with the volumes. @@ -153,13 +163,30 @@ struct World : public Object // Power-proportional Light Pick, rebuilt with the light instances. HostDeviceArray m_lightPickCdf; - // Per-slot discrete pick probability (power_i/total), parallel to m_lightPickCdf. + // Per-slot discrete pick probability (power_i/total), parallel to + // m_lightPickCdf. HostDeviceArray m_lightPickDelta; float m_totalLightPower{0.f}; float m_hdriPower{0.f}; float m_sceneRadius{0.f}; }; +template +inline bool World::uploadArrays(Arrays &...arrays) +{ + if ((arrays.empty() && ...)) + return true; + auto &state = *deviceState(); + const auto error = state.preparationStream.upload(arrays...); + if (error == cudaSuccess) + return true; + m_bvhBuildFailed = true; + reportMessage(ANARI_SEVERITY_ERROR, + "world upload failed: %s", + cudaGetErrorString(error)); + return false; +} + } // namespace visrtx VISRTX_ANARI_TYPEFOR_SPECIALIZATION(visrtx::World *, ANARI_WORLD); diff --git a/devices/rtx/docs/geometry-preparation-reuse.md b/devices/rtx/docs/geometry-preparation-reuse.md new file mode 100644 index 000000000..ab14fb0c1 --- /dev/null +++ b/devices/rtx/docs/geometry-preparation-reuse.md @@ -0,0 +1,369 @@ +# Preparation-preserving geometry updates + +## Terminology + +A **geometry-wide attribute** supplies one value for the entire geometry: +`attribute0`–`attribute3` or `color`, rather than a per-vertex or per-primitive +attribute array. The storage/shading representation may still call these values +*uniform attributes*; that term describes their scope, not an update strategy. + +A **preparation-preserving update** reuses successfully prepared geometry because +its preparation inputs are unchanged. Geometry-wide attribute edits can take +this path, but not if coalesced with an input change or applied to a failed +preparation. A scalar parameter such as `radius` is still a preparation input. + +## Scope + +Triangle, quad, sphere, curve, cone, cylinder, and SDF geometries opt into a +preparation-preserving finalization path. Changing only geometry-wide attributes +republishes the geometry registry slot without regenerating tangents, indices, +radii, bounds, or area CDFs, and without invalidating the surface BLAS timestamp. +Normal object-finalization timestamps still advance, so automatic accumulation +reset remains intact. Before replacing parameter references, the input-retirement +check compares the declared committed preparation inputs and referenced-object +versions with the last successful preparation. Unchanged inputs skip retirement; +first preparation, changed inputs, failed preparation, and non-opt-in types request +retirement. Retirement waits only when `cudaStreamQuery` reports outstanding +render-stream work. This check performs no GPU uploads. Parameter lookup names are +cached once per geometry rather than rebuilt on every finalization. Finalization +still revalidates values, object versions, and backing pointers before reusing +derived data: dependencies can be updated between commit and finalization, so the +earlier retirement verdict is not a reusable preparation verdict. + +This is deliberately not general fine-grained invalidation. Any changed +preparation input takes the existing full preparation path, including shading +arrays and scalar/string parameters that could be narrowed further later. +Isosurfaces, optional neural geometry, and unknown geometries retain their +existing full-preparation behavior; they do not opt in. + +## Reuse contract + +`Geometry::declarePreparationParameters(parameters)` is the opt-in seam, called +once in the subtype constructor before its first commit. A subtype must list +**every consumed parameter except geometry-wide attributes**, including inputs +read lazily by tangent generation or `gpuData()`. These are the subtype's +preparation inputs. The base adds primitive and vertex +attribute arrays and primitive IDs. When adding a subtype parameter, update its +list or keep that subtype on the default conservative path. The declaration is +fixed per subtype; do not conditionally add/remove names based on current values. + +The helper compares committed parameter values, not live staging iterators. +For referenced arrays it also records object update/finalization timestamps, +data modification timestamp, and device backing pointer. Consequently: + +- Changed handles, values, logical ranges, or backing pointers invalidate reuse. +- A geometry-wide attribute commit coalesced with an array unmap or + privatization cannot hide it. +- Observer-only finalization always follows the full preparation path. +- Missing/invalid initial data and previously failed preparation cannot reuse + uninitialized or failed derived state. +- Reuse becomes eligible only after a valid, successful geometry upload. + +Only present parameters occupy snapshot storage. The cached `AnariAny` values +retain internal references to the current input objects until replacement or +geometry destruction; they do not copy authored data. This also prevents cached +parameter identity from becoming a dangling object pointer. The extra reference +lifetime is intentional. For a multi-geometry input batch, obsolete snapshot +references are dropped after commit-time retirement checks and parameter reads, +before replacement input uploads are allocated. This avoids retaining a whole +cohort of obsolete device copies through the replacement batch. Single-geometry +and observer-only updates retain the existing snapshot replacement order during +full preparation. + +Geometry-wide attribute values are excluded because they do not change geometric +area or bounds. +Geometry Light synthesis uses the material's emission estimate, while sampled +attribute-driven radiance reads the updated geometry registry data at rendering +time. Material changes continue to use their existing light-set invalidation. + +## Correctness checks + +`TestGeometryPreparationReuse` exercises seven types with host and shared-device +inputs. It verifies all five geometry-wide attributes and their removal against +the initial full-preparation rendering, stable bounds, and no preparation/BVH-build +diagnostic messages. Debug rendering modulates attributes by geometric facing, so the initial +full-preparation image is the exact per-shape reference, with a separate nonzero +control. Scalar/string edits, array ranges, in-place host unmaps, and device-array +privatization act as positive controls requiring preparation and BVH rebuilding. + +The test also stages an input removal **after** a geometry-wide attribute commit: +that uncommitted edit must not leak into the committed update. Emissive materials +request area data where supported. Existing numeric-failure tests additionally verify that a +geometry-wide attribute commit cannot rehabilitate a failed generation. + +## Local performance checks + +Use the [benchmark skill](../../../.agents/skills/benchmark-geometry-preprocessing/SKILL.md) +to compare against a revision before the optimization with matched builds. +Measure `small-recommit` for bounds/BVH readiness and add +`--extra-case reuse-render:32:64:recommit:1` for registry publication and a +completed render. Keep replacement and unchanged-frame cases as guards. +The [benchmark guide](geometry-preprocessing-performance.md) defines the timed +boundaries and local result interpretation; no historical baseline is required. + +## Preparation stream and retirement + +Checked geometry preprocessing (bounds, area CDFs, generated quad/curve indices +and radii, and SDF alignment) and OptiX BVH build/compaction use one device-owned +nonblocking preparation stream. `PreparationStream` +(`utility/PreparationStream.h`, the member +`DeviceGlobalState::preparationStream`) owns its lifetime, the event used to +import producer dependencies and the pinned BVH readback. BVH builds, registry +uploads and world-table uploads use it directly: `stream()`, +`orderAfterRender()`, `orderAfter()`, `sync()`, `upload()` and `readback()`. +`orderAfterRender()` is the one render-ordering call; it skips the event wait +when `cudaStreamQuery` reports the render stream idle. `upload()` orders its +copies after rendering itself and takes that wait even on an idle render +stream. Scene-update submission is serialized; each event wait captures the corresponding record before the +event is reused. + +`GeometryPreparation` (`geometry/GeometryPreparation.h`, the member +`DeviceGlobalState::preparation`) holds a reference to that stream and owns the +two collection queues, the small-geometry batch, the scalar results and the +input allocation cache. Its header describes one scene update as one +transaction (commit, upload, submit, collect) and is the place to read the +lifecycle. Other code sees a small surface: `collect()` and `busy()`; +`waitForHostReaders()` and `waitForDeviceReaders()` for array privatization; +`fail()`, `check()`, `reject()` and `finish()` for geometry code; `defer()`, +`deferSmall()`, `deviceResults()` and `hostResults()` for `Preprocessing`. The +steps that `Geometry` and the owner call on each other are private on both +sides. Nothing in it locks: calls are serialized by the scene-update path. + +- Full preparation imports prior render work before overwriting derived buffers. +- For the seven opt-in geometry types, parameter commits capture references to + dirty declared host arrays. The first geometry finalizer submits the captured + inputs across geometries on the preparation stream and waits once before any + finalizer consumes them. Shared arrays are deduplicated by handle and data + version. Sources remain retained through completion; only successful geometry + submissions mark their still-current array versions uploaded. A failed + geometry remains unprepared even if another geometry successfully shares one + of its arrays. Legacy consumers can safely use completed copies afterward. +- Observer-only updates, and arrays modified after submission, have no commit + to capture them. The geometry's finalizer captures its still-dirty declared + host arrays and collects them through the same batch, as a batch of that + geometry alone: there is one upload implementation with two triggers. A + failure there fails that finalization, so the next one retries. A later + geometry commit or observer update may retry a failed input generation; + unchanged failed inputs cannot silently become prepared. Preparation reuse + does not capture or submit an upload batch. +- These checked geometry kernels no longer import the default stream: authored + inputs are ready before they run. Other array consumers retain their existing + upload path. +- The BVH builder imports both render-stream producers (including legacy field + and isosurface work) and default-stream input uploads. Its build, readbacks, + and compaction execute on the preparation stream. +- OptiX instance arrays and proxy AABBs are uploaded on the preparation stream + before their builds. World tracing tables (surface/volume/light records, proxy + records, and Light Pick arrays) are batched after their final CPU edits; proxy + flags no longer require a separate re-upload. +- All dirty object registries are uploaded in one preparation-stream batch before + tracing. Registry pointer access no longer performs implicit uploads. Stable + host snapshots survive object creation or edits during the batch; only dirty + slots are staged unless registry growth requires a full copy. Edits made after + a snapshot remain dirty for the next batch. No registry lock is held during + CUDA waits, so completion callbacks cannot be blocked by that lock. +- Host bounds/area summaries are collected after batched submission (see below). + BVH publication still requires preparation-stream completion. BVH scratch + survives through that completion; handles/bounds are + published only on success. Group/World failure state prevents failed builds + from being treated as ready and permits a later retry. +- Parameter-reference replacement and last-public-release privatization require + completed old render consumers. `GeometryPreparation::retireRender()` + asks `cudaStreamQuery` whether the render stream is idle and synchronizes it + only when it is not, so frame submission, denoising, channel resolution, + transfer-function opacity bounds and isosurface brick preparation need no + bookkeeping of their own. A failed query never counts as idle: it takes the + synchronize and reports that result. Scene submission remains serialized. + Handling a CUDA error uses unconditional drains, not the query, before + storage can be retired or retried. Rejected input (`reject()`) is not a CUDA + error and does no stream work. + +The existing shared-array, privatization, frame, denoiser and isosurface tests +exercise the producer paths. + +This is not concurrent in-place scene replacement. Legacy default-stream events +can include preceding work on blocking streams; tangent generation and field-grid +preparation retain their legacy synchronization, and `cudaMalloc`/`cudaFree` can +still serialize work. Frame/renderer payloads and group index tables still use +legacy uploads. Removing those dependencies requires further producer migration +and allocation ownership changes. Overlapping replacement with active rendering also +requires separate storage generations and last-use tracking for all consumers, +including shared geometry and registries. + +`TestPreparationStream` checks explicit producer ordering and independence from +an unrelated nonblocking stream. The shared-cudart failure tests additionally +cover preparation dependency/completion failures and BLAS/TLAS readback/completion +failures, publication suppression, and retry. Host-upload cases also check copy +stream selection, allocation/copy/completion failures, partial-batch retry, and +an in-place unmap coalesced with a geometry-wide attribute commit. Scene-upload cases cover +instance allocation, instance/world copy and completion errors, registry copy +and completion errors, partial registry batches, and retry without recommitting +already-finalized objects. `TestRegistrySnapshot` verifies stable copy sources +across host-vector growth and preservation of newer dirty edits. + +## Geometry submission and collection + +Checked bounds and area-CDF preparation queue kernels that write their scalar +results into the device's `PreparationResults`, at the geometry's position in the +preparation queue. A successful submission is not publication: +scalar outputs, numeric validation, and geometry registry updates happen only +after collection. The device queue retains each submitted geometry, and thereby +its arrays and derived buffers, until those operations finish. Ownership stays +in the queue through descriptor allocation and registry publication; queued flags +are cleared only after every publication completes. A host exception leaves the +owners and queued flags available for retry, including already-drained results +whose publication must be retried. Collection reentry remains refused. +Committed input uploads are queued and collected by the same `PreparationQueue` +transaction; their unwind step fails and drains the batch before the owners +become collectable again. + +`TestPreparationQueue` tests this ownership transaction directly with throwing +completion/publication callbacks, orphaned owners, retry and teardown. It does +not route exceptions through ANARI's fatal C API handler or change that public +exception policy. + +Group/World rebuilds collect queued finalizations before constructing BVHs. Lazy +Geometry Light area requests are submitted for all candidate surfaces first, +then collected together before configuring lights. Shared geometry is queued +once. A numeric failure invalidates its geometry only; a stream-completion error +invalidates every pending generation, including errors observed by an intervening +upload or legacy completion wait. Failed generations cannot take preparation reuse. + +A recommit or observer-only re-finalization drains the geometry's previous queued +work before reusing its storage. Last-public-release privatization of shared CUDA +arrays also drains pending preparation readers, not just rendering. Device +teardown collects the queue before releasing objects or CUDA/OptiX resources. +Status callbacks cannot reenter device property queries or rendering while +collection is resolving results; those calls are refused instead of publishing +a partially collected scene. + +### Backend input allocation cache + +Only backend-owned device copies created by `Array::enqueueUpload()` participate +in `DeviceAllocationCache`. Imported CUDA pointers, captured-device deleters, +privatization copies, generic device buffers and legacy uploads retain their +existing allocation behavior. Reuse is exact-size, so logical array capacity +never grows to match an oversized cached block. + +Returned blocks enter a pending cohort, not the reusable list. After retiring +obsolete snapshots, committed input collection freezes that cohort, flushes +pending geometry preparation, then performs one checked `cudaDeviceSynchronize` +before promoting the blocks. This deliberately preserves the conservative +coverage of legacy consumers that ordinary `cudaFree` provided per allocation; +it is not a claim of stream-isolated replacement. Returns during the boundary +belong to the next cohort. Failure or a host exception keeps the cohort pending, +and affected input generations cannot publish until a later successful retry. +No cache mutex is held during CUDA operations or callbacks. + +The device-local cache retains at most 64 MiB and 256 returned blocks, counting +pending, reusable and frozen cohorts together. Overflow uses ordinary freeing. +On allocation OOM, certified reusable blocks of other sizes are released and +the allocation is retried once if any were freed. Pending blocks are not reused +as an OOM shortcut. Teardown closes and drains the cache before destroying its +streams; outstanding owned allocations retain the closed cache and late returns +use ordinary freeing rather than resurrecting it. + +`TestDeviceAllocationCache` checks exact-size reuse, deferred submission, +completion failure, cohort freezing, byte/entry bounds, concurrent returns, +host exceptions, OOM trimming/retry, move ownership, captured deleters and late +returns after close. `TestGeometryInputBatch` checks actual replacement reuse +without a second allocation cohort and rejects/retries a failed shared completion +boundary. + +### Small-geometry computation batches + +For 1–256 primitives, bounds and area requests are held as device-owned batches +of descriptors. One CUDA block handles each geometry in a single batch launch: +block-local reductions produce its bounds summary, and a double-precision +block scan produces its area CDF. Bounds and area requests for the same geometry +share a descriptor when both arrive before the completion boundary. Requests +above 256 primitives retain the general multi-block/CUB path. Zero-count +handling is unchanged. SDF bounds retain their zero epsilon-scale convention. + +Every `GeometryPreparation::flush()` flushes these descriptors before waiting, +including intervening upload waits and shared-array privatization. This is +necessary because a queued descriptor still references its original inputs even +before GPU work has been launched. Collection retains owners through descriptor +upload, dispatch and readback completion. Descriptors remain stable through +fallback drains; dispatch or transfer failure invalidates the pending batch, +while numeric failures remain local to their geometry. + +Small jobs and the general path write the same results storage, so a geometry's +bounds and area results sit at its queue position whichever path produced them. +Small jobs write only the results they request: a bounds-only flush followed by a +later area request preserves the earlier bounds result. + +`TestSmallGeometryBatch` exercises mixed sphere/cone/cylinder/triangle batches +at 1, 31, 32, 33, 255, 256 and 257 primitives with host and device-backed logical +array slices. It checks independent bounds, zero-area light removal, recovery, +and transitions between small and general paths. Failure injection covers the +descriptor upload, dispatch-status check, readback and batch device/pinned +allocation, including batch-wide invalidation and retry. With shared CUDA runtime +interposition, the mixed-size test also checks one summary copy per collection +(two initial collections for bounds and lazy areas, then one for combined jobs). + +`TestGeometryAreaCDF` checks the actual published GPU records after completed +frames, using the device's build definitions and matching runtime library. An +independent double-precision analytic oracle checks every prefix and total area +for triangles, spheres, cones and cylinders. Counts straddle warp boundaries +(31/32/33) and the small/general cutoff (255/256/257 at the current cutoff), with +indexed/unindexed geometry and host/device-backed logical slices. Unequal weights, +sharp weight changes, zero-area bins, varying segment caps, an all-zero generation +and restoration with new weights discriminate weighting, order, normalization +and stale sampling data rather than just bounds or light counts. No public debug +property or shared production area helper is used by the oracle. + +`PreparationResults` holds two results per queued geometry: bounds (epsilon +scale and validity) and total area. Kernels write its device storage; every +`GeometryPreparation::flush()` that follows a write copies the queued range to +pinned host storage in one transfer, then synchronizes. `complete()` reads the +host copy at the geometry's queue position. There is no per-geometry pinned +storage and no host-side copy between pinned buffers. Device and pinned storage +grow together, starting at 256 geometries (4 KiB each with the current result +layout), doubling when the queue outgrows them, and staying at their high-water +size until device teardown. The general path reserves at submission, so an +allocation failure fails only the submitting geometry; the small batch reserves +when it launches, so a failure there fails the whole batch. Device growth +synchronizes the preparation stream and copies the earlier results into the new +storage; the old pinned storage holds nothing still needed, because each +readback completes in its own finish and the next one transfers the whole +queued range. A failed allocation keeps existing storage and clears CUDA +last-error state, so a retry can succeed. `TestPreparationResults` covers first +and growth allocation failure and retry on either side, preservation across +growth, rewrites between readbacks and the readback range. + +BVH builds read back their bounds and compacted size through one pinned +block owned by `PreparationStream`. The first build allocates it; builds are +serialized and complete before returning, so no transfer outlives a build. + +Committed host inputs now complete in a cross-geometry batch before finalizers +run. Observer-only input updates take the same path one geometry at a time. +Last-public-release of +shared host arrays during an active upload joins the preparation stream before +the application may free its source memory. Quad/curve generated-data completion, +tangent generation, and field/isosurface +preparation retain their current synchronous paths. This does not introduce +independent scene generations or concurrent in-place replacement during tracing. + +`TestDeferredGeometryPreparation` covers recommitting a queued geometry, retained +captured-device inputs, last-reference queue ownership through teardown, unrelated +numeric failures, and collection-time callback reentry. Injection cases also +cover results allocation failure, completion failure across multiple +queued geometries, an intervening upload completion failure, and shared CUDA +array retirement while preparation remains pending. `TestGeometryInputBatch` +checks submission-before-wait across multiple geometries, shared-array dedup, +preparation-preserving and observer-only controls, coalesced unmaps/commits, and host-source +retirement during an active copy. Input failure cases cover batch-wide completion +failure and recovery through an array unmap without a geometry recommit. + +## Remaining work + +Broader array/shading invalidation precision, reducing the extra CPU snapshot +comparison cost, batched readback/dispatch, and fine-grained area-vs-bounds +invalidation are separate improvements. Registry, bounds, and area-result +collection and committed input uploads now span geometries. Observer-only input +batching, legacy finalizers, and allocation-related synchronization require +further producer migration while preserving source lifetimes and failure +propagation. This change does not repack or download +inputs, introduce CPU preprocessing, or weaken the guarantee that changed inputs +are prepared on the GPU before their derived data is published. diff --git a/devices/rtx/docs/geometry-preprocessing-performance.md b/devices/rtx/docs/geometry-preprocessing-performance.md new file mode 100644 index 000000000..1625adcfb --- /dev/null +++ b/devices/rtx/docs/geometry-preprocessing-performance.md @@ -0,0 +1,114 @@ +# Local geometry-preprocessing benchmarks + +Use this tool to assess whether a development change improves end-to-end latency +on your machine. It is a manual before/after helper, not a performance regression +CTest or a historical baseline. Performance evolution tracking belongs in a +separate controlled CI job; this tool does not establish that infrastructure. + +## Quick comparison + +Build `BenchmarkGeometryPreprocessing` in the candidate and `anari_library_visrtx` +in a separate control workspace, with matching compiler, CUDA, OptiX, architecture, +optional-component settings and library suffix. The same benchmark executable +loads either ABI-compatible device library. The control needs no benchmark code. +Use the project [benchmark skill](../../../.agents/skills/benchmark-geometry-preprocessing/SKILL.md) +for workspace/build preparation and interpretation. + +```bash +python3 devices/rtx/apps/tests/api/benchmark_preprocessing.py \ + CANDIDATE_BUILD/BenchmarkGeometryPreprocessing \ + CONTROL_LIBRARY_DIR CANDIDATE_LIBRARY_DIR +``` + +Pass the directories **containing the shared libraries**, not an install prefix. +For a multi-configuration build these may be `BUILD/RelWithDebInfo`. Verify with +`LD_LIBRARY_PATH=LIBRARY_DIR ldd BENCHMARK` that each side loads the intended +library and a real CUDA driver, rather than a toolkit link-time driver stub. + +The runner prints before/after warm medians, trial-median ranges, and ratios. +Defaults cover small recommits, small/large input replacement, unchanged rendering, +and two completed frames after replacement. It alternates order across fresh +process trials. Run `--help` for controls. Examples: + +```bash +# Focus on a preparation-reuse change. +python3 devices/rtx/apps/tests/api/benchmark_preprocessing.py \ + BENCHMARK BEFORE_LIB AFTER_LIB --case small-recommit + +# Include a completed frame and use another geometry family. +python3 devices/rtx/apps/tests/api/benchmark_preprocessing.py \ + BENCHMARK BEFORE_LIB AFTER_LIB --case unchanged-frame \ + --extra-case reuse-render:32:64:recommit:1 --geometry triangle + +# Longer comparison with optional local raw output. +python3 devices/rtx/apps/tests/api/benchmark_preprocessing.py \ + BENCHMARK BEFORE_LIB AFTER_LIB /tmp/preprocessing-comparison.json \ + --trials 6 --repeats 101 +``` + +The optional JSON contains commands, library paths, stdout/stderr and trial +medians. It is written incrementally: a failed command leaves partial results, +not a successful comparison. Keep results and profiler captures in local scratch. +Record revision IDs and environment alongside local results when needed to +interpret them; do not add one-off evidence files or result tables to the repo. + +## Workload and timing contract + +The executable can also run one workload directly: + +```text +BenchmarkGeometryPreprocessing TYPE COUNT DEVICE REPEATS \ + [SHARED_SURFACES] [DISTINCT_GEOMETRIES] \ + [recommit|replace|unchanged|overlap|update] [FRAMES:0=bounds] [EMISSIVE:0|1] +``` + +- COUNT is primitives **per geometry**. The paired runner uses emissive geometry, + one surface per geometry and host inputs by default. `--device` requires device + input support on both revisions; unsupported input paths are not comparisons. +- `recommit` changes a geometry-wide attribute; `replace` replaces inputs, including + allocation, host staging, application H2D copy and parameter installation in + the measured interval; `unchanged` retains the initial inputs. +- `update` maps and changes existing host position arrays in place, unmaps them, + and commits a geometry-wide attribute on each geometry. It measures coalesced array + updates plus geometry commits without replacing the input allocations; it is + not an observer-only workload. Supported for host inputs of non-SDF types. + For example, add `--extra-case in-place-ready:32:64:update:0` and + `--extra-case in-place-frame:32:64:update:1` to the paired runner. +- FRAMES=0 ends at completed bounds/BVH readiness. FRAMES>0 includes submission + and completion of all frames, registry publication and tracing, then bounds. + Multiple frames share one device/world; this is not a concurrency benchmark. +- `overlap` requires FRAMES=1 and uses a 1024x1024 frame with 32 pixel samples. + It submits rendering, commits geometry-wide attribute updates, then queries bounds before + waiting for the frame. `overlap ... query_ms` measures the bounds query alone; + `sample ... ms` still includes completed rendering. This isolates CPU blocking + on an outstanding frame, not a rendering-throughput improvement. Run it + directly (the paired runner does not summarize query latency): + `BENCHMARK cylinder 32 0 11 1 64 overlap 1 1`. +- Initial setup is outside each iteration's timer. `setup_to_ready_ms` also + includes fixture generation and initial input setup, but not device creation. + Iteration zero is reported separately and excluded from warm statistics. +- The runner reports the median of per-process warm medians and their range. + Ranges are not confidence intervals. Thermal state, clocks and system load + affect results; rerun suspicious cases before attributing a delta to code. +- DEVICE=1 stages host fixtures to the GPU. It does not model an upstream GPU + producer or prove that real GPU-produced input needs an H2D copy. +- The harness checks finite bounds/images, sample counts and frame completion + outside the timed interval. These guard against skipped work, not radiometric + equivalence. Run the affected correctness tests separately. + +## Optional investigation + +Profile only when timing leaves an explanatory question: + +```bash +nsys profile --trace=cuda --sample=none -o /tmp/preprocessing-trace \ + env LD_LIBRARY_PATH=LIBRARY_DIR \ + BENCHMARK cylinder 32 0 6 1 64 recommit 1 1 +nsys stats --report cuda_api_sum,cuda_gpu_mem_size_sum /tmp/preprocessing-trace.nsys-rep +``` + +Compare work counts when claiming work elimination. Profiled whole-process totals +include initialization and teardown and are not comparable to unprofiled warm +latencies. `BenchmarkCudaOrdering` is an optional stream-ordering probe, not an +end-to-end timing or correctness test. Synchronization changes must still protect +input retirement, host readbacks and publication; timing cannot establish safety.