diff --git a/devices/rtx/README.md b/devices/rtx/README.md index b60959a26..e0fa1a0af 100644 --- a/devices/rtx/README.md +++ b/devices/rtx/README.md @@ -263,6 +263,46 @@ they are not enumerated as literal parameter names by the query API. Binding and argument edits retain the material and compiled code; changing the source builds a table for that source's string IDs. +#### VISRTX_GEOMETRY_MDL_SCENE_DATA + +With native MDL enabled, triangle, quad, sphere, cylinder, cone, curve, SDF and +isosurface geometries accept `sceneData.` (`ANARI_STRING`) aliases to +`attribute0` through `attribute3` or `color`. One material can therefore read the +same name from different slots on different geometries: + +```cpp +anariSetParameter(device, geometryA, "sceneData.temperature", + ANARI_STRING, "attribute0"); +anariSetParameter(device, geometryB, "sceneData.temperature", + ANARI_STRING, "attribute2"); +anariCommitParameters(device, geometryA); +anariCommitParameters(device, geometryB); +// Supply the corresponding attribute arrays or constants normally, then share +// an mdl material that calls scene::data_lookup_float("temperature", fallback). +``` + +A geometry alias overrides a material binding for that exact, case-sensitive +name. Multiple names may select the same slot. If the selected slot has no +effective data, MDL returns its default; it does not retry the material slot. +Unsetting an alias restores material fallback. Empty names, non-string values +and targets other than the five supported slots produce a warning and are +omitted from the committed snapshot, allowing material fallback. + +Aliases reuse the existing interpolation and attribute-source precedence, +including instance fallback; they do not turn varying data into uniform data. +Float/color lookups and `data_isvalid` use the same name resolution, including +emission evaluated at geometry-light samples. These aliases add no data slots +and do not affect built-in materials or `state::texture_coordinate` numbering. +They are dynamic metadata and are not enumerated as literal query parameters. +Alias edits keep the compiled material and renderer pipeline; the current +geometry finalization path still invalidates the surface BLAS on any edit. + +Names are interned exactly in a synchronized, device-local table. Its strings +and tokens remain allocated until device destruction, so memory use grows with +the number of distinct names seen. Each material string ID carries a token; +each lookup searches the geometry's compact alias list before using material +fallback. Geometries without aliases require no alias-list search. + #### VISRTX_MDL_ANIMATION_TIME With native MDL enabled, frame `mdl.animationTime` (`ANARI_FLOAT32`, default @@ -363,6 +403,7 @@ The following extensions are either partially or fully implemented by VisRTX: - `VISRTX_MATERIAL_MATERIALX` (requires `VISRTX_ENABLE_MATERIALX_SUPPORT`) - `VISRTX_MATERIAL_MDL` (requires `VISRTX_ENABLE_MDL_SUPPORT`) - `VISRTX_MDL_SCENE_DATA` (requires `VISRTX_ENABLE_MDL_SUPPORT`) +- `VISRTX_GEOMETRY_MDL_SCENE_DATA` (requires `VISRTX_ENABLE_MDL_SUPPORT`) - `VISRTX_MDL_ANIMATION_TIME` (requires `VISRTX_ENABLE_MDL_SUPPORT`) - `VISRTX_RENDERER_DEBUG` - `VISRTX_RENDERER_DEFAULT` diff --git a/devices/rtx/apps/tests/api/TestMdlSceneData.cpp b/devices/rtx/apps/tests/api/TestMdlSceneData.cpp index 3d3bfcc65..7e71ec306 100644 --- a/devices/rtx/apps/tests/api/TestMdlSceneData.cpp +++ b/devices/rtx/apps/tests/api/TestMdlSceneData.cpp @@ -35,6 +35,7 @@ #include #include +#include #include #include #include @@ -42,6 +43,7 @@ #include #include #include +#include using vec2 = std::array; using vec3 = std::array; @@ -50,6 +52,7 @@ using uvec2 = std::array; static int errors = 0; static int timeWarnings = 0; static int metadataWarnings = 0; +static int geometryAliasWarnings = 0; static void statusFunc(const void *, ANARIDevice, @@ -66,6 +69,9 @@ static void statusFunc(const void *, if (severity == ANARI_SEVERITY_WARNING && std::strstr(message, "mdl.animationTime must be finite")) ++timeWarnings; + if (severity == ANARI_SEVERITY_WARNING + && std::strstr(message, "requires a nonempty scene-data name")) + ++geometryAliasWarnings; if (severity == ANARI_SEVERITY_WARNING && std::strstr(message, "sceneData.") && std::strstr(message, "is not a valid parameter for an MDL material")) { ++metadataWarnings; @@ -143,8 +149,9 @@ struct Scene ANARI_WAIT) != 0, "device extension query failed"); - for (const char *name : - {"ANARI_VISRTX_MDL_SCENE_DATA", "ANARI_VISRTX_MDL_ANIMATION_TIME"}) { + for (const char *name : {"ANARI_VISRTX_MDL_SCENE_DATA", + "ANARI_VISRTX_GEOMETRY_MDL_SCENE_DATA", + "ANARI_VISRTX_MDL_ANIMATION_TIME"}) { bool found = false; for (auto p = extensions; p && *p; ++p) found |= std::strcmp(*p, name) == 0; @@ -222,11 +229,8 @@ struct Scene anari::commitParameters(device, material); } - void check(const char *label, - vec3 expected, - anari::Frame f = nullptr, - unsigned xBegin = 16, - unsigned xEnd = 48) + vec3 renderMean( + anari::Frame f = nullptr, unsigned xBegin = 16, unsigned xEnd = 48) { f = f ? f : frame; anari::render(device, f); @@ -241,6 +245,17 @@ struct Scene for (int c = 0; c < 3; ++c) mean[c] += fb.data[y * 64 + x][c] / area; anari::unmap(device, f, "channel.color"); + require(errors == 0, "renderer reported an error"); + return mean; + } + + void check(const char *label, + vec3 expected, + anari::Frame f = nullptr, + unsigned xBegin = 16, + unsigned xEnd = 48) + { + const auto mean = renderMean(f, xBegin, xEnd); printf("%s: %.4f %.4f %.4f\n", label, mean[0], mean[1], mean[2]); for (int c = 0; c < 3; ++c) require( @@ -266,6 +281,105 @@ struct Scene } }; +static void testNamedLightEmission() +{ + Scene s; + const auto d = s.device; + // Keep emission provably nonnegative so the existing registration policy + // admits it as a Geometry Light even though scene data is host-unknown. + anari::setParameter(d, s.material, "source", R"mdl(mdl 1.7; +import ::df::*; import ::scene::*; import ::math::*; +export material main() = material(surface: material_surface( + emission: material_emission(emission: df::diffuse_edf(), intensity: + color(math::saturate(scene::data_lookup_float("scalar", 0.25))) * math::PI))); +)mdl"); + anari::commitParameters(d, s.material); + auto floor = anari::newObject(d, "triangle"); + auto matte = anari::newObject(d, "matte"); + auto floorSurface = anari::newObject(d); + const std::array floorVertices = {vec3{-1, -1, 0}, + vec3{1, -1, 0}, + vec3{1, 1, 0}, + vec3{-1, -1, 0}, + vec3{1, 1, 0}, + vec3{-1, 1, 0}}; + const std::array lightVertices = { + vec3{1.2f, -1, 1}, vec3{2.2f, -1, 1}, vec3{2.2f, 1, 1}, vec3{1.2f, 1, 1}}; + anari::setParameterArray1D( + d, floor, "vertex.position", floorVertices.data(), 6); + anari::commitParameters(d, floor); + anari::setParameter(d, matte, "color", vec3{1, 1, 1}); + anari::commitParameters(d, matte); + anari::setParameter(d, floorSurface, "geometry", floor); + anari::setParameter(d, floorSurface, "material", matte); + anari::commitParameters(d, floorSurface); + anari::setParameterArray1D( + d, s.geometry, "vertex.position", lightVertices.data(), 4); + anari::setParameter(d, s.geometry, "attribute2", vec4{0.4f, 0, 0, 1}); + anari::commitParameters(d, s.geometry); + const std::array surfaces = {s.surface, floorSurface}; + anari::setParameterArray1D( + d, s.group, "surface", surfaces.data(), surfaces.size()); + anari::commitParameters(d, s.group); + // With one bounce, the camera only sees the diffuse receiver. All its light + // comes from synthetic next-event hits on the off-camera MDL emitter. + anari::setParameter(d, s.renderer, "maxRayDepth", 1); + anari::setParameter(d, s.renderer, "pixelSamples", 128); + anari::commitParameters(d, s.renderer); + const auto baseline = s.renderMean(); + require(baseline[0] > 0.005f, + "material-only geometry light did not light receiver"); + anari::setParameter(d, s.geometry, "sceneData.scalar", "attribute2"); + anari::commitParameters(d, s.geometry); + const auto aliased = s.renderMean(); + printf("named light emission: reference %.6f, alias %.6f\n", + baseline[0], + aliased[0]); + for (int c = 0; c < 3; ++c) + require(std::isfinite(aliased[c]) + && std::abs(aliased[c] / baseline[c] - 0.5f) < 0.04f, + "synthetic geometry-light hit ignored alias override"); + // Release application refs while the scene still retains the receiver. + anari::release(d, floorSurface); + anari::release(d, matte); + anari::release(d, floor); +} + +static void benchmarkGeometryAliases() +{ + Scene s; + const auto d = s.device; + anari::setParameter(d, s.frame, "size", uvec2{256, 256}); + anari::commitParameters(d, s.frame); + anari::setParameter(d, s.renderer, "pixelSamples", 64); + anari::setParameter(d, s.renderer, "maxRayDepth", 1); + anari::commitParameters(d, s.renderer); + for (unsigned count : {0u, 8u, 32u}) { + for (unsigned i = 0; i + 1 < count; ++i) { + const auto name = "sceneData.benchmark." + std::to_string(i); + anari::setParameter(d, s.geometry, name.c_str(), "attribute0"); + } + if (count) + anari::setParameter(d, s.geometry, "sceneData.scalar", "attribute0"); + anari::commitParameters(d, s.geometry); + std::vector durations; + for (unsigned i = 0; i < 20; ++i) { + anari::render(d, s.frame); + anari::wait(d, s.frame); + float duration = 0.f; + require(anari::getProperty(d, s.frame, "duration", duration, ANARI_WAIT), + "frame duration query failed"); + if (i >= 4) + durations.push_back(duration); + } + std::sort(durations.begin(), durations.end()); + printf("geometry aliases=%u, median GPU frame=%.3f ms (256x256, 64 spp)\n", + count, + 1000.f * durations[durations.size() / 2]); + } + require(errors == 0, "benchmark reported an ANARI error"); +} + static void testSharedSource(Scene &s) { auto d = s.device; @@ -308,6 +422,196 @@ static void testSharedSource(Scene &s) anari::commitParameters(d, s.geometry); } +static void testGeometryAliases(Scene &s) +{ + const auto d = s.device; + s.check("material-only baseline", {0.8f, 0.8f, 0.8f}); + uint64_t fingerprint = 0; + require( + anari::getProperty(d, d, "mdlPtxFingerprint", fingerprint, ANARI_WAIT), + "PTX fingerprint query failed"); + anari::setParameter(d, s.geometry, "attribute2", vec4{0.3f, 0, 0, 1}); + anari::setParameter(d, s.geometry, "sceneData.scalar", "attribute2"); + anari::commitParameters(d, s.geometry); + s.check("geometry overrides material binding", {0.3f, 0.3f, 0.3f}); + const auto initialSamples = s.samples(); + s.check("unchanged alias accumulates", {0.3f, 0.3f, 0.3f}); + require(s.samples() > initialSamples, "unchanged alias reset accumulation"); + anari::setParameter(d, s.geometry, "sceneData.scalar", "attribute0"); + anari::commitParameters(d, s.geometry); + s.check("alias-only edit resets accumulation", {0.8f, 0.8f, 0.8f}); + require( + s.samples() == initialSamples, "alias edit did not reset accumulation"); + anari::setParameter(d, s.geometry, "sceneData.scalar", "attribute2"); + anari::setParameter(d, s.geometry, "sceneData.missing", "attribute2"); + anari::commitParameters(d, s.geometry); + s.mode(8); + s.check("geometry-only name shares a slot", {0.3f, 0, 0}); + anari::setParameter(d, s.geometry, "color", vec4{0.1f, 0.2f, 0.3f, 0.4f}); + anari::setParameter(d, s.geometry, "sceneData.missing", "color"); + anari::commitParameters(d, s.geometry); + s.check("geometry-only name selects color", {0.1f, 0.2f, 0.3f}); + anari::unsetParameter(d, s.geometry, "color"); + anari::commitParameters(d, s.geometry); + s.mode(5); + s.check("geometry alias preserves uniform constant", {0.3f, 0.3f, 0.3f}); + const std::array vertex = {0.2f, 0.8f, 0.8f, 0.2f}; + anari::setParameterArray1D( + d, s.geometry, "vertex.attribute2", vertex.data(), vertex.size()); + anari::commitParameters(d, s.geometry); + s.check( + "geometry alias preserves uniform rejection", {0.125f, 0.125f, 0.125f}); + s.mode(0); + s.check( + "geometry alias uses indexed vertex interpolation", {0.5f, 0.5f, 0.5f}); + const std::array face = {0.4f, 0.4f, 0.4f, 0.4f, 0.4f, 0.4f}; + anari::setParameterArray1D( + d, s.geometry, "faceVarying.attribute2", face.data(), face.size()); + anari::commitParameters(d, s.geometry); + s.check("geometry alias selects face-varying data", {0.4f, 0.4f, 0.4f}); + anari::unsetParameter(d, s.geometry, "faceVarying.attribute2"); + anari::unsetParameter(d, s.geometry, "vertex.attribute2"); + const std::array primitive = {0.6f, 0.6f}; + anari::setParameterArray1D(d, + s.geometry, + "primitive.attribute2", + primitive.data(), + primitive.size()); + anari::commitParameters(d, s.geometry); + s.check("geometry alias selects primitive data", {0.6f, 0.6f, 0.6f}); + anari::unsetParameter(d, s.geometry, "primitive.attribute2"); + anari::setParameter(d, + s.geometry, + "attribute2", + vec4{std::numeric_limits::quiet_NaN(), 0, 0, 1}); + anari::commitParameters(d, s.geometry); + s.check("nonfinite geometry alias returns default", {0.25f, 0.25f, 0.25f}); + s.mode(6); + s.check("nonfinite geometry alias remains present", {1, 1, 1}); + s.mode(0); + anari::unsetParameter(d, s.geometry, "attribute2"); + anari::commitParameters(d, s.geometry); + s.check("absent aliased data does not retry material slot", + {0.25f, 0.25f, 0.25f}); + s.mode(6); + s.check("geometry alias isvalid checks selected slot", {0, 0, 0}); + const vec4 instanceValue{0.55f, 0, 0, 1}; + anari::setParameterArray1D(d, s.instance, "attribute2", &instanceValue, 1); + anari::commitParameters(d, s.instance); + s.mode(5); + s.check("geometry alias preserves uniform instance fallback", + {0.55f, 0.55f, 0.55f}); + anari::unsetParameter(d, s.instance, "attribute2"); + anari::commitParameters(d, s.instance); + s.mode(0); + const auto warnings = geometryAliasWarnings; + for (const char *target : {"attribute4", "objectPosition", ""}) { + anari::setParameter(d, s.geometry, "sceneData.scalar", target); + anari::commitParameters(d, s.geometry); + s.check( + "invalid geometry slot restores material fallback", {0.8f, 0.8f, 0.8f}); + } + anari::setParameter(d, s.geometry, "sceneData.scalar", 42); + anari::setParameter(d, s.geometry, "sceneData.", "attribute0"); + anari::commitParameters(d, s.geometry); + s.check("invalid geometry name and type", {0.8f, 0.8f, 0.8f}); + require( + geometryAliasWarnings == warnings + 5, "missing geometry alias warnings"); + for (const char *name : + {"sceneData.scalar", "sceneData.missing", "sceneData."}) + anari::unsetParameter(d, s.geometry, name); + anari::commitParameters(d, s.geometry); + s.check("unsetting geometry aliases restores fallback", {0.8f, 0.8f, 0.8f}); + uint64_t after = 0; + require(anari::getProperty(d, d, "mdlPtxFingerprint", after, ANARI_WAIT) + && after == fingerprint, + "geometry aliases changed compiled material PTX"); +} + +static void testSharedMaterialAliases(Scene &s) +{ + const auto d = s.device; + auto right = anari::newObject(d, "triangle"); + auto rightSurface = anari::newObject(d); + const std::array leftVertices = { + vec3{-1, -1, 0}, vec3{0, -1, 0}, vec3{0, 1, 0}, vec3{-1, 1, 0}}; + const std::array rightVertices = {vec3{0, -1, 0}, + vec3{1, -1, 0}, + vec3{1, 1, 0}, + vec3{0, -1, 0}, + vec3{1, 1, 0}, + vec3{0, 1, 0}}; + anari::setParameterArray1D( + d, s.geometry, "vertex.position", leftVertices.data(), 4); + anari::setParameter(d, s.geometry, "attribute2", vec4{0.3f, 0, 0, 1}); + anari::setParameter(d, s.geometry, "sceneData.scalar", "attribute2"); + anari::commitParameters(d, s.geometry); + anari::setParameterArray1D( + d, right, "vertex.position", rightVertices.data(), 6); + anari::setParameter(d, right, "attribute1", vec4{0.65f, 0, 0, 1}); + anari::setParameter(d, right, "sceneData.scalar", "attribute1"); + anari::commitParameters(d, right); + anari::setParameter(d, rightSurface, "geometry", right); + anari::setParameter(d, rightSurface, "material", s.material); + anari::commitParameters(d, rightSurface); + const std::array surfaces = {s.surface, rightSurface}; + anari::setParameterArray1D( + d, s.group, "surface", surfaces.data(), surfaces.size()); + anari::commitParameters(d, s.group); + s.check("shared material left geometry alias", + {0.3f, 0.3f, 0.3f}, + nullptr, + 16, + 28); + s.check("shared material right geometry alias", + {0.65f, 0.65f, 0.65f}, + nullptr, + 36, + 48); + + // A different target-code descriptor consumes the same geometry name. + auto other = anari::newObject(d, "mdl"); + anari::setParameter(d, other, "sourceType", "code"); + anari::setParameter(d, other, "materialName", "main"); + anari::setParameter(d, other, "source", R"mdl(mdl 1.7; +import ::df::*; import ::scene::*; +export material main() = material(surface: material_surface( + emission: material_emission(emission: df::diffuse_edf(), intensity: + (scene::data_lookup_color("another", color(0)) + + color(scene::data_lookup_float("scalar", 0.1))) * 3.14159265))); +)mdl"); + anari::commitParameters(d, other); + anari::setParameter(d, rightSurface, "material", other); + anari::commitParameters(d, rightSurface); + s.check("shared geometry with different material string table", + {0.65f, 0.65f, 0.65f}, + nullptr, + 36, + 48); + anari::setParameter(d, rightSurface, "material", s.material); + anari::commitParameters(d, rightSurface); + s.check("material replacement retains geometry alias", + {0.65f, 0.65f, 0.65f}, + nullptr, + 36, + 48); + anari::release(d, other); + + const std::array original = { + vec3{-1, -1, 0}, vec3{1, -1, 0}, vec3{1, 1, 0}, vec3{-1, 1, 0}}; + anari::setParameterArray1D( + d, s.geometry, "vertex.position", original.data(), 4); + anari::unsetParameter(d, s.geometry, "sceneData.scalar"); + anari::unsetParameter(d, s.geometry, "attribute2"); + anari::commitParameters(d, s.geometry); + anari::setParameterArray1D(d, s.group, "surface", &s.surface, 1); + anari::commitParameters(d, s.group); + anari::release(d, rightSurface); + anari::release(d, right); + s.check("geometry destruction leaves material fallback intact", + {0.8f, 0.8f, 0.8f}); +} + static void testSharedAttributeCache(Scene &s) { auto d = s.device; @@ -444,10 +748,10 @@ static void testSceneData(Scene &s) s.mode(0); s.check("instance array", {0.6f, 0.6f, 0.6f}); const std::array, 2> transforms = { - std::array{0.5f, 0, 0, 0, 0, 1, 0, 0, - 0, 0, 1, 0, -0.5f, 0, 0, 1}, - std::array{0.5f, 0, 0, 0, 0, 1, 0, 0, - 0, 0, 1, 0, 0.5f, 0, 0, 1}}; + std::array{ + 0.5f, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -0.5f, 0, 0, 1}, + std::array{ + 0.5f, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0.5f, 0, 0, 1}}; const std::array instanceValues = { vec4{0.2f, 0, 0, 1}, vec4{0.8f, 0, 0, 1}}; anari::setParameterArray1D(d, @@ -474,8 +778,10 @@ static void testSceneData(Scene &s) anari::commitParameters(d, s.geometry); s.check("isvalid authored zero", {1, 1, 1}); const std::array partlyNonfinite = { - std::numeric_limits::quiet_NaN(), 0.8f, - 0.8f, std::numeric_limits::quiet_NaN()}; + std::numeric_limits::quiet_NaN(), + 0.8f, + 0.8f, + std::numeric_limits::quiet_NaN()}; anari::setParameterArray1D( d, s.geometry, "vertex.attribute0", partlyNonfinite.data(), 4); anari::commitParameters(d, s.geometry); @@ -568,7 +874,8 @@ static void testCurve(Scene &s) anari::setParameterArray1D( d, s.geometry, "vertex.position", positions.data(), 2); anari::setParameterArray1D( - d, s.geometry, "vertex.attribute0", values.data(), 2); + d, s.geometry, "vertex.attribute2", values.data(), 2); + anari::setParameter(d, s.geometry, "sceneData.scalar", "attribute2"); anari::setParameterArray1D(d, s.geometry, "primitive.index", &index, 1); anari::setParameter(d, s.geometry, "radius", 0.8f); anari::commitParameters(d, s.geometry); @@ -580,8 +887,8 @@ static void testCurve(Scene &s) s.check("curve vertex interpolation", {0.5f, 0.5f, 0.5f}); s.mode(5); s.check("uniform rejects curve interpolation", {0.125f, 0.125f, 0.125f}); - anari::unsetParameter(d, s.geometry, "vertex.attribute0"); - anari::setParameter(d, s.geometry, "attribute0", vec4{0.45f, 0, 0, 1}); + anari::unsetParameter(d, s.geometry, "vertex.attribute2"); + anari::setParameter(d, s.geometry, "attribute2", vec4{0.45f, 0, 0, 1}); anari::commitParameters(d, s.geometry); s.check("curve uniform constant", {0.45f, 0.45f, 0.45f}); } @@ -635,15 +942,23 @@ static void testAnimation(Scene &s) require(timeWarnings == 2, "missing invalid-time warnings"); } -int main() +int main(int argc, char **argv) { + std::setvbuf(stdout, nullptr, _IONBF, 0); try { + if (argc > 1 && std::strcmp(argv[1], "--benchmark") == 0) { + benchmarkGeometryAliases(); + return 0; + } Scene scene; + testGeometryAliases(scene); + testSharedMaterialAliases(scene); testSharedSource(scene); testSharedAttributeCache(scene); testSceneData(scene); testCurve(scene); testAnimation(scene); + testNamedLightEmission(); require( metadataWarnings == 0, "valid scene-data metadata reported invalid"); puts("MDL scene data and animation time passed"); diff --git a/devices/rtx/apps/tests/unit/CMakeLists.txt b/devices/rtx/apps/tests/unit/CMakeLists.txt index 405713910..3522659cd 100644 --- a/devices/rtx/apps/tests/unit/CMakeLists.txt +++ b/devices/rtx/apps/tests/unit/CMakeLists.txt @@ -263,7 +263,7 @@ if (VISRTX_ENABLE_MDL_SUPPORT) ${CMAKE_CURRENT_LIST_DIR}/../../../device/mdl/SceneDataInstance.cpp) target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_LIST_DIR}/../../../device) - target_link_libraries(${PROJECT_NAME} PRIVATE libmdl) + target_link_libraries(${PROJECT_NAME} PRIVATE libmdl Threads::Threads) target_compile_features(${PROJECT_NAME} PRIVATE cxx_std_17) add_test(NAME rtx::MdlSceneDataInstance COMMAND ${PROJECT_NAME}) endif() diff --git a/devices/rtx/apps/tests/unit/test_MdlSceneDataInstance.cpp b/devices/rtx/apps/tests/unit/test_MdlSceneDataInstance.cpp index bff868df3..444cfc7ab 100644 --- a/devices/rtx/apps/tests/unit/test_MdlSceneDataInstance.cpp +++ b/devices/rtx/apps/tests/unit/test_MdlSceneDataInstance.cpp @@ -4,6 +4,7 @@ #include "mdl/SceneDataInstance.h" #include +#include #include #include #include @@ -37,7 +38,8 @@ SceneDataDescriptor descriptor() void testSnapshots() { - SceneDataInstance instance(descriptor()); + visrtx::SceneDataNames names; + SceneDataInstance instance(descriptor(), names); require(instance.data().size() == 6, "string IDs were compacted"); for (const auto &binding : instance.data()) require(binding.attribute == MaterialAttribute::UNKNOWN, @@ -84,7 +86,8 @@ void testSnapshots() void testAttributeWhitelist() { - SceneDataInstance instance(descriptor()); + visrtx::SceneDataNames names; + SceneDataInstance instance(descriptor(), names); for (auto attribute : {MaterialAttribute::ATTRIB_0, MaterialAttribute::ATTRIB_1, MaterialAttribute::ATTRIB_2, @@ -121,8 +124,9 @@ void testAttributeWhitelist() void testOwnershipAndSourceChanges() { + visrtx::SceneDataNames names; auto source = descriptor(); - SceneDataInstance first(source); + SceneDataInstance first(source, names); source.m_namesById[1] = "replacement"; require(update(first, {{"temperature", MaterialAttribute::ATTRIB_0}}), "instance borrowed the source descriptor"); @@ -134,7 +138,7 @@ void testOwnershipAndSourceChanges() // Equal table sizes do not imply equal names or IDs. std::swap(source.m_namesById[1], source.m_namesById[3]); - SceneDataInstance second(source); + SceneDataInstance second(source, names); update(second, {{"temperature", MaterialAttribute::ATTRIB_0}, {"tint", MaterialAttribute::COLOR}}); @@ -146,17 +150,68 @@ void testOwnershipAndSourceChanges() SceneDataDescriptor large; large.m_namesById.resize(65); large.m_namesById[64] = "last"; - SceneDataInstance highIds(large); + SceneDataInstance highIds(large, names); require(update(highIds, {{"last", MaterialAttribute::COLOR}}) && highIds.data()[64].attribute == MaterialAttribute::COLOR, "high string ID was truncated"); - SceneDataInstance empty(SceneDataDescriptor{}); + SceneDataInstance empty(SceneDataDescriptor{}, names); require(empty.data().empty(), "empty descriptor produced binding entries"); require(!update(empty, {{"unused", MaterialAttribute::COLOR}}), "unknown name changed an empty table"); } +void testGeometryTokens() +{ + visrtx::SceneDataNames names; + SceneDataInstance first(descriptor(), names); + auto other = descriptor(); + std::swap(other.m_namesById[1], other.m_namesById[3]); + SceneDataInstance second(other, names); + require(first.data()[1].nameToken != 0 + && first.data()[1].nameToken == second.data()[3].nameToken, + "the same name acquired different tokens across target codes"); + require(first.data()[0].nameToken == 0 && first.data()[2].nameToken == 0, + "empty string acquired a valid token"); + require(first.data()[1].nameToken != first.data()[5].nameToken, + "case-sensitive names acquired the same token"); + const auto token = first.data()[1].nameToken; + const visrtx::MDLSceneDataBinding aliases[] = { + {MaterialAttribute::COLOR, names.intern("unrelated")}, + {MaterialAttribute::ATTRIB_2, token}}; + update(first, {{"temperature", MaterialAttribute::ATTRIB_0}}); + require(visrtx::resolveSceneDataAttribute(first.data()[1], aliases, 2) + == MaterialAttribute::ATTRIB_2, + "geometry alias did not override the material binding"); + require(visrtx::resolveSceneDataAttribute(second.data()[3], aliases, 2) + == MaterialAttribute::ATTRIB_2, + "geometry alias required an explicit material binding"); + require(visrtx::resolveSceneDataAttribute(first.data()[1], nullptr, 0) + == MaterialAttribute::ATTRIB_0, + "empty geometry aliases lost material fallback"); + update(first, {}); + require(first.data()[1].nameToken == token + && visrtx::resolveSceneDataAttribute(first.data()[1], aliases, 2) + == MaterialAttribute::ATTRIB_2, + "unsetting material bindings lost geometry name identity"); + visrtx::SceneDataNames independent; + independent.intern("extra"); + require(independent.intern("temperature") != token + && names.intern("temperature") == token, + "different devices share name-token state"); + + std::vector> jobs; + for (int worker = 0; worker < 8; ++worker) { + jobs.push_back(std::async(std::launch::async, [&names, worker] { + for (int i = 0; i < 1000; ++i) + names.intern(std::to_string(worker) + "." + std::to_string(i)); + return names.intern("temperature"); + })); + } + for (auto &job : jobs) + require(job.get() == token, "concurrent interning changed string identity"); +} + } // namespace int main() @@ -165,6 +220,7 @@ int main() testSnapshots(); testAttributeWhitelist(); testOwnershipAndSourceChanges(); + testGeometryTokens(); } catch (const std::exception &e) { std::fprintf(stderr, "FAIL: %s\n", e.what()); return 1; diff --git a/devices/rtx/device/CMakeLists.txt b/devices/rtx/device/CMakeLists.txt index 6a490ddb8..64118fd03 100644 --- a/devices/rtx/device/CMakeLists.txt +++ b/devices/rtx/device/CMakeLists.txt @@ -418,7 +418,7 @@ endif() set(VISRTX_OPTIONAL_DEVICE_DEPENDENCIES_LIST "") if(VISRTX_ENABLE_MDL_SUPPORT) list(APPEND VISRTX_OPTIONAL_DEVICE_DEPENDENCIES_LIST visrtx_material_mdl - visrtx_mdl_scene_data visrtx_mdl_animation_time) + visrtx_mdl_scene_data visrtx_geometry_mdl_scene_data visrtx_mdl_animation_time) endif() if(VISRTX_ENABLE_MATERIALX_SUPPORT) list(APPEND VISRTX_OPTIONAL_DEVICE_DEPENDENCIES_LIST visrtx_material_materialx) diff --git a/devices/rtx/device/geometry/Geometry.cpp b/devices/rtx/device/geometry/Geometry.cpp index a00502c1f..d51f8e8f8 100644 --- a/devices/rtx/device/geometry/Geometry.cpp +++ b/devices/rtx/device/geometry/Geometry.cpp @@ -30,6 +30,7 @@ */ #include "Geometry.h" +#include "sampler/Sampler.h" // specific types #include "Cone.h" #include "Curve.h" @@ -130,6 +131,33 @@ void Geometry::commitParameters() m_uniformAttributes.attribute3 = getUniformAttribute("attribute3"); m_uniformAttributes.color = getUniformAttribute("color"); m_primitiveId = getParamObject("primitive.id"); + +#ifdef USE_MDL + std::vector aliases; + constexpr std::string_view prefix = "sceneData."; + for (auto param = params_begin(); param != params_end(); ++param) { + const auto &[name, value] = *param; + if (name.rfind(prefix, 0) != 0) + continue; + const auto alias = std::string_view(name).substr(prefix.size()); + const auto attribute = value.type() == ANARI_STRING + ? attributeFromString(value.getString()) + : MaterialAttribute::UNKNOWN; + if (alias.empty() || static_cast(attribute) >= 5) { + reportMessage(ANARI_SEVERITY_WARNING, + "geometry parameter '%s' requires a nonempty scene-data name and " + "a string selecting attribute0..3 or color; binding ignored", + name.c_str()); + continue; + } + aliases.push_back({attribute, deviceState()->sceneDataNames.intern(alias)}); + } + m_numSceneData = static_cast(aliases.size()); + if (aliases.empty()) + m_sceneDataBuffer.reset(); + else + m_sceneDataBuffer.upload(aliases); +#endif } void Geometry::markFinalized() @@ -169,6 +197,10 @@ GeometryGPUData Geometry::gpuData() const retval.primitiveId = (const uint32_t *)(m_primitiveId ? m_primitiveId->dataGPU() : nullptr); retval.epsilonScale = m_epsilonScale; +#ifdef USE_MDL + retval.sceneData = m_sceneDataBuffer.ptrAs(); + retval.numSceneData = m_numSceneData; +#endif return retval; } diff --git a/devices/rtx/device/geometry/Geometry.h b/devices/rtx/device/geometry/Geometry.h index c0a0f7a47..fe576da61 100644 --- a/devices/rtx/device/geometry/Geometry.h +++ b/devices/rtx/device/geometry/Geometry.h @@ -96,6 +96,12 @@ struct Geometry : public RegisteredObject // Set by analytic-primitive subtypes in finalize(); see // GeometryGPUData::epsilonScale. float m_epsilonScale{0.f}; + + private: +#ifdef USE_MDL + DeviceBuffer m_sceneDataBuffer; + uint32_t m_numSceneData{0}; +#endif }; } // namespace visrtx diff --git a/devices/rtx/device/gpu/gpu_objects.h b/devices/rtx/device/gpu/gpu_objects.h index bd4493e8b..fa6d6226b 100644 --- a/devices/rtx/device/gpu/gpu_objects.h +++ b/devices/rtx/device/gpu/gpu_objects.h @@ -320,6 +320,8 @@ struct NeuralGeometryData struct GeometryGPUData { GeometryType type{GeometryType::UNKNOWN}; + const MDLSceneDataBinding *sceneData{nullptr}; + uint32_t numSceneData{0}; AttributeDataSet attr; AttributeDataSetUniform attrUniform; bool attrUniformPresent[5]; diff --git a/devices/rtx/device/gpu/materialAttributes.h b/devices/rtx/device/gpu/materialAttributes.h index 47763f67d..dc2c21862 100644 --- a/devices/rtx/device/gpu/materialAttributes.h +++ b/devices/rtx/device/gpu/materialAttributes.h @@ -3,6 +3,8 @@ #pragma once +#include "gpu_decl.h" + #include namespace visrtx { @@ -25,6 +27,23 @@ enum class MaterialAttribute : uint8_t struct MDLSceneDataBinding { MaterialAttribute attribute{MaterialAttribute::UNKNOWN}; + uint32_t nameToken{0}; }; +// The material table is indexed by target-code-local string ID. Only the +// interned token can be compared with geometry aliases from another material. +VISRTX_HOST_DEVICE MaterialAttribute resolveSceneDataAttribute( + const MDLSceneDataBinding &binding, + const MDLSceneDataBinding *aliases, + uint32_t numAliases) +{ + if (binding.nameToken != 0) { + for (uint32_t i = 0; i < numAliases; ++i) { + if (aliases[i].nameToken == binding.nameToken) + return aliases[i].attribute; + } + } + return binding.attribute; +} + } // namespace visrtx diff --git a/devices/rtx/device/gpu/shadingState.h b/devices/rtx/device/gpu/shadingState.h index a192c577d..958c8a045 100644 --- a/devices/rtx/device/gpu/shadingState.h +++ b/devices/rtx/device/gpu/shadingState.h @@ -178,6 +178,8 @@ struct TextureHandler : mi::neuraylib::Texture_handler_base unsigned int attributeUniformMask; const visrtx::MDLSceneDataBinding *sceneData; unsigned int numSceneData; + const visrtx::MDLSceneDataBinding *geometrySceneData; + unsigned int numGeometrySceneData; }; using ShadingStateMaterial = mi::neuraylib::Shading_state_material; diff --git a/devices/rtx/device/include/anari/ext/visrtx/visrtx_extensions.h b/devices/rtx/device/include/anari/ext/visrtx/visrtx_extensions.h index 6cd387f16..dc073e016 100644 --- a/devices/rtx/device/include/anari/ext/visrtx/visrtx_extensions.h +++ b/devices/rtx/device/include/anari/ext/visrtx/visrtx_extensions.h @@ -55,6 +55,7 @@ struct VisRTXExtensions int VISRTX_TRIANGLE_FACE_VARYING_ATTRIBUTES; int VISRTX_RENDERER_FOG; int VISRTX_MDL_SCENE_DATA; + int VISRTX_GEOMETRY_MDL_SCENE_DATA; int VISRTX_MDL_ANIMATION_TIME; int VISRTX_LIGHT_QUAD_SHAPING; int VISRTX_LIGHT_QUAD_FOCUS; @@ -167,6 +168,8 @@ inline void fillExtensionStruct( extensions->VISRTX_RENDERER_FOG = 1; else if (feature == "ANARI_VISRTX_MDL_SCENE_DATA") extensions->VISRTX_MDL_SCENE_DATA = 1; + else if (feature == "ANARI_VISRTX_GEOMETRY_MDL_SCENE_DATA") + extensions->VISRTX_GEOMETRY_MDL_SCENE_DATA = 1; else if (feature == "ANARI_VISRTX_MDL_ANIMATION_TIME") extensions->VISRTX_MDL_ANIMATION_TIME = 1; else if (feature == "ANARI_VISRTX_LIGHT_QUAD_SHAPING") diff --git a/devices/rtx/device/material/MDL.cpp b/devices/rtx/device/material/MDL.cpp index 270fdeef0..334386058 100644 --- a/devices/rtx/device/material/MDL.cpp +++ b/devices/rtx/device/material/MDL.cpp @@ -464,7 +464,8 @@ void MDL::syncSource() m_uuid = acquired.uuid; m_argumentBlockInstance = coordinator.invokeSerial( [&] { return materialRegistry.createArgumentBlock(acquired.arguments); }); - m_sceneDataInstance.emplace(acquired.sceneData); + m_sceneDataInstance.emplace( + acquired.sceneData, deviceState()->sceneDataNames); // A fresh instance may be entirely unbound and report no CPU-table change. // Discard the previous source's GPU table so the initial upload still runs. m_sceneDataBuffer.reset(); @@ -734,7 +735,7 @@ void MDL::syncSceneData() if (data.empty()) m_sceneDataBuffer.reset(); else if (changed || m_sceneDataBuffer.bytes() == 0) - m_sceneDataBuffer.upload(data.data(), data.size_bytes()); + m_sceneDataBuffer.upload(data.data(), data.size()); } MaterialGPUData MDL::gpuData() const diff --git a/devices/rtx/device/material/shaders/MDLShader_ptx.cu b/devices/rtx/device/material/shaders/MDLShader_ptx.cu index ccf3c1f4b..ebdf08276 100644 --- a/devices/rtx/device/material/shaders/MDLShader_ptx.cu +++ b/devices/rtx/device/material/shaders/MDLShader_ptx.cu @@ -167,6 +167,9 @@ VISRTX_CALLABLE void __direct_callable__init(MDLShadingState *shadingState, shadingState->textureHandler.normalAdapted = false; shadingState->textureHandler.sceneData = md->sceneData; shadingState->textureHandler.numSceneData = md->numSceneData; + shadingState->textureHandler.geometrySceneData = hit->geometry->sceneData; + shadingState->textureHandler.numGeometrySceneData = + hit->geometry->numSceneData; shadingState->resData = {nullptr, &shadingState->textureHandler}; // Front facing for transmission diff --git a/devices/rtx/device/material/shaders/MDLTexture_ptx.cu b/devices/rtx/device/material/shaders/MDLTexture_ptx.cu index b1ff5e7d4..1fb5b71af 100644 --- a/devices/rtx/device/material/shaders/MDLTexture_ptx.cu +++ b/devices/rtx/device/material/shaders/MDLTexture_ptx.cu @@ -414,7 +414,10 @@ VISRTX_DEVICE unsigned int sceneDataSlot( { if (!self->sceneData || id >= self->numSceneData) return ~0u; - const auto slot = static_cast(self->sceneData[id].attribute); + const auto slot = + static_cast(resolveSceneDataAttribute(self->sceneData[id], + self->geometrySceneData, + self->numGeometrySceneData)); return slot < 5 ? slot : ~0u; } diff --git a/devices/rtx/device/mdl/SceneDataInstance.cpp b/devices/rtx/device/mdl/SceneDataInstance.cpp index 0381a3bb0..513fb872d 100644 --- a/devices/rtx/device/mdl/SceneDataInstance.cpp +++ b/devices/rtx/device/mdl/SceneDataInstance.cpp @@ -9,9 +9,12 @@ namespace visrtx::mdl { SceneDataInstance::SceneDataInstance( - const libmdl::SceneDataDescriptor &descriptor) + const libmdl::SceneDataDescriptor &descriptor, SceneDataNames &names) : m_descriptor(descriptor), m_bindings(descriptor.m_namesById.size()) -{} +{ + for (size_t id = 0; id < m_bindings.size(); ++id) + m_bindings[id].nameToken = names.intern(descriptor.m_namesById[id]); +} nonstd::span SceneDataInstance::data() const { @@ -20,7 +23,9 @@ nonstd::span SceneDataInstance::data() const bool SceneDataInstance::update(nonstd::span bindings) { - std::vector next(m_descriptor.m_namesById.size()); + auto next = m_bindings; + for (auto &binding : next) + binding.attribute = MaterialAttribute::UNKNOWN; for (const auto &binding : bindings) { const auto id = m_descriptor.find(binding.name); if (!id) diff --git a/devices/rtx/device/mdl/SceneDataInstance.h b/devices/rtx/device/mdl/SceneDataInstance.h index 3dc2487c3..9452e0430 100644 --- a/devices/rtx/device/mdl/SceneDataInstance.h +++ b/devices/rtx/device/mdl/SceneDataInstance.h @@ -5,6 +5,7 @@ #include "gpu/materialAttributes.h" #include "libmdl/SceneDataDescriptor.h" +#include "utility/SceneDataNames.h" #include @@ -22,7 +23,8 @@ class SceneDataInstance MaterialAttribute attribute{MaterialAttribute::UNKNOWN}; }; - explicit SceneDataInstance(const libmdl::SceneDataDescriptor &descriptor); + SceneDataInstance( + const libmdl::SceneDataDescriptor &descriptor, SceneDataNames &names); SceneDataInstance(const SceneDataInstance &) = default; SceneDataInstance &operator=(const SceneDataInstance &) = default; diff --git a/devices/rtx/device/optix_visrtx.h b/devices/rtx/device/optix_visrtx.h index ffeaf323b..86299e71a 100644 --- a/devices/rtx/device/optix_visrtx.h +++ b/devices/rtx/device/optix_visrtx.h @@ -49,6 +49,7 @@ #include "mdl/Logger.h" #include "mdl/MaterialRegistry.h" #include "mdl/SamplerRegistry.h" +#include "utility/SceneDataNames.h" #include "utility/TaskExecutor.h" #endif // defined(USE_MDL) // std @@ -227,6 +228,7 @@ struct DeviceGlobalState : public helium::BaseGlobalDeviceState // MDL #ifdef USE_MDL + SceneDataNames sceneDataNames; struct MDL { libmdl::Core core; diff --git a/devices/rtx/device/utility/SceneDataNames.h b/devices/rtx/device/utility/SceneDataNames.h new file mode 100644 index 000000000..3b9edb870 --- /dev/null +++ b/devices/rtx/device/utility/SceneDataNames.h @@ -0,0 +1,47 @@ +// Copyright (c) 2019-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: BSD-3-Clause + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace visrtx { + +/* + * Device-local, exact string identity. Tokens never move or get reused during + * the device lifetime; no SDK string IDs or worker-owned state enter this map. + */ +class SceneDataNames +{ + public: + uint32_t intern(std::string_view name); + + private: + std::mutex m_mutex; + std::unordered_map m_tokens; +}; + +// Inlined definitions //////////////////////////////////////////////////////// + +inline uint32_t SceneDataNames::intern(std::string_view name) +{ + if (name.empty()) + return 0; + const std::lock_guard lock(m_mutex); + const auto found = m_tokens.find(std::string(name)); + if (found != m_tokens.end()) + return found->second; + if (m_tokens.size() >= std::numeric_limits::max()) + throw std::runtime_error("MDL scene-data name token capacity exhausted"); + const auto token = static_cast(m_tokens.size() + 1); + m_tokens.emplace(name, token); + return token; +} + +} // namespace visrtx diff --git a/devices/rtx/device/visrtx_geometry_mdl_scene_data.json b/devices/rtx/device/visrtx_geometry_mdl_scene_data.json new file mode 100644 index 000000000..bcec6b935 --- /dev/null +++ b/devices/rtx/device/visrtx_geometry_mdl_scene_data.json @@ -0,0 +1,59 @@ +{ + "info": { + "name": "VISRTX_GEOMETRY_MDL_SCENE_DATA", + "type": "extension", + "dependencies": [ + "visrtx_mdl_scene_data" + ] + }, + "objects": [ + { + "type": "ANARI_GEOMETRY", + "name": "triangle", + "description": "Native MDL scene-data aliases: sceneData. (ANARI_STRING) selects attribute0..3 or color. A geometry alias overrides the material binding for the same exact name, including when the selected attribute is absent. Unsetting restores material fallback. Empty names, non-string values and unsupported slots warn and are ignored. Existing attribute-source precedence, interpolation and uniform eligibility apply. Dynamic names are documented rather than enumerated as literal query parameters.", + "parameters": [] + }, + { + "type": "ANARI_GEOMETRY", + "name": "quad", + "description": "Native MDL scene-data aliases: sceneData. (ANARI_STRING) selects attribute0..3 or color. A geometry alias overrides the material binding for the same exact name, including when the selected attribute is absent. Unsetting restores material fallback. Empty names, non-string values and unsupported slots warn and are ignored. Existing attribute-source precedence, interpolation and uniform eligibility apply. Dynamic names are documented rather than enumerated as literal query parameters.", + "parameters": [] + }, + { + "type": "ANARI_GEOMETRY", + "name": "sphere", + "description": "Native MDL scene-data aliases: sceneData. (ANARI_STRING) selects attribute0..3 or color. A geometry alias overrides the material binding for the same exact name, including when the selected attribute is absent. Unsetting restores material fallback. Empty names, non-string values and unsupported slots warn and are ignored. Existing attribute-source precedence, interpolation and uniform eligibility apply. Dynamic names are documented rather than enumerated as literal query parameters.", + "parameters": [] + }, + { + "type": "ANARI_GEOMETRY", + "name": "cylinder", + "description": "Native MDL scene-data aliases: sceneData. (ANARI_STRING) selects attribute0..3 or color. A geometry alias overrides the material binding for the same exact name, including when the selected attribute is absent. Unsetting restores material fallback. Empty names, non-string values and unsupported slots warn and are ignored. Existing attribute-source precedence, interpolation and uniform eligibility apply. Dynamic names are documented rather than enumerated as literal query parameters.", + "parameters": [] + }, + { + "type": "ANARI_GEOMETRY", + "name": "cone", + "description": "Native MDL scene-data aliases: sceneData. (ANARI_STRING) selects attribute0..3 or color. A geometry alias overrides the material binding for the same exact name, including when the selected attribute is absent. Unsetting restores material fallback. Empty names, non-string values and unsupported slots warn and are ignored. Existing attribute-source precedence, interpolation and uniform eligibility apply. Dynamic names are documented rather than enumerated as literal query parameters.", + "parameters": [] + }, + { + "type": "ANARI_GEOMETRY", + "name": "curve", + "description": "Native MDL scene-data aliases: sceneData. (ANARI_STRING) selects attribute0..3 or color. A geometry alias overrides the material binding for the same exact name, including when the selected attribute is absent. Unsetting restores material fallback. Empty names, non-string values and unsupported slots warn and are ignored. Existing attribute-source precedence, interpolation and uniform eligibility apply. Dynamic names are documented rather than enumerated as literal query parameters.", + "parameters": [] + }, + { + "type": "ANARI_GEOMETRY", + "name": "sdf", + "description": "Native MDL scene-data aliases: sceneData. (ANARI_STRING) selects attribute0..3 or color. A geometry alias overrides the material binding for the same exact name, including when the selected attribute is absent. Unsetting restores material fallback. Empty names, non-string values and unsupported slots warn and are ignored. Existing attribute-source precedence, interpolation and uniform eligibility apply. Dynamic names are documented rather than enumerated as literal query parameters.", + "parameters": [] + }, + { + "type": "ANARI_GEOMETRY", + "name": "isosurface", + "description": "Native MDL scene-data aliases: sceneData. (ANARI_STRING) selects attribute0..3 or color. A geometry alias overrides the material binding for the same exact name, including when the selected attribute is absent. Unsetting restores material fallback. Empty names, non-string values and unsupported slots warn and are ignored. Existing attribute-source precedence, interpolation and uniform eligibility apply. Dynamic names are documented rather than enumerated as literal query parameters.", + "parameters": [] + } + ] +} diff --git a/devices/rtx/docs/geometry-attribute-names-investigation.md b/devices/rtx/docs/geometry-attribute-names-investigation.md new file mode 100644 index 000000000..6218576fa --- /dev/null +++ b/devices/rtx/docs/geometry-attribute-names-investigation.md @@ -0,0 +1,240 @@ +# Geometry attribute names: initial investigation + +Status: prototype implemented and validated in the `geom_attrib_names` worktree. +Baseline: next_release at 51d32f5f. Scope: RTX native MDL scene-data bindings. + +## Intended application behavior + +One MDL material can request `temperature` while different geometries store +that quantity in different existing ANARI attribute slots. Applications should +be able to share the material instead of cloning it solely to change bindings. + +A minimal API consistent with the existing material feature is: + +```cpp +anariSetParameter(device, geometryA, "sceneData.temperature", + ANARI_STRING, "attribute0"); +anariSetParameter(device, geometryB, "sceneData.temperature", + ANARI_STRING, "attribute2"); +// Supply vertex.attribute0 / vertex.attribute2 through the normal array API. +// Both surfaces can reference the same mdl material. +anariCommitParameters(device, geometryA); +anariCommitParameters(device, geometryB); +``` + +Provisional extension name: `ANARI_VISRTX_GEOMETRY_MDL_SCENE_DATA`. +This is an MDL-specific name-to-slot alias map, not additional data channels. +The initial scope keeps attribute0..3 and color, existing interpolation and +existing float/color lookup support. It does not add arbitrary named arrays, +integer/matrix lookups, instance naming, or shared world values. + +An alternative is `attribute0.name = "temperature"`. That reads naturally as +naming a slot and could become a general geometry naming extension, but limits +each slot to one name and differs from the existing name-to-slot material API. +Decide the intended broader scope before promising a generic extension name. +No collision is apparent in the inspected VisRTX implementation; external +ANARI extension naming and specification review remains to be done. + +## Proposed precedence + +Use an explicit geometry binding first, then the existing material binding +when the geometry does not bind that name. This lets geometry describe its own +layout while material bindings remain useful defaults. Existing applications +without geometry aliases retain their behavior. + +Resolve the name to a slot before resolving the slot's data. A geometry alias +that selects an absent attribute should produce MDL's default value, not silently +fall back to a different slot selected by the material. Unsetting the geometry +alias restores material fallback. Reject invalid target strings with a warning +and omit them from the committed alias snapshot; document this separately from +a valid binding whose data happens to be missing. Empty names should be rejected. + +Material-first precedence is also feasible, but would prevent geometry aliases +from overriding a shared material's existing binding. This is an API decision, +not an ANARI attribute-data precedence rule imposed by the current code. + +Once a slot is selected, reuse `resolveAttribute` and the existing attribute +cache. Geometry/instance constants, instance arrays, primitive, vertex and +face-varying sources retain their current precedence and uniform eligibility. +Names do not make a varying attribute uniform. A name declared on geometry can +therefore still obtain an instance value when normal slot resolution selects it. + +## Current implementation and the missing bridge + +- `MDL::syncSceneData()` scans material `sceneData.*` string parameters. +- `libmdl::SceneDataDescriptor` owns target-code strings at their original IDs. +- `mdl::SceneDataInstance` converts material aliases into an ID-indexed slot table. +- `MaterialGPUData::materialData.mdl` owns the GPU table reference. +- `MDLShader_ptx.cu` places that table in the per-hit TextureHandler. +- `MDLTexture_ptx.cu::sceneDataSlot()` selects the slot; `sceneDataValue()` + checks cached presence, uniform eligibility and finite values. `data_isvalid` + uses the same slot resolution but intentionally does not read values. +- `Geometry` currently stores attribute data but no name map. + +The MDL string ID is local to the target code, not a device-global identifier. +The same geometry can be used by materials with different ID assignments. +Copying a material's numeric IDs into GeometryGPUData would therefore be wrong. + +## Preferred prototype: device-local interned name tokens + +Intern exact name strings on the host, giving each distinct string a stable +device-local token (reserve zero as invalid). Keep tokens stable for the device +lifetime initially; do not treat an unchecked string hash as identity. Account +for token exhaustion and the memory cost of applications generating many names. + +Store committed geometry aliases as a compact GPU list of token/slot pairs. +Allow multiple names to refer to a slot. Add a token alongside each entry in +the material's ID-indexed scene-data table. Material binding updates continue +to populate its fallback slot. Target-code descriptor creation supplies the +tokens even for names that have no explicit material binding. + +At shading initialization, pass the hit geometry's alias list to TextureHandler. +For a lookup, use its material-local ID to fetch a token, search the geometry +list for that token, and otherwise use the material fallback slot. Both +`sceneDataValue` and `scene_data_isvalid` must use this single resolution helper. +An empty geometry list preserves the existing constant-time material-only path. + +Advantages: no per-surface material clones, no material recompilation for a +geometry-name edit, and no geometry/material cross-product cache. Costs: extra +GPU metadata and an alias-list search per lookup. Measure this cost with a +realistic number of names; choose a different lookup representation if needed. +Interning must be synchronized or confined to a known host owner: the existing +MDL coordinator/worker architecture must not gain unsynchronized shared state. + +Alternative: resolve a dense ID-to-slot table per surface (geometry/material +pair) on the host and pass that at each hit. This keeps GPU lookup cheap but +requires invalidation when either object changes, more storage proportional +to surfaces and descriptor sizes, and wiring through synthetic geometry-light +hits. Prefer it only if measurement justifies that extra lifetime machinery. + +## Implementation checkpoints + +1. Finalize extension name, alias syntax, precedence, invalid-input semantics, + and initial geometry subtype coverage. Add extension JSON, dependencies, + extension-query exposure and README examples using existing conventions. +2. Parse geometry aliases in the common Geometry commit path as a complete + snapshot so unset parameters disappear. Own the strings and uploaded list. + Audit each subtype's GPU-data population to initialize the new fields. +3. Add host name-token ownership and descriptor-to-token conversion without + changing MDL backend string IDs or compiled-material cache identity. +4. Extend shared GPU structs and TextureHandler; resolve geometry override + then material fallback in the common scene-data slot helper. +5. Audit edit propagation: GPU upload, accumulation reset, resource lifetime, + and geometry destruction. Name-only edits should not require PTX rebuilds; + inspect whether current Geometry finalization unnecessarily rebuilds BLAS. +6. Audit all MDL evaluation paths, especially emission on synthetic light hits, + so direct lighting and visible emission resolve the same names. Preserve + emission classification's treatment of scene-dependent expressions. + +## Validation required before publishing an implementation + +- One shared material on two geometries with different name-to-slot maps. +- One shared geometry with two materials whose target-code string IDs differ. +- Conflicting geometry/material bindings; missing geometry alias; unsetting; + valid alias with missing data; invalid strings; multiple aliases for one slot. +- Existing material-only results unchanged, including data_isvalid and missing, + nonfinite, uniform versus varying, and default-return behavior. +- Primitive, vertex and triangle face-varying values; geometry constants and + instance fallback. Test indexed data where the selected source needs it. +- Retained edits after rendering, geometry/material replacement and destruction, + multiple devices, descriptor rebuild, and existing parallel MDL compilation. +- Named emission through visible hits and geometry-light sampling where supported. +- Existing MDL scene-data and rendering regressions; build with MDL disabled. +- Performance comparison for no geometry aliases and representative alias counts. + +No source implementation or build was performed during the initial investigation. +Keep future build output under this worktree (for example `_build/mdl`); never +reuse the parent checkout's CMake cache or build directories. + +## Implementation decisions (2026-11-17) + +The prototype adopts `ANARI_VISRTX_GEOMETRY_MDL_SCENE_DATA`, the +`sceneData.` syntax and geometry-first precedence described above. +Initial advertised subtypes are triangle, quad, sphere, cylinder, cone, curve, +SDF and isosurface. It does not extend the ANARI attribute channel count. + +- `SceneDataNames` owns exact, case-sensitive strings per device, synchronizes + interning with a mutex, reserves token zero for the empty name and checks + 32-bit token exhaustion. Tokens and their strings live until device teardown. + Descriptor conversion happens in material source synchronization on the commit + thread, after collecting the compile result. No worker or compiler-cache + identity changes are required. +- `SceneDataInstance` retains a name token for every target-code string-table + entry even without a material binding. Updating the material snapshot replaces + fallback slots while retaining tokens. Geometry commits upload their complete + alias snapshots through the common Geometry path; invalid entries warn and + are omitted, and unsetting the last alias releases its GPU buffer. +- Each geometry GPU record carries its alias pointer/count. Shading initialization + passes these to the MDL TextureHandler. Float/color lookups and `data_isvalid` + share `resolveSceneDataAttribute`, which searches tokens before selecting the + material fallback. Attribute presence, finite-value handling and uniform + eligibility remain in the existing cache lookup. +- Synthetic geometry-light hits already point at the real geometry GPU record. + They use the same shading initialization, so this path needs no special alias + cache or changes to emission classification/registration policy. +- Alias edits retain compiled target code and renderer pipelines. Current Geometry + finalization still marks the surface BLAS dirty for all parameter edits; removing + that rebuild requires broader geometry dirty-state tracking and is deferred. +- Expanding material table entries exposed an upload call passing byte size to + the element-count overload. It now uploads `data.size()` entries. + +## Validation results (2026-11-17) + +Environment: Windows, Visual Studio 2022, CUDA 13.2, OptiX 7.7, ANARI 0.16.0, +MDL SDK 2025.0.5, NVIDIA RTX A3000 Laptop GPU (driver 595.97). Builds and logs +are isolated under this worktree's `_build/` directory. + +- MDL-enabled Release library and selected MDL regression targets built under + `_build/mdl`; MDL-disabled Release library and rendering smoke test built under + `_build/no-mdl`. +- `TestMdlSceneData`: passed through CTest. Covers shared materials/geometries, + target-code replacement, geometry/material precedence, unsetting, missing and + invalid aliases, multiple names per slot, color, nonfinite values, presence, + uniform eligibility, indexed vertex/primitive/face-varying data, instance-array + fallback, curves, retained edits, accumulation and destruction. Alias-only edits + preserve the material PTX fingerprint. Existing material-only scene-data and + animation-time checks also pass. +- Named emission through synthetic geometry-light hits: the camera sees only a + diffuse receiver, with the emitter outside its view. The material uses + `math::saturate` so the existing nonnegative-emission policy admits it as a + Geometry Light. Changing its geometry alias from the slot holding 0.8 to the + slot holding 0.4 changes receiver radiance from 0.036212 to 0.018106. The + existing emission registration policy is unchanged. +- `rtx::MdlSceneDataInstance`, `rtx::MdlSceneDataDescriptor` and + `rtx::MdlEmissionClassifier`: passed. The instance test includes reordered + target-code IDs, device independence and concurrent interning of 8,000 names + across eight host tasks. +- MDL-disabled `TestDenoiserReuse`: passed through CTest. +- `git diff --check`: passed. + +The optional `TestMdlSceneData --benchmark` measures the median of 16 GPU frame +durations after four warm-up frames, at 256x256 pixels and 64 samples per pixel: + +| Geometry aliases | GPU frame duration | Relative to zero aliases | +| --- | --- | --- | +| 0 | 53.183 ms | baseline | +| 8 | 53.729 ms | +1.0% | +| 32 | 56.540 ms | +6.3% | + +This is one microbenchmark on a laptop GPU, not a general throughput guarantee +or a comparison against the pre-feature binary. The linear list is acceptable +for the prototype; larger alias maps may justify a different representation. + +## Remaining limitations and coverage gaps + +- The existing `rtx::MdlMaterialRegistry` test fails its Windows canonical-module + recovery fixture (`source acquire failed (no fallback permitted)`). The same + failure was reproduced using the untouched parent checkout's registry test, + MaterialRegistry, TaskExecutor and PTX source files, linked against a fresh + build of unchanged libmdl code. This feature does not change that path. +- Validation uses normal Release compiler settings. An initial failed compiler + detection left an empty flag cache; an assertion-enabled attempt then hit the + existing World light/surface-array cursor check before the surface array is + rebuilt. Restoring normal Release flags resolved that validation setup issue; + assertion-enabled World ordering remains outside this feature's scope. +- External extension-name/specification review, MaterialX-specific coverage, + neural geometry, every individual geometry subtype, and broad application + performance testing remain follow-ups. Common Geometry setup and GPU-data + population were audited across implemented subtypes. +- Geometry finalization still rebuilds BLAS for alias-only edits, and distinct + interned names remain allocated until device destruction.