From c9fd309c3bc070e57bdf9ea260b643452957f75c Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:58:58 +0000 Subject: [PATCH 1/2] Share one MDL SDK instance across VisRTX devices mi_factory hands out at most one live INeuray per loaded library image, and dlopen of the same path returns the same refcounted handle. Each libmdl::Core acquired its own instance, so creating a second VisRTX device while a first was alive got a null INeuray, threw, and reported "Failed initializing VisRTX MDL support." Introduce detail::SharedNeuray, owning the library image and the INeuray, held by every Core through a shared_ptr handed out via a static weak_ptr and mutex. The SDK is shut down and unloaded only when the last Core dies, so destroying every device and creating a new one still reacquires a fresh instance. Teardown is serialized against a replacement: the weak_ptr expires before the destructor has unloaded the image, and a concurrent acquire that reloaded it meanwhile would overlap loadLibrary/freeLibrary. The destructor cannot simply take the mutex, because the Core constructor's scope_fail destroys the object while already holding it. The SDK accepts a single receiving logger per instance, so a shared instance has one master logger: the first Core in installs the sink it was given and later ones leave it alone. SDK-internal diagnostics reach that master whichever device provoked them. Messages VisRTX logs itself never pass through the SDK's logger, so they still reach the device they belong to. Attributing SDK diagnostics per device is possible -- route through a shim consulting a thread-local "active device" -- and an earlier revision did, but it cost a routing logger, a scope guard on all sixteen SDK entry points and self-reference guards for instances handed back in, to redirect a trickle of compiler warnings that no application can act on programmatically. An application that needs precise attribution configures its own INeuray and hands it over, which makes the question moot. Recorded in the doc as a deliberate trade rather than an oversight. Devices from another vendor in the same process cannot see VisRTX's internals, so sharing with them is mediated by the application. Expose the instance as an `ineuray` device property to pair with the existing `ineuray` parameter, and describe both -- plus mdlSearchPaths and mdlResourceSearchPaths -- in VISRTX_MATERIAL_MDL so the contract is discoverable rather than folklore. docs/mdl-instance-sharing.md covers the handoff and why an automatic rendezvous was prototyped and rejected. The ANARI_DEVICE entry in the extension JSON deliberately carries no "name": a named subtype makes the query generator emit a subtype-dispatching ANARI_DEVICE_info, and callers pass NULL for the device subtype (visrtx_extensions.h), which then crashes in subtype_hash. Properties are not introspectable at all -- the generator's info vocabulary has no "property" entry, which is why the core spec's own geometryMaxIndex is absent too -- so TestMdlIneurayIntrospect verifies the property by reading it. Tests: TestMdlMultiDevice (overlapping devices, sequential create/destroy, concurrent creation), TestMdlIneurayHandoff (end-to-end property-to-parameter handoff) and TestMdlIneurayIntrospect, plus TestMdlLogging pinning both halves of the logging contract. The first three were confirmed to fail without the fix. Review follow-ups in this commit: the teardown announcement moved from the destructor into the shared_ptr's deleter, because the weak_ptr expires at the last strong decrement and a flag set inside the destructor leaves a window in which a concurrent acquire sees an expired weak_ptr, no announced teardown, and reloads the image while the old instance is still alive (reproduced 197/200 in a model of the ordering); a failed INeuray::start() is no longer published as a successful acquisition; and the self-reference hazard in the adopt path disappeared with the router itself. --- devices/rtx/apps/tests/api/CMakeLists.txt | 8 + .../apps/tests/api/TestMdlIneurayHandoff.cpp | 122 ++++++++ .../tests/api/TestMdlIneurayIntrospect.cpp | 75 +++++ devices/rtx/apps/tests/api/TestMdlLogging.cpp | 201 ++++++++++++ .../rtx/apps/tests/api/TestMdlMultiDevice.cpp | 210 +++++++++++++ devices/rtx/device/VisRTXDevice.cpp | 14 + devices/rtx/device/visrtx_material_mdl.json | 32 ++ devices/rtx/docs/mdl-instance-sharing.md | 102 ++++++ devices/rtx/libmdl/Core.cpp | 295 +++++++++++++----- devices/rtx/libmdl/Core.h | 26 +- 10 files changed, 1005 insertions(+), 80 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestMdlIneurayHandoff.cpp create mode 100644 devices/rtx/apps/tests/api/TestMdlIneurayIntrospect.cpp create mode 100644 devices/rtx/apps/tests/api/TestMdlLogging.cpp create mode 100644 devices/rtx/apps/tests/api/TestMdlMultiDevice.cpp create mode 100644 devices/rtx/docs/mdl-instance-sharing.md diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 764c15896..61aba3364 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -126,6 +126,14 @@ if (VISRTX_ENABLE_MDL_SUPPORT) add_test(NAME TestMdlModuleReuseSerial COMMAND TestMdlModuleReuse) set_tests_properties(TestMdlModuleReuseSerial PROPERTIES ENVIRONMENT "VISRTX_MDL_COMPILE_THREADS=1" TIMEOUT 120) + make_test(TestMdlIneurayHandoff) + make_test(TestMdlIneurayIntrospect) + set_tests_properties(TestMdlIneurayHandoff TestMdlIneurayIntrospect + PROPERTIES TIMEOUT 120) + make_test(TestMdlLogging) + set_tests_properties(TestMdlLogging PROPERTIES TIMEOUT 120) + make_test(TestMdlMultiDevice) + set_tests_properties(TestMdlMultiDevice PROPERTIES TIMEOUT 300) make_test(TestMdlMaterialRegistryRelease) make_test(TestMdlConcurrentCompile) make_test(TestMdlCompileBenchmark) diff --git a/devices/rtx/apps/tests/api/TestMdlIneurayHandoff.cpp b/devices/rtx/apps/tests/api/TestMdlIneurayHandoff.cpp new file mode 100644 index 000000000..028344d89 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestMdlIneurayHandoff.cpp @@ -0,0 +1,122 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. +// SPDX-License-Identifier: BSD-3-Clause + +// Application-mediated INeuray handoff: the app reads the SDK instance from +// one device's `ineuray` property and passes it to another device's `ineuray` +// parameter. This is the supported path for sharing MDL across devices from +// different vendors, which cannot see each other's internals. + +#define ANARI_EXTENSION_UTILITY_IMPL +#include +#include +#include +#include +#include +#include +using Vec3 = std::array; +using Vec4 = std::array; +static int errs = 0; +static void st(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity s, + ANARIStatusCode, + const char *m) +{ + if (s == ANARI_SEVERITY_ERROR || s == ANARI_SEVERITY_FATAL_ERROR) { + ++errs; + std::fprintf(stderr, "ERR: %s\n", m); + } +} +static std::string src() +{ + return "mdl 1.6; import ::df::*; export material emitter()=material(surface: material_surface(" + "emission: material_emission(emission: df::diffuse_edf(), intensity: color(4.0))));"; +} +static anari::Frame scene(anari::Device d) +{ + const std::array v = { + Vec3{-1, -1, 0}, Vec3{1, -1, 0}, Vec3{1, 1, 0}, Vec3{-1, 1, 0}}; + const std::array, 2> i = { + std::array{0, 1, 2}, std::array{0, 2, 3}}; + auto g = anari::newObject(d, "triangle"); + anari::setParameterArray1D(d, g, "vertex.position", v.data(), v.size()); + anari::setParameterArray1D(d, g, "primitive.index", i.data(), i.size()); + anari::commitParameters(d, g); + auto m = anari::newObject(d, "mdl"); + anari::setParameter(d, m, "sourceType", "code"); + anari::setParameter(d, m, "source", src()); + anari::setParameter(d, m, "materialName", "emitter"); + anari::commitParameters(d, m); + auto s = anari::newObject(d); + anari::setAndReleaseParameter(d, s, "geometry", g); + anari::setAndReleaseParameter(d, s, "material", m); + anari::commitParameters(d, s); + auto w = anari::newObject(d); + anari::setParameterArray1D(d, w, "surface", &s, 1); + anari::commitParameters(d, w); + anari::release(d, s); + auto c = anari::newObject(d, "orthographic"); + anari::setParameter(d, c, "position", Vec3{0, 0, 3}); + anari::setParameter(d, c, "direction", Vec3{0, 0, -1}); + anari::setParameter(d, c, "up", Vec3{0, 1, 0}); + anari::setParameter(d, c, "height", 2.f); + anari::setParameter(d, c, "aspect", 1.f); + anari::commitParameters(d, c); + auto r = anari::newObject(d, "quality"); + anari::setParameter(d, r, "pixelSamples", 1); + anari::setParameter(d, r, "background", Vec4{0, 0, 0, 1}); + anari::setParameter(d, r, "ambientRadiance", 0.f); + anari::commitParameters(d, r); + auto f = anari::newObject(d); + anari::setParameter(d, f, "size", std::array{32, 32}); + anari::setParameter(d, f, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(d, f, "camera", c); + anari::setAndReleaseParameter(d, f, "renderer", r); + anari::setAndReleaseParameter(d, f, "world", w); + anari::commitParameters(d, f); + return f; +} +int main() +{ + auto A = makeVisRTXDevice(st); + anari::setParameter(A, A, "forceInit", true); + anari::commitParameters(A, A); + // Can the app READ the instance back out of device A? + void *p = nullptr; + int ok = anariGetProperty( + A, A, "ineuray", ANARI_VOID_POINTER, &p, sizeof(p), ANARI_WAIT); + std::printf("getProperty(\"ineuray\") -> returned=%d ptr=%p\n", ok, p); + if (!ok || !p) { + std::fprintf( + stderr, "FAIL: `ineuray` property unreadable; handoff impossible\n"); + return 1; + } + { + auto B = makeVisRTXDevice(st); + anari::setParameter(B, B, "ineuray", p); + anari::setParameter(B, B, "forceInit", true); + anari::commitParameters(B, B); + auto f = scene(B); + anari::render(B, f); + anari::wait(B, f); + auto px = anari::map(B, f, "channel.color"); + const float r = px.data[16 * 32 + 16][0]; + std::printf("handoff render pixel r=%.3f errors=%d\n", r, errs); + if (r <= 0.1f) { + std::fprintf(stderr, "FAIL: adopted instance did not render MDL\n"); + return 1; + } + anari::unmap(B, f, "channel.color"); + anari::release(B, f); + anari::release(B, B); + } + anari::release(A, A); + if (errs) { + std::fprintf(stderr, "FAIL: %d error(s) during handoff\n", errs); + return 1; + } + std::puts("INeuray handoff between devices succeeded"); + return 0; +} diff --git a/devices/rtx/apps/tests/api/TestMdlIneurayIntrospect.cpp b/devices/rtx/apps/tests/api/TestMdlIneurayIntrospect.cpp new file mode 100644 index 000000000..4aa60d09f --- /dev/null +++ b/devices/rtx/apps/tests/api/TestMdlIneurayIntrospect.cpp @@ -0,0 +1,75 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. +// SPDX-License-Identifier: BSD-3-Clause + +// The INeuray handoff is only usable if an application can discover it, so the +// `ineuray` device parameter and property must be part of the published +// VISRTX_MATERIAL_MDL extension description, not merely accepted by the code. + +#include +#include + +#include +#include + +namespace { + +bool hasParameter(ANARIDevice d, const char *name, ANARIDataType type) +{ + auto *params = (const ANARIParameter *)anariGetObjectInfo( + d, ANARI_DEVICE, "device", "parameter", ANARI_PARAMETER_LIST); + for (auto *p = params; p && p->name; ++p) + if (!std::strcmp(p->name, name) && p->type == type) + return true; + return false; +} + +// ANARI's query generator has no "property" info name (its vocabulary is +// required/default/minimum/maximum/description/elementType/value/ +// sourceExtension/extension/parameter/channel/use), so object properties -- +// including the core spec's own geometryMaxIndex -- are not introspectable. +// The property is therefore verified by reading it, not by listing it. +bool propertyReadable(ANARIDevice d, const char *name) +{ + void *value = nullptr; + return anariGetProperty( + d, d, name, ANARI_VOID_POINTER, &value, sizeof(value), ANARI_WAIT) + && value != nullptr; +} + +bool check(bool ok, const char *what) +{ + std::printf("%-56s %s\n", what, ok ? "ok" : "MISSING"); + return ok; +} + +} // namespace + +int main() +{ + auto device = makeVisRTXDevice(); + bool ok = true; + ok &= check(hasParameter(device, "ineuray", ANARI_VOID_POINTER), + "device parameter `ineuray` (ANARI_VOID_POINTER)"); + // Readable only once MDL is initialized. + anari::setParameter(device, device, "forceInit", true); + anari::commitParameters(device, device); + ok &= check(propertyReadable(device, "ineuray"), + "device property `ineuray` readable (ANARI_VOID_POINTER)"); + ok &= check(hasParameter(device, "mdlSearchPaths", ANARI_STRING), + "device parameter `mdlSearchPaths` (ANARI_STRING)"); + ok &= check(hasParameter(device, "mdlResourceSearchPaths", ANARI_STRING), + "device parameter `mdlResourceSearchPaths` (ANARI_STRING)"); + // The core device parameters must survive the merge. + ok &= check(hasParameter(device, "statusCallback", ANARI_STATUS_CALLBACK), + "core parameter `statusCallback` still advertised"); + anari::release(device, device); + + if (!ok) { + std::fprintf(stderr, + "FAIL: the MDL instance-sharing contract is not discoverable through " + "ANARI introspection\n"); + return 1; + } + std::puts("MDL device parameters and properties are advertised"); + return 0; +} diff --git a/devices/rtx/apps/tests/api/TestMdlLogging.cpp b/devices/rtx/apps/tests/api/TestMdlLogging.cpp new file mode 100644 index 000000000..6a977d3b9 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestMdlLogging.cpp @@ -0,0 +1,201 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. +// SPDX-License-Identifier: BSD-3-Clause + +// The MDL SDK takes a single receiving logger per INeuray instance, and every +// device in a process shares one instance. There is therefore one "master" +// logger per instance -- the first device in installs it -- and SDK-internal +// diagnostics reach that one whichever device provoked them. +// +// This pins down both halves of that contract: +// - SDK diagnostics (module compilation and friends) go to the master, +// even when a later device caused them; +// - VisRTX's own messages still reach the device they belong to, because +// they never go through the SDK's logger at all. +// +// See "Logging" in docs/mdl-instance-sharing.md for why per-device routing of +// SDK diagnostics was deliberately dropped. + +#define ANARI_EXTENSION_UTILITY_IMPL +#include +#include +#include + +#include +#include +#include +#include + +using Vec3 = std::array; +using Vec4 = std::array; + +namespace { + +int failures = 0; + +void check(bool ok, const char *what) +{ + std::printf("%-58s %s\n", what, ok ? "ok" : "FAILED"); + if (!ok) + ++failures; +} + +// Counted separately per device so we can see where each message landed. +struct Counters +{ + int sdk = 0; // MDL SDK's own diagnostics ("MDLC" category) + int visrtx = 0; // messages VisRTX logs itself +}; + +Counters firstDevice; +Counters secondDevice; +bool counting = false; + +void record(Counters &counters, const char *message) +{ + if (!counting || std::strstr(message, "VISRTX:MDL") == nullptr) + return; + if (std::strstr(message, "MDLC") != nullptr) + ++counters.sdk; + else + ++counters.visrtx; +} + +void firstStatus(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity, + ANARIStatusCode, + const char *message) +{ + record(firstDevice, message); +} + +void secondStatus(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity, + ANARIStatusCode, + const char *message) +{ + record(secondDevice, message); +} + +// The unreferenced local function makes the MDL core compiler emit a C225 +// warning, giving a deterministic SDK-sourced diagnostic to trace. +std::string warningSource() +{ + return "mdl 1.6; import ::df::*; float unused_fn(float x){return x;} " + "export material emitter()=material(surface: material_surface(" + "emission: material_emission(emission: df::diffuse_edf(), " + "intensity: color(4.0))));"; +} + +anari::Frame makeScene(anari::Device device) +{ + const std::array vertices = {Vec3{-1.f, -1.f, 0.f}, + Vec3{1.f, -1.f, 0.f}, + Vec3{1.f, 1.f, 0.f}, + Vec3{-1.f, 1.f, 0.f}}; + const std::array, 2> indices = { + std::array{0, 1, 2}, std::array{0, 2, 3}}; + auto geometry = anari::newObject(device, "triangle"); + anari::setParameterArray1D( + device, geometry, "vertex.position", vertices.data(), vertices.size()); + anari::setParameterArray1D( + device, geometry, "primitive.index", indices.data(), indices.size()); + anari::commitParameters(device, geometry); + + auto material = anari::newObject(device, "mdl"); + anari::setParameter(device, material, "sourceType", "code"); + anari::setParameter(device, material, "source", warningSource()); + anari::setParameter(device, material, "materialName", "emitter"); + anari::commitParameters(device, material); + + auto surface = anari::newObject(device); + anari::setAndReleaseParameter(device, surface, "geometry", geometry); + anari::setAndReleaseParameter(device, surface, "material", material); + anari::commitParameters(device, surface); + + auto world = anari::newObject(device); + anari::setParameterArray1D(device, world, "surface", &surface, 1); + anari::commitParameters(device, world); + anari::release(device, surface); + + auto camera = anari::newObject(device, "orthographic"); + anari::setParameter(device, camera, "position", Vec3{0.f, 0.f, 3.f}); + anari::setParameter(device, camera, "direction", Vec3{0.f, 0.f, -1.f}); + anari::setParameter(device, camera, "up", Vec3{0.f, 1.f, 0.f}); + anari::setParameter(device, camera, "height", 2.f); + anari::setParameter(device, camera, "aspect", 1.f); + anari::commitParameters(device, camera); + + auto renderer = anari::newObject(device, "quality"); + anari::setParameter(device, renderer, "pixelSamples", 1); + anari::commitParameters(device, renderer); + + auto frame = anari::newObject(device); + anari::setParameter(device, frame, "size", std::array{32, 32}); + anari::setParameter(device, frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(device, frame, "camera", camera); + anari::setAndReleaseParameter(device, frame, "renderer", renderer); + anari::setAndReleaseParameter(device, frame, "world", world); + anari::commitParameters(device, frame); + return frame; +} + +} // namespace + +int main() +{ + // The first device to initialize MDL installs the instance's logger. + auto first = makeVisRTXDevice(firstStatus); + anari::setParameter(first, first, "forceInit", true); + anari::commitParameters(first, first); + + auto second = makeVisRTXDevice(secondStatus); + anari::setParameter(second, second, "forceInit", true); + anari::commitParameters(second, second); + + counting = true; + // Compile and render on the *second* device only. Its MDL compile runs on + // that device's worker pool, so this also covers messages raised off the + // calling thread. + auto frame = makeScene(second); + anari::render(second, frame); + anari::wait(second, frame); + counting = false; + + std::printf( + "rendered on the second device: first saw %d SDK / %d VisRTX, " + "second saw %d SDK / %d VisRTX\n", + firstDevice.sdk, + firstDevice.visrtx, + secondDevice.sdk, + secondDevice.visrtx); + + anari::release(second, frame); + anari::release(first, first); + anari::release(second, second); + + // SDK diagnostics land on the master logger, which belongs to the first + // device. This is the documented trade for not routing per device. + check(firstDevice.sdk > 0, + "SDK diagnostics reach the instance's master logger"); + check(secondDevice.sdk == 0, + "SDK diagnostics do not also reach the provoking device"); + // VisRTX's own messages never go through the SDK's logger, so they stay + // with the device that produced them. + check( + secondDevice.visrtx > 0, "VisRTX's own messages stay with their device"); + check(firstDevice.visrtx == 0, + "an idle device sees none of the other's VisRTX messages"); + + if (failures) { + std::fprintf(stderr, "FAIL: %d logging check(s) failed\n", failures); + return 1; + } + std::puts("MDL logging follows the shared-instance master-logger contract"); + return 0; +} diff --git a/devices/rtx/apps/tests/api/TestMdlMultiDevice.cpp b/devices/rtx/apps/tests/api/TestMdlMultiDevice.cpp new file mode 100644 index 000000000..4dac7fb5f --- /dev/null +++ b/devices/rtx/apps/tests/api/TestMdlMultiDevice.cpp @@ -0,0 +1,210 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. +// SPDX-License-Identifier: BSD-3-Clause + +// `mi_factory` hands out a single live INeuray per loaded library image, so +// devices must share one refcounted SDK instance rather than each acquiring +// their own. This covers overlapping lifetimes, sequential create/destroy +// cycles, and concurrent creation. + +#define ANARI_EXTENSION_UTILITY_IMPL +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +using Vec3 = std::array; +using Vec4 = std::array; + +namespace { + +void check(bool condition, const char *message) +{ + if (!condition) { + std::fprintf(stderr, "FAIL: %s\n", message); + std::exit(1); + } +} + +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity == ANARI_SEVERITY_FATAL_ERROR + || severity == ANARI_SEVERITY_ERROR) { + std::fprintf(stderr, "ERROR: %s\n", message); + std::exit(1); + } +} + +// A module whose single material emits `channel` at full intensity, so the +// rendered pixel identifies which module and which device produced it. +std::string moduleSource(int channel) +{ + const Vec3 intensity = {channel == 0 ? 4.f : 0.f, + channel == 1 ? 4.f : 0.f, + channel == 2 ? 4.f : 0.f}; + return "mdl 1.6; import ::df::*; export material emitter() = material(" + "surface: material_surface(emission: material_emission(" + "emission: df::diffuse_edf(), intensity: color(" + + std::to_string(intensity[0]) + ", " + std::to_string(intensity[1]) + + ", " + std::to_string(intensity[2]) + "))));"; +} + +struct Setup +{ + anari::Device device{}; + anari::Frame frame{}; +}; + +// Builds a device rendering a full-screen quad with the given MDL material. +Setup makeSetup(int channel) +{ + Setup setup; + setup.device = makeVisRTXDevice(status); + + const std::array vertices = {Vec3{-1.f, -1.f, 0.f}, + Vec3{1.f, -1.f, 0.f}, + Vec3{1.f, 1.f, 0.f}, + Vec3{-1.f, 1.f, 0.f}}; + const std::array, 2> indices = { + std::array{0, 1, 2}, std::array{0, 2, 3}}; + auto geometry = anari::newObject(setup.device, "triangle"); + anari::setParameterArray1D(setup.device, + geometry, + "vertex.position", + vertices.data(), + vertices.size()); + anari::setParameterArray1D(setup.device, + geometry, + "primitive.index", + indices.data(), + indices.size()); + anari::commitParameters(setup.device, geometry); + + auto material = anari::newObject(setup.device, "mdl"); + anari::setParameter(setup.device, material, "sourceType", "code"); + anari::setParameter(setup.device, material, "source", moduleSource(channel)); + anari::setParameter(setup.device, material, "materialName", "emitter"); + anari::commitParameters(setup.device, material); + + auto surface = anari::newObject(setup.device); + anari::setAndReleaseParameter(setup.device, surface, "geometry", geometry); + anari::setAndReleaseParameter(setup.device, surface, "material", material); + anari::commitParameters(setup.device, surface); + + auto world = anari::newObject(setup.device); + anari::setParameterArray1D(setup.device, world, "surface", &surface, 1); + anari::commitParameters(setup.device, world); + anari::release(setup.device, surface); + + auto camera = anari::newObject(setup.device, "orthographic"); + anari::setParameter(setup.device, camera, "position", Vec3{0.f, 0.f, 3.f}); + anari::setParameter(setup.device, camera, "direction", Vec3{0.f, 0.f, -1.f}); + anari::setParameter(setup.device, camera, "up", Vec3{0.f, 1.f, 0.f}); + anari::setParameter(setup.device, camera, "height", 2.f); + anari::setParameter(setup.device, camera, "aspect", 1.f); + anari::commitParameters(setup.device, camera); + + auto renderer = anari::newObject(setup.device, "quality"); + anari::setParameter( + setup.device, renderer, "background", Vec4{0.f, 0.f, 0.f, 1.f}); + anari::setParameter(setup.device, renderer, "ambientRadiance", 0.f); + anari::setParameter(setup.device, renderer, "pixelSamples", 1); + anari::setParameter(setup.device, renderer, "fireflyFilterMode", "none"); + anari::commitParameters(setup.device, renderer); + + setup.frame = anari::newObject(setup.device); + anari::setParameter( + setup.device, setup.frame, "size", std::array{32, 32}); + anari::setParameter( + setup.device, setup.frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(setup.device, setup.frame, "camera", camera); + anari::setAndReleaseParameter( + setup.device, setup.frame, "renderer", renderer); + anari::setAndReleaseParameter(setup.device, setup.frame, "world", world); + anari::commitParameters(setup.device, setup.frame); + return setup; +} + +// Renders and asserts the quad emits on `channel` only: an MDL failure would +// fall back to a different material or leave the frame black. +void renderAndCheck(const Setup &setup, int channel, const char *context) +{ + anari::render(setup.device, setup.frame); + anari::wait(setup.device, setup.frame); + auto pixels = anari::map(setup.device, setup.frame, "channel.color"); + check(pixels.data != nullptr, context); + const auto &pixel = pixels.data[16 * 32 + 16]; + for (int c = 0; c < 3; ++c) { + check(std::isfinite(pixel[c]), context); + if (c == channel) + check(pixel[c] > 0.1f, context); + else + check(std::abs(pixel[c]) < 0.001f, context); + } + anari::unmap(setup.device, setup.frame, "channel.color"); +} + +void releaseSetup(const Setup &setup) +{ + anari::release(setup.device, setup.frame); + anari::release(setup.device, setup.device); +} + +} // namespace + +int main() +{ + // 1. Overlapping devices: the original failure. The second device used to + // get a null INeuray from mi_factory and abort MDL initialization. + { + auto first = makeSetup(0); + renderAndCheck(first, 0, "first device failed before second was created"); + auto second = makeSetup(1); + renderAndCheck(second, 1, "second concurrent device failed"); + // The first device must be unaffected by the second one's existence. + renderAndCheck(first, 0, "first device broke after second was created"); + releaseSetup(second); + // ... and must survive the second one's teardown, which must not shut the + // shared SDK instance down. + renderAndCheck(first, 0, "first device broke after second was destroyed"); + releaseSetup(first); + } + + // 2. Sequential cycles: the last release does shut the SDK down, so a later + // device has to reload and restart it. + for (int i = 0; i < 2; ++i) { + auto setup = makeSetup(2); + renderAndCheck(setup, 2, "device after full shutdown failed"); + releaseSetup(setup); + } + + // 3. Concurrent creation, covering the shared-instance acquisition lock. + { + constexpr int kDeviceCount = 3; + std::vector setups(kDeviceCount); + std::vector threads; + for (int i = 0; i < kDeviceCount; ++i) + threads.emplace_back([&setups, i] { setups[i] = makeSetup(i % 3); }); + for (auto &thread : threads) + thread.join(); + for (int i = 0; i < kDeviceCount; ++i) + renderAndCheck(setups[i], i % 3, "concurrently created device failed"); + for (const auto &setup : setups) + releaseSetup(setup); + } + + std::puts("MDL multi-device creation and teardown passed"); + return 0; +} diff --git a/devices/rtx/device/VisRTXDevice.cpp b/devices/rtx/device/VisRTXDevice.cpp index 4f46ad64e..25d0429cb 100644 --- a/devices/rtx/device/VisRTXDevice.cpp +++ b/devices/rtx/device/VisRTXDevice.cpp @@ -569,6 +569,20 @@ int VisRTXDevice::deviceGetProperty(const char *name, helium::writeToVoidP(mem, count); return 1; } + // Counterpart to the `ineuray` device parameter: lets an application hand + // this device's MDL SDK instance to another MDL-capable device (possibly + // from a different vendor). mi_factory yields at most one live INeuray per + // loaded library image, so without this handoff the second device's own + // acquisition fails. Ownership stays here; the recipient must not start or + // shut the instance down, and must outlive neither it nor this device. + if (prop == "ineuray" && type == ANARI_VOID_POINTER) { + auto &state = *deviceState(); + if (!state.mdl) + return 0; // MDL not initialized (or unavailable): nothing to hand over. + helium::writeToVoidP( + mem, static_cast(state.mdl->core.getINeuray())); + return 1; + } if (prop == "maxConcurrentMdlCompiles" && type == ANARI_UINT32) { auto &state = *deviceState(); if (flags & ANARI_WAIT) diff --git a/devices/rtx/device/visrtx_material_mdl.json b/devices/rtx/device/visrtx_material_mdl.json index c6dec1c85..858300bb9 100644 --- a/devices/rtx/device/visrtx_material_mdl.json +++ b/devices/rtx/device/visrtx_material_mdl.json @@ -6,6 +6,38 @@ }, "objects" : [ + { + "type" : "ANARI_DEVICE", + "description" : "device object", + "parameters" : [ + { + "name": "ineuray", + "types": ["ANARI_VOID_POINTER"], + "tags": [], + "description": "Optional `mi::neuraylib::INeuray*` for this device to use instead of acquiring its own. The MDL SDK yields at most one live INeuray per loaded library image, so an application combining several MDL-capable devices in one process must share a single instance: read it from the `ineuray` property of the first such device (or create it itself) and set it here before this device initializes MDL. The instance must already be started, and must outlive every device using it: destroy the recipients before whatever owns the instance. When the pointer came from another device's `ineuray` property, ownership stays with that device -- the application does not acquire it by passing the pointer on. Ignored once this device has initialized MDL." + }, + { + "name": "mdlSearchPaths", + "types": ["ANARI_STRING"], + "tags": [], + "description": "Platform-separated list (`:` on POSIX, `;` on Windows) of MDL module search roots. System and user paths are always appended." + }, + { + "name": "mdlResourceSearchPaths", + "types": ["ANARI_STRING"], + "tags": [], + "description": "Platform-separated list of search roots for MDL resources (textures, light profiles)." + } + ], + "properties" : [ + { + "name": "ineuray", + "type": "ANARI_VOID_POINTER", + "tags": [], + "description": "The `mi::neuraylib::INeuray*` this device is using, for handing to another MDL-capable device through its `ineuray` parameter. Readable once this device has initialized MDL; querying earlier, or when MDL is unavailable, returns 0 and writes nothing. Ownership stays on this side: a recipient must not start or shut the instance down, and must be destroyed before the devices that share the instance here. Where several VisRTX devices share one instance they all report the same pointer, and it stays alive until the last of them is destroyed." + } + ] + }, { "type" : "ANARI_MATERIAL", "name" : "mdl", diff --git a/devices/rtx/docs/mdl-instance-sharing.md b/devices/rtx/docs/mdl-instance-sharing.md new file mode 100644 index 000000000..2be2e6d14 --- /dev/null +++ b/devices/rtx/docs/mdl-instance-sharing.md @@ -0,0 +1,102 @@ +# Sharing one MDL SDK instance between ANARI devices + +The MDL SDK's `mi_factory` hands out at most **one live `INeuray` per loaded +library image**, and `dlopen`/`LoadLibrary` of the same path returns the same +refcounted image. Any second consumer that calls `mi_factory` gets `nullptr`. + +This bites in two places. + +## Two VisRTX devices — handled internally + +Every `libmdl::Core` in a process shares one refcounted `SharedNeuray` +(`libmdl/Core.cpp`). The SDK is created and started by the first `Core` and +shut down and unloaded when the last one goes away, so creating several VisRTX +devices — overlapping, sequentially, or concurrently — needs nothing from the +application. + +Two consequences follow from the instance being shared, both of which the +implementation has to handle because they used to be per-device: + +- **Search paths** are a property of the `INeuray` instance, not of a device, + so one device setting them affects every device sharing that instance. +- **Logging** has a single receiving logger per instance. See below. + +## Logging + +The SDK takes one receiving logger per `INeuray`, so there is one *master* +logger per instance: the first device to initialize MDL installs its own sink, +and later devices leave it in place. SDK-internal diagnostics — module +compilation and the like — therefore reach that master, whichever device +provoked them. + +Messages VisRTX logs itself never pass through the SDK's logger, so they still +reach the device they belong to. + +This is a deliberate trade. Attributing SDK diagnostics per device is possible +— route through a shim that consults a thread-local "currently active device" +— but it costs a routing logger, a scope guard on every SDK entry point, and +self-reference guards for instances handed back and forth, to redirect a +trickle of compiler warnings. ANARI status messages are diagnostic rather than +programmatic, so nothing an application does depends on which device a +compiler warning arrives on. An application that cares installs its own logger +on its own `INeuray` and hands that over, which makes the question moot. + +So: if you need MDL diagnostics attributed precisely, create and configure the +`INeuray` yourself and pass it in. + +## A VisRTX device plus another vendor's — application-mediated + +Another MDL-capable ANARI device (Barney, say) in the same process cannot see +VisRTX's internals, and VisRTX cannot see its. The instance therefore has to be +handed over by the application. `VISRTX_MATERIAL_MDL` declares, on the device +object: + +- parameter `ineuray` (`ANARI_VOID_POINTER`) — use this instance instead of + acquiring one. Read before the device initializes MDL; ignored afterwards. +- property `ineuray` (`ANARI_VOID_POINTER`) — the instance this device is + using, readable once it has initialized MDL. + +So the application reads the property from whichever device initialized MDL +first, and sets it as the parameter on every other one: + +```c +void *instance = nullptr; +anariGetProperty(first, first, "ineuray", ANARI_VOID_POINTER, + &instance, sizeof(instance), ANARI_WAIT); +anariSetParameter(second, second, "ineuray", ANARI_VOID_POINTER, &instance); +``` + +Ownership stays on the providing side. A recipient must not `start()` or +`shutdown()` the instance, and must not outlive it. + +Concretely: the instance is shut down and its library unloaded when the last +VisRTX `Core` that *owns* it is destroyed. A device that merely received the +pointer holds a reference to the `INeuray` interface, which is not a lease on +the started SDK or on the loaded image — so **destroy the recipients before the +devices that provided the instance**. Where several VisRTX devices share one +instance automatically they all report the same pointer and none of them is +individually "the" owner; the instance lives until the last of them goes. + +Handing one VisRTX device's instance to another VisRTX device is unnecessary — +they already share automatically — and loses that protection, so don't. + +> Properties are not introspectable in ANARI: the query generator's info +> vocabulary has no `property` entry, which is why the core specification's own +> `geometryMaxIndex` is absent from generated queries too. The `ineuray` +> property is discoverable from this document, not at runtime. + +### Why not something automatic + +An automatic rendezvous — devices discovering each other through a shared +broker library and refcounting a published instance — was prototyped and +rejected. It needs a shim library loaded into the global symbol scope, a +published record with its own ABI, cross-binary allocation and locking rules, +and SDK-version arbitration; and it still cannot help when one participant +does not implement it, because that participant takes the instance from +`mi_factory` regardless. The handoff above is a few lines in the application +and has none of that surface. + +## Status + +Tested on Linux/glibc against MDL SDK 2026.0.2, with +`VISRTX_USE_MDL_FOR_PHYSICALLY_BASED=OFF`. diff --git a/devices/rtx/libmdl/Core.cpp b/devices/rtx/libmdl/Core.cpp index f56220c0e..0f4cebbbe 100644 --- a/devices/rtx/libmdl/Core.cpp +++ b/devices/rtx/libmdl/Core.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -64,13 +65,205 @@ static_assert(sizeof(HMODULE) <= sizeof(void *)); #include +#include +#include +#include +#include #include +#include using namespace std::string_literals; using mi::base::make_handle; namespace visrtx::libmdl { +namespace detail { + +struct SharedNeuray; + +std::mutex g_sharedNeurayMutex; +std::weak_ptr g_sharedNeuray; +// An instance is "occupied" from the moment it is published until its image is +// unloaded. A replacement that reloaded the image while the old one was still +// unloading would overlap loadLibrary/freeLibrary and can make mi_factory +// refuse for the rest of the process. +// +// The weak_ptr alone cannot express this: it expires at the last strong +// decrement, which is strictly before the destructor runs. A flag set inside +// the destructor therefore leaves a window in which a concurrent acquire sees +// an expired weak_ptr and no announced teardown, and proceeds. The flag is +// instead claimed by the shared_ptr's deleter, which runs under this mutex +// before the object is destroyed, so expiry and occupancy change together as +// far as any lock holder can observe. +bool g_sharedNeurayTearingDown = false; +std::condition_variable g_sharedNeurayIdle; + +// Owns the MDL SDK library image and the single INeuray instance +// `mi_factory` is willing to hand out while one is alive. Held through a +// shared_ptr by every self-owned Core; the SDK is shut down and the library +// unloaded when the last one goes away. +struct SharedNeuray +{ + void *dllHandle{}; + mi::base::Handle neuray; + // The logger the SDK reports its own diagnostics through. The first Core to + // create the instance installs the one it was given, if any; everyone else + // reads whatever is installed. See "Logging" in + // docs/mdl-instance-sharing.md. + mi::base::Handle logger; + // Set once this object is reachable through g_sharedNeuray, so its teardown + // has to be serialized against a replacement. + bool published{}; + + ~SharedNeuray() + { + if (neuray.is_valid_interface()) + neuray->shutdown(); + neuray = {}; + logger = {}; + if (dllHandle) + freeLibrary(dllHandle); + } +}; + +// Runs when the last shared_ptr goes, which is also when the weak_ptr expires. +// Claiming the teardown flag here -- under the mutex, before `delete` -- means +// no lock holder can ever see an expired weak_ptr without also seeing the +// instance announced as occupied. +struct SharedNeurayDeleter +{ + void operator()(SharedNeuray *instance) const + { + const bool announce = instance->published; + if (announce) { + std::lock_guard guard(g_sharedNeurayMutex); + g_sharedNeurayTearingDown = true; + } + delete instance; + if (announce) { + { + std::lock_guard guard(g_sharedNeurayMutex); + g_sharedNeurayTearingDown = false; + } + g_sharedNeurayIdle.notify_all(); + } + } +}; + +namespace { + +// The shared instance if this process already created one, else null. Unlike +// acquireSharedNeuray() this never creates one. +std::shared_ptr peekSharedNeuray() +{ + std::lock_guard guard(g_sharedNeurayMutex); + return g_sharedNeuray.lock(); +} + +// One-time setup for a freshly created instance. Must run before +// INeuray::start(): load_plugin_library fails on a running instance (measured +// -1 on MDL SDK 2026.0.2), so deferring any of this until after startup would +// silently leave the instance without its image plugins. +void configureInstance(SharedNeuray &shared, mi::neuraylib::INeuray *neuray) +{ + auto mdlConfiguration = make_handle( + neuray->get_api_component()); + mdlConfiguration->add_mdl_system_paths(); + mdlConfiguration->add_mdl_user_paths(); + + auto loggingConfig = make_handle( + neuray->get_api_component()); + // The instance gets one receiving logger, and every Core sharing it reports + // through that. Install the creator's sink if it supplied one; otherwise + // adopt whatever the SDK already has. + if (shared.logger.is_valid_interface()) + loggingConfig->set_receiving_logger(shared.logger.get()); + else + shared.logger = make_handle(loggingConfig->get_receiving_logger()); + + auto pluginConf = make_handle( + neuray->get_api_component()); + if (mi::Sint32 res = pluginConf->load_plugin_library( + "nv_openimageio" MI_BASE_DLL_FILE_EXT); + res != 0) { + shared.logger->message(mi::base::MESSAGE_SEVERITY_WARNING, + "MDL", + "Failed to load the nv_openimageio plugin"); + } + if (mi::Sint32 res = + pluginConf->load_plugin_library("dds" MI_BASE_DLL_FILE_EXT); + res != 0) { + shared.logger->message(mi::base::MESSAGE_SEVERITY_WARNING, + "MDL", + "Failed to load the dds plugin"); + } +} + +// `preferredLogger`, when set and when this call is the one that creates the +// instance, becomes the instance's receiving logger. +std::shared_ptr acquireSharedNeuray( + mi::base::ILogger *preferredLogger) +{ + static constexpr const auto filename = "libmdl_sdk" MI_BASE_DLL_FILE_EXT; + + std::unique_lock guard(g_sharedNeurayMutex); + + // An instance whose last reference has gone may still be shutting down and + // unloading its image. Wait for it to finish before considering a + // replacement; the deleter announces this before the weak_ptr can be + // observed as expired, so there is no window between the two. + g_sharedNeurayIdle.wait(guard, [] { return !g_sharedNeurayTearingDown; }); + + if (auto existing = g_sharedNeuray.lock()) + return existing; + + // Never std::make_shared: the deleter is what closes the teardown window. + std::shared_ptr shared(new SharedNeuray, SharedNeurayDeleter{}); + if (preferredLogger) + shared->logger = mi::base::make_handle_dup(preferredLogger); + + shared->dllHandle = loadLibrary(filename); + if (shared->dllHandle == nullptr) + throw std::runtime_error("Failed to load MDL SDK library "s + filename); + + void *symbol = getProcAddress(shared->dllHandle, "mi_factory"); + if (symbol == nullptr) + throw std::runtime_error("Failed to find MDL SDK mi_factory symbol"); + + shared->neuray = mi::neuraylib::mi_factory(symbol); + if (!shared->neuray.is_valid_interface()) { + // Check if we have a valid neuray instance, otherwise check why. + auto version = + make_handle(mi::neuraylib::mi_factory(symbol)); + if (!version) { + throw std::runtime_error("Cannot get MDL SDK library version"); + } else { + throw std::runtime_error( + "Cannot get INeuray interface from mi_factory, either there is a version mismatch or the interface has already been acquired: "s + "Expected version is " MI_NEURAYLIB_PRODUCT_VERSION_STRING + ", library version is " + + version->get_product_version()); + } + } + + configureInstance(*shared, shared->neuray.get()); + // A failed startup must not be published: every later Core would adopt a + // non-started instance and fail far from the cause. + if (const mi::Sint32 result = shared->neuray->start(); result != 0) { + throw std::runtime_error( + "Failed to start the MDL SDK, INeuray::start() returned "s + + std::to_string(result)); + } + + shared->published = true; + g_sharedNeuray = shared; + return shared; +} + +} // namespace + +} // namespace detail + Core::Core() : Core({}, {}) {} Core::Core(mi::base::ILogger *logger) : Core({}, logger) {} @@ -84,81 +277,43 @@ Core::Core(mi::neuraylib::INeuray *neuray, mi::base::ILogger *logger) "Only one of neuray or logger can be provided to libmdl::Core"); } - static constexpr const auto filename = "libmdl_sdk" MI_BASE_DLL_FILE_EXT; - nonstd::scope_fail handleCleanup([this]() { m_executionContext = {}; + m_mdlFactory = {}; m_globalScope = {}; m_neuray = {}; - - if (m_dllHandle) - freeLibrary(m_dllHandle); - m_dllHandle = {}; + m_logger = {}; + m_shared = {}; }); if (neuray) { + // Externally owned instance: whoever owns it configures and shuts it down, + // including its logger. Note this Core takes no lease on the started SDK + // or its loaded image -- holding an INeuray reference is not that -- so + // the owner must outlive it (docs/mdl-instance-sharing.md). m_neuray = mi::base::make_handle_dup(neuray); - m_dllHandle = {}; - } else { - // Load library - m_dllHandle = loadLibrary(filename); - - if (m_dllHandle == nullptr) - throw std::runtime_error("Failed to load MDL SDK library "s + filename); - - // Get neuray main entry point - void *symbol = getProcAddress(m_dllHandle, "mi_factory"); - if (symbol == nullptr) - throw std::runtime_error("Failed to find MDL SDK mi_factory symbol"); - - m_neuray = mi::neuraylib::mi_factory(symbol); - if (m_neuray == nullptr) { - // Check if we have a valid neuray instance, otherwise check why. - auto version = make_handle( - mi::neuraylib::mi_factory(symbol)); - if (!version) { - throw std::runtime_error("Cannot get MDL SDK library version"); - } else { - throw std::runtime_error( - "Cannot get INeuray interface from mi_factory, either there is a version mismatch or the interface has already been acquired: "s - "Expected version is " MI_NEURAYLIB_PRODUCT_VERSION_STRING - ", library version is " - + version->get_product_version()); - } - } - - // Get the MDL configuration component so main path can be added. - auto mdlConfiguration = make_handle( - m_neuray->get_api_component()); - mdlConfiguration->add_mdl_system_paths(); - mdlConfiguration->add_mdl_user_paths(); + // Report through the instance's logger, so this Core's own messages do + // not silently fall back to stderr. auto loggingConfig = make_handle( m_neuray->get_api_component()); - if (logger) { - loggingConfig->set_receiving_logger(logger); - } else { - logger = loggingConfig->get_receiving_logger(); - } - - m_logger = logger; - - auto pluginConf = make_handle( - m_neuray->get_api_component()); - if (mi::Sint32 res = pluginConf->load_plugin_library( - "nv_openimageio" MI_BASE_DLL_FILE_EXT); - res != 0) { - logMessage(mi::base::MESSAGE_SEVERITY_WARNING, - "Failed to load the nv_openimageio plugin"); - } - if (mi::Sint32 res = - pluginConf->load_plugin_library("dds" MI_BASE_DLL_FILE_EXT); - res != 0) { - logMessage( - mi::base::MESSAGE_SEVERITY_WARNING, "Failed to load the dds plugin"); - } - - m_neuray->start(); + m_logger = make_handle(loggingConfig->get_receiving_logger()); + } else { + // A supplied sink is offered to the shared instance as its receiving + // logger: the first Core in installs it, later ones leave it alone, since + // the SDK takes only one per instance. That governs where the SDK's own + // diagnostics go. + // + // This Core keeps its own sink regardless, so the messages VisRTX logs + // itself -- which never pass through the SDK's logger -- still reach the + // device they belong to. Only Cores given no sink fall back to the + // instance's. + if (logger) + m_logger = mi::base::make_handle_dup(logger); + m_shared = detail::acquireSharedNeuray(m_logger.get()); + m_neuray = mi::base::make_handle_dup(m_shared->neuray.get()); + if (!m_logger.is_valid_interface()) + m_logger = mi::base::make_handle_dup(m_shared->logger.get()); } // Get the global scope from the database @@ -194,12 +349,10 @@ Core::~Core() m_executionContext = {}; m_mdlFactory = {}; m_globalScope = {}; - if (m_dllHandle) { - m_neuray->shutdown(); - m_neuray = {}; - freeLibrary(m_dllHandle); - } - m_dllHandle = {}; + m_logger = {}; + m_neuray = {}; + // Shuts down and unloads the SDK if this was the last live Core. + m_shared = {}; } mi::neuraylib::IScope *Core::createScope( @@ -612,7 +765,7 @@ auto Core::setMdlResourceSearchPaths(nonstd::span paths) m_neuray->get_api_component()); mdlConfiguration->clear_resource_paths(); for (const auto &path : paths) { - mdlConfiguration->add_resource_path(path.string().c_str()); + mdlConfiguration->add_resource_path(path.generic_string().c_str()); } } diff --git a/devices/rtx/libmdl/Core.h b/devices/rtx/libmdl/Core.h index 28ab335c5..99a9c3a28 100644 --- a/devices/rtx/libmdl/Core.h +++ b/devices/rtx/libmdl/Core.h @@ -32,19 +32,27 @@ #include #include +#include #include #include #include namespace visrtx::libmdl { +namespace detail { +// Process-wide owner of the MDL SDK library image and its single INeuray +// instance. See Core.cpp. +struct SharedNeuray; +} // namespace detail + class Core { public: - // The main neuray interface can only be acquired once. Possibly get it - // as a parameter instead of allocating it internally. - // Note that we allow overriding the logger only if we own the - // neuray instance, otherwise we assume logging is already taken care of + // `mi_factory` hands out at most one live INeuray per loaded library image, + // so several self-owned Core instances (one per ANARI device) share a single + // refcounted SDK instance. The SDK is shut down and unloaded once the last + // Core is destroyed. Alternatively an externally owned INeuray can be passed + // in, in which case its lifetime and logging stay with the caller. Core(); Core(mi::base::ILogger *logger); Core(mi::neuraylib::INeuray *neuray); @@ -72,9 +80,9 @@ class Core const mi::neuraylib::IModule *accessModule( std::string_view moduleName, mi::neuraylib::ITransaction *transaction); - // The main neuray interface can only be acquired once. Make sure it can be - // shared if taken from there. The original subsystem keeps the ownership of - // the returned value. + // The returned instance is shared with every other Core in this process and + // possibly with the application. Ownership stays with the original + // subsystem; do not start or shut it down. mi::neuraylib::INeuray *getINeuray() const; mi::neuraylib::IMdl_factory *getMdlFactory() const; @@ -152,8 +160,8 @@ class Core std::string_view moduleSource, mi::neuraylib::ITransaction *transaction); - using DllHandle = void *; - DllHandle m_dllHandle; + // Null when an externally owned INeuray was provided. + std::shared_ptr m_shared; mi::base::Handle m_neuray; mi::base::Handle m_globalScope; mi::base::Handle m_mdlFactory; From 55e9c530b778d2c2bf5d2f4aa79db554399010c2 Mon Sep 17 00:00:00 2001 From: Thomas Arcila <134677+tarcila@users.noreply.github.com> Date: Wed, 28 Oct 2026 19:10:32 +0000 Subject: [PATCH 2/2] Combine MDL search paths across devices sharing one SDK instance MDL search paths are a property of the INeuray instance, and every device in a process shares one. IMdl_configuration offers only add_mdl_path and clear_mdl_paths -- no way to withdraw a single root or to add one on behalf of a particular owner -- so a device applying its own `mdlSearchPaths` had to clear first and silently dropped every other device's roots. A device updating its own parameter does want its previous roots retired, so neither "always clear" nor "never clear" is correct. detail::SearchPathRegistry keeps each Core's contribution separately, keyed by instance and then by owner, and rebuilds the instance's list as their union on every change. Setting one device's roots leaves the others' in place; re-setting the same device's parameter replaces only that device's contribution; destroying a device withdraws it. Duplicates are added once, and the system and user paths are re-appended after every rebuild since the clear removes those too. Keyed on the INeuray rather than on VisRTX's shared-instance object, so it equally covers devices that adopted an application-supplied instance through the `ineuray` parameter -- previously those bypassed the union entirely and cleared the shared list outright. Withdrawing a root does not unload a module: one already loaded stays in the MDL database and keeps resolving by name whatever the search paths later say (verified against the SDK). TestMdlSearchPaths therefore asserts that new roots start resolving rather than that retired ones stop. It writes a module per directory, each emitting on a different channel, and loads them by module name so resolution has to come off the search path; the rendered pixel identifies which module was found and a black pixel means the root was lost. It covers three concurrent devices with disjoint roots, devices leaving, a device updating its own roots, and a device updating them while another is live. The last case fails without this change. docs/mdl-search-paths.md records the constraint and the module-caching caveat. Review follow-ups in this commit: forget() rebuilds before erasing the last owner's entry, so a departed owner's roots do not stay installed on an instance that outlives it; both path kinds stringify with generic_string() so de-duplication is consistent on Windows; and the docs and JSON now say the union covers participating VisRTX devices rather than every user of a shared instance, and that precedence between conflicting roots is unspecified. --- devices/rtx/apps/tests/api/CMakeLists.txt | 2 + .../rtx/apps/tests/api/TestMdlSearchPaths.cpp | 266 ++++++++++++++++++ devices/rtx/device/visrtx_material_mdl.json | 4 +- devices/rtx/docs/mdl-instance-sharing.md | 4 +- devices/rtx/docs/mdl-search-paths.md | 63 +++++ devices/rtx/libmdl/Core.cpp | 132 ++++++++- 6 files changed, 453 insertions(+), 18 deletions(-) create mode 100644 devices/rtx/apps/tests/api/TestMdlSearchPaths.cpp create mode 100644 devices/rtx/docs/mdl-search-paths.md diff --git a/devices/rtx/apps/tests/api/CMakeLists.txt b/devices/rtx/apps/tests/api/CMakeLists.txt index 61aba3364..4784f628d 100644 --- a/devices/rtx/apps/tests/api/CMakeLists.txt +++ b/devices/rtx/apps/tests/api/CMakeLists.txt @@ -126,6 +126,8 @@ if (VISRTX_ENABLE_MDL_SUPPORT) add_test(NAME TestMdlModuleReuseSerial COMMAND TestMdlModuleReuse) set_tests_properties(TestMdlModuleReuseSerial PROPERTIES ENVIRONMENT "VISRTX_MDL_COMPILE_THREADS=1" TIMEOUT 120) + make_test(TestMdlSearchPaths) + set_tests_properties(TestMdlSearchPaths PROPERTIES TIMEOUT 300) make_test(TestMdlIneurayHandoff) make_test(TestMdlIneurayIntrospect) set_tests_properties(TestMdlIneurayHandoff TestMdlIneurayIntrospect diff --git a/devices/rtx/apps/tests/api/TestMdlSearchPaths.cpp b/devices/rtx/apps/tests/api/TestMdlSearchPaths.cpp new file mode 100644 index 000000000..9eccbe805 --- /dev/null +++ b/devices/rtx/apps/tests/api/TestMdlSearchPaths.cpp @@ -0,0 +1,266 @@ +// Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. +// SPDX-License-Identifier: BSD-3-Clause + +// MDL search paths belong to the INeuray instance, not to a device, and every +// device in a process shares one instance. So a device setting its roots must +// not drop another device's, and changing a device's `mdlSearchPaths` +// parameter must make the new roots resolve. +// +// Each case renders a quad whose MDL material lives in a per-device directory: +// the material emits on a known channel, so the rendered pixel says which +// module was actually resolved, and a black pixel means the search path was +// lost. +// +// Note what is deliberately *not* asserted: that a retired root stops +// resolving. A module already loaded stays in the MDL database and keeps +// resolving by name no matter what the search paths later say (verified +// against the SDK), so retirement is only observable for modules that were +// never loaded. + +#define ANARI_EXTENSION_UTILITY_IMPL +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using Vec3 = std::array; +using Vec4 = std::array; + +namespace { + +int failures = 0; + +void check(bool ok, const char *what) +{ + std::printf("%-62s %s\n", what, ok ? "ok" : "FAILED"); + if (!ok) + ++failures; +} + +void status(const void *, + ANARIDevice, + ANARIObject, + ANARIDataType, + ANARIStatusSeverity severity, + ANARIStatusCode, + const char *message) +{ + if (severity == ANARI_SEVERITY_FATAL_ERROR) + std::fprintf(stderr, "FATAL: %s\n", message); +} + +// A module whose single material emits on `channel` only. +std::string moduleSource(int channel) +{ + return "mdl 1.6; import ::df::*; export material emitter() = material(" + "surface: material_surface(emission: material_emission(" + "emission: df::diffuse_edf(), intensity: color(" + + std::to_string(channel == 0 ? 4.f : 0.f) + ", " + + std::to_string(channel == 1 ? 4.f : 0.f) + ", " + + std::to_string(channel == 2 ? 4.f : 0.f) + "))));"; +} + +std::string writeModule( + const std::filesystem::path &dir, const std::string &name, int channel) +{ + std::filesystem::create_directories(dir); + std::ofstream out(dir / (name + ".mdl")); + out << moduleSource(channel); + return "::" + name; +} + +struct Setup +{ + anari::Device device{}; + anari::Frame frame{}; + anari::Material material{}; +}; + +// A device rendering a quad with the named MDL module, loaded by name so it +// has to come off the search path. +Setup makeSetup(const std::string &searchPath, const std::string &moduleName) +{ + Setup setup; + setup.device = makeVisRTXDevice(status); + anari::setParameter(setup.device, setup.device, "mdlSearchPaths", searchPath); + anari::commitParameters(setup.device, setup.device); + + const std::array vertices = {Vec3{-1.f, -1.f, 0.f}, + Vec3{1.f, -1.f, 0.f}, + Vec3{1.f, 1.f, 0.f}, + Vec3{-1.f, 1.f, 0.f}}; + const std::array, 2> indices = { + std::array{0, 1, 2}, std::array{0, 2, 3}}; + auto geometry = anari::newObject(setup.device, "triangle"); + anari::setParameterArray1D(setup.device, + geometry, + "vertex.position", + vertices.data(), + vertices.size()); + anari::setParameterArray1D(setup.device, + geometry, + "primitive.index", + indices.data(), + indices.size()); + anari::commitParameters(setup.device, geometry); + + setup.material = anari::newObject(setup.device, "mdl"); + anari::setParameter(setup.device, setup.material, "sourceType", "module"); + anari::setParameter(setup.device, setup.material, "source", moduleName); + anari::setParameter(setup.device, setup.material, "materialName", "emitter"); + anari::commitParameters(setup.device, setup.material); + + auto surface = anari::newObject(setup.device); + anari::setAndReleaseParameter(setup.device, surface, "geometry", geometry); + anari::setParameter(setup.device, surface, "material", setup.material); + anari::commitParameters(setup.device, surface); + + auto world = anari::newObject(setup.device); + anari::setParameterArray1D(setup.device, world, "surface", &surface, 1); + anari::commitParameters(setup.device, world); + anari::release(setup.device, surface); + + auto camera = anari::newObject(setup.device, "orthographic"); + anari::setParameter(setup.device, camera, "position", Vec3{0.f, 0.f, 3.f}); + anari::setParameter(setup.device, camera, "direction", Vec3{0.f, 0.f, -1.f}); + anari::setParameter(setup.device, camera, "up", Vec3{0.f, 1.f, 0.f}); + anari::setParameter(setup.device, camera, "height", 2.f); + anari::setParameter(setup.device, camera, "aspect", 1.f); + anari::commitParameters(setup.device, camera); + + auto renderer = anari::newObject(setup.device, "quality"); + anari::setParameter( + setup.device, renderer, "background", Vec4{0.f, 0.f, 0.f, 1.f}); + anari::setParameter(setup.device, renderer, "ambientRadiance", 0.f); + anari::setParameter(setup.device, renderer, "pixelSamples", 1); + anari::commitParameters(setup.device, renderer); + + setup.frame = anari::newObject(setup.device); + anari::setParameter( + setup.device, setup.frame, "size", std::array{32, 32}); + anari::setParameter( + setup.device, setup.frame, "channel.color", ANARI_FLOAT32_VEC4); + anari::setAndReleaseParameter(setup.device, setup.frame, "camera", camera); + anari::setAndReleaseParameter( + setup.device, setup.frame, "renderer", renderer); + anari::setAndReleaseParameter(setup.device, setup.frame, "world", world); + anari::commitParameters(setup.device, setup.frame); + return setup; +} + +// True if the quad emits on `channel`, i.e. the expected module resolved. +bool renders(const Setup &setup, int channel) +{ + anari::render(setup.device, setup.frame); + anari::wait(setup.device, setup.frame); + auto pixels = anari::map(setup.device, setup.frame, "channel.color"); + if (!pixels.data) { + anari::unmap(setup.device, setup.frame, "channel.color"); + return false; + } + const auto &pixel = pixels.data[16 * 32 + 16]; + bool ok = true; + for (int c = 0; c < 3; ++c) { + if (!std::isfinite(pixel[c])) + ok = false; + else if (c == channel) + ok = ok && pixel[c] > 0.1f; + else + ok = ok && std::abs(pixel[c]) < 0.001f; + } + anari::unmap(setup.device, setup.frame, "channel.color"); + return ok; +} + +void releaseSetup(const Setup &setup) +{ + anari::release(setup.device, setup.material); + anari::release(setup.device, setup.frame); + anari::release(setup.device, setup.device); +} + +} // namespace + +int main() +{ + const auto root = std::filesystem::temp_directory_path() + / ("visrtx_mdl_paths_" + std::to_string(::getpid())); + std::filesystem::remove_all(root); + const auto first = writeModule(root / "first", "visrtx_paths_first", 0); + const auto second = writeModule(root / "second", "visrtx_paths_second", 1); + const auto third = writeModule(root / "third", "visrtx_paths_third", 2); + + // 1. Two devices with disjoint roots. Both share one INeuray, so the second + // device's roots must not displace the first device's. + { + auto a = makeSetup((root / "first").string(), first); + check(renders(a, 0), "first device resolves its own module"); + + auto b = makeSetup((root / "second").string(), second); + check(renders(b, 1), "second device resolves its own module"); + check(renders(a, 0), "first device still resolves after the second joined"); + + // A third device must see neither of the others' roots displaced. + auto c = makeSetup((root / "third").string(), third); + check(renders(c, 2), "third device resolves its own module"); + check(renders(a, 0) && renders(b, 1), + "first and second survive a third device"); + + releaseSetup(c); + check(renders(a, 0) && renders(b, 1), + "survivors unaffected by a device leaving"); + releaseSetup(b); + check(renders(a, 0), "first device unaffected by the second leaving"); + releaseSetup(a); + } + + // 2. Updating a device's own paths. The new roots must take effect, and the + // retired ones must stop resolving -- a device that only ever added would + // silently keep stale roots alive for every other device too. + { + auto a = makeSetup((root / "first").string(), first); + check(renders(a, 0), "device resolves its initial root"); + + // Point the same device at a different root and rebuild the material. + anari::setParameter( + a.device, a.device, "mdlSearchPaths", (root / "second").string()); + anari::commitParameters(a.device, a.device); + anari::setParameter(a.device, a.material, "source", second); + anari::commitParameters(a.device, a.material); + check(renders(a, 1), "device resolves a module from its new root"); + + releaseSetup(a); + } + + // 3. One device changing its roots must not disturb another device's. + { + auto a = makeSetup((root / "first").string(), first); + auto b = makeSetup((root / "second").string(), second); + anari::setParameter( + a.device, a.device, "mdlSearchPaths", (root / "third").string()); + anari::commitParameters(a.device, a.device); + anari::setParameter(a.device, a.material, "source", third); + anari::commitParameters(a.device, a.material); + check(renders(a, 2), "device resolves a module from its updated root"); + check(renders(b, 1), "the other device is unaffected by that update"); + releaseSetup(b); + releaseSetup(a); + } + + std::filesystem::remove_all(root); + + if (failures) { + std::fprintf(stderr, "FAIL: %d search-path check(s) failed\n", failures); + return 1; + } + std::puts("MDL search paths combine across devices and track updates"); + return 0; +} diff --git a/devices/rtx/device/visrtx_material_mdl.json b/devices/rtx/device/visrtx_material_mdl.json index 858300bb9..34ef7f284 100644 --- a/devices/rtx/device/visrtx_material_mdl.json +++ b/devices/rtx/device/visrtx_material_mdl.json @@ -20,13 +20,13 @@ "name": "mdlSearchPaths", "types": ["ANARI_STRING"], "tags": [], - "description": "Platform-separated list (`:` on POSIX, `;` on Windows) of MDL module search roots. System and user paths are always appended." + "description": "Platform-separated list (`:` on POSIX, `;` on Windows) of MDL module search roots. Search paths belong to the MDL SDK instance rather than to a device, so the roots set here are combined with those of every other VisRTX device sharing that instance rather than replacing them; re-setting this parameter replaces only this device's contribution. Roots installed directly on a shared instance by the application or by another vendor's device are not known to VisRTX and are not preserved. System and user paths are always appended. Note that a module already loaded keeps resolving by name even after its root is withdrawn." }, { "name": "mdlResourceSearchPaths", "types": ["ANARI_STRING"], "tags": [], - "description": "Platform-separated list of search roots for MDL resources (textures, light profiles)." + "description": "Platform-separated list of search roots for MDL resources (textures, light profiles). Combined across VisRTX devices sharing one MDL SDK instance, like `mdlSearchPaths`, with the same caveat about roots VisRTX did not install." } ], "properties" : [ diff --git a/devices/rtx/docs/mdl-instance-sharing.md b/devices/rtx/docs/mdl-instance-sharing.md index 2be2e6d14..3d85ac89d 100644 --- a/devices/rtx/docs/mdl-instance-sharing.md +++ b/devices/rtx/docs/mdl-instance-sharing.md @@ -17,8 +17,8 @@ application. Two consequences follow from the instance being shared, both of which the implementation has to handle because they used to be per-device: -- **Search paths** are a property of the `INeuray` instance, not of a device, - so one device setting them affects every device sharing that instance. +- **Search paths** are a property of the `INeuray` instance, not of a device. + See `mdl-search-paths.md`. - **Logging** has a single receiving logger per instance. See below. ## Logging diff --git a/devices/rtx/docs/mdl-search-paths.md b/devices/rtx/docs/mdl-search-paths.md new file mode 100644 index 000000000..cbb58d4a0 --- /dev/null +++ b/devices/rtx/docs/mdl-search-paths.md @@ -0,0 +1,63 @@ +# MDL search paths across devices + +MDL search paths are a property of the `INeuray` instance, not of a device, +and every device in a process shares one instance +(`mdl-instance-sharing.md`). Two consequences follow. + +## The SDK only offers clear-and-rebuild + +`IMdl_configuration` exposes `add_mdl_path` and `clear_mdl_paths`, with no way +to withdraw a single root or to add one on behalf of a particular owner. A +device that simply applied its own parameter would therefore have to clear +first, silently dropping every other device's roots — and dropping its own +previous roots is exactly what it *does* want, so neither "always clear" nor +"never clear" is right. + +`detail::SearchPathRegistry` in `libmdl/Core.cpp` keeps each `Core`'s +contribution separately, keyed by instance and then by owner, and rebuilds the +instance's path list as their union on every change. So: + +- setting one device's `mdlSearchPaths` leaves the others' roots in place; +- re-setting the same device's parameter replaces only that device's + contribution, retiring its previous roots; +- destroying a device withdraws its contribution. + +Duplicate roots across devices are added once. System and user paths are +re-appended after every rebuild, since the clear removes them too. + +Two limits follow from the clear-and-rebuild shape: + +- The registry only knows roots that went through it. On an + application-supplied instance, roots the application or another vendor's + device installed directly are not preserved across a rebuild — and + symmetrically, another vendor doing its own clear-and-rebuild would drop + VisRTX's. The guarantee covers participating VisRTX devices, not arbitrary + users of a shared instance. +- Contributions are keyed by owner address, so the order roots are applied in + is unspecified. If two devices supply roots that each contain a module of + the same name, which one resolves is unspecified. + +The registry is keyed on the `INeuray*` rather than on VisRTX's internal +shared-instance object, so it equally covers devices that adopted an +application-supplied instance through the `ineuray` parameter. + +## Withdrawing a root does not unload a module + +A module that has been loaded stays in the MDL database and keeps resolving by +name no matter what the search paths later say. Verified against the SDK: +after loading `::m` and then clearing the search paths, `load_module("::m")` +still succeeds. + +So withdrawing a root only affects modules that have not been loaded yet. This +is SDK behaviour, not something the registry can change, and it is why +`TestMdlSearchPaths` asserts that new roots *start* resolving rather than that +retired roots stop. + +## Testing + +`TestMdlSearchPaths` writes a module per directory, each emitting on a +different colour channel, and loads them by module name so resolution has to +come off the search path. The rendered pixel identifies which module was +found; a black pixel means the root was lost. It covers up to three concurrent +devices with disjoint roots, devices leaving, a device updating its own roots, +and a device updating its roots while another is live. diff --git a/devices/rtx/libmdl/Core.cpp b/devices/rtx/libmdl/Core.cpp index 0f4cebbbe..6cb126dee 100644 --- a/devices/rtx/libmdl/Core.cpp +++ b/devices/rtx/libmdl/Core.cpp @@ -262,6 +262,118 @@ std::shared_ptr acquireSharedNeuray( } // namespace +// MDL search paths are a property of the INeuray instance, and every Core +// sharing that instance sets them independently -- including Cores that merely +// adopted an application-supplied instance. The SDK offers no way to add a +// path on behalf of one owner, only clear-and-rebuild, so the latest caller +// would silently drop every other Core's roots. Keep each Core's contribution +// and re-apply their union on every change. +// +// Keyed on the instance rather than on a SharedNeuray, so an externally +// supplied INeuray shared by several Cores is handled the same way. +class SearchPathRegistry +{ + public: + using Paths = std::vector; + + static SearchPathRegistry &instance() + { + static SearchPathRegistry registry; + return registry; + } + + void setMdlPaths( + mi::neuraylib::INeuray *neuray, const void *owner, Paths paths) + { + std::lock_guard guard(m_mutex); + auto &entry = m_entries[neuray]; + entry.mdl[owner] = std::move(paths); + applyMdl(neuray, entry); + } + + void setResourcePaths( + mi::neuraylib::INeuray *neuray, const void *owner, Paths paths) + { + std::lock_guard guard(m_mutex); + auto &entry = m_entries[neuray]; + entry.resource[owner] = std::move(paths); + applyResource(neuray, entry); + } + + // Drop an owner's contribution and re-apply what is left. The instance is + // passed in because a Core is forgotten while its handle is still valid. + void forget(mi::neuraylib::INeuray *neuray, const void *owner) + { + std::lock_guard guard(m_mutex); + const auto it = m_entries.find(neuray); + if (it == m_entries.end()) + return; + auto &entry = it->second; + const bool hadMdl = entry.mdl.erase(owner) != 0; + const bool hadResource = entry.resource.erase(owner) != 0; + // Rebuild before forgetting the instance, or the departed owner's roots + // stay installed on an INeuray that outlives us -- an application-supplied + // instance, typically. + if (hadMdl) + applyMdl(neuray, entry); + if (hadResource) + applyResource(neuray, entry); + if (entry.mdl.empty() && entry.resource.empty()) { + // Last owner gone: forget the instance too, so a later instance that + // reuses the address does not inherit stale contributions. + m_entries.erase(it); + } + } + + private: + // Keyed by owner address, so the order in which contributions are applied + // is unspecified. Where two devices supply roots containing a module of the + // same name, which one wins is therefore unspecified too -- documented in + // docs/mdl-search-paths.md rather than papered over with an arbitrary rule. + struct Entry + { + std::map mdl; + std::map resource; + }; + + static void applyMdl(mi::neuraylib::INeuray *neuray, const Entry &entry) + { + auto mdlConfiguration = make_handle( + neuray->get_api_component()); + mdlConfiguration->clear_mdl_paths(); + std::set seen; + for (const auto &[owner, paths] : entry.mdl) { + for (const auto &path : paths) { + auto asString = path.generic_string(); + if (seen.insert(asString).second) + mdlConfiguration->add_mdl_path(asString.c_str()); + } + } + mdlConfiguration->add_mdl_system_paths(); + mdlConfiguration->add_mdl_user_paths(); + } + + static void applyResource(mi::neuraylib::INeuray *neuray, const Entry &entry) + { + auto mdlConfiguration = make_handle( + neuray->get_api_component()); + mdlConfiguration->clear_resource_paths(); + std::set seen; + for (const auto &[owner, paths] : entry.resource) { + for (const auto &path : paths) { + // generic_string() throughout, so the same root spelled two ways + // de-duplicates on Windows as well as POSIX. + auto asString = path.generic_string(); + if (seen.insert(asString).second) + mdlConfiguration->add_resource_path(asString.c_str()); + } + } + } + + std::mutex m_mutex; + std::map m_entries; +}; + } // namespace detail Core::Core() : Core({}, {}) {} @@ -349,6 +461,8 @@ Core::~Core() m_executionContext = {}; m_mdlFactory = {}; m_globalScope = {}; + if (m_neuray.is_valid_interface()) + detail::SearchPathRegistry::instance().forget(m_neuray.get(), this); m_logger = {}; m_neuray = {}; // Shuts down and unloads the SDK if this was the last live Core. @@ -748,25 +862,15 @@ auto Core::getLogger() const -> mi::base::ILogger * auto Core::setMdlSearchPaths(nonstd::span paths) -> void { - auto mdlConfiguration = make_handle( - m_neuray->get_api_component()); - mdlConfiguration->clear_mdl_paths(); - for (const auto &path : paths) { - mdlConfiguration->add_mdl_path(path.generic_string().c_str()); - } - mdlConfiguration->add_mdl_system_paths(); - mdlConfiguration->add_mdl_user_paths(); + detail::SearchPathRegistry::instance().setMdlPaths( + m_neuray.get(), this, {std::cbegin(paths), std::cend(paths)}); } auto Core::setMdlResourceSearchPaths(nonstd::span paths) -> void { - auto mdlConfiguration = make_handle( - m_neuray->get_api_component()); - mdlConfiguration->clear_resource_paths(); - for (const auto &path : paths) { - mdlConfiguration->add_resource_path(path.generic_string().c_str()); - } + detail::SearchPathRegistry::instance().setResourcePaths( + m_neuray.get(), this, {std::cbegin(paths), std::cend(paths)}); } auto Core::resolveResource(std::string_view resourceId,