Performance notes and the C++ API reference
Performance notes
rayrai defaults to one simulation/render thread. Applications that explicitly
opt into ThreadingMode::MultiThread use one renderer and current OpenGL
context per worker, as described in rayrai Visualizer. The renderer keeps the
main performance controls explicit:
Disable shadows for high-throughput camera observations when shadows are not part of the desired output. Use
RenderOverrides::doShadows = falseor disable the light’s shadow map globally.Prefer
addInstancedVisualsfor repeated primitives or meshes. A single instanced visual renders many copies with one instance buffer instead of many separate visual objects.Opaque RaiSim single-body primitives (spheres, boxes, cylinders, capsules) are batched into instanced draws in shadow-map passes and in simple-shading color passes. With PBR primitives (
Balancedand above) the color pass batches them only in renders without shadows.TCP viewer scenes synthesize repeated articulated mesh visuals into internal
InstancedVisualsbatches when mesh path, scale, color policy, and color match.RemoteScene::tcpMeshBatchCount()andtcpMeshBatchMeshColorCount()expose diagnostics for this path.Use
InstancedVisuals::setMaxRenderedInstancesandPointCloud::setMaxRenderedPointsas simple LOD caps for debug overlays, particles, scans, or dense markers that do not need full density in every frame.Keep non-visible debug geometry outside the camera frustum when possible. rayrai performs coarse frustum culling for RaiSim objects, custom visuals, instanced visuals, and point clouds, so off-camera content is skipped before draw submission. Mesh-local bounds are used when available, so offset meshes, articulated links, deformables, and heightmaps cull and frame from their rendered bounds rather than only from the object origin.
Scenes with many local lights can give point, spot and area lights a finite range with
additionalLightContributionThreshold(see Render quality, tone mapping, color grading).updateObjectLists()copies only what changed in the bound World: an unchanged object costs a revision check, and the object cache is rebuilt only when objects are added or removed. A heightmap edit copies and uploads only the rows it changes.rayrai_world_sync_benchmarkmeasures the copy and a small frame for moving boxes, robots, edited heightmaps and a deformable terrain.RGB/depth CPU readback supports an optional PBO-backed asynchronous path. The synchronous path remains the deterministic default for simple RL loops.
Dynamic point clouds and instanced visuals support partial buffer updates for streaming changes.
Deformable TCP streaming sends topology/indices only during initialization or topology changes; normal frames send vertex positions only.
Physics snapshots for independent cameras
Use Physics snapshots to separate physics capture from camera rendering. Capture a shared immutable frame immediately after integration under the World mutex, then apply and render it on the owning GL thread after releasing that mutex. The capture pool reuses buffers only after consumers release them. Persistent shape descriptions are shared, articulated frames contain one pose per link, and geometry and appearance have separate revisions. Membership is reconciled only when it changes; dynamic mesh updates preserve unchanged indices and heightmap patch ranges.
The source target rayrai_physics_snapshot_benchmark measures capture/apply
for 1,000 unchanged and moving boxes after warmup, excluding rendering and
readback. The dedicated guide includes API examples, the latest-frame mailbox
pattern, copied RGB/depth camera state, and lifetime rules.
Animated articulated visuals retain their loaded meshes when only scale, local pose, link attachment or color changes. Candidate bounds and shadows follow transform edits. Replacing a mesh file or resizing a capsule retains unrelated model assets while acquiring the new geometry; see Physics snapshots for the visual fields to edit.
The engine source target rayrai_animated_mesh_reuse_test --benchmark
measures capture/apply while a robot’s authored mesh scale changes over 1,000
updates. It releases frame-scoped asset owners as rendering does and reports
animated_mesh_apply_us and model_reloads. With unchanged model files,
model_reloads should remain zero. Run with one thread and a working
OpenGL context, for example from a standalone visualizer build:
OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 MKL_NUM_THREADS=1 LP_NUM_THREADS=1 \
./build-visualizer/rayrai/rayrai_animated_mesh_reuse_test --benchmark
The test without --benchmark checks synchronous and asynchronous loading,
both applied snapshots and a bound World, rendered depth, capsule resizing,
and mesh-file replacement.
GPU paths and OpenGL requirements
Several instanced-rendering paths run on the GPU when the context supports them and fall back automatically otherwise:
Instanced visuals with 4096 or more rendered instances are culled with a compute shader (OpenGL 4.3). Without it, culling runs on the CPU.
Instanced meshes made of several submeshes can be submitted with multi-draw-indirect (OpenGL 4.3 or
GL_ARB_multi_draw_indirect); otherwise each submesh is drawn separately.Foliage visuals with 4096 or more instances are occlusion-culled against opaque geometry already drawn in the frame, using a hierarchical depth pyramid or occlusion queries. The compute-shader pyramid needs OpenGL 4.3.
With OpenGL 4.3 and MSAA, foliage is also culled against the depth rendered so far in the same frame (see Dense foliage).
Most of these fallbacks print a one-time WARN line to stderr; the matching
RAYRAI_SUPPRESS_*_FALLBACK_WARNINGS variable silences it (see
Environment variables).
macOS provides OpenGL 4.1 (no compute shaders or multi-draw-indirect), so it uses the fallback of every path above; see Platform support. The renderer also selects a full, compact or limited shader tier from the number of fragment texture units when it is constructed; the lower tiers render fewer material and post-process features (see GPU capability tiers).
Dense foliage
Instanced visuals with alpha-masked foliage materials use a dedicated path with no extra API calls:
Compatible foliage draws in the color and shadow passes are merged into batched runs. Other objects between them split a run instead of disabling batching.
Visibility, and for larger plants the LOD level, are chosen per instance and per submesh from the automatic mesh LOD chain. A level is used when its projected simplification error is at most 2.25 pixels, or 2.5 shadow-map texels in shadow passes.
RAYRAI_FOLIAGE_LOD_PIXEL_ERRORandRAYRAI_FOLIAGE_SHADOW_LOD_PIXEL_ERRORoverride these budgets for the whole process (values in(0, 8]).With OpenGL 4.3 and MSAA, passes that contain a foliage visual with 2048 or more instances cull foliage against the depth already rendered in the same frame, tested in 8-pixel tiles that cover every sample.
Foliage casts shadows by default. Call
setCastsShadows(false)on anInstancedVisualsto exclude it; wind and grass-patch configuration keep that choice. When the main viewer refreshes cascaded shadows every frame, foliage that cannot shadow anything inside a cascade’s part of the view is skipped for that cascade.With asynchronous mesh loading (Capture, diagnostics, and headless rendering), file imports, texture decoding, base geometry and instanced LOD chains are prepared on worker threads: imports and texture decodes share up to eight, up to half the hardware threads prepare geometry and LOD chains of different assets at once, and a large LOD chain builds up to three of its levels at once. Larger models go first: their textures decode first and their stages run first on the render thread, which only builds materials and issues uploads. With OpenGL 4.4 (or
GL_ARB_buffer_storage) the workers copy textures and vertex buffers into persistently mapped staging buffers, so an upload is a GPU copy; a context holds up to two 128 MiB blocks of them while it loads. Eachupdate()and external-camera render spends up to 8 ms of render-thread time on loading (one stage runs even when it takes longer), so a scene of many assets loads in a few frames. EachpollAsyncMeshLoads(n)call advances at mostnimport/upload stages (0does nothing) and uploads at most one prepared submesh per pending instanced visual;pendingAsyncMeshLoadCount()includes these jobs. Prepared LOD chains are cached on disk (see On-disk caches).rayrai/Bc7TextureStorage.hppprovides an opt-in load-time helper,raisin::compressRgbTextureBc7(texture), that re-stores an RGB8/SRGB8 texture and all of its mip levels as BC7. It needs OpenGL 4.2 orGL_ARB_texture_compression_bptc(checksupportsBc7TextureStorage()) and is lossy. Alpha, float, immutable and already compressed textures are left unchanged.
Frame submission and measurement
The renderer applies these submission optimizations automatically; none of them changes the rendered image:
After shadow maps or the planar reflection were rendered in a frame, one
glFlushsubmits them so the GPU works on them while the CPU encodes the scene pass. This lowers frame time at the cost of some process CPU time. TheRAYRAI_DEBUG_DISABLE_PASS_FLUSH=1debug switch skips this flush.The environment background is drawn inside the scene pass. After an opaque depth prepass it is depth-tested, so only pixels that no surface covers are shaded.
environmentBackgroundDiagnostics()reports how the last scene pass drew it.The transparent pass skips the proximity-fade depth copy and the screen-space refraction capture when no drawn material samples them.
An external
Camerakeeps its multisampled render target between frames; the next render of that camera without MSAA releases it.Camera::setSceneMsaaSamples(samples, keepAllocation)exposes the same behavior.
While RenderQualitySettings::geometryRefraction is on, the frame caches that
let unchanged external-camera renders reuse earlier results are bypassed, so
every render is drawn in full.
captureViewerPassTimings(width, height) renders the built-in viewer camera
once with blocking GPU timer queries (the renderer’s context must be current)
and returns the shadow, scene_color_and_resolve and postprocess
passes. captureRenderPassTimings does the same for an external camera. When
foliage instanced visuals are present, both render a second frame and append
shadow_foliage* and scene_foliage* entries that are nested inside the
coarse passes. shadowCacheDiagnostics(), foliageRenderDiagnostics() and
conservativeOcclusionCullingDiagnostics() report shadow-map reuse and
culling without extra GPU work.
Shader binary cache and multi-threaded prewarming
rayrai’s PBR shaders compile in 10-30 seconds on first run depending on the GL driver. Two features (available since v2.3.0) remove that wait in production RL pipelines:
Persistent shader binary cache. Compiled GL programs are written to a per-driver cache directory and reloaded on subsequent runs.
Static prewarm helper for multi-threaded RL setups where many worker threads will each construct their own
RayraiWindow— one thread can pre-compile every shader, then every worker thread reads from the cache.
Both are wired through the RayraiWindow constructor:
raisin::RayraiWindow viewer(
world,
/*width=*/1280, /*height=*/720,
raisin::RayraiWindow::ThreadingMode::SingleThread,
/*shaderCompileThreadCount=*/1, // 1 = matches rayrai's default
/*shaderBinaryCacheEnabled=*/true, // on by default
/*shaderBinaryCacheDirectory=*/"", // empty → default location
/*logShaderBinaryCache=*/false);
shaderCompileThreadCountis passed toglMaxShaderCompilerThreadsARBon drivers that exposeGL_ARB_parallel_shader_compileand is ignored elsewhere. Raise it only when the host application is itself multi-threaded.shaderBinaryCacheEnabled = true(the default) writes program binaries under the cache directory keyed by GL vendor / renderer / version + GLSL source, when the driver reports at least one program binary format. On the next run, identical configurations are loaded directly, skipping the GLSL compile entirely. Several processes can share one cache directory.shaderBinaryCacheDirectory = ""uses the first writable directory in this order, then falls back to<temp>/raisim/rayrai:Linux:
$XDG_CACHE_HOME/raisim/rayrai,~/.cache/raisim/rayrai,~/.raisim/rayraimacOS:
$XDG_CACHE_HOME/raisim/rayrai,~/Library/Caches/raisim/rayrai,~/.cache/raisim/rayrai,~/.raisim/rayraiWindows:
%LOCALAPPDATA%\RaiSim\rayrai,%HOME%\.raisim\rayrai(whenHOMEis set),%USERPROFILE%\AppData\Local\RaiSim\rayrai,%USERPROFILE%\.raisim\rayrai
logShaderBinaryCache = trueprints every hit/miss/store to stderr — useful for verifying the cache is actually being consulted.
The compile thread count and the cache settings are process-wide: each
RayraiWindow constructor applies its arguments to the whole process, so pass
the same values to every renderer, including a prewarmer.
Cache statistics (per process, across all Shader::compile calls):
auto s = raisin::Shader::binaryCacheStats();
std::printf("hits=%llu misses=%llu stores=%llu coordinated_waits=%llu\n",
static_cast<unsigned long long>(s.hits),
static_cast<unsigned long long>(s.misses),
static_cast<unsigned long long>(s.stores),
static_cast<unsigned long long>(s.coordinatedWaits));
raisin::Shader::resetBinaryCacheStats(); // scope a measurement window
Pre-warming for parallel RL can be done with the rayrai_shader_prewarm
utility when it is available in the rayrai package. The utility creates an
offscreen context and compiles every built-in shader into the persistent binary
cache:
rayrai_shader_prewarm --cache-dir /tmp/rayrai-cache --compile-threads 4 --multi-thread
rayrai_shader_prewarm --log-cache
For an embedded application, create an offscreen context on the main thread,
release it, and call prewarmShadersForCurrentContext once from a background
thread that adopts it. SDL windows must be created and destroyed on the main
thread, and every renderer in the process, including the prewarmer, must use
the same ThreadingMode. Worker threads that later construct their own
RayraiWindow will find the heavy shaders already cached (or briefly block on
a per-shader compile mutex if the warm-up is still in flight):
// Main thread: create the prewarm context, then release it.
SDL_Window* w = nullptr;
SDL_GLContext gl = nullptr;
raisin::RayraiWindow::createOffscreenGlContext(w, gl, "rayrai_prewarm");
raisin::RayraiWindow::detachOffscreenGlContext(w);
std::thread prewarm([w, gl] {
raisin::RayraiWindow::makeOffscreenContextCurrent(w, gl);
raisin::RayraiWindow::prewarmShadersForCurrentContext(
raisin::RayraiWindow::ThreadingMode::MultiThread);
raisin::RayraiWindow::detachOffscreenGlContext(w);
});
// ... start the rendering workers ...
prewarm.join(); // main thread
SDL_GL_DeleteContext(gl);
SDL_DestroyWindow(w);
Pass the workers’ cache directory as the second argument of
prewarmShadersForCurrentContext when they do not use the default location.
With the binary cache enabled, each registered program is compiled from GLSL
once per process, however many worker threads construct renderers.
When you only want to warm a specific subset:
// Names of every program registered with the running RayraiWindow.
auto names = viewer.linkedShaderNames();
// Compile the heaviest authored-content shader explicitly.
long long ms = viewer.compileShaderByName("pbrMeshHigh");
std::printf("pbrMeshHigh warmup: %lld ms\n", ms);
// Iterate every program, one per call. `done` flips true when all are
// linked; useful for spreading shader work across multiple frames.
bool done = false;
while (!done) {
viewer.warmupNextShader(done);
}
For diagnostics on the cost of the lazy-compile pipeline (how long each
program took on first use, how many are linked so far), call
shaderWarmupDiagnostics().
On-disk caches
Besides the shader binary cache, rayrai keeps these caches. All of them are regenerated when missing, so the files can be deleted at any time. The mesh caches are also checked against their source and rebuilt when stale.
Contents |
Default location |
Override |
|---|---|---|
Imported-mesh metadata and generated LOD chains |
|
|
LOD chains prepared by asynchronous loading of instanced meshes, and the prepared geometry and import description of asynchronously loaded models of at least 65,536 vertices |
|
|
Procedural cloud noise textures |
|
|
<temp> is the system temporary directory. The asynchronous LOD and
prepared-geometry sidecars store full vertex data and can be large for dense
assets; an import description holds the model’s materials, its embedded
textures and what the import measured of its meshes.
Environment variables
rayrai reads these variables from the process environment; set them before the
renderer starts. Boolean switches are on when set to a non-empty value that does
not start with 0, unless noted otherwise.
RAYRAI_MESH_PREPROCESS_CACHE_DIR,RAYRAI_ASYNC_LOD_CACHE_DIR,RAYRAI_CLOUD_TEXTURE_CACHE_DIR: cache directories (see On-disk caches).RAYRAI_FOLIAGE_LOD_PIXEL_ERRORandRAYRAI_FOLIAGE_SHADOW_LOD_PIXEL_ERROR: foliage LOD error budgets (defaults2.25pixels and2.5texels; read once per process). The shadow budget follows the color budget when only the latter is set.RAYRAI_SUPPRESS_<PATH>_FALLBACK_WARNINGS: silence the one-time warning of a GPU path fallback, for exampleRAYRAI_SUPPRESS_GPU_INSTANCE_CULLING_FALLBACK_WARNINGS.RAYRAI_FORCE_COMPACT_PBR_SAMPLER_FALLBACKandRAYRAI_FORCE_LIMITED_PBR_SAMPLER_FALLBACK: select the compact or limited shader tier on a larger GPU, for testing.RAYRAI_EAGER_SHADER_WARMUP: compile every registered shader when a renderer is constructed instead of on first use.RAYRAI_PBR_DEBUG_OUTPUT: PBR debug visualization channel (0is off).RayraiWindow::setPbrDebugOutputModeoverrides it for one renderer, andcaptureDebugPassesoverrides it for the frames it renders.
The TCP viewer reads its own RAYRAI_TCP_VIEWER_* variables
(Rayrai TCP Viewer). Variables named RAYRAI_DEBUG_* and
RAYRAI_LOG_* are renderer-development diagnostics (debug switches and
logging) and may change between releases. Apart from these debug switches,
optimizations have no switches to turn them off.
Additional tips
Every
updateand external-camera render callsRayraiWindow::updateObjectLists(), so RaiSim objects added to or removed from the world are picked up automatically. Call it yourself only when the renderer’s object lists must be current before the next render.Use
setShowCollisionBodies(true)for debug visualization of collision shapes.If you want rayrai overlays to use your ImGui font, pass it via
setExternalFont.
API
Core types
-
class RayraiWindow
Offscreen renderer and visual scene manager for raisim.
RayraiWindow maintains an internal Camera, shader set, and a set of visual objects that can be rendered into an offscreen texture. It can render raisim world objects, custom visuals, point clouds, and coordinate frames.
Quick start
auto world = std::make_shared<raisim::World>(); world->addSphere(0.5, 1.0); // A GL context must be current first, e.g.: // SDL_Window* win; SDL_GLContext ctx; // raisin::RayraiWindow::createOffscreenGlContext(win, ctx); raisin::RayraiWindow renderer(world, 1280, 720); // Add a free-standing visual using the glm::vec4 colour overload. renderer.addVisualSphere("marker", 0.25, glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)); // (Optional) IBL: one struct instead of four GL handles. auto env = raisin::PbrEnvironment::loadFromHdrFile("studio.hdr"); // Drive the simulation and render one frame. world->integrate(); renderer.update(1280, 720, false, 0, 0, false); unsigned int textureId = renderer.getImageTexture();
Lifetime
The
shared_ptrconstructor stores the pointer, so the window shares ownership of the world and keeps it alive. Theraisim::World&constructor wraps the reference in a non-owningshared_ptr; that world must outlive the window (or be replaced with swapWorld() before it is destroyed).
GL context
Construction, rendering, resource creation (textures, cubemaps, probes) and destruction issue OpenGL calls, so they must run on the thread that has this renderer’s GL context current (see createOffscreenGlContext()). The pure-CPU helpers (e.g. analyzeRgbaLuminance(), recommendExposure(), loadReflectionProbeSidecar()) do not touch GL.
Error model
Named entities are strict:
addVisual*(),addInstancedVisuals(),addPointCloud()andaddCoordinateFrame()abort (RSFATAL) when the name is already in use, andgetVisualObject(),getInstancedVisuals(),removeVisualObject(),removeInstancedVisuals(),removePointCloud()andremoveCoordinateFrame()abort when it does not exist. UsefindVisualObject()/findInstancedVisuals()for a lookup that returns nullptr instead. A few newer entry points throwstd::invalid_argumentinstead of aborting; this is noted on each of them.The texture and cubemap loaders (
loadTextureWithTiling(),loadHdrEquirectangularCubemap(), …) return 0 on failure.Threading-mode mismatch at construction is fatal (
RSFATAL).Type and limit aliases
Re-exports of namespace-level rayrai types (RenderQuality.hpp, Weather.hpp, SceneEffects.hpp) so they can be spelled
RayraiWindow::X. See the aliased type for its documentation.-
using AdditionalLight = ::raisin::AdditionalLight
Alias of raisin::AdditionalLight (see addAdditionalLight()).
-
using RenderQualityPreset = ::raisin::RenderQualityPreset
Alias of raisin::RenderQualityPreset (see setRenderQualityPreset()).
-
using ViewerColorMode = ::raisin::ViewerColorMode
Alias of raisin::ViewerColorMode.
-
using ColorGradePreset = ::raisin::ColorGradePreset
Alias of raisin::ColorGradePreset.
-
using GlowBlendMode = ::raisin::GlowBlendMode
Alias of raisin::GlowBlendMode (bloom composite mode).
-
using ViewerUpscaleFilter = ::raisin::ViewerUpscaleFilter
Alias of raisin::ViewerUpscaleFilter.
-
using PostProcessDebugMode = ::raisin::PostProcessDebugMode
Alias of raisin::PostProcessDebugMode.
-
using PointShadowPolicy = ::raisin::PointShadowPolicy
Alias of raisin::PointShadowPolicy.
-
using RenderQualitySettings = ::raisin::RenderQualitySettings
Alias of raisin::RenderQualitySettings (see setRenderQualitySettings()).
-
using WeatherPreset = ::raisin::WeatherPreset
Alias of raisin::WeatherPreset (see setWeatherPreset()).
-
using WeatherQuality = ::raisin::WeatherQuality
Alias of raisin::WeatherQuality.
-
using LocalFogVolume = ::raisin::LocalFogVolume
Alias of raisin::LocalFogVolume (see addLocalFogVolume()).
-
using WeatherSettings = ::raisin::WeatherSettings
Alias of raisin::WeatherSettings (see setWeatherSettings()).
-
using WeatherDiagnostics = ::raisin::WeatherDiagnostics
Alias of raisin::WeatherDiagnostics (see weatherDiagnostics()).
-
using WeatherSkyEnvironment = ::raisin::WeatherSkyEnvironment
Alias of raisin::WeatherSkyEnvironment (see generateWeatherSkyEnvironment()).
-
using ProjectedDecal = ::raisin::ProjectedDecal
Alias of raisin::ProjectedDecal (see addProjectedDecal()).
-
using IrradianceVolume = ::raisin::IrradianceVolume
Alias of raisin::IrradianceVolume (see addIrradianceVolume()).
-
static size_t kMaxAdditionalLights
Maximum number of additional lights kept by addAdditionalLight(); extra lights are dropped.
-
static size_t kMaxAdditionalShadowLights
Maximum number of additional lights that can render shadow maps in one frame.
-
static size_t kMaxLocalFogVolumes
Maximum number of local fog volumes kept by addLocalFogVolume().
-
static size_t kMaxProjectedDecals
Maximum number of projected decals kept by addProjectedDecal().
-
static size_t kMaxIrradianceVolumes
Maximum number of irradiance volumes kept by addIrradianceVolume().
Weather
While WeatherSettings::enabled is true, the resolved weather is applied on top of the last settings passed to setRenderQualitySettings(): main light, ambient, sky, clouds and wet/snow materials are overwritten and fog is combined with the user values (see raisin::WeatherSettings). Disabling weather restores the user settings; getUserRenderQualitySettings() returns them meanwhile. Transitions and wetness advance only in updateWeather().
-
using WeatherThunderCallback = std::function<void(const WeatherDiagnostics&)>
Callback invoked from updateWeather() once per new lightning event.
-
void setWeatherSettings(const WeatherSettings &settings)
Apply weather settings immediately.
Values are clamped to their valid ranges, any running transition is cancelled, a generated weather sky environment is released, and the render quality settings are updated (see the group description).
- Parameters:
settings – New weather settings.
-
inline const WeatherSettings &getWeatherSettings() const
- Returns:
Current (clamped) weather settings; mid-transition this is the blended state.
-
void setWeatherThunderCallback(WeatherThunderCallback callback)
Register the lightning/thunder callback (empty function to remove).
Called synchronously on the thread that calls updateWeather(), with the diagnostics of the frame in which a new lightning event started.
- Parameters:
callback – Callback to store.
-
void setWeatherPreset(WeatherPreset preset)
Apply defaultWeatherSettings(
preset) immediately.- Parameters:
preset – Preset to apply.
-
void transitionWeather(WeatherPreset preset, double transitionSeconds)
Blend from the current weather to a preset’s defaults over time.
- Parameters:
preset – Target preset.
transitionSeconds – Duration; <= 0 applies the target immediately.
-
void transitionWeather(const WeatherSettings &target, double transitionSeconds)
Blend from the current weather to
targetover time.The blend advances only in updateWeather().
- Parameters:
target – Target settings.
transitionSeconds – Duration in seconds; <= 0 applies the target immediately.
-
void updateWeather(double dt)
Advance weather transitions, wetness accumulation/drying and lightning.
Call once per frame from the render thread before rendering.
- Parameters:
dt – Elapsed time in seconds (negative values are treated as 0).
-
WeatherDiagnostics weatherDiagnostics() const
Resolved weather state (sun/moon, clouds, fog, precipitation, wetness, lightning). CPU only.
- Returns:
Diagnostics for the current settings.
-
void printWeatherDiagnostics(std::ostream &out) const
Print weatherDiagnostics() in a human-readable multi-line form.
- Parameters:
out – Output stream.
-
WeatherSkyEnvironment generateWeatherSkyEnvironment(int environmentFaceSize = 256, int irradianceFaceSize = 32, bool setVisibleBackground = true)
Generate a weather-driven sky/environment cubemap on demand.
This is intentionally explicit. Applications should call it at weather or time-of-day transition points, not every frame. When setVisibleBackground is true, the generated radiance cubemap is also installed as the visible environment background. The previous generated environment is released first; the textures are owned by the renderer and are also released by clearWeatherSkyEnvironment() and setWeatherSettings(). Requires this renderer’s GL context.
- Parameters:
environmentFaceSize – Radiance cubemap face size, clamped to [16, 2048].
irradianceFaceSize – Irradiance cubemap face size, clamped to [0, 256]; 0 skips it.
setVisibleBackground – Install the radiance map as the visible background.
- Returns:
The generated environment (also available via weatherSkyEnvironment()).
-
void clearWeatherSkyEnvironment()
Delete the generated weather sky textures; unsets the visible background if it was installed.
-
inline const WeatherSkyEnvironment &weatherSkyEnvironment() const
- Returns:
Last generated weather sky environment (
validfalse when none).
-
static WeatherSettings defaultWeatherSettings(WeatherPreset preset)
Default settings for a weather preset (CPU only).
- Parameters:
preset – Preset to expand.
- Returns:
Settings with
enabled = true, High quality, 13:00 local time.
Internal: static/dynamic layer dirty rect
NDC bounds of the previous frame’s dynamic AABB union, used to compute a conservative scissor rect for the current frame’s dynamic redraw. Not part of the supported API.
-
mutable float lastDynamicLayerNdcMinX_
Internal: previous dynamic-layer NDC minimum x.
-
mutable float lastDynamicLayerNdcMinY_
Internal: previous dynamic-layer NDC minimum y.
-
mutable float lastDynamicLayerNdcMaxX_
Internal: previous dynamic-layer NDC maximum x.
-
mutable float lastDynamicLayerNdcMaxY_
Internal: previous dynamic-layer NDC maximum y.
-
mutable bool lastDynamicLayerDirtyRectValid_
Internal: the four bounds above are valid.
Ground and heightmap terrain textures
Textures applied to every halfspace (ground) and heightmap in the world. The public texture ids are written by the setters below; prefer the setters over assigning the ids directly, since they also refresh texture filtering and the terrain materials. Loading requires a current GL context.
-
unsigned int groundTextureId_
Ground (halfspace) albedo texture; a procedural checker texture by default.
-
unsigned int heightmapTextureId_
Heightmap albedo texture (sRGB), 0 for none; painted vertex colors tint it.
-
unsigned int heightmapNormalTextureId_
Heightmap tangent-space normal map, 0 for none.
-
unsigned int heightmapHeightTextureId_
Heightmap height (parallax) map, 0 for none.
-
inline void setHeightmapPatternResourcePath(const std::string &path)
Set a tiled albedo texture for all heightmaps.
- Parameters:
path – Path to the texture image, or empty to clear.
-
inline std::string getHeightmapPatternResourcePath() const
- Returns:
Path passed to setHeightmapPatternResourcePath(), empty when cleared.
-
inline void setHeightmapNormalResourcePath(const std::string &path)
Set a tiled normal map (linear) for all heightmaps.
- Parameters:
path – Path to the texture image, or empty to clear.
-
inline std::string getHeightmapNormalResourcePath() const
- Returns:
Path passed to setHeightmapNormalResourcePath(), empty when cleared.
-
inline void setHeightmapHeightResourcePath(const std::string &path)
Set a tiled height map (linear) used for parallax on all heightmaps.
- Parameters:
path – Path to the texture image, or empty to clear.
-
inline std::string getHeightmapHeightResourcePath() const
- Returns:
Path passed to setHeightmapHeightResourcePath(), empty when cleared.
-
inline void setHeightmapTerrainMaterialParameters(float normalStrength, float roughness, float parallaxScale, bool deepParallax = true)
Set heightmap terrain material parameters.
- Parameters:
normalStrength – Normal-map strength (default 1; negative acts as 0). Used only with a normal map.
roughness – PBR roughness (default 0.9), clamped to [0.04, 1] when applied.
parallaxScale – Parallax height scale (default 4). Used only with a height map.
deepParallax – Use layered (deep) parallax mapping. Used only with a height map.
-
inline float getHeightmapTerrainNormalStrength() const
- Returns:
Normal strength set by setHeightmapTerrainMaterialParameters().
-
inline float getHeightmapTerrainRoughness() const
- Returns:
Roughness set by setHeightmapTerrainMaterialParameters() (unclamped).
-
inline bool getHeightmapTerrainDeepParallax() const
- Returns:
Deep-parallax flag set by setHeightmapTerrainMaterialParameters().
-
inline float getHeightmapTerrainParallaxScale() const
- Returns:
Parallax scale set by setHeightmapTerrainMaterialParameters().
-
inline void setHeightmapSplatLayer(const std::string &albedoPath, unsigned int controlTexId, float primaryUvScale, float secondaryUvScale, const glm::vec4 &controlBounds)
Configure a secondary terrain splat layer for heightmap meshes.
The PBR mesh shader blends
albedoPathover the primary heightmap albedo using a single-channel control texture. SettingcontrolTexIdto 0 oralbedoPathempty disables splat blending. Blending only happens when a primary albedo (setHeightmapPatternResourcePath()) is set as well.- Parameters:
albedoPath – Secondary albedo image (sRGB); reloaded only when the path changes.
controlTexId – Single-channel control texture (e.g. from updateSingleChannelTexture()); its red channel is the secondary weight (0 = primary only, 1 = secondary only). Not owned. All coordinates below are world XY of the terrain as if it were unrotated (its translation applied, its orientation ignored), like raisim::HeightMap::getHeight(); for a rotated heightmap the layer therefore turns with the terrain.
primaryUvScale – Primary albedo tiling: UV = world XY * scale (default 0.25).
secondaryUvScale – Secondary albedo tiling: UV = world XY * scale (default 0.25).
controlBounds – World XY rectangle covered by the control texture as (minX, minY, sizeX, sizeY) in metres; outside it the edge value is used.
-
inline void clearHeightmapSplatLayer()
Disable splat blending and forget the secondary albedo (the control texture is not deleted).
-
inline unsigned int getHeightmapSplatAlbedoId() const
- Returns:
Secondary splat albedo texture id, 0 when unset.
-
inline unsigned int getHeightmapSplatControlId() const
- Returns:
Splat control texture id, 0 when unset.
-
inline float getHeightmapSplatPrimaryUvScale() const
- Returns:
Primary albedo UV scale used with splatting.
-
inline float getHeightmapSplatSecondaryUvScale() const
- Returns:
Secondary albedo UV scale used with splatting.
-
inline glm::vec4 getHeightmapSplatControlBounds() const
- Returns:
Control texture bounds (minX, minY, sizeX, sizeY).
-
bool hasHeightmapTerrainTextures() const
- Returns:
True when a heightmap albedo, normal or height texture, or a splat layer, is set.
-
void applyHeightmapTerrainTextures(OpenGLMesh &mesh) const
Give a heightmap mesh the terrain textures and material set above, as world heightmaps get them. The mesh’s texture coordinates must tile every 4 m of world XY, like those of world heightmaps; the TCP viewer builds its heightmaps that way while terrain textures are set.
- Parameters:
mesh – Heightmap mesh; its textures and material are replaced.
Local fog volumes, projected decals and irradiance volumes
Scene-effect lists rendered by the PBR path. Each
add*()copies and sanitizes its argument (e.g. clamps strengths and fades, orthonormalizes box orientations), silently ignores it once the matchingkMax*limit is reached, and returns the list size afterwards. The lists are cleared by swapWorld(). See SceneEffects.hpp / Weather.hpp for the field meanings.-
size_t addLocalFogVolume(const LocalFogVolume &volume)
Add a spherical local fog volume (density clamped to [-1, 1]; negative values clear fog).
- Parameters:
volume – Volume to add.
- Returns:
Number of volumes afterwards (capped at kMaxLocalFogVolumes).
-
void clearLocalFogVolumes()
Remove all local fog volumes.
-
inline size_t localFogVolumeCount() const
- Returns:
Number of local fog volumes.
-
inline const std::vector<LocalFogVolume> &localFogVolumes() const
- Returns:
Current local fog volumes (sanitized copies).
-
size_t addProjectedDecal(const ProjectedDecal &decal)
Add a projected (box) decal.
- Parameters:
decal – Decal to add.
- Returns:
Number of decals afterwards (capped at kMaxProjectedDecals).
-
void clearProjectedDecals()
Remove all projected decals.
-
inline size_t projectedDecalCount() const
- Returns:
Number of projected decals.
-
inline const std::vector<ProjectedDecal> &projectedDecals() const
- Returns:
Current projected decals (sanitized copies).
-
size_t addIrradianceVolume(const IrradianceVolume &volume)
Add a box-shaped irradiance volume.
- Parameters:
volume – Volume to add.
- Returns:
Number of volumes afterwards (capped at kMaxIrradianceVolumes).
-
void clearIrradianceVolumes()
Remove all irradiance volumes.
-
inline size_t irradianceVolumeCount() const
- Returns:
Number of irradiance volumes.
-
inline const std::vector<IrradianceVolume> &irradianceVolumes() const
- Returns:
Current irradiance volumes (sanitized copies).
Custom visuals
Render-only shapes that are not part of raisim::World. Names share one namespace (addVisual*(), importVisualScene(), addCameraFrustum()) and must be unique (
RSFATALotherwise). Sizes are in metres, colors are RGBA in [0, 1]. A new visual sits at the world origin with identity orientation; move it through the returned Visuals. The renderer keeps its own reference until removeVisualObject(), clearVisualizationObjects() or swapWorld().-
std::shared_ptr<Visuals> addVisualSphere(const std::string &name, double radius, float colorR = 1.f, float colorG = 1.f, float colorB = 1.f, float colorA = 1.f)
Add a visual sphere (not part of raisim::World).
- Parameters:
name – Visual name.
radius – Sphere radius.
colorR – Red channel.
colorG – Green channel.
colorB – Blue channel.
colorA – Alpha channel.
- Returns:
Shared pointer to the created visual.
-
inline std::shared_ptr<Visuals> addVisualSphere(const std::string &name, double radius, const glm::vec4 &color)
glm::vec4 color overload; prefer this in new code.
- Parameters:
name – Visual name.
radius – Sphere radius.
color – RGBA color.
- Returns:
Shared pointer to the created visual.
-
std::shared_ptr<Visuals> addVisualBox(const std::string &name, double xLength, double yLength, double zLength, float colorR = 1.f, float colorG = 1.f, float colorB = 1.f, float colorA = 1.f)
Add a visual box (not part of raisim::World).
- Parameters:
name – Visual name.
xLength – Box size in X.
yLength – Box size in Y.
zLength – Box size in Z.
colorR – Red channel.
colorG – Green channel.
colorB – Blue channel.
colorA – Alpha channel.
- Returns:
Shared pointer to the created visual.
-
inline std::shared_ptr<Visuals> addVisualBox(const std::string &name, double xLength, double yLength, double zLength, const glm::vec4 &color)
glm::vec4 color overload; prefer this in new code.
- Parameters:
name – Visual name.
xLength – Size in X.
yLength – Size in Y.
zLength – Size in Z.
color – RGBA color.
- Returns:
Shared pointer to the created visual.
-
std::shared_ptr<Visuals> addVisualCylinder(const std::string &name, double radius, double height, float colorR = 1.f, float colorG = 1.f, float colorB = 1.f, float colorA = 1.f)
Add a visual cylinder (not part of raisim::World).
- Parameters:
name – Visual name.
radius – Cylinder radius.
height – Cylinder height (along the visual’s local Z axis).
colorR – Red channel.
colorG – Green channel.
colorB – Blue channel.
colorA – Alpha channel.
- Returns:
Shared pointer to the created visual.
-
inline std::shared_ptr<Visuals> addVisualCylinder(const std::string &name, double radius, double height, const glm::vec4 &color)
glm::vec4 color overload; prefer this in new code.
- Parameters:
name – Visual name.
radius – Cylinder radius.
height – Cylinder height.
color – RGBA color.
- Returns:
Shared pointer to the created visual.
-
std::shared_ptr<Visuals> addVisualCapsule(const std::string &name, double radius, double height, float colorR = 1.f, float colorG = 1.f, float colorB = 1.f, float colorA = 1.f)
Add a visual capsule (not part of raisim::World).
- Parameters:
name – Visual name.
radius – Capsule radius.
height – Capsule height.
colorR – Red channel.
colorG – Green channel.
colorB – Blue channel.
colorA – Alpha channel.
- Returns:
Shared pointer to the created visual.
-
inline std::shared_ptr<Visuals> addVisualCapsule(const std::string &name, double radius, double height, const glm::vec4 &color)
glm::vec4 color overload; prefer this in new code.
- Parameters:
name – Visual name.
radius – Capsule radius.
height – Capsule height.
color – RGBA color.
- Returns:
Shared pointer to the created visual.
-
std::shared_ptr<Visuals> addVisualMesh(const std::string &name, const std::string &meshFile, double scaleX = 1.0, double scaleY = 1.0, double scaleZ = 1.0, float colorR = 1.f, float colorG = 1.f, float colorB = 1.f, float colorA = 1.f)
Add a visual mesh (not part of raisim::World).
The file is imported through the renderer’s asset manager. With async mesh loading enabled (the default) the visual is returned immediately and its geometry appears once pollAsyncMeshLoads() (called by every render) finalizes it.
- Parameters:
name – Visual name.
meshFile – Mesh file path.
scaleX – Mesh scale in X.
scaleY – Mesh scale in Y.
scaleZ – Mesh scale in Z.
colorR – Red channel.
colorG – Green channel.
colorB – Blue channel.
colorA – Alpha channel.
- Returns:
Shared pointer to the created visual.
-
inline std::shared_ptr<Visuals> addVisualMesh(const std::string &name, const std::string &meshFile, const glm::dvec3 &scale, const glm::vec4 &color = glm::vec4(1.f))
glm::vec3 scale + glm::vec4 color overload; prefer this in new code.
- Parameters:
name – Visual name.
meshFile – Mesh file path.
scale – Per-axis scale.
color – RGBA color.
- Returns:
Shared pointer to the created visual.
-
std::shared_ptr<Visuals> importVisualScene(const std::string &name, const std::string &sceneFile, SceneImportReport *report = nullptr, bool importLights = true, float lightIntensityScale = 1.0f, double scaleX = 1.0, double scaleY = 1.0, double scaleZ = 1.0, float colorR = 1.f, float colorG = 1.f, float colorB = 1.f, float colorA = 1.f)
Import a scene file as a mesh visual and, optionally, its authored lights.
Equivalent to addVisualMesh() plus importing the file’s lights as additional lights (dropping those beyond kMaxAdditionalLights). When lights were imported and RenderQualitySettings::autoSelectImportedShadowLight is set with a non-zero shadowedLightBudget, the dominant one is promoted to the main shadow caster (promoteDominantAdditionalLightToMainShadowCaster()). Light-import errors are reported in SceneImportReport::notes, not thrown.
- Parameters:
name – Visual name (must be unique).
sceneFile – Scene/mesh file path.
report – [out] Optional import summary.
importLights – Import the file’s lights.
lightIntensityScale – Multiplier applied to imported light intensities.
scaleX – Mesh scale in X.
scaleY – Mesh scale in Y.
scaleZ – Mesh scale in Z.
colorR – Red channel.
colorG – Green channel.
colorB – Blue channel.
colorA – Alpha channel.
- Returns:
Shared pointer to the created visual.
Public Types
-
enum class ThreadingMode
Threading contract for the renderer.
SingleThread(the default) promises the application creates exactly one RayraiWindow per process and never spawns additional threads that touch rayrai state. Render state is owned by the window or the calling thread.MultiThreadis for RL / batch-render setups that spawn one RayraiWindow per worker thread, each with its own offscreen GL context. State that would otherwise need synchronization is owned by the object it describes — a resolved uniform location by its Shader, GL context state by the renderer driving that context — rather than kept per-thread, so handing a context between threads does not strand it. Shared resources (immutable mesh templates and shader compilation) are coordinated. File textures and mutable material state are local to each worker/context.This is instance confinement, not concurrent access to one window. Construct, render, read back, edit, and destroy a renderer on its owning worker with its GL context current. Do not integrate or mutate its World on another thread while rendering. Prefer an independent World per worker. Keep application supplied mutable materials, cameras, visuals and GPU objects worker-local. Create/destroy SDL windows on the main thread and hand their contexts to workers with makeOffscreenContextCurrent after detaching them on the main thread. All renderers in the process, including prewarmers, must use this mode.
What workers share and what they duplicate: immutable mesh geometry is shared between contexts in one GL share group, so a model imported by one worker costs no second vertex/index upload. Textures are not: rayrai retunes filtering and anisotropy on the texture object itself, per material and per render-quality preset, so a shared texture would let one worker’s settings rewrite another’s. Each worker therefore decodes and uploads its own copy of every image, and a textured model’s geometry is not shared either. Lifting that needs filtering to move off the texture object onto GL sampler objects bound per texture unit.
Rendering draws a copy of the World’s render state (a PhysicsSnapshot), never the World itself. A render call (update(), renderWithExternalCamera(), renderDepthPlaneDistance(), …) first copies the bound World (updateObjectLists()); the shadow maps and the image then come from that copy. An application that steps or edits the World on another thread must keep that thread out of the copy, for example by holding the World’s mutex (raisim::World is lockable) for the render call. Reading the image back into an application buffer (Camera::getRawImage() with SensorStorageMode::CUSTOM_BUFFER) does not read the World and can follow after the lock is released. For independent physics and camera threads, capture a PhysicsSnapshot on the physics thread immediately after integration, then applyPhysicsSnapshot() on the render thread: render calls then never read a World. Snapshot capture performs no GL work and must not wait for a render mutex. The overloads that take a raisim sensor and the GPU lidar read the live World, so they are refused while an applied snapshot is shown.
Mixing the two — for example, constructing several
SingleThreadwindows on different threads — is unsupported.Values:
-
enumerator SingleThread
One renderer per process, driven from one thread (default).
-
enumerator MultiThread
One renderer per worker thread, each with its own GL context.
-
enumerator SingleThread
Public Functions
Construct an offscreen renderer tied to a raisim world.
Requires a current OpenGL context on the calling thread (see createOffscreenGlContext()); built-in shaders are registered here and the viewer render targets are allocated lazily on first render.
A world built from a RaiSim Engine scene (World::getRscene(): a .rscene file, or a RaiSim XML world file that includes one) is shown with that scene: the constructor applies it (see RsceneVisuals.hpp for the render settings and the created visuals). Its meshes load like any others, asynchronously by default (see setAsyncMeshLoadingEnabled() and pendingAsyncMeshLoadCount()), and so does an HDR background: it appears once a decode worker has resampled it. Settings changed afterwards (camera, render quality) override the scene’s. A scene rayrai cannot show, for example one with a missing texture, is a RaiSim fatal error.
- Parameters:
world – Shared world pointer used for pulling object state. The window keeps this
shared_ptr, i.e. it shares ownership.width – Initial render target width in pixels.
height – Initial render target height in pixels.
threadingMode – Concurrency contract — see ThreadingMode. Must match every other RayraiWindow in the process (
RSFATALotherwise).shaderCompileThreadCount – Driver-side shader compile threads (passed to
glMaxShaderCompilerThreadsARB); 0 is treated as 1. Defaults to 1 to match rayrai’s overall single-threaded default; raise this only when the host application explicitly opts into multi-threading. This is a process-wide setting shared by all renderers.shaderBinaryCacheEnabled – When true, compiled shader programs are persisted under
shaderBinaryCacheDirectoryand reused on next run, skipping driver compile entirely for unchanged GLSL/driver. Process-wide, like the two parameters below.shaderBinaryCacheDirectory – Explicit cache directory. Empty selects the first writable per-user cache directory:
LOCALAPPDATA%/RaiSim/rayraion Windows,$XDG_CACHE_HOME/raisim/rayrai,~/Library/Caches/raisim/rayrai(macOS) or~/.cache/raisim/rayrai, then~/.raisim/rayrai, then the system temp directory.logShaderBinaryCache – When true, cache hits/misses/stores are logged to stderr — useful when verifying that the cache is actually being consulted.
-
RayraiWindow(raisim::World &world, int width = 300, int height = 300, ThreadingMode threadingMode = ThreadingMode::SingleThread, unsigned int shaderCompileThreadCount = 1u, bool shaderBinaryCacheEnabled = true, std::string shaderBinaryCacheDirectory = std::string{}, bool logShaderBinaryCache = false)
Construct an offscreen renderer tied to a raisim world (non-owning).
Same as the
shared_ptroverload, butworldis wrapped with a no-op deleter: the caller keeps ownership and the world must outlive this window (or be replaced with swapWorld() first).- Parameters:
world – World reference used for pulling object state.
width – Initial render target width in pixels.
height – Initial render target height in pixels.
threadingMode – Concurrency contract — see ThreadingMode.
shaderCompileThreadCount – Process-wide driver shader compile threads.
shaderBinaryCacheEnabled – Enable the process-wide shader binary cache.
shaderBinaryCacheDirectory – Explicit cache directory; empty selects the default per-user cache directory.
logShaderBinaryCache – Log cache hits/misses/stores to stderr.
-
~RayraiWindow()
Releases GL resources owned by this renderer; call with its GL context current.
-
inline ThreadingMode threadingMode() const
Threading mode this renderer was constructed with.
- Returns:
The mode passed to the constructor.
Reset this renderer to host a different raisim::World, reusing compiled shaders, textures, and render targets.
Pointers into the previous world become invalid the moment the caller destroys it, so this method drops every renderer-side handle that referenced those objects (per-object draw wrappers, render/shadow candidate caches, picking ids, the target visual and camera targets) and every visual added via addVisualXxx / addInstancedVisuals / addPointCloud / addCoordinateFrame, plus tendon visuals. Additional lights, fog volumes, projected decals, irradiance volumes, and registered reflection probes are cleared so the caller’s scene-application step can repopulate them (probe textures are not deleted). Camera and render-quality settings are preserved, apart from those a world scene set (see below).
The dropped visuals are kept alive (unreferenced by the renderer) until the end of the next update(), renderWithExternalCamera(), or depth-only render, so a scene applied again in between reuses their meshes, mesh LODs and foliage partitions instead of reading and processing every model again. Models whose files changed since they were read are read again (RayraiGlobalAsset::forgetChangedModelFiles()).
Like the constructor, it applies the new world’s .rscene scene, if it has one. The previous world’s scene is removed, including its background, sky and terrain textures, and the viewer settings it replaced come back: render quality and weather, background color, main light and terrain material. The camera stays where it is unless the new world’s scene places it.
- Parameters:
world – New world; stored (shared ownership) like the constructor’s.
-
unsigned int loadSceneHdrCubemapCached(const std::string &path, int faceSize)
Load a scene HDR map once per path, file signature and face size. The viewer owns the texture until destruction; callers must not delete it. GL context required.
-
std::shared_ptr<const unsigned int> acquireSceneHdrCubemapCached(const std::string &path, int faceSize)
Acquire a scene HDR texture while it is installed in a background or visual. Unused scene entries are evicted; the viewer frees textures before context teardown.
-
size_t applyTextureFilteringQualityToLoadedTextures()
Apply current texture filtering quality to currently loaded RayRai visual textures.
Uses RenderQualitySettings::textureAnisotropy and textureMipLodBias and covers the ground texture, custom visuals and instanced visuals.
- Returns:
Number of texture ids updated.
-
void setAsyncMeshLoadingEnabled(bool enabled)
Enable or disable async mesh file import for future mesh visuals/world assets.
Async loading parses files and prepares base geometry and instanced LODs on workers. Pending instances are skipped; textures and incremental GPU uploads use the render thread. Disable it when a caller needs mesh assets to be available immediately after addVisualMesh()/importVisualScene(). Disabling it also finishes the meshes still loading before it returns, for example those of the world’s scene that the constructor applied; call it with this window’s GL context current. To load only the meshes requested next synchronously, use a SynchronousMeshLoadingScope instead. Enabled by default; USD files are always imported synchronously.
- Parameters:
enabled – True to import future mesh files asynchronously; false to load them synchronously and finish the pending ones.
-
bool asyncMeshLoadingEnabled() const
True when future mesh file imports are started asynchronously.
- Returns:
Current async-import flag.
-
size_t pollAsyncMeshLoads(size_t maxAssets = 1)
Finalize ready async mesh imports on the render thread.
- Parameters:
maxAssets – Maximum import/upload stages to advance (zero does no work). Instanced LOD preparation is also polled, with one submesh upload per batch.
- Returns:
Number of assets finalized.
-
size_t pendingAsyncMeshLoadCount() const
Pending imports plus instanced LOD jobs, including unfinished GPU uploads, and the HDR background of the world’s scene while it loads.
- Returns:
Number of pending jobs; 0 once everything has been finalized by pollAsyncMeshLoads().
-
inline RayraiGlobalAsset &debugAssets() const
The asset manager this renderer imports through.
Exposed so tests can inspect the meshes this renderer actually holds rather than re-deriving them through a second manager, which only agrees when the asset happens to be eligible for the process-wide GPU cache.
- Returns:
Reference owned by this renderer, valid for its lifetime.
-
inline std::shared_ptr<const void> modelHandle(const std::string &meshFile) const
A strong reference to a model file this renderer has read.
The model caches reference models weakly, and instanced foliage keeps only the meshes it derives from its model, so a model can be released while the scene still uses it. An application that rebuilds its scene (swapWorld(), then the same visuals again) can hold these handles across the rebuild, so the models are reused instead of read and prepared again.
- Parameters:
meshFile – Model file path, as passed when the visual was added.
- Returns:
The model, or nullptr when it was not read (it is not read here).
-
inline void setKeyboardShortcutsEnabled(bool enabled)
Whether this renderer reacts to global keyboard shortcuts.
The renderer’s built-in shortcuts read SDL’s keyboard state, which is one array for the whole process and carries no notion of which window has focus. A process running several renderers would otherwise see a key press act on all of them at once, so a multi-window application should leave this on only for the focused renderer. Defaults to true, which is the behaviour of a single-renderer application. Currently the only shortcut is
B, which toggles the picking-buffer debug view. Camera movement keys are controlled separately by setKeyboardInputEnabled().- Parameters:
enabled – False to ignore shortcut keys in this renderer.
-
inline bool keyboardShortcutsEnabled() const
- Returns:
True when this renderer reacts to global keyboard shortcuts (default true).
-
inline int pbrDebugOutputMode() const
PBR debug output mode in force for this renderer.
The environment variable RAYRAI_PBR_DEBUG_OUTPUT sets it process-wide; captureDebugPasses overrides it for the frames it renders. The override belongs to this renderer: rewriting the process environment raced every other worker’s getenv on the render path, and a thread-local override would follow whichever thread happened to drive the renderer.
- Returns:
Active mode; 0 is normal shading.
-
inline void setPbrDebugOutputMode(int mode)
Select a renderer-local material capture mode (0..31). -1 restores the process default. Changing the mode invalidates cached scene color.
- Parameters:
mode – Mode in [-1, 31]; throws std::invalid_argument otherwise.
-
void resize(int newWidth, int newHeight)
Resize the internal camera render target.
Non-positive or unchanged sizes are ignored. update() calls this with its own size every frame, so explicit calls are only needed before rendering through other paths.
- Parameters:
newWidth – New framebuffer width in pixels.
newHeight – New framebuffer height in pixels.
-
void update(int w, int h, bool isHovering, int cX, int cY, bool shouldClick)
Render one frame into the internal camera’s offscreen texture.
The interactive viewer path: resizes the target to
wxh, finalizes at most one pending async mesh import, syncs raisim objects, applies mouse and keyboard camera input, then renders shadows, the scene and post-processing. Read the result with getImageTexture(). Requires this renderer’s GL context.- Parameters:
w – Target width in pixels.
h – Target height in pixels.
isHovering – Whether the mouse is over the render area; mouse input is ignored otherwise.
cX – Cursor x position inside the render area, in pixels.
cY – Cursor y position inside the render area, in pixels.
shouldClick – Whether mouse click selection should be processed.
-
void cancelViewportMouseDrag()
Stop an in-progress viewport mouse drag without changing button state.
-
inline void setKeyboardInputEnabled(bool enabled)
Allow or block this renderer’s WASD/Space camera movement.
The camera reads the process-wide SDL keyboard state, which is shared by every renderer in the process. A host that draws more than one view at a time (the TCP viewer’s split panes) must therefore leave this on for just one of them, or a single key press walks every camera at once. Mouse input needs no such switch: it is already scoped by the hover flag passed to update().
- Parameters:
enabled – False to ignore the keyboard for this renderer.
-
inline bool keyboardInputEnabled() const
- Returns:
True when this renderer acts on camera keys (default true).
-
unsigned int getImageTexture() const
Return the GL texture id of the internal camera output.
- Returns:
Texture id for the most recent rendered frame, owned by the renderer (it can change after resize()).
-
void setCameraFixedDistance(bool fixed)
Keep the camera distance constant when orbiting a target.
- Parameters:
fixed – True to lock distance.
-
bool isCameraFixedDistance() const
True when the orbit distance is locked.
- Returns:
Lock state.
-
float cameraFixedDistance() const
Current locked orbit distance (metres).
- Returns:
Distance used while the orbit distance is locked.
-
void setCameraFixedTarget(bool fixed)
Keep the camera target fixed in world space.
- Parameters:
fixed – True to lock the target position.
-
bool isCameraFixedTarget() const
True when the camera target is locked to a fixed point.
- Returns:
Lock state.
-
void setBackgroundColor(const glm::vec4 &color)
Set background clear color using legacy 0..255 RGBA channels.
Identical to setBackgroundColorRgb255(); prefer that name or setBackgroundColorLinear() in new code. Overwritten by setRenderQualitySettings()/setRenderQualityPreset().
- Parameters:
color – RGBA color where each channel is in [0, 255].
-
void setBackgroundColorRgb255(const glm::vec4 &color)
Set background clear color using 0..255 RGBA channels.
- Parameters:
color – RGBA color where each channel is in [0, 255].
-
void setBackgroundColorLinear(const glm::vec4 &color)
Set background clear color using linear 0..1 RGBA channels.
- Parameters:
color – Linear RGBA color where each channel is in [0, 1].
-
glm::vec4 getBackgroundColor() const
Get the current background clear color in 0..255 RGBA channels.
Mirrors
setBackgroundColor*()so the value round-trips through serialization without a separate Camera lookup.- Returns:
RGBA color, each channel in [0, 255].
-
glm::vec4 getBackgroundColorLinear() const
Get the current background clear color in linear 0..1 RGBA channels.
- Returns:
Linear RGBA color.
-
inline void setEnvironmentBackground(unsigned int environmentMap, float exposure = 1.0f)
Render a cubemap behind the interactive viewer camera.
- Parameters:
environmentMap – Cubemap texture id, or 0 to disable the environment background. Not owned: the caller keeps it alive while it is installed.
exposure – Multiplier applied while drawing the environment background.
Install a background while retaining its scene HDR texture lease.
-
inline unsigned int environmentBackgroundMap() const
Current interactive viewer environment background cubemap.
- Returns:
Cubemap id, or 0 if disabled.
-
inline float environmentBackgroundExposure() const
Current interactive viewer environment background exposure.
- Returns:
Exposure multiplier.
-
inline void clearEnvironmentBackground()
Disable the interactive viewer environment background.
-
void setFogDensity(float density)
Set scene fog density used by the mesh shader.
Overwritten by setRenderQualitySettings() (RenderQualitySettings::fogDensity).
- Parameters:
density – Fog density in 1/m (default 0.01); negative values are clamped to 0.
-
float getFogDensity() const
Get current fog density.
- Returns:
Fog density value.
-
Camera &getCamera()
Access the internal camera for direct manipulation. Targets are allocated on first render or explicit ensureRenderTargets().
- Returns:
Reference to the internal camera.
-
inline const Visuals *getTargetVisual() const
Get the currently selected target visual, if any.
- Returns:
Pointer to the target visual or nullptr.
-
inline Visuals *getTargetVisual()
Get the currently selected target visual, if any.
- Returns:
Pointer to the target visual or nullptr.
-
void setTargetVisual(Visuals *visual)
Set the target visual for camera tracking.
A non-null visual locks the camera target and orbit distance onto it; nullptr unlocks both. The pointer is not owned; the target is dropped automatically when the visual is removed from this renderer.
- Parameters:
visual – Visual to target, or nullptr to clear.
-
Visuals *pickTargetVisualAt(int x, int y)
Pick a custom visual at a pixel of the internal camera.
Runs a picking pass immediately (GL context required). Only visuals added through this renderer can be returned.
- Parameters:
x – Pixel x coordinate in the internal camera’s framebuffer (top-left origin).
y – Pixel y coordinate, growing downward; out-of-range pixels pick nothing.
- Returns:
Pointer to the picked visual (owned by the renderer) or nullptr.
-
void setShadowOrtho(float halfSize, float zNear, float zFar)
Set the directional shadow box (orthographic) parameters.
Defaults are 12.5, 0.1 and 55 m; overwritten by setRenderQualitySettings().
- Parameters:
halfSize – Half-size of the ortho box in metres.
zNear – Near plane in metres.
zFar – Far plane in metres.
-
void setShadowCenterOffset(float meters)
Set the shadow center offset distance along the camera forward vector.
Default 10 m; overwritten by setRenderQualitySettings().
- Parameters:
meters – Distance ahead of the camera.
-
void requestShadowUpdate()
Mark viewer shadow maps stale so they are rebuilt on the next viewer frame.
This is useful when RenderQualitySettings::updateShadowsEveryFrame is false and the application moves static-looking lights or scene geometry manually.
-
void setUpdateShadowsEveryFrame(bool enabled)
Runtime shortcut for RenderQualitySettings::updateShadowsEveryFrame.
- Parameters:
enabled – True to refresh shadow maps every viewer frame, false to update on demand.
-
inline bool updateShadowsEveryFrame() const
True when viewer shadows are refreshed every frame.
-
inline float getShadowCenterOffset() const
Get the current shadow center offset distance.
- Returns:
Distance ahead of the camera.
-
SupersampledCapture captureSupersampledRgba(const Camera &externalCam, int scale, const RenderOverrides &ov)
Render an explicit supersampled viewer capture and downsample to the input camera size.
This is intended for documentation screenshots. It is opt-in and uses an internal temporary camera, so it does not resize or otherwise mutate
externalCam. Temporal AA and viewer upscaling are disabled for the capture.- Parameters:
externalCam – Camera whose pose, projection and render-target size define the output.
scale – Supersampling factor per axis, clamped to [1, 4].
ov – Render overrides, as for renderWithExternalCamera().
- Returns:
Downsampled RGBA8 image at the camera’s render-target size.
-
void renderWithExternalCamera(raisim::RGBCamera &sensorCam, Camera &externalCam, const RenderOverrides &ov)
Render using a raisim RGB camera and an external render camera.
Only the sensor’s world pose is copied into
externalCam(see syncRaisimCameraPose(): sensor +X is the view direction, +Z is up); projection and resolution come fromexternalCamitself. Custom visuals, point clouds and coordinate frames are never drawn, MSAA/temporal AA/viewer upscaling are disabled, and weather effects follow WeatherSettings::affectSensors, regardless ofov.- Parameters:
sensorCam – Raisim RGB camera providing the pose; its pose is updated.
externalCam – Render camera to use for rendering; receives the output.
ov – Shader/toggle overrides (see RenderOverrides).
-
void renderWithExternalCamera(raisim::DepthCamera &sensorCam, Camera &externalCam, const RenderOverrides &ov)
Render using a raisim depth camera’s pose and an external render camera.
Same as the RGB overload (pose only, sensor-safe overrides). This renders the color image; use renderDepthPlaneDistance() for linear depth.
- Parameters:
sensorCam – Raisim depth camera providing the pose; its pose is updated.
externalCam – Render camera to use for rendering; receives the output.
ov – Shader/toggle overrides (see RenderOverrides).
-
void renderWithExternalCamera(Camera &externalCam, const RenderOverrides &ov)
Render using an external render camera.
Renders into
externalCam'sown render targets (allocated on first use at its configured size); read the result from the camera, e.g. its final texture. Syncs raisim objects and finalizes at most one pending async mesh import first. When nothing that affects the image has changed since the last call with the same camera, the previous frame may be reused; call invalidateExternalFrameCache() after changes the renderer cannot see. Requires this renderer’s GL context.- Parameters:
externalCam – Render camera to use for rendering; receives the output.
ov – Shader/toggle overrides (see RenderOverrides). Throws std::invalid_argument when a custom
postshader is combined with reprojected temporal AA.
-
void invalidateExternalFrameCache()
Force the next viewer/external render to redraw instead of reusing a cached frame.
-
void invalidateExternalFrameCache(bool invalidateStaticSceneLayer)
Internal: not implemented (no definition is provided); use invalidateExternalFrameCache().
- Parameters:
invalidateStaticSceneLayer – Unused.
-
bool buildExternalFrameCacheKey(const Camera &externalCam, const RenderOverrides &ov, bool useTemporalAa, int sceneMsaaSamples, uint64_t &key, bool pointCloudsMustBeDetectable = false) const
Internal: compute the frame-cache key for an external render.
- Parameters:
externalCam – Camera to be rendered.
ov – Overrides to be used.
useTemporalAa – Whether temporal AA will run.
sceneMsaaSamples – Scene MSAA sample count.
key – [out] Resulting key.
pointCloudsMustBeDetectable – Only detectable point clouds contribute.
- Returns:
False when the frame must not be cached.
-
std::vector<RenderPassTiming> captureRenderPassTimings(Camera &externalCam, const RenderOverrides &ov)
Explicitly render once and return GPU elapsed-time measurements by pass.
This inserts blocking OpenGL timer queries and is intended for diagnostics and benchmarks only. Normal rendering does not issue timer queries. Viewer upscaling is disabled for the measurement; scenes with foliage are rendered a second time to time foliage sub-passes.
- Parameters:
externalCam – Camera to render with (receives the image).
ov – Render overrides.
- Returns:
One entry per timed pass, in submission order.
-
std::vector<RenderPassTiming> captureViewerPassTimings(int width, int height)
Blocking diagnostic renders of the native viewer, including non-detectable foliage. Call with a current GL context; timings exclude presentation/UI. Runs update() (twice with foliage) on the internal camera.
- Parameters:
width – Viewer width in pixels; must be positive (throws std::invalid_argument).
height – Viewer height in pixels; must be positive.
- Returns:
One entry per timed pass.
-
inline ConservativeOcclusionCullingDiagnostics conservativeOcclusionCullingDiagnostics() const
- Returns:
Diagnostics: occlusion-culling counters of the last scene color pass.
-
inline FoliageRenderDiagnostics foliageRenderDiagnostics() const
- Returns:
Diagnostics: foliage/instanced draw counters of the last rendered frame.
-
inline EnvironmentBackgroundDiagnostics environmentBackgroundDiagnostics() const
- Returns:
Diagnostics: how the last scene pass drew the environment background.
-
inline ShadowCacheDiagnostics shadowCacheDiagnostics() const
- Returns:
Diagnostics: shadow-map caching counters of the last rendered frame.
-
std::vector<DebugPassCapture> captureDebugPasses(Camera &externalCam, const RenderOverrides &ov)
Capture the standard RayRai PBR/postprocess debug pass set for any scene.
The capture uses the caller-provided camera and render overrides, temporarily switches to Ultra quality, disables temporal history/upscaling for deterministic per-pass readback, and afterwards re-applies the previous quality settings through setRenderQualitySettings() and resets the renderer-local PBR debug mode to -1 (process default). Because it goes through setRenderQualitySettings(), application-added additional lights are cleared and the preset reads Custom afterwards (see setRenderQualitySettings()). Returned pixels are top-left ordered RGBA8 buffers so callers can write PNGs or analyze them without a RayRai image writer dependency.
- Parameters:
externalCam – Camera to render with; its size defines the capture size.
ov – Render overrides (temporal AA and upscaling are forced off).
- Returns:
25 passes (final, material channels, lighting terms, shadows, fog, AO, …).
-
DirectionalShadowCascadePlan planDirectionalShadowCascades(const Camera &camera) const
Compute stable directional-light cascade splits and light-space bounds.
The shadow pass uses this same planner for the main directional light; calling it is CPU-only and does not allocate shadow maps or change renderer state. Cascades are enabled when RenderQualitySettings::directionalShadowCascadeCount is greater than 1.
- Parameters:
camera – Camera whose frustum is split.
- Returns:
Cascade plan (see DirectionalShadowCascadePlan).
-
ShadowAtlasPlan planAdditionalShadowAtlas() const
Compute a deterministic tile plan for selected local-light shadow maps.
The renderer uses this plan for its 2D additional-light shadow atlas (point lights keep standalone cubemaps unless the point-shadow policy says otherwise). Calling it is CPU-only; the result depends on the shadow lights selected by the last rendered frame.
- Returns:
Atlas plan (see ShadowAtlasPlan).
-
ShadowDebugOverlaySummary shadowDebugOverlaySummary() const
Build the CPU summary used by the optional in-view shadow debug overlay.
This does not render UI, allocate GL resources, or mutate settings. It is useful for tests, benchmarks, and applications that want to show their own shadow tuning panel.
- Returns:
Summary for the internal camera.
-
unsigned int captureReflectionProbeCubemap(const glm::vec3 &position)
Capture a static local reflection probe into a cubemap.
This is a raster, load-time/manual operation. It renders six 90-degree faces from
positionand returns an RGBA8 OpenGL cubemap id with mipmaps. The caller owns the returned texture and may bind it to PBR materials through Visuals or Material. Faces are rendered without post-processing. Requires this renderer’s GL context.- Parameters:
position – World-space capture position.
- Returns:
OpenGL cubemap id, or 0 on failure.
-
unsigned int captureReflectionProbeCubemap(const glm::vec3 &position, const ReflectionProbeCaptureSettings &settings)
Capture a static local reflection probe with explicit capture settings.
- Parameters:
position – World-space capture position.
settings – What to draw and at which resolution.
- Returns:
Caller-owned OpenGL cubemap id, or 0 on failure.
-
ReflectionProbe captureFilteredReflectionProbe(const glm::vec3 &position, float radius, float strength)
Capture a static local probe and generate irradiance, prefiltered specular, and BRDF maps.
This is an explicit bounded setup operation for High/Ultra. It does not update automatically after scene changes and does not affect Fast unless the caller uses the returned probe. Uses default capture settings and reflectionProbeFilterSettingsForCurrentQuality(), so with probe filtering disabled only the raw environment map is produced. All returned textures are owned by the caller. Pass the probe to addReflectionProbe() to make it selectable.
- Parameters:
position – World-space capture position.
radius – Influence radius in metres (negative values become 0 = unbounded).
strength – Probe strength (negative values become 0).
- Returns:
The probe; map ids are 0 for maps that were skipped or failed.
-
ReflectionProbe captureFilteredReflectionProbe(const glm::vec3 &position, float radius, float strength, const ReflectionProbeCaptureSettings &captureSettings)
Capture a static local probe and generate irradiance, prefiltered specular, and BRDF maps. Uses filter settings for the current quality.
- Parameters:
position – World-space capture position.
radius – Influence radius in metres.
strength – Probe strength.
captureSettings – What to draw and at which resolution.
- Returns:
The probe; textures are owned by the caller.
-
ReflectionProbe captureFilteredReflectionProbe(const glm::vec3 &position, float radius, float strength, const ReflectionProbeCaptureSettings &captureSettings, const ReflectionProbeFilterSettings &filterSettings)
Capture a static local probe and generate irradiance, prefiltered specular, and BRDF maps.
- Parameters:
position – World-space capture position.
radius – Influence radius in metres.
strength – Probe strength.
captureSettings – What to draw and at which resolution.
filterSettings – CPU filtering settings; zero sizes skip the corresponding map.
- Returns:
The probe; textures are owned by the caller.
-
inline ReflectionProbe captureFilteredReflectionProbe(const CaptureFilteredReflectionProbeOptions &opts)
Options-struct overload; prefer this in new code.
- Parameters:
opts – Capture options.
- Returns:
The probe; textures are owned by the caller.
-
inline ReflectionProbe captureFilteredReflectionProbeCached(const CaptureFilteredReflectionProbeOptions &opts)
Cached variant of the options-struct overload.
- Parameters:
opts – Capture options.
- Returns:
The cached or newly captured probe; textures are owned by the renderer.
-
unsigned int captureReflectionProbeCubemapCached(const glm::vec3 &position, const ReflectionProbeCaptureSettings &settings)
Capture or reuse a cached static local reflection probe cubemap.
The cache is explicit and does not recapture automatically. The returned cubemap is owned by RayRai until clearReflectionProbeCache() or destruction. Applications should clear the cache after changing scene content that should be reflected in future probe captures. Entries are keyed by position and settings.
- Parameters:
position – World-space capture position.
settings – Capture settings.
- Returns:
Renderer-owned cubemap id, or 0 on failure (failures are not cached).
-
ReflectionProbe captureFilteredReflectionProbeCached(const glm::vec3 &position, float radius, float strength)
Cached captureFilteredReflectionProbe(); textures stay owned by the renderer.
Entries are keyed by all arguments and live until clearReflectionProbeCache().
- Parameters:
position – World-space capture position.
radius – Influence radius in metres.
strength – Probe strength.
- Returns:
The cached or newly captured probe.
-
ReflectionProbe captureFilteredReflectionProbeCached(const glm::vec3 &position, float radius, float strength, const ReflectionProbeCaptureSettings &captureSettings)
Cached captureFilteredReflectionProbe(); textures stay owned by the renderer.
- Parameters:
position – World-space capture position.
radius – Influence radius in metres.
strength – Probe strength.
captureSettings – Capture settings.
- Returns:
The cached or newly captured probe.
-
ReflectionProbe captureFilteredReflectionProbeCached(const glm::vec3 &position, float radius, float strength, const ReflectionProbeCaptureSettings &captureSettings, const ReflectionProbeFilterSettings &filterSettings)
Cached captureFilteredReflectionProbe(); textures stay owned by the renderer.
- Parameters:
position – World-space capture position.
radius – Influence radius in metres.
strength – Probe strength.
captureSettings – Capture settings.
filterSettings – Filter settings.
- Returns:
The cached or newly captured probe.
-
void clearReflectionProbeCache()
Delete every texture held by the probe caches and empty them. GL context required. Probes previously returned by the cached functions become dangling.
-
inline size_t reflectionProbeCacheSize() const
- Returns:
Number of entries in both probe caches.
-
bool applyReflectionProbeSidecarQualitySettings(const std::string &sceneFile)
Apply the
qualityblock of a scene’s reflection-probe sidecar.Copies the provided probe selection/filter values into the current render quality settings via setRenderQualitySettings() (which has side effects, see there). Probes themselves are not captured.
- Parameters:
sceneFile – Scene/mesh file path, or the sidecar path itself.
- Returns:
True when the sidecar provided at least one quality value.
-
bool applyEnvironmentSidecarSettings(const std::string &sceneFile)
Apply a scene’s environment sidecar to the current render quality settings.
Present values are written into a copy of the current settings, which is then applied with setRenderQualitySettings() (see its side effects). A background map is loaded as a 512 px cubemap and installed with setEnvironmentBackground(). Requires this renderer’s GL context.
- Parameters:
sceneFile – Scene/mesh file path, or the sidecar path itself.
- Returns:
True when the sidecar provided at least one value.
-
bool applyWeatherSidecarSettings(const std::string &sceneFile)
Apply a scene’s weather sidecar.
Calls setWeatherSettings() when weather data is present, and replaces all local fog volumes when the sidecar has
local_fog_volumes.- Parameters:
sceneFile – Scene/mesh file path, or the sidecar path itself.
- Returns:
True when anything was applied.
-
ReflectionProbeFilterSettings reflectionProbeFilterSettingsForCurrentQuality() const
- Returns:
Probe filter settings derived from the current RenderQualitySettings (all zero when reflection-probe filtering is disabled).
-
size_t addReflectionProbe(const ReflectionProbe &probe)
Register a captured probe for selectReflectionProbeBlend() / applyNearestReflectionProbe().
The probe is copied with radius/strength clamped to >= 0 and box projection disabled for degenerate boxes. Registered probes are not bound to visuals automatically, and the registry does not take ownership of the textures.
- Parameters:
probe – Probe to register; ignored when it has no environment, irradiance or prefiltered map.
- Returns:
Number of registered probes afterwards.
-
void clearReflectionProbes()
Unregister every probe added with addReflectionProbe(); their textures stay with the caller.
-
bool selectReflectionProbeBlend(const glm::vec3 &position, ReflectionProbeBlend &blend) const
Pick up to two registered probes influencing a position.
Weight per probe is
strength * (1 - d / radius)inside a positive radius (0 outside), orstrength / (1 + d)for radius 0, where d is the distance to the probe position, or to its box when box projection is valid. Probes at or below RenderQualitySettings::minReflectionProbeWeight are skipped; the second probe is used only when maxReflectionProbesPerSelection is 2.- Parameters:
position – World-space query position.
blend – [out] Selected probes and normalized weights.
- Returns:
True when at least one probe influences the position.
-
ReflectionProbeDebugView reflectionProbeDebugView(const glm::vec3 &position) const
Diagnostics: probe selection at a position plus per-probe weights.
- Parameters:
position – World-space query position.
- Returns:
Debug view; CPU only.
-
ReflectionProbeDebugOverlaySummary reflectionProbeDebugOverlaySummary(const glm::vec3 &position) const
Build the CPU summary used by the optional in-view reflection probe overlay.
This is diagnostics-only: it does not capture probes, filter maps, allocate GL resources, or mutate probe selection state.
- Parameters:
position – World-space query position.
- Returns:
Overlay summary.
-
ReflectionProbePlacementSuggestion suggestReflectionProbePlacementFromSceneBounds() const
Suggest a static local reflection-probe placement from current scene bounds.
This is CPU-only and non-mutating. It does not capture or register a probe; callers can use the returned position/radius/box bounds with captureFilteredReflectionProbe() or a sidecar file after explicit approval. Halfspaces and heightmaps are ignored so infinite/default grounds do not dominate imported-room probe placement. Bounds are the union of approximate bounding spheres of raisim objects, custom visuals and instanced visuals.
- Returns:
Suggestion;
validis false when there is nothing to bound.
-
bool applyNearestReflectionProbe(Visuals &visual, const glm::vec3 &position) const
Bind the best registered reflection probe at
positionto a visual’s PBR environment.Uses the primary probe of selectReflectionProbeBlend() with the blend strength.
- Parameters:
visual – Visual to update.
position – World-space position used for selection (typically the visual’s).
- Returns:
False when no probe influences the position (the visual is left unchanged).
-
inline size_t reflectionProbeCount() const
- Returns:
Number of probes registered with addReflectionProbe().
-
uint32_t pickWithExternalCamera(Camera &externalCam, int x, int y, Shader *pickingOverride = nullptr)
Run the picking pass and return object id at a pixel.
- Parameters:
externalCam – Render camera used for the picking pass.
x – Pixel x coordinate in framebuffer space (top-left origin).
y – Pixel y coordinate in framebuffer space, growing downward.
pickingOverride – Optional picking shader override.
- Returns:
Encoded object id (24-bit), or 0 if nothing is picked or the pixel is out of range.
-
std::shared_ptr<PointCloud> addPointCloud(const std::string &name)
Create a named point cloud.
- Parameters:
name – Unique name for the point cloud; aborts (
RSFATAL) if already used.- Returns:
Shared pointer to the point cloud; the renderer keeps its own reference until removePointCloud() / clearVisualizationObjects() / swapWorld().
-
void removePointCloud(const std::string &name)
Remove a point cloud by name.
- Parameters:
name – Name of the point cloud to remove; aborts (
RSFATAL) if unknown.
-
void clearVisualizationObjects()
Remove all visual objects, instanced visuals, and point clouds.
Also drops automatically maintained tendon visuals and the target visual. Coordinate frames are kept.
-
std::shared_ptr<CoordinateFrame> addCoordinateFrame(const std::string &name)
Create a named coordinate frame set.
- Parameters:
name – Unique name for the coordinate frame set; aborts (
RSFATAL) if already used.- Returns:
Shared pointer to the coordinate frame set (also held by the renderer).
-
void removeCoordinateFrame(const std::string &name)
Remove a coordinate frame set by name.
- Parameters:
name – Name of the coordinate frame set to remove; aborts (
RSFATAL) if unknown.
-
inline std::shared_ptr<Visuals> importVisualScene(const std::string &name, const std::string &sceneFile, const ImportVisualSceneOptions &opts)
Options-struct overload; prefer this in new code.
- Parameters:
name – Visual name.
sceneFile – Scene/mesh file path.
opts – Import options.
- Returns:
Shared pointer to the created visual.
-
inline VisualMeshBuilder makeVisualMesh(std::string name, std::string meshFile)
Start a fluent build of an
addVisualMeshvisual. SeeVisualMeshBuilder.- Parameters:
name – Visual name.
meshFile – Mesh file path.
- Returns:
Builder bound to this renderer; call add() to create the visual.
-
std::shared_ptr<Visuals> addVisualPlane(const std::string &name, double width, double height, float colorR = 1.f, float colorG = 1.f, float colorB = 1.f, float colorA = 1.f)
Add a custom visual plane backed by the shared primitive plane mesh.
Flat-shaded; the unit plane lies in the local XY plane with a +Z normal and
width/heightscale it along local X / Y. Duplicate names are fatal.- Parameters:
name – Visual name.
width – Size along local X.
height – Size along local Y.
colorR – Red channel.
colorG – Green channel.
colorB – Blue channel.
colorA – Alpha channel.
- Returns:
Shared pointer to the created visual.
-
inline std::shared_ptr<Visuals> addVisualPlane(const std::string &name, double width, double height, const glm::vec4 &color)
glm::vec4 color overload; prefer this in new code.
- Parameters:
name – Visual name.
width – Size along local X.
height – Size along local Y.
color – RGBA color.
- Returns:
Shared pointer to the created visual.
Add a visual from custom OpenGL meshes.
The mesh list is shared, not copied. Duplicate names are fatal.
- Parameters:
name – Visual name.
meshes – Mesh list to render.
color – Default color for non-textured meshes.
- Returns:
Shared pointer to the created visual.
addVisualCustomMesh() variant that can disable automatic mesh LOD (for already prepared terrain LODs).
Unlike the other overload this throws std::invalid_argument for a duplicate or empty name, a null/empty mesh list, or a null mesh.
- Parameters:
name – Visual name.
meshes – Mesh list to render (shared).
color – Default color for non-textured meshes.
automaticMeshLodEnabled – False to disable generic mesh simplification.
- Returns:
Shared pointer to the created visual.
-
std::shared_ptr<Visuals> getVisualObject(const std::string &name)
Look up a visual by name.
- Parameters:
name – Visual name.
- Returns:
Shared pointer to the visual. Aborts (
RSFATAL) if not found; use findVisualObject() for a non-fatal lookup.
-
std::shared_ptr<Visuals> findVisualObject(const std::string &name)
Look up a custom visual by name without aborting.
- Parameters:
name – Visual name.
- Returns:
The visual, or nullptr when it does not exist.
-
void removeVisualObject(const std::string &name)
Remove a visual object by name.
Clears the target visual if it was this one.
- Parameters:
name – Visual name to remove; aborts (
RSFATAL) if unknown.
-
std::shared_ptr<InstancedVisuals> addInstancedVisuals(const std::string &name, raisim::Shape::Type type, const glm::vec3 &size, const glm::vec4 &color1, const glm::vec4 &color2, const std::string &meshFile = "")
Create instanced visuals for repeated shapes or meshes.
Instances are added through the returned object; each instance color is a blend of
color1andcolor2(see InstancedVisuals). Instanced names form their own namespace and must be unique (RSFATALotherwise). Automatic mesh LOD is enabled.- Parameters:
name – Visual name.
type – Shape type.
size – Base size for the instances.
color1 – Primary instance color (linear RGBA).
color2 – Secondary instance color (linear RGBA).
meshFile – Mesh file for mesh instances.
- Returns:
Shared pointer to the created instanced visuals (also held by the renderer).
-
std::shared_ptr<InstancedVisuals> addInstancedVisuals(const std::string &name, raisim::Shape::Type type, const glm::vec3 &size, const glm::vec4 &color1, const glm::vec4 &color2, const std::string &meshFile, bool automaticMeshLodEnabled)
Create instanced visuals for repeated shapes or meshes.
- Parameters:
name – Visual name.
type – Shape type.
size – Base size.
color1 – Primary color.
color2 – Secondary color.
meshFile – Mesh file.
automaticMeshLodEnabled – False to disable automatic mesh simplification.
- Returns:
Shared pointer to the created instanced visuals.
-
std::shared_ptr<InstancedVisuals> addInstancedVisuals(const std::string &name, const InstancedVisuals &prototype)
Create an empty cell batch sharing a ready prototype’s prepared meshes (see InstancedVisuals::cloneWithoutInstances()).
- Parameters:
name – Batch name; throws std::invalid_argument if already used.
prototype – Fully prepared source batch.
- Returns:
The new, empty batch.
Create instanced visuals from an already-created mesh list.
- Parameters:
name – Visual name (unique among instanced visuals).
meshes – Mesh list shared by all instances.
size – Base size for the instances.
color1 – Primary instance color.
color2 – Secondary instance color.
- Returns:
Shared pointer to the created instanced visuals.
Mesh-list overload with explicit automatic-LOD control.
- Parameters:
name – Visual name.
meshes – Shared mesh list.
size – Base size.
color1 – Primary color.
color2 – Secondary color.
automaticMeshLodEnabled – False to disable automatic mesh simplification.
- Returns:
Shared pointer to the created instanced visuals.
-
std::shared_ptr<InstancedVisuals> getInstancedVisuals(const std::string &name)
Look up instanced visuals by name.
- Parameters:
name – Visual name.
- Returns:
Shared pointer to the instanced visuals. Aborts if not found.
-
std::shared_ptr<InstancedVisuals> findInstancedVisuals(const std::string &name)
Look up instanced visuals by name without aborting when absent.
- Parameters:
name – Visual name.
- Returns:
The instanced visuals, or nullptr.
-
std::shared_ptr<InstancedVisuals> getTendonVisual(const std::string &name) const
Automatically maintained spatial tendon drawing, available after scene sync. Returns nullptr for an unknown or fixed tendon. Width is a radius; color, enabled state and path changes are reflected on the next rendered frame.
- Parameters:
name – Tendon name.
- Returns:
Renderer-maintained instanced visual, or nullptr.
-
void removeInstancedVisuals(const std::string &name)
Remove instanced visuals by name.
- Parameters:
name – Visual name to remove; aborts (
RSFATAL) if unknown.
-
std::shared_ptr<CameraFrustum> addCameraFrustum(const std::string &name, const glm::vec4 &color = glm::vec4(1.f, 1.f, 1.f, 1.f))
Create a camera frustum visualization.
Adds a line-mesh custom visual named
name(remove it with removeVisualObject()); duplicate names are fatal.- Parameters:
name – Visual name.
color – Frustum color.
- Returns:
Shared pointer to the frustum helper used to update its shape and pose.
-
inline void setGroundPatternResourcePath(const std::string &path)
Set a tiled ground texture for halfspace visuals.
Loaded with loadTextureWithTiling() (linear, not sRGB). GL context required.
- Parameters:
path – Path to the texture image.
-
inline std::string getGroundPatternResourcePath()
Get the current ground texture path.
- Returns:
Ground texture path string.
-
void updateObjectLists()
Copy the bound World’s render state for the next renders.
Captures the World’s objects, poses, appearance, terrain and deformable geometry, tendons and .rscene scene into a PhysicsSnapshot and applies it. Every render calls this automatically; renders draw the copy, not the World (see ThreadingMode for stepping the World on another thread). Does nothing while an applyPhysicsSnapshot() snapshot is shown. Requires a current GL context.
Show a physics snapshot instead of the bound World.
Capture with PhysicsSnapshotCapture immediately after integrate2() while the World is protected, publish the immutable snapshot to the render thread without holding a render mutex on the physics thread, and apply it on the render thread with its GL context current. Later renders draw it, including shadow maps, until the next applied snapshot or clearPhysicsSnapshot(); they never read a World. The snapshot can outlive removed physics objects. Scene files and materials must remain available.
- Parameters:
snapshot – Frame to show; must be non-null.
-
void clearPhysicsSnapshot()
Show the bound World again: copies it now, as updateObjectLists() does, so protect it as for a render. Requires a current GL context.
-
void setObjectHidden(raisim::Object *object, bool hidden)
Change render visibility without removing an object’s physics collision.
- Parameters:
object – Object in this renderer’s world; throws std::invalid_argument when null or not part of the world.
hidden – True to stop drawing it.
-
inline const RaisimObject *debugObjectFor(raisim::Object *object) const
Return the cached draw wrapper for tests and diagnostics.
- Parameters:
object – raisim object.
- Returns:
Renderer-owned wrapper, or nullptr if the object has not been synced.
-
inline uint64_t debugSceneObjectCandidateRevision() const
Return the object candidate cache revision for tests and diagnostics.
- Returns:
Counter value.
-
inline size_t debugSceneVisualizationCandidateRebuilds() const
Return visualization candidate cache rebuild count for tests and diagnostics.
- Returns:
Counter value.
-
inline size_t debugSceneVisualizationCandidateCacheHits() const
Return visualization candidate cache hit count for tests and diagnostics.
- Returns:
Counter value.
-
inline uint64_t debugActiveAdditionalLightSelectionRevision() const
Return active additional-light selection revision for tests and diagnostics.
- Returns:
Counter value.
-
inline size_t debugActiveAdditionalLightSelectionRebuilds() const
Return active additional-light selection rebuild count for tests and diagnostics.
- Returns:
Counter value.
-
inline size_t debugActiveAdditionalLightSelectionCacheHits() const
Return active additional-light selection cache hit count for tests and diagnostics.
- Returns:
Counter value.
-
void orthogonalViewSwitch()
Step the viewer camera through axis-aligned orthographic views.
Switches the internal camera to orthographic projection and, on each call, moves it to the next of six views placed 2 m from the camera target on the +X, +Y, -X, -Y, +Z and -Z sides, looking at the target. It does not switch back to perspective; use getCamera().setProjectionMode() for that.
-
void renderDepthPlaneDistance(raisim::DepthCamera &sensorCam, Camera &cam, Shader *depthPlaneOverride = nullptr, bool drawVisualizationObjects = false, bool visualizationObjectsMustBeDetectable = true)
Render a linear depth plane for a raisim depth camera.
Copies the sensor’s pose into
cam(as renderWithExternalCamera() does), then behaves like the Camera overload.- Parameters:
sensorCam – Raisim depth camera; its pose is updated and copied.
cam – Render camera to use; receives the depth image.
depthPlaneOverride – Optional shader override.
drawVisualizationObjects – Include custom and instanced visuals.
visualizationObjectsMustBeDetectable – When true, include only visualization objects marked detectable; when false, include all visualization objects.
-
void renderDepthPlaneDistance(Camera &cam, Shader *depthPlaneOverride = nullptr, bool drawVisualizationObjects = false, bool visualizationObjectsMustBeDetectable = true)
Render a linear depth plane with a given camera.
Writes camera-plane depth into
cam'sR32F linear-depth target (read it with Camera::getLinearDepthTexture()); pixels with no geometry are 0. Weather, post-processing and point clouds are not involved. Requires this renderer’s GL context.- Parameters:
cam – Render camera to use; receives the depth image.
depthPlaneOverride – Optional shader override.
drawVisualizationObjects – Include custom and instanced visuals.
visualizationObjectsMustBeDetectable – When true, include only visualization objects marked detectable; when false, include all visualization objects.
-
inline unsigned int getDepthPlaneTexture() const
Get the internal viewer camera’s linear depth texture id.
For an external camera passed to renderDepthPlaneDistance(), read that camera’s Camera::getLinearDepthTexture() instead.
- Returns:
OpenGL texture id for R32F linear depth (0 before it is allocated).
-
void measureSpinningLidarSingleDrawGPU(raisim::SpinningLidar &lidar, const glm::dvec3 &sensorPosW, const glm::dmat3 &sensorRotW, const raisim::Object *objectToExclude = nullptr)
Measure a spinning LiDAR on the GPU.
Advances the head with SpinningLidar::advanceSweep() (the sweep state is shared with SpinningLidar::update(), so the two can alternate) and casts the swept yaw columns against the world’s collision bodies (World::getRayCastBodies()), stores the hits in the sensor frame with lidar.setScan() and stamps the world time. The scan reproduces SpinningLidar::update(): the same columns and point order, exact intersections with primitives, heightmaps and meshes, rays starting at rangeMin, and the sensor’s own body ignored. Ranges agree to float precision (about 1e-5 of the range); a ray grazing a silhouette within that tolerance may differ. Requires this renderer’s GL context.
- Parameters:
lidar – Raisim spinning lidar to update.
sensorPosW – LiDAR position in world coordinates.
sensorRotW – LiDAR orientation in world coordinates.
objectToExclude – Optional object whose bodies are all ignored (e.g. the carrier).
- Throws:
std::runtime_error – if a GL resource cannot be created or the scene exceeds a GPU limit.
-
void setLinearHdrRenderingEnabled(bool enabled)
Keep scene radiance linear through MSAA, fog, bloom and DoF, then apply the selected exposure/tone curve/gamma in the existing post pass. Opt-in for compatibility. External captures with postProcess=false keep their legacy contract; internal reflection captures inherit the scene domain. Bloom thresholds are scene-linear radiance in this mode. Changing it resets temporal AA history.
- Parameters:
enabled – True to enable linear HDR rendering (default false).
-
inline bool linearHdrRenderingEnabled() const
- Returns:
True when linear HDR rendering is enabled (see setLinearHdrRenderingEnabled()).
-
GeometryRefractionDiagnostics geometryRefractionDiagnostics() const
- Returns:
Diagnostics: state of geometry (dielectric) refraction rendering; default-constructed when that path has never run. CPU only.
-
GeometryRefractionSamplingStatistics geometryRefractionSamplingStatistics() const
Explicit GPU readback; requires this renderer’s GL context and may stall.
- Returns:
Sampling statistics, default-constructed when the path has never run.
-
void setSkyVisibilityGrid(const SkyVisibilityGrid &grid, float strength = 1.0f, float edgeFadeMeters = 2.0f)
Upload a static sky-visibility grid that attenuates environment lighting.
Call on the rendering thread with its GL context current; the data is copied into a texture. Only global environment lighting is attenuated; direct light, authored ambient, lightmaps and local irradiance volumes keep their own visibility. Replaces any previous grid.
- Parameters:
grid – Visibility grid; validated (throws std::invalid_argument).
strength – Attenuation strength in [0, 1] (throws std::invalid_argument otherwise).
edgeFadeMeters – Fade distance at the grid boundary in metres, >= 0.
-
void clearSkyVisibilityGrid()
Remove the sky-visibility grid.
-
void setBakedIrradianceGrid(const BakedIrradianceGrid &grid, float strength = 1.f, float edgeFadeMeters = 2.f)
Upload a static baked-irradiance grid (scene-referred diffuse bounce).
Independent of environment sky fill. Upload/clear on the owning rendering GL context; disabled by default. Replaces any previous grid and resets temporal AA history.
- Parameters:
grid – Irradiance grid; validated (throws std::invalid_argument).
strength – Strength in [0, 4] (throws std::invalid_argument otherwise).
edgeFadeMeters – Fade distance at the grid boundary in metres, >= 0.
-
void clearBakedIrradianceGrid()
Remove the baked-irradiance grid.
-
inline Light &getLight()
Access the main scene light (the single main shadow caster).
Direct edits take effect on the next frame, but setRenderQualitySettings(), setRenderQualityPreset(), promoteDominantAdditionalLightToMainShadowCaster() and enabled weather overwrite parts of it. Call requestShadowUpdate() after moving it when shadows are not refreshed every frame.
- Returns:
Reference to the main light, owned by the renderer.
-
void addAdditionalLight(const AdditionalLight &light)
Add a light besides the main light.
The light is sanitized and copied. Additional lights with AdditionalLight::castsShadows set can receive shadow maps when shadows are enabled and RenderQualitySettings::shadowedLightBudget is greater than 1 (up to kMaxAdditionalShadowLights per frame); otherwise they only shade. Note that setRenderQualitySettings() / setRenderQualityPreset() clear all additional lights, so add lights after choosing the quality settings.
- Parameters:
light – Additional light. Ignored once kMaxAdditionalLights lights exist.
-
bool updateAdditionalLight(size_t index, const AdditionalLight &light)
Replace an existing additional light without forcing unrelated shadow maps dirty.
- Parameters:
index – Index in insertion order.
light – New light (sanitized and copied).
- Returns:
True if the light existed and was replaced.
-
void clearAdditionalLights()
Remove all additional lights (including their shadow maps).
The main light is unaffected.
-
inline size_t additionalLightCount() const
Return the current number of additional lights.
- Returns:
Number of additional lights (excluding the main light).
-
bool promoteDominantAdditionalLightToMainShadowCaster(bool preferSpotLights = true, bool removePromotedAdditionalLight = true)
Promote the dominant imported/local light to the single shadow-casting main light.
This is intended for authored glTF scenes that have a clear lamp/spot light. It keeps low-quality rendering fast because no additional shadow maps are created. Candidates must have AdditionalLight::castsShadows set and non-zero power; point lights are never promoted (they use cubemap shadows through the additional-light budget). The main light takes over the candidate’s type, pose, color and attenuation, and its shadows are enabled.
- Parameters:
preferSpotLights – Prefer spot lights over other light types when possible.
removePromotedAdditionalLight – Remove the promoted light from the additional-light list to avoid double-counting its direct contribution.
- Returns:
True if a suitable light was promoted.
-
size_t importSceneLights(const std::string &sceneFile, float intensityScale = 1.0f)
Import authored scene lights from a mesh/scene file through Assimp.
Imported lights are appended as additional lights (see addAdditionalLight()). This is explicit so low-quality rendering does not pay for scene lights unless an application imports them. When any light was added and RenderQualitySettings::autoSelectImportedShadowLight is set with a non-zero shadowedLightBudget, the dominant one is promoted to the main shadow caster. Import errors are printed to stderr, not thrown.
- Parameters:
sceneFile – Scene/mesh file to read lights from.
intensityScale – Multiplier applied to imported light intensities.
- Returns:
Number of lights appended, capped by kMaxAdditionalLights.
-
void setRenderQualityPreset(RenderQualityPreset preset)
Apply a named viewer-quality preset at runtime.
Equivalent to setRenderQualitySettings(defaultRenderQualitySettings(preset)) followed by recording
presetas the active preset; the same side effects apply.- Parameters:
preset – Quality preset to apply.
-
inline RenderQualityPreset getRenderQualityPreset() const
Return the active named quality preset, or Custom after explicit settings.
- Returns:
Preset; Fast for a freshly constructed renderer.
-
void setRenderQualitySettings(const RenderQualitySettings &settings)
Apply explicit viewer-quality settings at runtime.
Besides storing (and clamping) the settings, this re-derives renderer state from them: background color, fog density, gamma, depth of field, the main light (type reset to directional, direction, colors, shadow resolution and parameters), the shadow box and center offset, and texture filtering of loaded textures. It also clears all additional lights and, when RenderQualitySettings::addViewerFillLights is set, adds the built-in fill and rim lights. The active preset becomes Custom. With weather enabled the settings become the base that weather is applied on.
- Parameters:
settings – Settings to apply. Throws std::invalid_argument for an unknown temporal AA method, a non-finite jitter scale, a current weight outside [0.02, 1] or a sharpness outside [0, 1].
-
inline const RenderQualitySettings &getRenderQualitySettings() const
Return the active explicit viewer-quality settings.
- Returns:
Effective settings, including weather overrides and clamping.
-
inline const RenderQualitySettings &getUserRenderQualitySettings() const
- Returns:
Settings as last set by the user, i.e. without weather overrides while weather is enabled; otherwise the same as getRenderQualitySettings().
-
void setDepthPrepassesEnabled(bool opaque, bool foliageAlpha)
Toggle depth prepasses while preserving authored lights and materials.
Unlike setRenderQualitySettings() this does not reset lights; the preset becomes Custom.
- Parameters:
foliageAlpha – RenderQualitySettings::foliageAlphaDepthPrepass.
-
void setAdditionalLightContributionThreshold(float threshold)
Set the total additional-light incident-radiance cutoff budget without resetting authored lights. Zero (default) keeps exact unlimited lighting. Invalid/negative values disable culling. This is not a final-pixel tolerance. The preset becomes Custom.
- Parameters:
threshold – RenderQualitySettings::additionalLightContributionThreshold.
-
void setFoliageWindTimeSeconds(float seconds)
Set the global foliage wind animation clock without changing quality preset state.
- Parameters:
seconds – Clock value in seconds; negative or non-finite values become 0.
-
void advanceFoliageWindTime(float deltaSeconds)
Advance the global foliage wind animation clock.
- Parameters:
deltaSeconds – Elapsed seconds; non-positive or non-finite values are ignored. The clock wraps at 100000 s.
-
void printRenderDiagnostics(std::ostream &out = std::cout) const
Print active viewer-quality, light, shadow, and post-process diagnostics.
- Parameters:
out – Output stream.
-
void writeRenderDiagnosticsJson(std::ostream &out, const SceneImportReport *importReport = nullptr) const
Write structured render diagnostics as JSON.
The JSON is intended for regression tests, issue reports, and imported-scene debugging. It contains render-quality settings, scene/resource counts, lights, shadow selection state, postprocess state, and an optional scene-import report.
- Parameters:
out – Output stream.
importReport – Optional report to embed (not stored).
-
std::string renderDiagnosticsJson(const SceneImportReport *importReport = nullptr) const
Return structured render diagnostics as a JSON string.
- Parameters:
importReport – Optional report to embed.
- Returns:
Same JSON as writeRenderDiagnosticsJson().
-
RenderPassAccounting estimateRenderPassAccounting() const
Return estimated render-pass accounting for the current quality settings.
This is an estimate-only diagnostic. It does not insert GPU timers or render any frame. Use captureRenderPassTimings() when exact blocking GPU timings are required.
- Returns:
Estimated pass counts.
-
TransparentDrawDebugView transparentDrawDebugView(size_t maxItems = 32) const
Return the transparent draw order that the viewer path should use for the current camera.
The result is diagnostic-only. It does not render and does not mutate instance buffers.
- Parameters:
maxItems – Maximum entries in backToFrontOrder; 0 returns all.
- Returns:
Transparent draw diagnostics for the internal camera.
-
TransparentDrawDebugView transparentDrawDebugView(const Camera &camera, size_t maxItems = 32) const
Return transparent draw diagnostics for an explicit render camera.
- Parameters:
camera – Camera used for sorting and the overdraw estimate.
maxItems – Maximum entries in backToFrontOrder; 0 returns all.
- Returns:
Transparent draw diagnostics.
-
ShaderWarmupDiagnostics shaderWarmupDiagnostics() const
Return startup shader compile/warmup diagnostics for built-in RayRai programs.
RayRai registers all built-in shader programs during construction and compiles optional shaders lazily on first use. This exposes the measured compile/link cost and linked program count so startup and first-use stalls can be tracked.
- Returns:
Warmup diagnostics (queries GL program state; GL context required).
-
std::vector<std::string> linkedShaderNames() const
Names of every shader program currently linked, sorted alphabetically. Useful for diagnostics and for callers that want to record the “hot set” of shaders an application actually uses so a future run can pre-warm only those.
- Returns:
Sorted program names.
-
long long warmupNextShader(bool &done)
Compile one not-yet-compiled built-in shader program, if any.
Returns the number of milliseconds spent compiling (0 if no work was done). The output flag
doneis set to true when every registered program has been compiled at least once. Iterates all registered programs — most of which an application typically doesn’t use; prefercompileShaderByNameto pre-warm just the heavy shaders your active scene actually exercises. Must be called on the thread that owns the GL context.- Parameters:
done – [out] Set to true when nothing was left to compile, false otherwise.
- Returns:
Milliseconds spent compiling. Throws std::runtime_error when a shader fails.
-
long long compileShaderByName(const std::string &name)
Compile a specific built-in shader by name if not already linked. Returns the milliseconds spent compiling (0 if already linked or unknown name). Lets the application warm just the shaders it knows will be needed — e.g.
pbrMeshHigh(the high-fidelity PBR mesh program) is typically the dominant cost for content rendering, so pre-warming only that one avoids most of the visible “freeze” on the first content frame without paying for unused shader variants. Must be called on the thread that owns the GL context.- Parameters:
name – Built-in program name (see linkedShaderNames()).
- Returns:
Milliseconds spent compiling. Throws std::runtime_error when the shader fails.
-
MaterialTextureBudgetRecommendation recommendMaterialTextureBudget(size_t budgetBytes = 0) const
Build a non-mutating material texture memory fallback recommendation.
If budgetBytes is zero, a conservative preset-aware default is used. The recommendation only changes quality settings that reduce texture sampling/setup cost; it does not unload existing textures or alter sensor behavior. Texture sizes are queried from GL, so call it with this renderer’s GL context current.
- Parameters:
budgetBytes – Texture memory budget in bytes; 0 selects the preset default.
- Returns:
Recommendation; apply recommendedSettings yourself if desired.
-
void writeRenderDiagnosticsFiles(const std::filesystem::path &directory, const SceneImportReport *importReport = nullptr) const
Write structured diagnostics files, including uncapped mesh/material tables.
This is intended for explicit issue reports and offline analysis. The regular in-memory JSON remains capped so Fast/Balanced users do not accidentally pay for large debug payloads unless they request file export.
- Parameters:
directory – Output directory, created if needed; files such as
render_diagnostics.jsonandmesh_diagnostics_full.jsonare overwritten.importReport – Optional report to embed.
-
inline void setDOFEnabled(bool e)
Enable or disable depth of field post-processing.
Overwritten by setRenderQualitySettings() (depthOfFieldEnabled).
- Parameters:
e – True to enable.
-
inline void setDOFParams(float focusDist, float focusRange, float maxRadius)
Set depth of field parameters.
Overwritten by setRenderQualitySettings().
- Parameters:
focusDist – Focus distance in view space.
focusRange – Focus range around the focus distance.
maxRadius – Max blur radius in pixels.
-
inline void setShowCollisionBodies(bool show)
Toggle rendering of collision shapes for articulated systems.
- Parameters:
show – True to render collision bodies (default false).
-
inline bool getShowCollisionBodies() const
Return collision-body rendering state.
- Returns:
True if collision bodies are shown.
-
void setExternalFont(ImFont *font)
Provide an ImGui font to use for the viewer overlay.
Also installed as ImGui’s default font when an ImGui context exists.
- Parameters:
font – Pointer to an ImGui font (not owned).
-
inline ImFont *getExternalFont() const
Retrieve the external ImGui font pointer.
- Returns:
Font pointer or nullptr.
Public Static Functions
-
static unsigned int loadTextureWithTiling(const char *path, bool useSrgbFormat = false)
Load an image file into an OpenGL texture with repeat tiling.
The texture gets GL_REPEAT wrapping, mipmaps, and the process-wide defaults from setDefaultTextureFilteringQuality(). Results are cached per thread and per GL context by (path, sRGB flag), so repeated calls return the same id; a failed load is cached as 0 too. Requires a current GL context.
- Parameters:
path – Path to an image file supported by stb_image.
useSrgbFormat – If true, RGB/RGBA textures are uploaded as sRGB color textures. Use true for albedo/emissive color maps and false for data maps such as normal, metallic-roughness, AO, depth, and masks.
- Returns:
OpenGL texture id, or 0 on failure.
-
static unsigned int updateSingleChannelTexture(unsigned int existingTextureId, int width, int height, const unsigned char *data)
Create or update a single-channel R8 2D texture from raw pixel data.
Used for terrain splat control maps. Pass
existingTextureId0 to allocate a new texture, otherwise the existing texture is updated in place (and reallocated if the dimensions differ). New textures use linear filtering and clamp-to-edge wrapping. Requires a current GL context.- Parameters:
existingTextureId – Texture to update, or 0 (or a deleted id) to create one.
width – Width in pixels; must be positive.
height – Height in pixels; must be positive.
data –
width * heighttightly packed bytes; must not be null.
- Returns:
The texture id (new or reused), or 0 on invalid input.
-
static unsigned int loadHdrEquirectangularCubemap(const char *path, int faceSize = 128, bool generateMipmaps = true)
Load a Radiance .hdr equirectangular environment into a cubemap texture.
This is intended for High/Ultra viewer PBR workflows. It does not allocate anything unless the application explicitly calls it.
- Parameters:
path – Path to a .hdr image supported by stb_image.
faceSize – Cubemap face size in pixels.
generateMipmaps – Whether to generate mip levels for roughness sampling.
- Returns:
OpenGL cubemap id, or 0 on failure.
-
static unsigned int createHdrIrradianceCubemap(const char *path, int faceSize = 32, int sampleCount = 256)
Generate a diffuse irradiance cubemap from a Radiance .hdr equirectangular environment.
This is CPU-side cosine-hemisphere integration intended for High/Ultra PBR setup. Creation is explicit so Fast/Balanced RL rendering does not pay the cost.
- Parameters:
path – Path to a .hdr image supported by stb_image.
faceSize – Irradiance cubemap face size in pixels.
sampleCount – Number of hemisphere samples per texel.
- Returns:
OpenGL cubemap id, or 0 on failure.
-
static unsigned int createHdrPrefilteredEnvironmentCubemap(const char *path, int faceSize = 128, int mipLevels = 5, int sampleCount = 256)
Generate a prefiltered specular environment cubemap from a Radiance .hdr equirectangular environment.
Mip level 0 is sharp and higher mip levels are GGX-prefiltered with increasing roughness. Use this as Material::prefilteredEnvironmentMap together with createSplitSumBrdfLut().
- Parameters:
path – Path to a .hdr image supported by stb_image.
faceSize – Base cubemap face size in pixels.
mipLevels – Number of mip levels to allocate and integrate.
sampleCount – Number of GGX samples per texel.
- Returns:
OpenGL cubemap id, or 0 on failure.
-
static unsigned int createSplitSumBrdfLut(int size = 256, int sampleCount = 512)
Create a numerically integrated split-sum BRDF LUT.
Use this as Material::brdfLut for High/Ultra PBR. Creation is explicit so Fast/Balance paths do not pay for it. The result is an RG16F texture (x = N.V, y = roughness).
- Parameters:
size – LUT width and height in texels.
sampleCount – GGX samples per texel.
- Returns:
OpenGL texture id owned by the caller, or 0 if either argument is not positive.
-
static void setTextureAnisotropy(unsigned int target, unsigned int textureId, float requestedLevel)
Apply anisotropic filtering to an existing 2D or cubemap texture if supported.
- Parameters:
target – Texture target such as GL_TEXTURE_2D or GL_TEXTURE_CUBE_MAP.
textureId – OpenGL texture id.
requestedLevel – Requested anisotropy level. Values <= 1 leave the texture unchanged.
-
static void setTextureFilteringQuality(unsigned int target, unsigned int textureId, float anisotropy, float mipLodBias)
Apply minification quality controls to an existing texture.
Positive mip LOD bias prefers blurrier mips and reduces distant texture shimmer. Negative values sharpen but can alias, so RayRai clamps the bias to [-1, 2].
- Parameters:
target – Texture target such as GL_TEXTURE_2D.
textureId – OpenGL texture id; 0 is ignored.
anisotropy – Requested anisotropy, see setTextureAnisotropy().
mipLodBias – Mip LOD bias, clamped to [-1, 2].
-
static void setDefaultTextureFilteringQuality(float anisotropy, float mipLodBias)
Set process-wide filtering defaults used by future loadTextureWithTiling() calls.
- Parameters:
anisotropy – Default anisotropy, clamped to [1, 16].
mipLodBias – Default mip LOD bias, clamped to [-1, 2].
-
static void getDefaultTextureFilteringQuality(float &anisotropy, float &mipLodBias)
Read process-wide filtering defaults used by future loadTextureWithTiling() calls.
- Parameters:
anisotropy – [out] Default anisotropy.
mipLodBias – [out] Default mip LOD bias.
-
static void setTextureSamplerState(unsigned int target, unsigned int textureId, int wrapS, int wrapT, int minFilter, int magFilter)
Apply sampler wrap/filter state to an existing texture.
- Parameters:
target – Texture target such as GL_TEXTURE_2D.
textureId – OpenGL texture id; 0 is ignored.
wrapS – GL wrap mode for S (e.g. GL_REPEAT).
wrapT – GL wrap mode for T.
minFilter – GL minification filter.
magFilter – GL magnification filter.
-
static inline unsigned int loadColorTextureWithTiling(const char *path)
Load an albedo/emissive color texture as sRGB.
- Parameters:
path – Path to an image file supported by stb_image.
- Returns:
OpenGL texture id, or 0 on failure.
-
static inline unsigned int loadDataTextureWithTiling(const char *path)
Load a data texture as linear values.
- Parameters:
path – Path to an image file supported by stb_image.
- Returns:
OpenGL texture id, or 0 on failure.
-
static void createOffscreenGlContext(SDL_Window *&window, SDL_GLContext &glContext, const char *title = "rayrai_offscreen")
Create a hidden SDL window and an offscreen OpenGL context.
If the calling thread already has a current SDL OpenGL context, the new context joins its share group. This lets worker renderers reuse immutable untextured mesh buffers while retaining context-local VAOs and render targets. With no current context, an independent root context is created. Initializes SDL video if needed and requests an OpenGL 4.3 core context, falling back to 3.3. The new context is left current on the calling thread. Aborts (
RSFATAL) when the window or context cannot be created. The caller owns both handles (SDL_GL_DeleteContext / SDL_DestroyWindow).- Parameters:
window – Output pointer for the created SDL window.
glContext – Output handle for the OpenGL context.
title – Window title for the hidden SDL window.
-
static void makeOffscreenContextCurrent(SDL_Window *window, SDL_GLContext glContext)
Make an existing offscreen context current and update glbinding.
Also resets rayrai’s per-context binding caches. Aborts (
RSFATAL) on a null argument or when SDL cannot make the context current.- Parameters:
window – SDL window owning the OpenGL context.
glContext – OpenGL context to make current.
-
static void detachOffscreenGlContext(SDL_Window *window)
Detach the GL context currently bound to
windowon this thread.createOffscreenGlContext leaves the context it made current on the calling thread, so a context created on the main thread has to be released before a worker can adopt it with makeOffscreenContextCurrent — a context is current on at most one thread at a time. Safe to call with no context current.
- Parameters:
window – SDL window whose context should be released; nullptr is a no-op.
-
static void prewarmShadersForCurrentContext(ThreadingMode threadingMode = ThreadingMode::MultiThread, std::string shaderBinaryCacheDirectory = std::string{})
Compile every built-in shader using the GL context currently bound to the calling thread, populating the on-disk binary cache.
Intended for parallel RL workflows: spawn a background thread that holds its own offscreen GL context, call this once, and worker threads that later construct
RayraiWindowinstances will find the heavy shaders already in the cache (or briefly block on the per-shader compile mutex for any program this thread is still finishing).Net effect across a process: each shader’s GLSL→binary compile runs exactly once, regardless of how many worker threads concurrently construct
RayraiWindows.Pre-conditions: the caller’s thread has made a valid offscreen GL context current. Post-condition: the temporary
RayraiWindowused for compilation is destroyed before this returns; the caller’s context is left current. The caller is responsible for the surroundingSDL_GL_MakeCurrent(nullptr)/SDL_GL_DeleteContext/ thread join.Side effect: the temporary renderer re-applies the process-wide shader settings (one compile thread, binary cache enabled at
shaderBinaryCacheDirectory, cache logging off), like any constructor.- Parameters:
threadingMode – Must match the mode used by the worker threads that will eventually construct their own
RayraiWindows. Defaults toMultiThreadsince prewarming only makes sense when other threads will also render.shaderBinaryCacheDirectory – Optional explicit cache directory. Empty selects the default per-user cache directory (see the RayraiWindow constructor).
-
static ReflectionProbeCaptureFrame reflectionProbeCaptureFrame(int face)
Return the capture camera frame used for a cubemap face.
The frame follows the same OpenGL cubemap convention used by environment-map sampling and CPU probe filtering. It is exposed so tests and tools can validate local reflection probe orientation without rendering a probe.
- Parameters:
face – Face index in GL order (+X, -X, +Y, -Y, +Z, -Z), clamped to [0, 5].
- Returns:
The face’s camera basis.
-
static std::vector<ReflectionProbeSidecarProbe> loadReflectionProbeSidecar(const std::string &sceneFile, ReflectionProbeSidecarSettings *settings = nullptr, std::string *loadedSidecarPath = nullptr)
Parse the reflection-probe sidecar that belongs to a scene file (CPU only).
Sidecar lookup (shared by all sidecar loaders): if
sceneFileitself ends in.jsonit is used; otherwise<sceneFile>.rayrai_probes.json, then<dir>/<stem>.rayrai_probes.json. The first existing file wins. Nothing is captured; use the returned entries with captureFilteredReflectionProbe().- Parameters:
sceneFile – Scene/mesh file path, or the sidecar path itself.
settings – [out] Optional
qualityblock; reset to defaults first.loadedSidecarPath – [out] Optional path of the file that was read (empty if none).
- Returns:
Parsed probes; empty when no sidecar exists or it has no
probesarray.
-
static inline ReflectionProbeSidecarLoadResult loadReflectionProbeSidecarResult(const std::string &sceneFile)
Struct-returning overload; prefer this in new code.
- Parameters:
sceneFile – Scene/mesh file path, or the sidecar path itself.
- Returns:
Probes, quality settings and the sidecar path.
-
static EnvironmentSidecarSettings loadEnvironmentSidecar(const std::string &sceneFile, std::string *loadedSidecarPath = nullptr)
Parse a scene’s
.rayrai_environment.jsonsidecar (CPU only).Uses the same lookup as loadReflectionProbeSidecar().
- Parameters:
sceneFile – Scene/mesh file path, or the sidecar path itself.
loadedSidecarPath – [out] Optional path of the file that was read (empty if none).
- Returns:
Parsed values with presence flags; all flags false when no sidecar exists.
-
static WeatherSidecarSettings loadWeatherSidecar(const std::string &sceneFile, std::string *loadedSidecarPath = nullptr)
Parse a scene’s
.rayrai_weather.jsonsidecar (CPU only).Uses the same lookup as loadReflectionProbeSidecar(). Weather keys are read from a
weatherobject when present, otherwise from the top level.- Parameters:
sceneFile – Scene/mesh file path, or the sidecar path itself.
loadedSidecarPath – [out] Optional path of the file, set only when it contained weather or fog data.
- Returns:
Parsed settings; both presence flags false when nothing was found.
-
static bool writeWeatherSidecar(const std::string &sidecarFile, const WeatherSettings &settings, const std::vector<LocalFogVolume> &localFogVolumes = {})
Write weather settings (and optional fog volumes) as a weather sidecar JSON file.
- Parameters:
sidecarFile – Output path; overwritten.
settings – Weather settings to write.
localFogVolumes – Fog volumes to write; at most kMaxLocalFogVolumes are written.
- Returns:
False when the file cannot be opened for writing.
-
static RenderQualitySettings defaultRenderQualitySettings(RenderQualityPreset preset)
Return the default settings for a named preset.
- Parameters:
preset – Preset to query.
- Returns:
Settings that setRenderQualityPreset() would apply.
-
static DynamicQualityRecommendation recommendDynamicQuality(const RenderQualitySettings &settings, RenderQualityPreset preset, const std::vector<RenderPassTiming> &timings)
Build a sensor-safe dynamic-quality recommendation from explicit GPU pass timings.
This does not mutate renderer state. It is intended for Fast/Balanced viewer loops that explicitly opt into adaptive render scale or static shadow updates after measuring GPU cost. High/Ultra recommendations never change settings. Otherwise, when the summed GPU time exceeds the preset budget, shadow-bound frames stop per-frame shadow updates, fill-bound frames lower viewerRenderScale by 15 % (not below 0.6 for Fast, 0.75 otherwise), and post-process-bound frames reduce bloom/AO/indirect-lighting cost.
- Parameters:
settings – Current settings.
preset – Preset that selects the budget (see DynamicQualityRecommendation::targetFrameMs).
timings – Pass timings, e.g. from captureRenderPassTimings().
- Returns:
Recommendation.
-
static RgbaLuminanceMetrics analyzeRgbaLuminance(const std::vector<unsigned char> &rgba, int width, int height)
Analyze display-space luminance and saturation from an RGBA8 capture.
This is intended for exposure/tone-map diagnostics and image regression tests. It does not render or read from OpenGL; callers pass already captured RGBA8 pixels.
- Parameters:
rgba – RGBA8 pixels (alpha ignored); at most width * height pixels are read.
width – Image width in pixels.
height – Image height in pixels.
- Returns:
Metrics; zero-filled for empty or invalid input.
-
static ExposureRecommendation recommendExposure(const RgbaLuminanceMetrics &metrics, double currentExposure = 1.0, double targetMedianLuminance = 0.45, double targetP95Luminance = 0.90, double minExposure = 0.125, double maxExposure = 8.0)
Build a bounded exposure recommendation from display-space luminance metrics.
This does not mutate renderer state. It is intended for explicit viewer calibration, quality-comparison reports, and offline screenshot tooling. Sensor renders should only apply the result if the caller explicitly opts into viewer-style postprocessing.
Highlights take priority: clipping (> 1 % channels) or p95 above target scales the exposure down to the p95 target; otherwise midtones below 70 % / above 135 % of the median target are corrected toward it without pushing p95 past its target.
- Parameters:
metrics – Metrics of an image rendered at
currentExposure.currentExposure – Exposure used for that image; must be positive.
targetMedianLuminance – Desired median display luminance.
targetP95Luminance – Desired 95th percentile display luminance.
minExposure – Lower clamp for the result; must be positive.
maxExposure – Upper clamp for the result.
- Returns:
Recommendation;
validis false for invalid input.
-
static double smoothExposure(double currentExposure, double targetExposure, double deltaSeconds, double brightenRate = 1.2, double darkenRate = 3.0, double minExposure = 0.125, double maxExposure = 8.0)
Smooth an explicitly chosen exposure target over time.
This helper is stateless and does not mutate renderer settings. Use a larger darken rate than brighten rate to adapt quickly away from clipping while avoiding flicker when lifting dark scenes. Computes
current + (target - current) * (1 - exp(-rate * dt))with both exposures clamped to [minExposure, maxExposure].- Parameters:
currentExposure – Current exposure.
targetExposure – Desired exposure.
deltaSeconds – Elapsed time in seconds.
brightenRate – Rate (1/s) used when the target is brighter.
darkenRate – Rate (1/s) used when the target is darker.
minExposure – Lower exposure bound.
maxExposure – Upper exposure bound.
- Returns:
New exposure; the clamped current exposure when any input is invalid.
-
static RgbaLuminanceHistogram analyzeRgbaLuminanceHistogram(const std::vector<unsigned char> &rgba, int width, int height, size_t binCount = 64)
Build a display-space luminance histogram from an RGBA8 capture.
This is a CPU diagnostics helper for exposure reports and regression artifacts. It does not render, read OpenGL state, or mutate color-management settings.
- Parameters:
rgba – RGBA8 pixels.
width – Image width in pixels.
height – Image height in pixels.
binCount – Number of equal-width bins over luminance [0, 1].
- Returns:
Histogram; empty for invalid input.
-
static std::vector<unsigned char> renderLuminanceHistogramRgba(const RgbaLuminanceHistogram &histogram, int width, int height)
Render a luminance histogram into a simple RGBA8 debug image.
The output is top-left row order. It is intended for reports and screenshots, not for the main frame path.
- Parameters:
histogram – Histogram to draw.
width – Output width in pixels.
height – Output height in pixels.
- Returns:
RGBA8 image of width * height pixels, or empty for a non-positive size.
-
static std::vector<unsigned char> renderCloudDebugRgba(const RenderQualitySettings &settings, int width, int height)
Render procedural cloud diagnostics into a three-panel RGBA8 image.
The panels are coverage mask, projected shadow attenuation, and approximate cloud-lighting contribution. The CPU path mirrors the shader-side procedural cloud mask, so tests and showcase images can inspect the weather cloud path without screenshots alone.
- Parameters:
settings – Settings providing the cloud parameters.
width – Total output width in pixels (panels side by side).
height – Output height in pixels.
- Returns:
RGBA8 image, or empty for a non-positive size.
-
static std::vector<unsigned char> renderRainDebugRgba(const RenderQualitySettings &settings, const WeatherDiagnostics &diagnostics, int width, int height)
Render rain/wet-material diagnostics into a four-panel RGBA8 image.
The panels are precipitation density, wet-surface mask, puddle mask, and material override strength. The CPU path uses the resolved weather diagnostics plus the same bounded wet/puddle/ripple model used by the PBR shader, so tests and showcase images can inspect the rain material path without relying on screenshots alone.
- Parameters:
settings – Settings providing the wet-material parameters.
diagnostics – Resolved weather, e.g. weatherDiagnostics().
width – Total output width in pixels (panels side by side).
height – Output height in pixels.
- Returns:
RGBA8 image, or empty for a non-positive size.
-
static std::vector<unsigned char> renderSnowDebugRgba(const RenderQualitySettings &settings, const WeatherDiagnostics &diagnostics, int width, int height)
Render snow-material diagnostics into a two-panel RGBA8 image.
The panels are accumulation mask and material override strength. The CPU path uses resolved weather diagnostics plus the same bounded snow accumulation model used by the PBR shader.
- Parameters:
settings – Settings providing the snow-material parameters.
diagnostics – Resolved weather, e.g. weatherDiagnostics().
width – Total output width in pixels (panels side by side).
height – Output height in pixels.
- Returns:
RGBA8 image, or empty for a non-positive size.
-
static std::vector<unsigned char> transformRgbaForOutput(const std::vector<unsigned char> &rgba, int width, int height, const RgbaOutputTransform &transform)
Apply a bounded CPU output transform to RGBA8 pixels for screenshots/reports.
This clamps RGB into displayable range and preserves alpha. It is intended for explicit PNG/screenshot tooling, not for simulation sensor outputs unless requested.
- Parameters:
rgba – RGBA8 pixels.
width – Image width in pixels.
height – Image height in pixels.
transform – Transform to apply (see RgbaOutputTransform for the order).
- Returns:
Transformed RGBA8 pixels, or empty for invalid input.
-
static RgbaCalibrationMetrics analyzeRgbaCalibrationPatches(const std::vector<unsigned char> &rgba, int width, int height, const std::vector<RgbaCalibrationPatch> &patches)
Measure color-calibration patches in display-space RGBA8 pixels.
Patch coordinates use top-left row order, matching RayRai PNG/debug buffers. This is an offline/report helper for calibration scenes and does not mutate renderer exposure, tone mapping, or sensor behavior.
- Parameters:
rgba – RGBA8 pixels; must contain at least width * height pixels.
width – Image width in pixels.
height – Image height in pixels.
patches – Reference patches.
- Returns:
Per-patch and aggregate errors.
-
static std::vector<unsigned char> renderCalibrationPatchReportRgba(const RgbaCalibrationMetrics &metrics, int width, int height)
Render a compact calibration error report image from patch metrics.
One row per patch: measured swatch, target swatch, and an error bar that saturates at an RGB error of 0.5.
- Parameters:
metrics – Metrics from analyzeRgbaCalibrationPatches().
width – Output width in pixels.
height – Output height in pixels.
- Returns:
RGBA8 image, or empty for a non-positive size.
-
static RgbaCalibrationRecommendation recommendCalibrationOutputTransform(const RgbaCalibrationMetrics &metrics)
Build a bounded screenshot/report output transform from calibration patches.
Neutral patches drive exposure and white balance; saturated patches drive a conservative saturation correction. This returns a recommendation only and never mutates renderer state.
- Parameters:
metrics – Metrics from analyzeRgbaCalibrationPatches().
- Returns:
Recommendation; apply it with transformRgbaForOutput().
-
class SynchronousMeshLoadingScope
Loads the mesh files requested while it lives synchronously, without finishing the other pending work.
Unlike setAsyncMeshLoadingEnabled(false), which finishes every pending import and LOD job, possibly a whole scene’s, the scope only makes each mesh requested in it ready when its visual is created; a requested file that is still loading asynchronously is waited for. The rest keep loading in the background. For example, foliage placed by its mesh’s bounds uses one per layer. Asynchronous loading is enabled again at the end if it was enabled at the start. The scope may outlive the window, as one kept across frames can; it then ends without touching the window’s mesh assets.
-
struct RenderOverrides
Override shaders and rendering toggles when using external cameras.
For
Camera-based external renders,drawVisualizationObjectsanddrawPointCloudsenable only custom visuals, instanced visuals, and point clouds markedVisualCategory::Detectable. Non-detectable helper geometry remains visible in the normal interactive viewer but is skipped by these capture paths. The RaiSim RGB/depth sensor-camera overloads disable custom visualization objects and point clouds entirely, regardless of these toggles.Public Members
-
Shader *mesh
Mesh shader override (defaults to shaders_[“mesh”]).
-
Shader *pointcloud
Point cloud shader override (defaults to shaders_[“pointcloud”]).
-
Shader *picking
Picking shader override (defaults to shaders_[“picking”]).
-
Shader *post
Post-process shader override (defaults to shaders_[“post”]).
-
bool doShadows
Enable shadow passes.
-
bool drawCoordinateFrames
Draw coordinate frames.
-
bool drawPointClouds
Draw point clouds that are marked detectable in external-camera captures.
-
bool drawVisualizationObjects
Draw custom visuals and instanced visuals that are marked detectable.
-
bool drawWeatherEffects
Draw viewer-only weather effects such as precipitation particles.
-
bool skipGroundObjects
Skip halfspace and heightmap ground objects in scene-color rendering.
-
unsigned int environmentBackgroundMap
Optional cubemap rendered as a viewer background before scene geometry.
-
float environmentBackgroundExposure
Exposure applied to environmentBackgroundMap when rendered as background.
-
bool postProcess
Apply external-camera postprocessing after rendering.
-
bool allowViewerMsaa
Allow quality preset MSAA for this external render. Sensor overloads force this off.
-
bool allowTemporalAa
Allow quality preset temporal AA for this external render. Sensor overloads force this off.
-
bool allowViewerUpscale
Allow quality preset lower-resolution viewer rendering followed by upscale.
-
bool fixedShadowCenterEnabled
Use fixedShadowCenter instead of the camera-derived directional shadow center, so offline multi-view captures share one shadow region. Uses one cascade; normal shadow dirty tracking remains active.
-
glm::vec3 fixedShadowCenter
World-space directional shadow center used when fixedShadowCenterEnabled is true.
-
Shader *mesh
-
struct SupersampledCapture
Result of captureSupersampledRgba().
Public Members
-
int width
Output width in pixels (the input camera’s render-target width).
-
int height
Output height in pixels (the input camera’s render-target height).
-
int scale
Supersampling factor actually used, clamped to [1, 4].
-
std::vector<unsigned char> rgba
Box-downsampled RGBA8 pixels, top-left row order.
-
int width
-
struct DebugPassCapture
One pass returned by captureDebugPasses().
Public Members
-
std::string fileName
Suggested PNG file name, e.g.
debug_02_normal.png.
-
std::string label
Short pass label, e.g.
normal.
-
int pbrDebugOutput
PBR debug output mode used for this pass (see setPbrDebugOutputMode()).
-
PostProcessDebugMode postProcessDebugMode
Post-process debug mode used for this pass.
-
int width
Capture width in pixels.
-
int height
Capture height in pixels.
-
std::vector<unsigned char> rgba
RGBA8 pixels in top-left row order, ready for PNG writers.
-
std::string fileName
-
struct RgbaLuminanceMetrics
Display-space luminance statistics returned by analyzeRgbaLuminance().
Luminance is Rec. 709 luma (0.2126 R + 0.7152 G + 0.0722 B) of the 8-bit values divided by 255, so all luminance fields are in [0, 1]. Saturation is (max - min) / max per pixel. All fields stay zero for empty input.
Public Members
-
int width
Image width passed in.
-
int height
Image height passed in.
-
size_t pixelCount
Number of pixels analysed.
-
double averageLuminance
Mean luminance.
-
double medianLuminance
50th percentile luminance.
-
double p95Luminance
95th percentile luminance.
-
double p99Luminance
99th percentile luminance.
-
double minLuminance
Minimum luminance.
-
double maxLuminance
Maximum luminance.
-
double averageSaturation
Mean per-pixel saturation.
-
double contrastP95ToMedian
p95Luminance / medianLuminance (0 when the median is ~0).
-
double clippedChannelFraction
Fraction of RGB channel values >= 250.
-
int width
-
struct ExposureRecommendation
Result of recommendExposure(); the target/limit fields echo the inputs.
Public Members
-
bool valid
False when the inputs were invalid (reason is
invalid_input).
-
bool changed
True when the recommended scale differs from 1 by more than 2 %.
-
bool underexposed
Midtones are below 70 % of the target median.
-
bool overexposed
Highlights exceed the p95 target or midtones exceed 135 % of the target median.
-
bool clippingRisk
More than 1 % of channel values are clipped.
-
double currentExposure
Exposure the metrics were captured with.
-
double recommendedExposure
Suggested exposure, clamped to [minExposure, maxExposure].
-
double recommendedExposureScale
recommendedExposure / currentExposure.
-
double targetMedianLuminance
Target median luminance used.
-
double targetP95Luminance
Target 95th percentile luminance used.
-
double minExposure
Lower exposure bound used.
-
double maxExposure
Upper exposure bound used.
-
std::string reason
Machine-readable reason, e.g.
highlight_clipping,lift_midtones,within_target.
-
bool valid
-
struct RgbaLuminanceHistogram
Display-space luminance histogram returned by analyzeRgbaLuminanceHistogram().
Public Members
-
int width
Image width passed in.
-
int height
Image height passed in.
-
size_t pixelCount
Number of pixels counted.
-
size_t binCount
Number of equal-width bins over luminance [0, 1].
-
size_t peakBin
Index of the most populated bin.
-
double peakFraction
Fraction of pixels in peakBin.
-
std::vector<size_t> bins
Pixel count per bin.
-
int width
-
struct RgbaOutputTransform
CPU output transform for screenshots (see transformRgbaForOutput()).
Applied per pixel in this order: multiply by exposure and white balance, scale saturation around Rec. 709 luma, clamp to [0, 1], then apply
value^(1/gamma). The identity defaults leave pixels unchanged.
-
struct RgbaCalibrationPatch
A rectangular reference patch for analyzeRgbaCalibrationPatches().
Public Members
-
std::string name
Patch name, copied to the result.
-
int x
Left edge in pixels (top-left origin).
-
int y
Top edge in pixels (top-left origin).
-
int width
Width in pixels; clipped to the image.
-
int height
Height in pixels; clipped to the image.
-
glm::vec3 targetRgb
Expected display-space RGB in [0, 1].
-
std::string name
-
struct RgbaCalibrationPatchResult
Per-patch measurement inside RgbaCalibrationMetrics.
Public Members
-
std::string name
Patch name.
-
bool valid
False when the patch does not overlap the image.
-
size_t sampleCount
Number of pixels averaged.
-
glm::vec3 measuredRgb
Mean measured display-space RGB in [0, 1].
-
glm::vec3 targetRgb
Target RGB, clamped to [0, 1].
-
double rgbError
Euclidean RGB distance between measured and target.
-
double maxChannelError
Largest absolute per-channel difference.
-
double luminanceError
Absolute luminance difference.
-
double saturationError
Absolute saturation difference.
-
std::string name
-
struct RgbaCalibrationMetrics
Result of analyzeRgbaCalibrationPatches(); averages cover valid patches only.
Public Members
-
int width
Image width passed in.
-
int height
Image height passed in.
-
size_t patchCount
Number of patches passed in.
-
size_t validPatchCount
Number of patches that overlapped the image.
-
double averageRgbError
Mean of RgbaCalibrationPatchResult::rgbError.
-
double rmsRgbError
Root mean square of rgbError.
-
double maxRgbError
Largest rgbError.
-
double averageLuminanceError
Mean luminance error.
-
double averageSaturationError
Mean saturation error.
-
std::vector<RgbaCalibrationPatchResult> patches
One entry per input patch, in input order.
-
int width
-
struct RgbaCalibrationRecommendation
Result of recommendCalibrationOutputTransform().
Public Members
-
bool valid
False when no usable neutral or saturated reference patch exists.
-
bool changed
True when the transform differs noticeably from identity.
-
size_t neutralPatchCount
Patches with target saturation below 0.08 (drive exposure and white balance).
-
size_t saturatedPatchCount
Patches with target saturation above 0.15 (drive saturation).
-
double averageRgbErrorBefore
RgbaCalibrationMetrics::averageRgbError of the input.
-
RgbaOutputTransform outputTransform
Suggested transform for transformRgbaForOutput(); gamma is always 1.
-
std::string reason
Machine-readable reason, e.g.
calibration_output_transform,already_calibrated.
-
bool valid
-
struct ReflectionProbeCaptureSettings
Explicit static reflection-probe capture settings.
Probe capture is never automatic. Applications call captureReflectionProbeCubemap() when they want a bounded real-time local reflection approximation. Custom visuals, instanced visuals, and point clouds are captured only when their draw toggles are enabled and they are marked detectable.
Public Members
-
int resolution
Cubemap face size in pixels, clamped to [16, 512].
-
bool drawVisualizationObjects
Draw custom visuals and instanced visuals that are marked detectable.
-
bool drawCoordinateFrames
Draw coordinate frames into the probe.
-
bool drawPointClouds
Draw point clouds that are marked detectable.
-
bool doShadows
Render shadows while capturing.
-
bool includeEnvironmentBackground
Draw environmentBackgroundMap behind the captured scene.
-
unsigned int environmentBackgroundMap
Background cubemap used when includeEnvironmentBackground is true.
-
float environmentBackgroundExposure
Exposure applied to environmentBackgroundMap.
-
int resolution
-
struct ReflectionProbeFilterSettings
Explicit CPU filtering settings for captured local reflection probes.
Filtering is a load-time/manual Ultra operation. Fast/Balanced do not allocate or run this unless the application calls captureFilteredReflectionProbe().
Public Members
-
int irradianceResolution
Diffuse irradiance cubemap face size, clamped to [0, 128]; 0 skips the irradiance map.
-
int irradianceSamples
Cosine-hemisphere samples per irradiance texel; 0 skips the irradiance map.
-
int prefilteredResolution
Prefiltered specular cubemap base face size, clamped to [0, 512]; 0 skips it.
-
int prefilteredMipLevels
Prefiltered mip levels (roughness steps), limited to the full mip chain; 0 skips it.
-
int prefilteredSamples
GGX samples per prefiltered texel; 0 skips the prefiltered map.
-
int brdfLutSize
Split-sum BRDF LUT size (clamped to [16, 512] when used); 0 skips the LUT.
-
int brdfLutSamples
GGX samples per BRDF LUT texel; 0 skips the LUT.
-
int irradianceResolution
-
struct ReflectionProbeSidecarProbe
One probe entry parsed from a
.rayrai_probes.jsonsidecar (see loadReflectionProbeSidecar()).Public Members
-
bool boxProjection
Box-projected parallax correction (
box_projection); cleared when the box is degenerate.
-
glm::vec3 boxMin
Box-projection minimum corner (
box_min).
-
glm::vec3 boxMax
Box-projection maximum corner (
box_max).
-
ReflectionProbeCaptureSettings capture
Capture settings from the optional
captureobject.
-
ReflectionProbeFilterSettings filter
Per-probe filter settings; meaningful only when hasFilter is true.
-
bool boxProjection
-
struct ReflectionProbeSidecarSettings
Optional
qualityblock of a reflection-probe sidecar; eachhasXflag says whether X was present.Public Members
-
bool hasMaxReflectionProbesPerSelection
Set when
max_reflection_probes_per_selectionwas present.
-
int maxReflectionProbesPerSelection
Probes blended per selection, clamped to [1, 2].
-
bool hasMinReflectionProbeWeight
Set when
min_reflection_probe_weightwas present.
-
float minReflectionProbeWeight
Probes with a raw weight at or below this are ignored (>= 0).
-
bool hasReflectionProbeFilteringEnabled
Set when
filtering_enabledwas present.
-
bool reflectionProbeFilteringEnabled
Value of
filtering_enabled.
-
bool hasReflectionProbeFilter
Set when a
filterobject was present.
-
ReflectionProbeFilterSettings reflectionProbeFilter
Default filter settings from the
filterobject.
-
bool hasMaxReflectionProbesPerSelection
-
struct EnvironmentSidecarSettings
Contents of a
.rayrai_environment.jsonsidecar (see loadEnvironmentSidecar()).Each value has a
hasXflag that is true only when the sidecar provided it; applyEnvironmentSidecarSettings() copies only flagged values. Plain keys are read from theenvironmentobject when it exists, otherwise from the top level; theprocedural_sky,sun,bloom/glowandheight_foggroups may sit at either level. Values are clamped to the ranges noted below.Public Members
-
bool hasEnvironmentIntensity
Set when
environment.intensitywas present.
-
float environmentIntensity
-
bool hasEnvironmentRotation
Set when
environment.rotation(radians) orrotation_degreeswas present.
-
float environmentRotation
RenderQualitySettings::pbrEnvironmentRotation, in radians.
-
bool hasSkyTint
Set when
environment.sky_tintwas present.
-
glm::vec3 skyTint
-
bool hasHorizonTint
Set when
environment.horizon_tintwas present.
-
glm::vec3 horizonTint
-
bool hasGroundTint
Set when
environment.ground_tintwas present.
-
glm::vec3 groundTint
-
bool hasHorizonStrength
Set when
environment.horizon_strengthwas present.
-
float horizonStrength
RenderQualitySettings::pbrEnvironmentHorizonStrength, in [0, 1].
-
bool hasBackgroundTint
Set when
environment.background_tintwas present.
-
glm::vec3 backgroundTint
-
bool hasBackgroundExposureScale
Set when
environment.background_exposure_scalewas present.
-
float backgroundExposureScale
RenderQualitySettings::environmentBackgroundExposureScale (>= 0).
-
bool hasBackgroundMapPath
Set when
environment.background_maporvisible_background_mapwas present.
-
std::string backgroundMapPath
Equirectangular .hdr shown as the visible background; relative paths resolve against the sidecar.
-
bool hasBackgroundMapExposure
Set when
environment.background_map_exposurewas present.
-
float backgroundMapExposure
Exposure of the visible background map (>= 0).
-
bool hasProceduralSkyEnabled
Set when
procedural_sky.enabledwas present.
-
bool proceduralSkyEnabled
-
bool hasProceduralSkySunStrength
Set when
procedural_sky.sun_strengthwas present.
-
float proceduralSkySunStrength
-
bool hasProceduralSkySunSize
Set when
procedural_sky.sun_sizewas present.
-
float proceduralSkySunSize
RenderQualitySettings::proceduralSkySunSize (>= 0.0001).
-
bool hasSunDirection
Set when
sun.directionorsun.azimuth_degrees+sun.elevation_degreeswas present.
-
glm::vec3 sunDirection
Normalized RenderQualitySettings::mainLightDirection (direction the light travels, world frame).
-
bool hasSunColor
Set when
sun.colorwas present.
-
glm::vec3 sunColor
Sun color; mainLightDiffuse becomes sunColor * sunIntensity.
-
bool hasSunIntensity
Set when
sun.intensitywas present.
-
float sunIntensity
Sun intensity multiplier (>= 0).
-
bool hasExposure
Set when
environment.exposurewas present.
-
float exposure
-
bool hasBloomEnabled
Set when
bloom.enabled(orglow.enabled) was present.
-
bool bloomEnabled
-
bool hasBloomThreshold
Set when
bloom.thresholdwas present.
-
float bloomThreshold
-
bool hasBloomStrength
Set when
bloom.strengthwas present.
-
float bloomStrength
-
bool hasBloomRadius
Set when
bloom.radiuswas present.
-
float bloomRadius
-
bool hasBloomKnee
Set when
bloom.kneewas present.
-
float bloomKnee
RenderQualitySettings::bloomKnee (>= 0.001).
-
bool hasBloomQuality
Set when
bloom.qualitywas present.
-
int bloomQuality
RenderQualitySettings::bloomQuality, in [1, 3].
-
bool hasBloomSourceClamp
Set when
bloom.source_clampwas present.
-
float bloomSourceClamp
-
bool hasBloomAnamorphic
Set when
bloom.anamorphicwas present.
-
float bloomAnamorphic
RenderQualitySettings::bloomAnamorphic, in [0, 1].
-
bool hasBloomDirtStrength
Set when
bloom.dirt_strengthwas present.
-
float bloomDirtStrength
RenderQualitySettings::bloomDirtStrength, in [0, 1].
-
bool hasBloomDirtScale
Set when
bloom.dirt_scalewas present.
-
float bloomDirtScale
RenderQualitySettings::bloomDirtScale, in [0.05, 32].
-
bool hasBloomBlendMode
Set when
bloom.blend_mode(orglow_blend_mode,mode) was present.
-
GlowBlendMode bloomBlendMode
-
bool hasBloomMix
Set when
bloom.mix(orglow_mix) was present.
-
float bloomMix
RenderQualitySettings::bloomMix, in [0, 1].
-
bool hasFogDensity
Set when
environment.fog_densitywas present.
-
float fogDensity
-
bool hasHeightFogEnabled
Set when
height_fog.enabledwas present.
-
bool heightFogEnabled
-
bool hasHeightFogDensity
Set when
height_fog.densitywas present.
-
float heightFogDensity
-
bool hasHeightFogBaseHeight
Set when
height_fog.base_heightwas present.
-
float heightFogBaseHeight
RenderQualitySettings::heightFogBaseHeight (world Z, metres).
-
bool hasHeightFogFalloff
Set when
height_fog.falloffwas present.
-
float heightFogFalloff
-
bool hasEnvironmentIntensity
-
struct WeatherSidecarSettings
Contents of a
.rayrai_weather.jsonsidecar (see loadWeatherSidecar()).Public Members
-
bool hasWeather
True when the sidecar set any weather field.
-
WeatherSettings weather
Weather settings: preset defaults (if
presetgiven) overridden by explicit fields.
-
bool hasLocalFogVolumes
True when the sidecar contained
local_fog_volumes.
-
std::vector<LocalFogVolume> localFogVolumes
Parsed local fog volumes.
-
bool hasWeather
-
struct ReflectionProbe
A captured local reflection probe (see captureFilteredReflectionProbe(), addReflectionProbe()).
Public Members
-
glm::vec3 position
World-space capture position.
-
unsigned int environmentMap
Raw captured cubemap (GL id), or 0.
-
unsigned int irradianceMap
Diffuse irradiance cubemap (GL id), or 0 when not filtered.
-
unsigned int prefilteredEnvironmentMap
GGX-prefiltered specular cubemap (GL id), or 0 when not filtered.
-
unsigned int brdfLut
Split-sum BRDF LUT (GL id), or 0 when not generated.
-
float strength
Blend strength (>= 0).
-
bool boxProjection
Use box-projected parallax correction; distance is then measured to the box.
-
glm::vec3 boxMin
World-space box-projection minimum corner.
-
glm::vec3 boxMax
World-space box-projection maximum corner.
-
glm::vec3 position
-
struct ReflectionProbeBlend
Result of selectReflectionProbeBlend(): up to two probes and their normalized weights.
Public Members
-
bool valid
True when at least one probe influences the position.
-
size_t primaryIndex
Index of the highest-weight probe.
-
size_t secondaryIndex
Index of the second probe, or primaryIndex when there is none.
-
float primaryWeight
Normalized weight of the primary probe.
-
float secondaryWeight
Normalized weight of the secondary probe (0 when unused).
-
float strength
Sum of raw weights, clamped to [0, 1].
-
bool primaryBoxProjection
True when the primary probe has a valid projection box.
-
bool secondaryBoxProjection
True when the secondary probe has a valid projection box.
-
glm::vec3 primaryProbePosition
Primary probe position.
-
glm::vec3 secondaryProbePosition
Secondary probe position.
-
glm::vec3 primaryBoxMin
Primary probe box minimum corner.
-
glm::vec3 primaryBoxMax
Primary probe box maximum corner.
-
glm::vec3 secondaryBoxMin
Secondary probe box minimum corner.
-
glm::vec3 secondaryBoxMax
Secondary probe box maximum corner.
-
bool valid
-
struct ReflectionProbePlacementSuggestion
Result of suggestReflectionProbePlacementFromSceneBounds().
Public Members
-
bool valid
False when the scene has no finite, non-degenerate bounds.
-
glm::vec3 position
Center of the scene bounds.
-
float radius
Half of boundsDiagonal.
-
bool boxProjection
True when the bounds have positive extent on all axes.
-
glm::vec3 boxMin
Scene bounds minimum corner.
-
glm::vec3 boxMax
Scene bounds maximum corner.
-
size_t boundedObjectCount
Objects and visuals that contributed to the bounds.
-
float boundsDiagonal
Length of the bounds diagonal in metres.
-
bool valid
-
struct ReflectionProbeDebugItem
Per-probe entry of ReflectionProbeDebugView.
Public Members
-
size_t index
Index in the registered probe list.
-
bool selected
True when used as primary or secondary.
-
bool primary
True when this is the primary probe.
-
bool secondary
True when this is the (non-zero weight) secondary probe.
-
float rawWeight
Unnormalized influence weight at the sample position (0 without maps).
-
float normalizedWeight
Blend weight after normalization (0 when not selected).
-
glm::vec3 position
Probe position.
-
float radius
Probe influence radius.
-
bool boxProjection
Requested box projection flag.
-
bool boxProjectionValid
True when box projection is requested and the box is non-degenerate.
-
glm::vec3 boxMin
Box minimum corner.
-
glm::vec3 boxMax
Box maximum corner.
-
size_t index
-
struct ReflectionProbeDebugView
Result of reflectionProbeDebugView().
Public Members
-
bool valid
True when a blend was found.
-
glm::vec3 samplePosition
Query position.
-
ReflectionProbeBlend blend
Selected blend.
-
std::vector<ReflectionProbeDebugItem> probes
One entry per registered probe.
-
bool valid
-
struct ReflectionProbeDebugOverlaySummary
Result of reflectionProbeDebugOverlaySummary(); blend fields mirror ReflectionProbeBlend.
Public Members
-
bool available
Always true for a returned summary.
-
bool overlayEnabled
-
bool validBlend
True when a blend was found.
-
size_t registeredProbeCount
Number of registered probes.
-
size_t selectedProbeCount
Probes used by the blend (0 to 2).
-
size_t boxProjectionProbeCount
Probes that request box projection.
-
size_t validBoxProjectionProbeCount
Probes with a valid projection box.
-
size_t primaryIndex
Primary probe index.
-
size_t secondaryIndex
Secondary probe index.
-
float primaryWeight
Primary normalized weight.
-
float secondaryWeight
Secondary normalized weight.
-
float strength
Blend strength.
-
glm::vec3 samplePosition
Query position.
-
glm::vec3 primaryPosition
Primary probe position.
-
glm::vec3 secondaryPosition
Secondary probe position.
-
bool primaryBoxProjection
Primary probe has a valid projection box.
-
bool secondaryBoxProjection
Secondary probe has a valid projection box.
-
bool available
-
struct SceneImportReport
What importVisualScene() loaded.
Public Members
-
bool visualLoaded
True when the mesh visual was created and is valid.
-
size_t totalSceneLightCount
Lights found in the scene file.
-
size_t importedLightCount
Lights added as additional lights.
-
size_t droppedLightCount
Lights dropped because kMaxAdditionalLights was reached.
-
bool shadowLightPromoted
True when a light was promoted to the main shadow caster.
-
size_t remainingShadingLightCount
Additional-light count after import and promotion.
-
std::string notes
Error message from light import, if any.
-
bool visualLoaded
-
struct RenderPassTiming
GPU time of one render pass (see captureRenderPassTimings()).
-
struct FoliageRenderDiagnostics
Diagnostics: foliage and instanced-draw counters (see foliageRenderDiagnostics()).
Reset at the start of every update() / renderWithExternalCamera() frame and accumulated while that frame renders. Counters prefixed
scenebelong to the color pass andshadowto shadow passes. GPU times are filled only by captureRenderPassTimings() / captureViewerPassTimings().Public Members
-
bool available
True when the frame drew at least one foliage visual.
-
bool timingCaptureAvailable
True when foliage GPU timings were captured.
-
size_t sceneFoliageDrawCalls
Foliage draws in the scene pass.
-
size_t sceneFoliageOccludedDrawCalls
Scene foliage draws skipped by occlusion culling.
-
size_t sceneFoliageAuthoredInstanceVisits
Authored instances of drawn scene foliage visuals.
-
size_t sceneFoliageCandidateInstanceVisits
Scene foliage instances left after culling stages that report candidates.
-
size_t sceneFoliageRenderedInstanceVisits
Scene foliage instances actually rendered. Instances whose occlusion is tested on the GPU count before that test.
-
size_t shadowFoliageDrawCalls
Foliage draws in shadow passes.
-
size_t shadowFoliageAuthoredInstanceVisits
Authored instances of shadow foliage draws.
-
size_t shadowFoliageCandidateInstanceVisits
Shadow foliage candidate instances.
-
size_t shadowFoliageRenderedInstanceVisits
Shadow foliage instances actually rendered.
-
size_t sceneGpuCulledDrawCalls
Scene draws that used GPU instance culling.
-
size_t shadowGpuCulledDrawCalls
Shadow draws that used GPU instance culling.
-
size_t sceneGpuCullSkippedDrawCalls
Scene draws that skipped GPU instance culling.
-
size_t shadowGpuCullSkippedDrawCalls
Shadow draws that skipped GPU instance culling.
-
size_t sceneVisibleInstanceFrameCacheHits
GPU-culled scene draws that reused this frame’s visible-instance list.
-
size_t sceneVisibleInstanceFrameCacheDispatches
GPU-culled scene draws that dispatched culling.
-
size_t sceneVisibleInstanceFrameCacheFallbackDrawCalls
Scene draws that could not use the visible-instance frame cache.
-
size_t sceneClusteredDrawCalls
Scene draws using hierarchical foliage clusters.
-
size_t shadowClusteredDrawCalls
Shadow draws using hierarchical foliage clusters.
-
size_t impostorDrawCalls
Impostor (billboard LOD) draws.
-
size_t shadowLodDrawCalls
Shadow draws using a shadow LOD.
-
size_t persistentSourceBufferDrawCalls
Draws served from persistent source instance buffers.
-
size_t sceneMultiDrawIndirectDrawCalls
Scene multi-draw-indirect submissions.
-
size_t shadowMultiDrawIndirectDrawCalls
Shadow multi-draw-indirect submissions.
-
size_t multiDrawIndirectCommandCount
Indirect commands issued.
-
size_t multiDrawIndirectFallbackDrawCalls
Draws that fell back from multi-draw-indirect.
-
size_t sceneAlphaDepthPrepassDrawCalls
Alpha-tested depth-prepass draws.
-
size_t sceneAlphaDepthPrepassInstanceVisits
Instances drawn in the alpha depth prepass.
-
size_t sceneAlphaDepthPrepassFallbackDrawCalls
Draws that could not use the alpha depth prepass.
-
size_t sceneFrontToBackOrderedInstancedDrawCalls
Instanced draws submitted front to back.
-
size_t sceneFrontToBackOrderedFoliageDrawCalls
Foliage draws submitted front to back.
-
size_t sceneFrontToBackOrderingFallbackDrawCalls
Draws that could not be front-to-back ordered.
-
size_t maxSourceTrianglesPerInstance
Largest source-mesh triangle count per instance.
-
size_t maxImpostorTrianglesPerInstance
Largest impostor triangle count per instance.
-
size_t conservativeOcclusionCandidates
Copy of ConservativeOcclusionCullingDiagnostics::candidates.
-
size_t conservativeOcclusionQueries
-
size_t conservativeOcclusionOccluded
-
size_t conservativeOcclusionDrawn
-
size_t hizOcclusionTests
-
size_t hizOcclusionOccluded
Copy of ConservativeOcclusionCullingDiagnostics::hizOccluded.
-
size_t hizOcclusionDepthReadbacks
Copy of ConservativeOcclusionCullingDiagnostics::hizDepthReadbacks.
-
size_t gpuHizOcclusionDrawCalls
Copy of ConservativeOcclusionCullingDiagnostics::gpuHizDrawCalls.
-
size_t gpuHizOcclusionDepthBuilds
Copy of ConservativeOcclusionCullingDiagnostics::gpuHizDepthBuilds.
-
size_t gpuHizOcclusionComputeDepthBuilds
Copy of ConservativeOcclusionCullingDiagnostics::gpuHizComputeDepthBuilds.
-
size_t gpuHizOcclusionRasterDepthBuilds
Copy of ConservativeOcclusionCullingDiagnostics::gpuHizRasterDepthBuilds.
-
size_t sceneGpuOcclusionFilteredDrawCalls
Collected scene foliage draws whose instances were occlusion-tested on the GPU.
-
double sceneFoliageGpuMs
Scene foliage GPU time in ms (timing captures only).
-
double shadowFoliageGpuMs
Shadow foliage GPU time in ms (timing captures only).
-
bool available
-
struct ShadowCacheDiagnostics
Diagnostics: shadow-map caching counters (see shadowCacheDiagnostics()).
Reset at the start of every update() / renderWithExternalCamera() frame. Three mechanisms are reported: the stable main shadow-map cache, per-light dirty tracking of additional shadow maps, and static/dynamic shadow composition.
*Availablesays the mechanism applies,*Enabledthat it ran,*Fallbackthat it had to be bypassed this frame.Public Members
-
bool available
Shadows are enabled for the main light.
-
bool eligible
The scene qualifies for the stable shadow-map cache.
-
bool enabled
The stable shadow-map cache was used.
-
bool fallback
The stable cache was bypassed this frame.
-
size_t shadowMapRenders
Main shadow maps rendered.
-
size_t shadowMapReuses
Main shadow maps reused from cache.
-
size_t fallbackFrames
Frames that fell back to re-rendering.
-
bool perLightDirtyTrackingAvailable
Additional shadow lights can be tracked individually (shadowedLightBudget > 1).
-
bool perLightDirtyTrackingEnabled
Per-light dirty tracking ran.
-
bool perLightDirtyTrackingFallback
Per-light dirty tracking was bypassed.
-
size_t perLightDirtyTrackingFallbackFrames
Frames that bypassed per-light dirty tracking.
-
size_t additionalShadowMapRenders
Additional-light shadow maps rendered.
-
size_t additionalShadowMapReuses
Additional-light shadow maps reused.
-
size_t additionalShadowDirtyLights
Additional shadow lights marked dirty.
-
size_t additionalShadowCleanLights
Additional shadow lights still clean.
-
bool staticDynamicCompositionAvailable
Static/dynamic composition applies (directional main light).
-
bool staticDynamicCompositionEnabled
Static/dynamic composition ran.
-
bool staticDynamicCompositionFallback
Static/dynamic composition was bypassed.
-
size_t staticDynamicCompositionFallbackFrames
Frames that bypassed static/dynamic composition.
-
size_t staticShadowMapRenders
Static-caster shadow layers rendered.
-
size_t staticShadowMapReuses
Static-caster shadow layers reused.
-
size_t dynamicShadowMapRenders
Dynamic-caster shadow layers rendered.
-
size_t staticDynamicCompositedLayers
Main cascade layers composited from static and dynamic parts.
-
size_t additionalStaticShadowMapRenders
Additional-light static atlas tiles rendered.
-
size_t additionalStaticShadowMapReuses
Additional-light static atlas tiles reused.
-
size_t additionalDynamicShadowMapRenders
Additional-light dynamic atlas tiles rendered.
-
size_t additionalStaticDynamicCompositedTiles
Additional-light atlas tiles composited.
-
size_t staticShadowCasterCount
Shadow casters classified as static.
-
size_t dynamicShadowCasterCount
Shadow casters classified as dynamic.
-
size_t receiverDepthFilteredMaps
Main shadow maps drawn after the camera’s depth prepass without the instanced casters whose shadows reach none of its visible surfaces.
-
bool available
-
struct DynamicQualityRecommendation
Result of recommendDynamicQuality(); GPU times are summed from the input timings by pass name.
Public Members
-
bool changed
True when recommendedSettings differs from the input.
-
bool fillRateBound
Scene + post-process time is at least 50 % of the total.
-
bool shadowBound
Shadow time is at least 35 % of the total.
-
bool postprocessBound
Post-process time is at least 35 % of the total and exceeds scene time.
-
double totalGpuMs
Sum of all positive pass times (ms).
-
double shadowGpuMs
Passes whose name contains
shadow(ms).
-
double sceneGpuMs
Scene color, background clear and planar reflection passes (ms).
-
double postprocessGpuMs
Passes whose name contains
postprocess(ms).
-
float targetFrameMs
GPU budget used: Fast 6, Balanced/Custom 8, High 12, Ultra 16.6 ms.
-
float recommendedRenderScale
Suggested RenderQualitySettings::viewerRenderScale.
-
bool recommendedUpdateShadowsEveryFrame
-
int recommendedBloomQuality
Suggested RenderQualitySettings::bloomQuality.
-
int recommendedScreenSpaceAoSamples
Suggested RenderQualitySettings::screenSpaceAoSamples.
-
bool recommendedScreenSpaceAoDenoiseEnabled
Suggested RenderQualitySettings::screenSpaceAoDenoiseEnabled.
-
RenderQualitySettings recommendedSettings
Input settings with the recommendations applied.
-
std::string reason
Machine-readable reason, e.g.
within_budgetor+-joined change names.
-
bool changed
-
struct RenderPassAccounting
Estimated per-frame pass counts from estimateRenderPassAccounting() (no rendering involved).
Public Members
-
bool fastForwardPathEligible
The cheap forward path applies.
-
bool postprocessActive
Any post-process work is enabled.
-
bool msaaActive
Viewer MSAA is enabled.
-
bool renderScaleActive
The viewer renders below native resolution.
-
bool probeFilteringActive
Reflection-probe filtering is configured.
-
bool localProbeSelectionActive
Local reflection-probe selection is in use.
-
bool additionalShadowActive
Additional-light shadows are active.
-
size_t mainShadowPassesPerFrame
Main-light shadow passes.
-
size_t additional2dShadowPassesPerFrame
2D additional-light shadow passes.
-
size_t additionalPointShadowFacePassesPerFrame
Point-light shadow cubemap face passes.
-
size_t shadowPassesPerFrame
All shadow passes.
-
size_t sceneColorPassesPerFrame
Scene color passes.
-
size_t planarReflectionPassesPerFrame
Planar reflection passes.
-
size_t renderScaleResolvePassesPerFrame
Render-scale resolve passes.
-
size_t transparentPassesPerFrame
Transparent passes.
-
size_t postprocessPassesPerFrame
Post-process passes.
-
size_t bloomExtraPassesPerFrame
Extra bloom passes.
-
size_t aoDenoisePassesPerFrame
AO denoise passes.
-
size_t debugReadbackPassesPerFrame
Debug readback passes.
-
size_t totalEstimatedPassesPerFrame
Sum of all estimated passes.
-
size_t activeAdditionalLights
Additional lights registered.
-
size_t activeAdditionalShadowLights
Additional lights currently selected for shadows.
-
size_t activeReflectionProbes
Registered reflection probes.
-
int activeUltraFeatureCount
Number of enabled Ultra-tier features.
-
std::string likelyBottleneck
One of
scene_shading,fast_forward,shadow,postprocess_or_fill,light_shading,pass_count.
-
bool fastForwardPathEligible
-
struct ExternalFrameCache
Internal: reuse key of the last externally rendered frame (see invalidateExternalFrameCache()).
Public Members
-
bool valid
Internal: a reusable frame is stored.
-
uint64_t key
Internal: content key of the stored frame.
-
uint64_t lastCameraSignature
Internal: pose/projection signature of lastCamera.
-
bool hasLastCameraSignature
Internal: lastCameraSignature is valid.
-
bool fastReuseKeyValid
Internal: fastReuseKey is valid.
-
uint64_t fastReuseKey
Internal: cheap pre-check key.
-
bool valid
-
struct StaticSceneLayerCache
Internal: cached render of static scene content reused under dynamic objects.
Public Members
-
bool valid
Internal: the layer holds a usable image.
-
uint64_t key
Internal: content key of the layer.
-
unsigned int fbo
Internal: GL framebuffer.
-
unsigned int colorTex
Internal: GL color texture.
-
unsigned int depthTex
Internal: GL depth texture.
-
int width
Internal: layer width in pixels.
-
int height
Internal: layer height in pixels.
-
bool valid
-
struct TransparentDrawItem
One transparent draw in TransparentDrawDebugView::backToFrontOrder.
Public Members
-
std::string source
world,visualorinstanced_visual.
-
std::string name
Visual name, or
world_object_<n>for raisim objects.
-
glm::vec3 center
World-space sort center.
-
float radius
Approximate bounding radius in metres.
-
float distanceSquared
Squared distance from the camera to the sort point.
-
float sortOffset
Per-visual transparent sort offset.
-
int renderPriority
Render priority of the source.
-
bool detectable
True when the source is marked detectable.
-
bool sortUsesBoundsCenter
True when sorting uses the bounds center rather than the origin.
-
std::string source
-
struct TransparentDrawDebugView
Diagnostics: transparent rendering state and estimated overdraw (see transparentDrawDebugView()).
Flags mirror the active RenderQualitySettings;
*Availablesays whether the feature can actually run with the current settings. Overdraw is estimated by splatting each transparent item’s projected bounding sphere onto 32 px tiles.Public Members
-
bool sortTransparentInstances
-
bool weightedBlendedOit
-
bool weightedBlendedOitAvailable
Weighted blended OIT requested and viewer MSAA is off.
-
bool transparentDepthPrepass
-
bool transparentShadowDithering
-
float transparentShadowOpacityScale
Transparent shadow opacity scale, clamped to [0, 4].
-
bool screenSpaceRefraction
-
bool screenSpaceRefractionAvailable
Screen-space refraction requested and high-fidelity PBR is on.
-
float screenSpaceRefractionStrength
Refraction strength, clamped to [0, 1].
-
float screenSpaceRefractionMaxPixels
Maximum refraction offset in pixels, clamped to [0, 96].
-
bool transparentFogAlphaWeighted
-
float transparentFogStrength
Transparent fog strength, clamped to [0, 1].
-
bool alphaToCoverage
-
bool depthWrite
Transparent passes write depth (always false).
-
bool depthTest
Transparent passes depth-test (always true).
-
int overdrawTileSize
Overdraw tile size in pixels.
-
int overdrawTileColumns
Number of tile columns.
-
int overdrawTileRows
Number of tile rows.
-
size_t overdrawCoveredTileCount
Tiles touched by at least one transparent item.
-
size_t overdrawHotTileCount
Tiles touched by three or more items.
-
int maxEstimatedOverdraw
Highest per-tile item count.
-
float averageEstimatedOverdraw
Mean item count over covered tiles.
-
std::vector<int> overdrawTileCounts
Per-tile item counts, row-major.
-
size_t worldTransparentCount
Transparent raisim objects.
-
size_t visualTransparentCount
Transparent custom visuals.
-
size_t instancedTransparentCount
Transparent instanced visuals.
-
size_t totalTransparentCount
Sum of the three counts above.
-
std::vector<TransparentDrawItem> backToFrontOrder
Sorted draw order, truncated to maxItems (0 = all).
-
bool sortTransparentInstances
-
struct DirectionalShadowCascade
One cascade of DirectionalShadowCascadePlan. Depths are view distances in metres.
Public Members
-
int index
Cascade index, 0 nearest.
-
float nearPlane
Cascade start distance.
-
float farPlane
Cascade end distance.
-
float splitDepth
Split distance (equal to farPlane).
-
float texelWorldSize
World-space size of one shadow texel in metres.
-
glm::vec3 center
World-space center of the cascade’s shadow projection.
-
glm::vec3 lightSpaceMin
Minimum of the cascade frustum corners in light view space.
-
glm::vec3 lightSpaceMax
Maximum of the cascade frustum corners in light view space.
-
glm::vec3 lightSpaceHalfExtents
Half extents of that light-space box.
-
glm::mat4 lightSpaceMatrix
World-to-shadow-clip matrix (projection * view), texel-snapped when enabled.
-
int index
-
struct DirectionalShadowCascadePlan
Result of planDirectionalShadowCascades().
Public Members
-
bool enabled
True when shadows are on, the main light is directional and more than one cascade is requested.
-
int requestedCascadeCount
RenderQualitySettings::directionalShadowCascadeCount as given.
-
int cascadeCount
Cascade count clamped to [1, 4].
-
float lambda
Blend between uniform (0) and logarithmic (1) splits.
-
float farPlane
Shadowed range end: min(camera far, maxDistance) (m).
-
float maxDistance
Maximum shadow distance (m); the main light’s shadow far plane when not set.
-
float shadowResolution
Shadow map resolution in texels.
-
bool stableTexelSnap
Cascade matrices are snapped to the texel grid to avoid shimmering.
-
bool splitOverridesEnabled
True when the user split overrides are valid and used.
-
std::array<float, 4> splitOverrides
Split distances from the settings (unused entries zeroed).
-
std::vector<DirectionalShadowCascade> cascades
Per-cascade data, near to far.
-
bool enabled
-
struct ShadowAtlasTile
One tile of ShadowAtlasPlan. Pixel coordinates are in atlas texels.
Public Members
-
size_t shadowIndex
Index among the selected additional shadow lights.
-
size_t sourceLightIndex
Index into the additional-light list, or
size_t(-1)if unknown.
-
int face
Cubemap face for point lights, otherwise 0.
-
bool pointShadow
True for a point-light cubemap face.
-
int resolution
Tile size in texels.
-
int x
Left edge.
-
int y
Top edge.
-
int w
Width.
-
int h
Height.
-
glm::vec4 uvRect
Normalized rectangle (u0, v0, u1, v1).
-
size_t shadowIndex
-
struct ShadowAtlasPlan
Result of planAdditionalShadowAtlas().
Public Members
-
bool enabled
Atlas planning is enabled, shadows are on and additional shadow lights are selected.
-
bool overflow
At least one tile did not fit.
-
PointShadowPolicy pointShadowPolicy
-
bool pointShadowsUseStandaloneCubemaps
True when point shadows use standalone cubemaps.
-
int atlasResolution
Atlas size in texels, clamped to [512, 16384].
-
int padding
Padding between tiles in texels, clamped to [0, 16].
-
int tileCount
Number of placed tiles.
-
int nonPointTileCount
Placed spot/directional/area tiles.
-
int pointShadowFaceTileCount
Placed point-light face tiles.
-
float occupancy
Fraction of atlas area covered by tiles.
-
std::vector<ShadowAtlasTile> tiles
Placed tiles, largest first.
-
bool enabled
-
struct ShadowDebugOverlaySummary
Result of shadowDebugOverlaySummary(); combines settings, the current plans and last-frame state.
Public Members
-
bool available
Always true for a returned summary.
-
bool overlayEnabled
-
bool shadowsEnabled
Shadows are enabled in settings and on the main light.
-
bool updateEveryFrame
-
bool contactHardening
-
bool cascadeRendered
Cascaded shadows were rendered in the last frame.
-
bool atlasRendered
The additional-light atlas was rendered in the last frame.
-
bool atlasOverflow
-
bool splitOverridesEnabled
-
int cascadeCount
-
int atlasTileCount
-
int atlasNonPointTileCount
-
int pointShadowFaceTileCount
-
int selectedAdditionalShadowLights
Additional lights currently selected for shadows.
-
int droppedShadowCandidates
Additional lights evaluated but not selected.
-
float shadowBias
-
float shadowNormalOffset
-
float shadowPcfRadius
-
float shadowStrength
-
float cascadeLambda
-
float cascadeMaxDistance
-
float atlasOccupancy
-
std::array<float, 4> cascadeSplits
Split distance of each planned cascade (unused entries 0).
-
std::array<float, 4> cascadeSplitOverrides
-
std::string cascadeMode
rendered_stable_cascades,planned_stable_cascadesorsingle_shadow_map.
-
std::string atlasMode
rendered_2d_atlas_point_standalone,planned_atlas_standalone_texturesorstandalone_textures.
-
bool available
-
struct ConservativeOcclusionCullingDiagnostics
Diagnostics: occlusion-culling counters of the last scene color pass (see conservativeOcclusionCullingDiagnostics()).
Three paths are reported: hardware occlusion queries, CPU Hi-Z (depth readback) and GPU Hi-Z.
*FallbackCodeis an internal reason code, 0 when the path was not rejected.Public Members
-
bool enabled
Occlusion-query culling is enabled.
-
bool used
Occlusion queries were issued.
-
bool supported
Occlusion queries are supported.
-
bool hizEnabled
CPU Hi-Z culling is enabled.
-
bool hizUsed
CPU Hi-Z culling was used.
-
bool gpuHizEnabled
GPU Hi-Z culling is enabled.
-
bool gpuHizUsed
GPU Hi-Z culling was used.
-
size_t candidates
Draws considered for occlusion queries.
-
size_t queries
Occlusion queries issued.
-
size_t occluded
Draws rejected as occluded.
-
size_t drawn
Candidate draws that were drawn.
-
size_t hizTests
CPU Hi-Z tests.
-
size_t hizOccluded
Draws rejected by CPU Hi-Z.
-
size_t hizDepthReadbacks
Depth readbacks for CPU Hi-Z.
-
size_t hizMipLevels
CPU Hi-Z pyramid levels.
-
size_t gpuHizDrawCalls
Draws culled through GPU Hi-Z.
-
size_t gpuHizDepthBuilds
GPU Hi-Z pyramid builds.
-
size_t gpuHizComputeDepthBuilds
GPU Hi-Z pyramid builds using compute shaders.
-
size_t gpuHizRasterDepthBuilds
GPU Hi-Z pyramid builds using raster passes.
-
size_t gpuHizMipLevels
GPU Hi-Z pyramid levels.
-
uint32_t fallbackCode
Reason occlusion queries were not used.
-
uint32_t hizFallbackCode
Reason CPU Hi-Z was not used.
-
uint32_t gpuHizFallbackCode
Reason GPU Hi-Z was not used.
-
bool enabled
-
struct ShaderWarmupDiagnostics
Result of shaderWarmupDiagnostics().
Public Members
-
size_t shaderProgramCount
Registered built-in shader programs.
-
size_t linkedProgramCount
Programs currently linked successfully.
-
double totalCompileMs
Total measured compile/link time (ms).
-
double slowestCompileMs
Slowest single program compile (ms).
-
std::string slowestShaderName
Name of the slowest program.
-
bool warmedUp
True when every registered program has been compiled and linked.
-
size_t shaderProgramCount
-
struct MaterialTextureBudgetRecommendation
Result of recommendMaterialTextureBudget(). Byte counts are estimates from GL texture sizes.
Public Members
-
size_t uniqueMaterialTextures
Distinct material textures.
-
size_t materialTextureBytes
Estimated bytes of the distinct textures.
-
size_t budgetBytes
Budget used (the argument, or the preset default: 128/256/512/1024 MiB).
-
bool overBudget
materialTextureBytes exceeds budgetBytes.
-
bool changed
recommendedSettings differs from the current settings.
-
float recommendedTextureAnisotropy
Suggested texture anisotropy (capped at 4 when over budget).
-
float recommendedTextureMipLodBias
Suggested texture mip bias (at least 0.75 when over budget).
-
float recommendedPbrEnvironmentMipLodBias
Suggested environment mip bias (at least 0.5 when over budget).
-
bool recommendedReflectionProbeFilteringEnabled
Suggested probe-filtering flag (false when over budget).
-
RenderQualitySettings recommendedSettings
Current settings with the recommendations applied.
-
std::string reason
Machine-readable reason, e.g.
within_material_texture_budget.
-
size_t uniqueMaterialTextures
-
struct EnvironmentBackgroundDiagnostics
How the last scene pass drew its environment background (see renderMeshes).
-
struct CaptureFilteredReflectionProbeOptions
Options bundle for
captureFilteredReflectionProbe; replaces the three positional overloads with a single struct so callers do not have to remember which overload accepts which knob.Public Members
-
glm::vec3 position
World-space capture position.
-
float radius
Influence radius in metres.
-
float strength
Probe strength.
-
std::optional<ReflectionProbeCaptureSettings> capture
Capture settings; defaults when empty.
-
std::optional<ReflectionProbeFilterSettings> filter
Filter settings; the current quality’s when empty. Ignored unless capture is set.
-
glm::vec3 position
-
struct ReflectionProbeSidecarLoadResult
Result bundle for the struct-returning
loadReflectionProbeSidecaroverload.Returned by value so callers do not have to thread
&settingsand&loadedSidecarPathout-parameters; theloadedSidecarPathis empty when no sidecar file was found.Public Members
-
std::vector<ReflectionProbeSidecarProbe> probes
Parsed probes.
-
ReflectionProbeSidecarSettings settings
Parsed
qualityblock.
-
std::string loadedSidecarPath
File that was read, or empty.
-
std::vector<ReflectionProbeSidecarProbe> probes
-
struct ImportVisualSceneOptions
Options bundle for
importVisualScene; collapses the seven trailing optional parameters from the flat-argument overload into a struct that is easier to read and to evolve without breaking call sites.
-
class VisualMeshBuilder
Fluent builder for
addVisualMesh.Collects scale/position/orientation/material and flags up front;
add()creates the visual via the correspondingaddVisualMeshoverload, then applies the deferred state via the existing setters and returns theshared_ptr<Visuals>. Setters on the returned visual still work for runtime mutations after creation.Example:
auto v = renderer.makeVisualMesh("rusty", path) .scale({1.0, 1.0, 1.0}) .position({0.0, 0.0, 0.5}) .orientation(glm::angleAxis(0.4f, glm::vec3{0, 0, 1})) .twoSided(true) .pickable(true) .castsShadows(true) .material(rusty) .pbrEnvironment(env) .add();
Only options that were set are applied. The builder stores a raw pointer to the renderer, which must outlive it.
Public Functions
-
inline VisualMeshBuilder(RayraiWindow &renderer, std::string name, std::string meshFile)
- Parameters:
renderer – Renderer that add() creates the visual in (not owned).
name – Visual name (must be unique).
meshFile – Mesh file path.
-
inline VisualMeshBuilder &scale(const glm::dvec3 &s)
Per-axis mesh scale (default 1).
- Parameters:
s – Scale.
- Returns:
*this.
-
inline VisualMeshBuilder &scale(double x, double y, double z)
Per-axis mesh scale.
- Parameters:
x – X scale.
y – Y scale.
z – Z scale.
- Returns:
*this.
-
inline VisualMeshBuilder &color(const glm::vec4 &c)
RGBA color in [0, 1] (default white).
- Parameters:
c – Color.
- Returns:
*this.
-
inline VisualMeshBuilder &position(const glm::vec3 &p)
World-space position.
- Parameters:
p – Position in metres.
- Returns:
*this.
-
inline VisualMeshBuilder &orientation(const glm::quat &q)
World-space orientation.
- Parameters:
q – Unit quaternion.
- Returns:
*this.
-
inline VisualMeshBuilder &twoSided(bool enabled = true)
Disable back-face culling.
- Parameters:
enabled – Flag.
- Returns:
*this.
-
inline VisualMeshBuilder &pickable(bool enabled = true)
Sets Visuals::setDetectable(), which controls picking and visibility in sensor-style captures.
- Parameters:
enabled – Flag.
- Returns:
*this.
-
inline VisualMeshBuilder &castsShadows(bool enabled = true)
Whether the visual casts shadows.
- Parameters:
enabled – Flag.
- Returns:
*this.
-
inline VisualMeshBuilder &useMeshColor(bool enabled)
Use the mesh file’s own colors instead of color().
- Parameters:
enabled – Flag.
- Returns:
*this.
-
inline VisualMeshBuilder &material(const Material &m)
Material override (copied).
- Parameters:
m – Material.
- Returns:
*this.
-
inline VisualMeshBuilder &pbrEnvironment(const PbrEnvironment &env)
Image-based lighting maps for the visual.
- Parameters:
env – Environment.
- Returns:
*this.
-
inline VisualMeshBuilder(RayraiWindow &renderer, std::string name, std::string meshFile)
-
using AdditionalLight = ::raisin::AdditionalLight
-
class Camera
Camera for offscreen rendering and interaction.
The camera owns its render targets (scene color/depth, post-process, linear depth, and picking). It can be driven by user input or by raisim sensor parameters.
Public Types
-
enum class ProjectionMode
Projection mode for view generation.
Values:
-
enumerator ORTHOGRAPHIC
Vertical extent from orthoScale.
-
enumerator ORTHOGRAPHIC
Public Functions
-
explicit Camera(glm::vec3 position = glm::vec3(5.0f, 4.0f, 5.0f), glm::vec3 up = glm::vec3(0.0f, 0.0f, 1.0f), float yaw = -135.0f, float pitch = -30.0f)
Construct a camera with a position, up vector, and yaw/pitch.
Does not allocate GL resources. The view direction is (cos(yaw)cos(pitch), sin(yaw)cos(pitch), sin(pitch)), i.e. yaw is measured about +Z from +X and pitch upward from the XY plane (Z-up world).
-
explicit Camera(raisim::RGBCamera &rgbCam)
Construct a camera from a raisim RGB camera (and allocate targets).
Copies resolution, clip planes, horizontal FOV (radians, or degrees if greater than pi) and lens model, then allocates the scene targets, so a GL context must be current. The pose is not copied.
- Parameters:
rgbCam – Raisim RGB camera to mirror.
-
explicit Camera(const raisim::RGBCamera &rgbCam)
Construct a camera from a const raisim RGB camera.
- Parameters:
rgbCam – Raisim RGB camera to mirror.
-
explicit Camera(raisim::DepthCamera &depthCam)
Construct a depth camera and allocate only its linear-depth target. Scene color targets are allocated if this camera is later used for RGB. Requires a current GL context; projection setup is as for the RGB overload.
- Parameters:
depthCam – Raisim depth camera to mirror.
-
explicit Camera(const raisim::DepthCamera &depthCam)
Construct a camera from a const raisim depth camera.
- Parameters:
depthCam – Raisim depth camera to mirror.
-
explicit Camera(const raisim::DepthCamera::DepthCameraProperties &properties)
Build render targets from copied calibration; never accesses a live sensor.
-
inline std::uint64_t instanceId() const
- Returns:
Process-unique id assigned at construction (never reused).
-
void update(bool processKeyboard = true)
Update camera orientation and handle input.
Recomputes front, right and up from yaw / pitch. When a target object or fixed distance is active, the camera is placed on the orbit around getTargetPosition() instead.
- Parameters:
processKeyboard – If true, WASD and Space (along worldUp) move the camera by movementSpeed per second assuming a fixed 1/60 s step. Ignored while orbiting a target or with a fixed distance.
-
glm::mat4 getViewMatrix() const
Get the view matrix for the current camera pose.
- Returns:
View matrix in column-major GLM format.
-
glm::mat4 getProjectionMatrix() const
Get the projection matrix for the current camera state.
- Returns:
Projection matrix in column-major GLM format.
-
glm::vec2 getProjectionClipRange() const
Near/far distances actually used by getProjectionMatrix().
Near is the smaller of nearPlane and zNear (when positive) and far the larger of farPlane and zFar, with fallbacks for invalid values.
- Returns:
(near, far) in metres.
-
void setProjectionJitterPixels(const glm::vec2 &jitterPixels)
Set subpixel projection jitter in pixels for temporal AA style viewer rendering.
- Parameters:
jitterPixels – Offset in render-target pixels.
-
inline void clearProjectionJitter()
Clear projection jitter.
-
inline glm::vec2 projectionJitterPixels() const
- Returns:
Current projection offset in render-target pixels (zero for sensor opt-out).
-
inline glm::vec3 getPosition() const
Get the current camera position.
- Returns:
Position in world coordinates.
-
void mouseDelta(float yawOffset, float pitchOffset)
Apply mouse delta to yaw/pitch or pan in orthographic mode.
Perspective:
yaw -= yawOffset,pitch += pitchOffset(pitch clamped to +-89 deg). Orthographic: pans the position by 0.05 m per unit. Call update() afterwards to refresh the direction vectors.- Parameters:
yawOffset – Delta yaw in degrees (screen-space delta).
pitchOffset – Delta pitch in degrees (screen-space delta).
-
void moveForward(float steps)
Move forward/backward or zoom in orthographic mode.
Free perspective camera: moves
stepsmetres along front. Orthographic: scales orthoScale by 0.9^steps (min 0.1), so positive zooms in. Orbiting a target or with a fixed distance: scales the orbit distance by 1.2^steps (min 0.05 m), so positive steps move away from the target.- Parameters:
steps – Signed step count (e.g. mouse-wheel delta).
-
void setCameraFixedDistance(bool fixed)
Lock camera distance while orbiting.
- Parameters:
fixed – True to keep distance constant.
-
inline bool isCameraFixedDistance() const
- Returns:
True when the orbit distance is locked.
-
inline float cameraFixedDistance() const
- Returns:
Current orbit distance in metres (tracked while orbiting, locked when fixed).
-
void setCameraFixedTarget(bool fixed)
Lock the target position to a fixed point.
- Parameters:
fixed – True to use the target field as the orbit/look-at point.
-
inline bool isCameraFixedTarget() const
- Returns:
True when the camera target is locked to a fixed point.
-
void setTargetObject(raisim::Object *target)
Set a raisim object to track as the camera target.
A non-null object clears the fixed-target lock. The camera never reads the object: the RayraiWindow that renders with this camera follows its origin in the rendered physics frame (followTargetObject()), and releases the camera once the object is gone. A fixed distance locked before the first followed frame is measured on that frame.
- Parameters:
target – Raisim object to follow, or nullptr to clear.
-
void releaseTarget()
Stop following: clears the target object and the fixed-target and fixed-distance locks.
-
bool followTargetObject(uint64_t instance, const glm::vec3 &position)
Internal: the followed targetObject as rendered, set by RayraiWindow whenever it renders; applications do not call this.
A camera that update() placed moves with the object.
- Parameters:
instance – RaisimObject::instanceId() of the object’s drawable.
position – World position of the object’s origin.
- Returns:
False when another object now has the target’s address: the caller releases it.
-
void setProjectionMode(ProjectionMode mode)
Set projection mode.
- Parameters:
mode – Projection mode (perspective or orthographic).
-
ProjectionMode getProjectionMode() const
Get the active projection mode.
- Returns:
Current projection mode.
-
void setLensModel(const raisim::CameraLensModel &lens, double hFovRad)
Configure the camera lens model used for sensor rendering.
Only stores the lens and horizontalFovRad; it does not change zoom.
- Parameters:
lens – Lens model (pinhole or fisheye).
hFovRad – Horizontal field of view in radians.
-
inline const raisim::CameraLensModel &getLensModel() const
Get the active sensor lens model.
- Returns:
Reference to the stored lens model.
-
inline bool isFisheyeLens() const
- Returns:
True when the camera is configured for OpenCV/ROS equidistant fisheye output.
-
void applyFisheyeRemap(Shader &fisheyeShader)
Resample scene color through the fisheye lens model.
No-op unless isFisheyeLens() and scene targets exist. Renders into the post target and blits the result back into the scene color texture.
- Parameters:
fisheyeShader – Fisheye remap shader (bound here).
-
glm::vec3 getTargetPosition() const
Get the current target position for orbiting.
- Returns:
target when the fixed-target lock is on, else the target object’s position, else the world origin.
-
void ensureRenderTargets(int width, int height)
Ensure render targets match the given size.
(Re)allocates the scene color/depth targets (and the MSAA target when enabled) and updates aspect. Requires a current GL context; ignored for non-positive sizes.
- Parameters:
width – Render target width.
height – Render target height.
-
void resizeRenderTargets(int width, int height)
Resize render targets, retaining depth-only allocation when applicable.
- Parameters:
width – Render target width.
height – Render target height.
-
void setSceneMsaaSamples(int samples)
Set scene-color MSAA samples for future scene FBO rendering.
Values <= 1 disable MSAA. The resolved color/depth are still written into the existing single-sample texture targets so postprocessing and readback APIs keep working.
- Parameters:
samples – Requested sample count; values above 1 are clamped to [2, GL_MAX_SAMPLES].
-
void setSceneMsaaSamples(int samples, bool keepAllocation)
Same as setSceneMsaaSamples(), optionally keeping an existing multisampled target.
With keepAllocation, disabling MSAA keeps the multisampled renderbuffers so re-enabling the same sample count reuses them instead of reallocating. Every scene render clears the target before drawing, so reuse cannot change the image. A later call without keepAllocation that leaves MSAA disabled releases the kept target.
- Parameters:
samples – Requested sample count, as in the single-argument overload.
keepAllocation – Keep the multisampled renderbuffers when disabling MSAA.
-
inline int sceneMsaaSamples() const
- Returns:
Current scene-color MSAA sample count. 1 means disabled.
-
void resolveSceneFboIfNeeded(bool restoreFramebuffer = true)
Resolve the multisampled scene target into the regular color/depth textures.
- Parameters:
restoreFramebuffer – Restore the previous read/draw framebuffer bindings afterwards.
-
void ensurePostRenderTarget()
Ensure the post-process render target exists.
-
void ensureLinearDepthRenderTarget()
Ensure the linear-depth render target exists.
-
void bindSceneFbo()
Bind the scene framebuffer for rendering.
Binds the MSAA framebuffer when MSAA is enabled, allocating targets on demand.
-
void bindPostFbo()
Bind the post-process framebuffer for rendering.
-
void bindLinearDepthFbo()
Bind the linear-depth framebuffer for rendering.
-
inline int rtWidth() const
Current render target width.
- Returns:
Width in pixels.
-
inline int rtHeight() const
Current render target height.
- Returns:
Height in pixels.
-
void beginSceneFboAndClear(bool preserveState = true)
Bind scene FBO and clear color, depth and stencil with the background color.
- Parameters:
preserveState – Restore the color/depth/stencil write masks and scissor state afterwards; false leaves scissor disabled and masks enabled.
-
void postProcessDoF(Shader &postShader, bool fxaaEnabled = false, bool bloomEnabled = false, float bloomThreshold = 0.82f, float bloomStrength = 0.18f, float bloomRadius = 4.0f, float bloomKnee = 0.22f, int bloomQuality = 1, float bloomSourceClamp = 8.0f, float bloomAnamorphic = 0.0f, float bloomDirtStrength = 0.0f, float bloomDirtScale = 1.0f, unsigned int bloomDirtTexture = 0, int bloomBlendMode = 0, float bloomMix = 0.05f, const glm::vec3 &viewerWhiteBalance = glm::vec3(1.0f), float viewerSaturation = 1.0f, bool screenSpaceAoEnabled = false, float screenSpaceAoRadius = 2.0f, float screenSpaceAoStrength = 0.0f, float screenSpaceAoBias = 0.02f, int screenSpaceAoSamples = 12, float screenSpaceAoFalloff = 0.08f, bool screenSpaceAoRadiusWorldSpace = false, float screenSpaceAoMaxPixelRadius = 48.0f, bool screenSpaceAoGeometryAware = false, float contactAoRadius = 0.0f, float contactAoStrength = 0.0f, int contactAoSamples = 8, float contactAoFalloff = 0.05f, bool screenSpaceAoDenoiseEnabled = false, float screenSpaceAoDenoiseStrength = 0.0f, int screenSpaceAoDenoiseRadius = 1, float screenSpaceAoDenoiseDepthSigma = 0.035f, bool screenSpaceIndirectLightingEnabled = false, float screenSpaceIndirectLightingRadius = 3.0f, float screenSpaceIndirectLightingStrength = 0.0f, int screenSpaceIndirectLightingSamples = 12, float screenSpaceIndirectLightingFalloff = 0.22f, float screenSpaceIndirectLightingNormalRejection = 0.75f, float screenSpaceIndirectLightingSaturation = 1.0f, bool volumetricFogEnabled = false, float volumetricFogDensity = 0.0f, float volumetricFogNoiseScale = 6.0f, float volumetricFogNoiseStrength = 0.55f, const glm::vec3 &volumetricFogColor = glm::vec3(0.72f, 0.80f, 0.90f), float volumetricFogAnisotropy = 0.0f, float volumetricFogAnimationTimeSeconds = 0.0f, const glm::vec2 &volumetricFogWindDirection = glm::vec2(1.0f, 0.0f), float volumetricFogWindSpeed = 0.0f, float volumetricFogTurbulenceSpeed = 0.0f, bool volumetricLightingEnabled = false, float volumetricLightStrength = 0.0f, float volumetricLightDecay = 0.88f, int volumetricLightSamples = 16, const glm::vec2 &volumetricLightScreenPosition = glm::vec2(0.5f), const glm::vec3 &volumetricLightColor = glm::vec3(1.0f), int localFogVolumeCount = 0, const std::array<glm::vec4, 8> &localFogVolumeCenterRadius = {}, const std::array<glm::vec4, 8> &localFogVolumeColorDensity = {}, const std::array<glm::vec4, 8> &localFogVolumeParams = {}, int projectedDecalCount = 0, const std::array<glm::mat4, 8> &projectedDecalWorldToLocal = {}, const std::array<glm::vec4, 8> &projectedDecalColor = {}, const std::array<glm::vec4, 8> &projectedDecalParams = {}, const std::array<unsigned int, 8> &projectedDecalAlbedoMaps = {}, const std::array<unsigned int, 8> &projectedDecalEmissionMaps = {}, const std::array<unsigned int, 8> &projectedDecalNormalMaps = {}, const std::array<unsigned int, 8> &projectedDecalOrmMaps = {}, const std::array<glm::vec4, 8> &projectedDecalTextureParams = {}, const std::array<glm::vec4, 8> &projectedDecalSurfaceParams = {}, const std::array<glm::vec4, 8> &projectedDecalUvScaleOffset = {}, bool temporalAaEnabled = false, float temporalAaBlend = 0.08f, bool temporalAaReset = false, int postProcessDebugMode = 0, bool aerialPerspectiveEnabled = false, unsigned int apVolumeTex = 0, float apStrength = 1.0f, int viewerColorGradePreset = 0, float viewerColorGradeStrength = 1.0f, float viewerVignetteStrength = 0.0f, float viewerChromaticAberrationStrength = 0.0f, float viewerFilmGrainStrength = 0.0f, float viewerLensCharacterTime = 0.0f, bool lightShaftsEnabled = false, float lightShaftsStrength = 1.0f, float lightShaftsDecay = 0.965f, float lightShaftsDensity = 1.0f, const glm::vec2 &lightShaftsSunScreenPos = glm::vec2(0.5f, 0.5f), const glm::vec3 &lightShaftsTint = glm::vec3(1.0f), float lensFlareGhostStrength = 0.0f, float lensFlareStreakStrength = 0.0f, const glm::vec3 &lensFlareTint = glm::vec3(1.0f), bool contactShadowsEnabled = false, float contactShadowsLength = 0.12f, float contactShadowsStrength = 0.7f, float contactShadowsThickness = 0.08f, const glm::vec2 &contactShadowsSunScreenPos = glm::vec2(0.5f, 0.5f), const glm::vec3 &contactShadowsLightDirectionWorld = glm::vec3(0.0f, 0.0f, -1.0f), bool motionBlurEnabled = false, const glm::vec2 &motionBlurDirection = glm::vec2(0.0f), float motionBlurStrength = 0.0f, bool ssrEnabled = false, float ssrStrength = 0.0f, int ssrSteps = 24, float ssrMaxDistance = 6.0f, float ssrThickness = 0.35f, bool heatHazeEnabled = false, float heatHazeStrength = 0.0f, float heatHazeFrequency = 4.0f, float heatHazeSpeed = 1.0f, float heatHazeMaxY = 0.55f, bool zoomBlurEnabled = false, float zoomBlurStrength = 0.0f, const glm::vec2 &zoomBlurCenter = glm::vec2(0.5f), float zoomBlurInnerRadius = 0.15f, bool posterizeEnabled = false, int posterizeLevels = 4, bool starburstEnabled = false, float starburstStrength = 0.0f, int starburstSpikes = 6, float starburstAngleOffset = 0.0f, float starburstRadius = 0.35f, const glm::vec3 &starburstTint = glm::vec3(1.0f, 0.95f, 0.85f), bool lensDistortionEnabled = false, float lensDistortionStrength = 0.0f, const glm::vec2 &lensDistortionCenter = glm::vec2(0.5f), bool underwaterEnabled = false, const glm::vec3 &underwaterTint = glm::vec3(0.30f, 0.60f, 0.85f), float underwaterCausticStrength = 0.5f, float underwaterCausticScale = 1.0f, float underwaterDepthExtinction = 1.0f, bool pixelateEnabled = false, int pixelateBlockSize = 4, bool nightVisionEnabled = false, float nightVisionStrength = 0.0f, float nightVisionGain = 2.5f, bool ditherEnabled = false, float ditherStrength = 0.004f, bool thermalEnabled = false, float thermalStrength = 0.0f, float thermalGain = 1.5f, bool scanlineEnabled = false, float scanlineStrength = 0.3f, float scanlineFrequency = 360.0f, bool letterboxEnabled = false, float letterboxAspect = 2.35f, const glm::vec3 &letterboxColor = glm::vec3(0.0f), Shader *aoPrepassShader = nullptr, Shader *contactShadowShader = nullptr)
Apply viewer post-processing.
Internal: called by RayraiWindow, which fills the long parameter list from its render-quality and weather settings. The remaining parameters map one-to-one onto post-shader uniforms. When no effect is enabled the pass is skipped and getFinalTexture() keeps returning the scene color.
- Parameters:
postShader – Shader configured for DoF, FXAA, and bloom.
fxaaEnabled – True to apply FXAA even when DoF is disabled.
aoPrepassShader – Optional leaner post program that runs the AO prepass, which caches AO for the denoiser, in place of
postShader(null:postShaderruns it).contactShadowShader – Post program that renders only the unfiltered contact shadows of the filter taps, into a texture
postShaderthen filters (uContactShadowTexture). Each tap is marched once although up to four pixels share it. Required whenpostShaderdeclares that sampler and contact shadows are enabled; ignored otherwise. That program’s decal map pool is one slot smaller.
-
void resetTemporalHistory()
Reset the temporal postprocess history before the next temporal frame.
-
void updateAutoExposure(float targetKey, float speed, float minFactor, float maxFactor)
Sample mean scene-color luma and lerp the auto-exposure factor.
Every 4th call issues an asynchronous PBO readback of the smallest mip of the post-process (or scene) color; a completed earlier readback, if any, yields the mean luma, and
autoExposureFactor_is smoothed towardtargetKey / mean. Never blocks: without a ready sample the factor is unchanged. Should be called once per frame, after post-process completes. The stored factor is then applied to the next frame’spbrExposure.- Parameters:
targetKey – Desired mean luma (approximately linear, 0..1).
speed – Lerp factor per update, clamped to [0, 1].
minFactor – Lower clamp of the exposure factor.
maxFactor – Upper clamp of the exposure factor.
-
inline float autoExposureFactor() const
- Returns:
Smoothed auto-exposure multiplier from the previous frame.
-
inline size_t debugAutoExposureIssuedReadbacks() const
Internal:
- Returns:
number of auto-exposure readbacks issued (diagnostics).
-
inline size_t debugAutoExposureCompletedReadbacks() const
Internal:
- Returns:
number of auto-exposure readbacks consumed (diagnostics).
-
inline size_t debugAutoExposureSkippedIssueFrames() const
Internal:
- Returns:
readback slots skipped because the ring was full or fencing failed (diagnostics).
-
inline void resetAutoExposure()
Reset auto-exposure to identity (no compensation).
-
bool temporalHistoryValid() const
- Returns:
True if a temporal history texture is available for the current render target.
-
int temporalHistoryFrameCount() const
- Returns:
Number of post-process frames copied into temporal history since the last reset.
-
void ensurePickFramebuffer()
Ensure the picking framebuffer is created.
-
uint32_t readPickIdAt(int x, int y) const
Read the encoded pick id at a pixel coordinate.
Synchronous glReadPixels from the pick framebuffer.
- Parameters:
x – X coordinate in render-target pixels from the left.
y – Y coordinate in render-target pixels from the top (flipped internally).
- Returns:
24-bit id encoded in the pick texture’s RGB bytes; 0 when out of bounds.
-
inline unsigned int getPickFbo() const
Get the picking FBO id.
- Returns:
OpenGL framebuffer id.
-
unsigned int getFinalTexture() const
Get the final texture to display (post or debug).
- Returns:
Pick texture when setDebugShowPick(true), else the post-process color if post-processing ran since the last scene bind, else the scene color texture.
-
inline unsigned int getSceneColorTex() const
Get the scene color texture id.
- Returns:
Color texture id, or zero before scene targets are allocated.
-
inline unsigned int getSceneDepthTex() const
Get the scene depth texture id.
- Returns:
Depth24/stencil8 texture id, or zero before scene targets are allocated.
-
inline unsigned int getSceneFbo() const
Get the scene framebuffer id.
- Returns:
Single-sample scene FBO id; zero before a color render or explicit ensureRenderTargets().
-
inline unsigned int getLinearDepthTexture() const
Get the linear depth texture id (R32F).
- Returns:
Linear depth texture id, or zero before the linear-depth target is allocated.
-
std::vector<RenderTargetDiagnostics> renderTargetDiagnostics() const
Return a diagnostics-only snapshot of camera-owned render targets.
Queries framebuffer status, so a current GL context is required.
- Returns:
One entry per target (scene, MSAA, post, temporal, bloom, picking, linear depth, …).
-
void getRawImage(raisim::RGBCamera &sensor, SensorStorageMode mode = SensorStorageMode::SENSOR_SETTER, char *customBuffer = nullptr, size_t customBufferSize = 0, bool flipVertical = true) const
Read the color buffer into a raisim RGB camera or custom buffer.
Synchronously reads the scene color target (before post-processing) as 8-bit BGRA, width*height*4 bytes; each channel is clamped to [0, 1] and rounded to the nearest 8-bit value. Hardware renderers pack the image on the GPU; software renderers convert native half-float pixels with exact CPU arithmetic. The sensor resolution must match the render target and the scene color target must exist (fatal otherwise). Requires a current GL context. The sensor’s configured measurement noise is applied in place after readback, in either storage mode; each call advances that sensor’s random stream.
- Parameters:
sensor – Raisim RGB camera providing the resolution; filled when using SENSOR_SETTER.
mode – Storage mode (sensor setter or custom buffer).
customBuffer – Destination for BGRA bytes when using CUSTOM_BUFFER (required then).
customBufferSize – Size of custom buffer in bytes (at least width*height*4).
flipVertical – Whether to flip rows from GL origin to image origin.
-
void getRawImage(raisim::DepthCamera &sensor, SensorStorageMode mode = SensorStorageMode::SENSOR_SETTER, float *customBuffer = nullptr, size_t customBufferLength = 0, bool flipVertical = true) const
Read the linear depth buffer into a raisim depth camera or custom buffer.
Synchronous read of the R32F linear-depth target. With
flipVerticalthe rows are reversed on the GPU for hardware renderers or in CPU memory for software renderers, preserving sample bytes. The sensor resolution must match the render target and the linear-depth target must exist (fatal otherwise). The sensor’s configured measurement noise, quantization and dropout are applied in place in either storage mode. Readback does not populate the sensor’s 3D points.- Parameters:
sensor – Raisim depth camera providing the resolution; filled when using SENSOR_SETTER.
mode – Storage mode (sensor setter or custom buffer).
customBuffer – Destination for float depth values when using CUSTOM_BUFFER (required then).
customBufferLength – Length of custom buffer in floats (at least width*height).
flipVertical – Whether to flip rows from GL origin to image origin.
-
void readSceneColorBgra(char *destination, size_t bytes, bool flipVertical = true) const
Synchronous BGRA8 readback into application-owned storage; no raisim sensor is accessed.
-
void readLinearDepth(float *destination, size_t samples, bool flipVertical = true) const
Synchronous float32 plane-depth readback; no raisim sensor is accessed.
-
void setAsyncReadbackEnabled(bool enabled, size_t ringSize = 3)
Configure optional PBO-backed readback helpers.
Sensor getRawImage() remains synchronous by default. After the configured PBO ring fills, the async helpers return an earlier completed frame and normally lag by
ringSizecalls.- Parameters:
enabled – Enable the async helpers; disabling releases the PBOs.
ringSize – Number of PBOs per ring (min 2).
-
inline bool isAsyncReadbackEnabled() const
- Returns:
True when the async readback helpers are enabled.
-
bool readSceneColorRgbaAsync(std::vector<unsigned char> &rgba, bool flipVertical = true) const
Queue a readback of the scene color (RGBA8) and fetch the oldest pending one.
- Parameters:
rgba – [out] Filled with width*height*4 bytes when a frame is returned.
flipVertical – Whether to flip rows from GL origin to image origin.
- Returns:
True if
rgbawas filled; false while the ring is filling, when disabled, or without a scene color target.
-
bool readLinearDepthAsync(std::vector<float> &depth, bool flipVertical = true) const
Queue a readback of the linear depth (float) and fetch the oldest pending one.
- Parameters:
depth – [out] Filled with width*height floats when a frame is returned.
flipVertical – Whether to flip rows from GL origin to image origin.
- Returns:
True if
depthwas filled; false while the ring is filling, when disabled, or without a linear-depth target.
-
inline void setBackgroundColor(const glm::vec4 &c)
Set the background clear color using legacy 0..255 RGBA channels.
Prefer setBackgroundColorRgb255() in new code to make the range explicit.
- Parameters:
c – RGBA color where each channel is in [0, 255].
-
inline void setBackgroundColorRgb255(const glm::vec4 &c)
Set the background clear color using 0..255 RGBA channels.
- Parameters:
c – RGBA color where each channel is in [0, 255].
-
inline void setBackgroundColorLinear(const glm::vec4 &c)
Set the background clear color using linear 0..1 RGBA channels.
- Parameters:
c – Linear RGBA color where each channel is in [0, 1].
-
inline glm::vec4 getBackgroundColor() const
Get the background clear color.
- Returns:
Legacy RGBA color in [0, 255].
-
inline glm::vec4 getBackgroundColorLinear() const
Get the background clear color in linear 0..1 channels.
- Returns:
Linear RGBA color in [0, 1].
-
inline void setGamma(float g)
Set the display gamma (output encoded as
c^(1/g); default 1).Applied to the background clear color and passed to the scene shaders.
- Parameters:
g – Gamma value.
-
inline float getGamma() const
Get gamma correction value.
- Returns:
Gamma value.
-
inline void setDOFEnabled(bool e)
Enable or disable DoF.
- Parameters:
e – True to enable.
-
inline bool getDOFEnabled() const
Get DoF enabled state.
- Returns:
True if DoF is enabled.
-
inline float getDOFFocusDistance() const
- Returns:
DoF focus distance in metres.
-
inline float getDOFFocusRange() const
- Returns:
Width of the fully sharp band in metres.
-
inline float getDOFMaxRadius() const
- Returns:
Maximum blur (bokeh) radius in pixels.
-
inline void setDOFParams(float focusDist, float focusRange, float maxRadius)
Set DoF parameters.
- Parameters:
focusDist – Focus distance in metres.
focusRange – Width of the fully sharp band centred on the focus distance, in metres.
maxRadius – Max blur (bokeh) radius in pixels.
-
inline void setDebugShowPick(bool e)
Toggle rendering of the pick buffer for debugging.
- Parameters:
e – True to show pick buffer.
-
inline bool isDebugShowingPick() const
Check if the pick buffer is shown for debugging.
- Returns:
True if pick buffer is displayed.
Public Members
-
glm::vec3 position
Camera pose and view parameters (public for quick access).
Distances are in world units (typically metres). Angles in degrees unless the field name ends in
Rad.nearPlane/farPlaneandzNear/zFarare overlapping pairs from earlier API revisions: they are not aliases; the projection uses the wider of the two ranges (see getProjectionClipRange()), so with the defaultzNearof 0.01 raising onlynearPlanehas no effect. PrefernearPlane/farPlanein new code.position,front,up,rightare world-space;front/up/rightare recomputed by update().targetis the orbit point used only while setCameraFixedTarget(true) is active.worldUpis the up reference.
-
glm::vec3 front
Unit view direction (world).
-
glm::vec3 target
Fixed orbit/look-at point, used while setCameraFixedTarget(true).
-
float yaw
Yaw in degrees, measured about +Z from +X.
-
float pitch
Degrees.
Pitch in degrees above the XY plane (clamped to +-89 by mouseDelta()).
-
float movementSpeed
Keyboard movement speed in m/s (default 5).
-
float zoom
Vertical field of view in degrees used by the perspective projection (default 45).
-
float aspect
Horizontal / vertical.
-
float horizontalFovRad
Radians (45°).
Horizontal FOV in radians used by the lens model / fisheye remap only; the perspective projection uses zoom. The constructor derives it from the default 45 deg vertical FOV and 16:9 aspect.
-
float nearPlane
Near clip distance in metres (see getProjectionClipRange()).
-
float farPlane
Metres.
Far clip distance in metres (see getProjectionClipRange()).
-
float orthoScale
Metres of vertical view extent in ortho mode.
Public Static Functions
-
static void unbindFbo()
Unbind any framebuffer (bind default).
-
struct RenderTargetDiagnostics
Internal: diagnostics snapshot of one camera-owned render target (returned by renderTargetDiagnostics()). GL ids are 0 when unallocated.
Public Members
-
std::string name
Target name, e.g. “scene”, “postprocess”, “picking”.
-
unsigned int framebuffer
GL framebuffer id.
-
unsigned int colorTexture
GL color texture id.
-
unsigned int depthTexture
GL depth texture id.
-
unsigned int colorRenderbuffer
GL color renderbuffer id (MSAA target).
-
unsigned int depthRenderbuffer
GL depth renderbuffer id.
-
int width
Allocated width in pixels.
-
int height
Allocated height in pixels.
-
int samples
MSAA sample count.
-
std::string colorFormat
Color format name; empty if none.
-
std::string depthFormat
Depth format name; empty if none.
-
size_t estimatedBytes
Estimated GPU memory; 0 when not ready.
-
bool ready
True when all required attachments exist.
-
unsigned int framebufferStatus
glCheckFramebufferStatus() result (0 if no FBO).
-
std::string framebufferStatusName
Readable form of framebufferStatus.
-
bool framebufferComplete
True when the status is GL_FRAMEBUFFER_COMPLETE.
-
std::string name
-
enum class ProjectionMode
-
class RayraiGlobalAsset
A caching asset manager for 3D models and primitive meshes.
This class loads models on demand and keeps them in memory as long as they are being used. Once all references to a model are released, its memory can be reclaimed. It also owns reusable meshes for primitives such as cubes, spheres, cylinders, and capsules.
Returned mesh lists are shared: every caller that requests the same asset gets the same
std::shared_ptr, so mutating a mesh’s material affects all users. Not thread-safe; use it from the thread that owns the GL context.Public Functions
-
RayraiGlobalAsset()
Construct the asset cache and generate primitive meshes.
Requires a current OpenGL context (primitive meshes are uploaded here, or reused from another context in the same share group).
-
~RayraiGlobalAsset()
Destroy the asset cache.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> getMeshes(const std::string &name)
Retrieves a model’s meshes by its asset name (usually file path).
Assets are keyed by canonical path, so different spellings of the same file share one mesh list. With async loading enabled (the default; USD files always load synchronously) a new file returns an empty list at once that is filled in place by a later pollAsyncLoads(); if that import fails the list stays empty. The cache holds only weak references. Requires a current GL context for synchronous loads.
- Parameters:
name – The unique identifier for the asset, typically the file path.
- Returns:
Shared mesh list (possibly still empty while loading), or nullptr if the path does not exist or a synchronous load fails.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> getMeshes(const std::string &name, std::string *canonicalKeyOut)
Retrieves meshes and returns the canonical cache key used for the lookup.
- Parameters:
name – The unique identifier for the asset, typically the file path.
canonicalKeyOut – Optional output for the canonical mesh key (”” if the path cannot be resolved).
- Returns:
Same as getMeshes(const std::string&).
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> findLoadedMeshes(const std::string &name) const
The meshes of a model file this cache has already read, without reading it.
- Parameters:
name – File path, as passed to getMeshes().
- Returns:
The cached mesh list (possibly still empty while an asynchronous read runs), or nullptr when the file was not read or nothing holds it any more.
-
std::string canonicalMeshKey(const std::string &path) const
Resolve a mesh path to the canonical key used by getMeshes() / the LOD cache.
- Parameters:
path – File path; results are memoized per input string.
- Returns:
Canonical absolute path, or “” if the path cannot be canonicalized (does not exist, etc.).
-
std::shared_ptr<MeshLodChain> getCachedMeshLods(const std::string &canonicalKey) const
Look up a cached automatic-LOD chain.
- Parameters:
canonicalKey – Key from canonicalMeshKey().
- Returns:
The chain, or nullptr on miss or when it has expired.
Register an automatic-LOD chain for a canonical source-mesh key. The cache holds weak references, so the chain stays alive only while at least one caller (typically a Visuals) keeps the returned shared_ptr.
- Parameters:
canonicalKey – Key from canonicalMeshKey(); empty keys are ignored.
chain – Chain to register; null is ignored.
-
std::shared_ptr<MeshPreprocessMetadata> getCachedMeshPreprocessMetadata(const std::string &canonicalKey) const
Look up file-backed mesh preprocessing metadata.
- Parameters:
canonicalKey – Key from canonicalMeshKey().
- Returns:
The metadata, or nullptr on miss or when it has expired.
Register file-backed mesh preprocessing metadata for later visuals.
Held by weak reference, like cacheMeshLods().
- Parameters:
canonicalKey – Key from canonicalMeshKey(); empty keys are ignored.
metadata – Metadata to register; null or invalid metadata is ignored.
-
size_t pollAsyncLoads(size_t maxAssets = 1)
Advance ready import, worker geometry, and incremental GPU upload stages.
This must be called on the OpenGL/render thread because it creates textures, vertex buffers, and vertex array objects. Each processed asset advances one stage (import, geometry preparation, or one submesh upload) per call.
- Parameters:
maxAssets – Maximum number of pending assets advanced in this call.
- Returns:
Number of assets finalized (successfully or not) in this call.
-
size_t pollAsyncLoadsUntil(std::chrono::steady_clock::time_point deadline)
Advance every pending import as far as it can go before
deadline.Like pollAsyncLoads(), on the OpenGL/render thread, but an asset keeps advancing (one submesh upload after another) until it waits for a worker or the deadline passes. Imports whose worker finished go first, so the next worker stages start early. With async loading enabled, an import is finished only once the background decodes of its textures are done, so the render thread decodes no image. At least one ready stage runs per call.
- Parameters:
deadline – Time after which no further stage starts.
- Returns:
Number of assets finalized (successfully or not) in this call.
-
inline size_t pendingAsyncLoadCount() const
- Returns:
Number of mesh file imports that have not been finalized yet.
-
inline void setAsyncMeshLoadingEnabled(bool enabled)
Enable or disable async mesh file import for future getMeshes() calls.
- Parameters:
enabled – True (default) to import on a worker thread; finalize with pollAsyncLoads().
-
void forgetChangedModelFiles()
Forget every cached model file whose sources changed since it was read.
A model’s sources are its file and every file its import read (glTF buffers, an OBJ material library, …). A changed one makes the next getMeshes() read the model again, even while visuals still hold the meshes read before. RayraiWindow::swapWorld() calls this, so a rebuilt scene shows edited files.
-
inline void releaseRecentlyReadModels()
Release the models read from files since the last call.
A model read from a file stays referenced until this is called, so every visual created in the same frame shares one read, even when a visual keeps only meshes derived from it (instanced foliage keeps its partitioned meshes, and a terrain foliage layer adds one visual per chunk). RayraiWindow calls this at the end of each update(), renderWithExternalCamera(), and depth-only render.
-
inline bool asyncMeshLoadingEnabled() const
- Returns:
True when future mesh file imports start on a worker thread.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> getCubeMesh()
Get a unit cube mesh (side length 1, centred at the origin).
- Returns:
Shared mesh list for a cube.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> getCylinderMesh()
Get a unit cylinder mesh (radius 1, height 1 along local Z).
- Returns:
Shared mesh list for a cylinder.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> getCapsuleMesh()
Get a unit capsule mesh (radius 1, cylinder height 1, along local Z).
- Returns:
Shared mesh list for a capsule.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> getSphereMesh()
Get a unit sphere mesh (radius 1).
- Returns:
Shared mesh list for a sphere.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> getPlaneMesh()
Get a unit plane mesh (1 x 1, centred on the XY plane).
- Returns:
Shared mesh list for a plane.
-
void setDefaultPrimitivePbrEnabled(bool enabled)
Enable High/Ultra primitive PBR defaults for shared primitive assets.
Applies configureDefaultPrimitivePbrMaterial() to the cube, sphere, cylinder and capsule meshes (not the plane).
- Parameters:
enabled – True to allow the PBR pass.
-
inline bool defaultPrimitivePbrEnabled() const
- Returns:
True when shared primitive assets currently use the High/Ultra PBR path.
Public Static Functions
Configure the default material used by built-in primitive meshes.
The material remains a PBR material, but
enabledcontrols whether it is allowed to enter the PBR pass or forced through the cheaper simple shader. Overwrites the base color, metallic, roughness and IBL strengths of every mesh inmeshes.- Parameters:
meshes – Mesh list to modify in place; null is ignored.
enabled – False sets Material::forceSimpleShading.
Process-wide shared GPU-asset cache diagnostics.
Byte counts cover indexed mesh VBO/EBO allocations. Textures and context-local VAOs are intentionally excluded. Thread-safe.
- Returns:
Snapshot of the counters.
Reset the process-wide counters to zero (cached assets are kept). Thread-safe.
Enable process-wide reuse of immutable mesh buffers across compatible contexts.
Compatibility is probed with OpenGL object visibility, so contexts outside the same share group automatically retain independent uploads. Enabled by default.
- Parameters:
enabled – True to reuse uploads; false makes every lookup upload anew.
- Returns:
True when process-wide mesh-buffer reuse is enabled.
Counters of the process-wide shared GPU-asset cache (see sharedGpuAssetStats()).
Public Members
Lookups served by an existing upload in a compatible context.
Lookups that had to create and upload new geometry.
VBO/EBO bytes uploaded on misses.
VBO/EBO bytes reused on hits.
Live count of published templates still held, summed over every key. One per distinct asset and share group; growth beyond that means the same asset is being published repeatedly and every lookup walks them.
-
struct MeshLodChain
Internal: cached automatic-LOD chain shared by Visuals of the same source mesh.
Public Members
-
std::vector<std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>>> levels
LOD 1, 2, … mesh lists.
-
std::vector<size_t> triangleCounts
Source (LOD 0) triangle count, then one per generated level.
-
std::shared_ptr<rayrai_internal::FoliageCaptureGeometry> captureGeometry
Internal foliage-capture data; may be null.
-
std::vector<std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>>> levels
-
RayraiGlobalAsset()
Visuals and geometry
-
class Visuals
Renderable visual object not owned by raisim::World.
Visuals encapsulate geometry, transform, and appearance for custom renderable shapes or meshes.
The world transform is position, then orientation, then a per-axis scale applied in the mesh’s local frame (Z-up world, quaternions passed as wxyz). Built-in primitives and file meshes come from RayraiGlobalAsset and are shared with other visuals; per-visual appearance belongs in the color, material override/remap/overlay and flags below rather than in the shared meshes. Setters only change state (and renderRevision()); GL work happens when the renderer draws, so drawing requires a current GL context.
Material queries
Internal: renderer pass-selection queries over the visual’s draw materials (override, remaps and overlay included). Each mirrors the RaisimObject query of the same name.
-
bool hasPbrMeshes() const
- Returns:
True when any draw material uses the PBR shader.
-
bool hasHighFidelityPbrMeshes() const
- Returns:
True when any PBR draw material requires the high-fidelity PBR path.
-
bool hasTransmissivePbrMeshes() const
- Returns:
True when any PBR draw material needs the transmission pass.
-
bool hasProximityFadePbrMeshes() const
- Returns:
True when any PBR draw material uses proximity fade.
-
bool usesDefaultDepthAndStencilState() const
- Returns:
True when every draw material uses default depth/stencil state.
-
bool hasFullPbrMeshes() const
- Returns:
True when any PBR draw material cannot use a compact PBR shader.
-
bool hasFoliageFastPbrMeshes() const
- Returns:
True when any draw material can use the foliage fast-PBR path.
-
bool hasWeatherEligiblePbrMeshes() const
- Returns:
True when any draw material reacts to active weather.
-
bool hasSimpleMeshes() const
- Returns:
True when any draw material uses the simple shader.
-
bool hasPlanarReflectionMeshes() const
- Returns:
True when any PBR draw material uses planar reflection.
-
bool hasProceduralGroundCheckerMeshes() const
- Returns:
True when any draw material enables Material::proceduralGroundChecker.
Public Types
-
enum class VisibilityRangeFadeMode
How setVisibilityRange() thresholds are applied.
Values:
-
enumerator Disabled
Hard cut at the thresholds.
-
enumerator Self
Alpha-fade this visual across the margins.
-
enumerator Dependencies
Stored only; the renderer treats it like Disabled (hard cut).
-
enumerator Disabled
Public Functions
Construct a visual from a built-in shape or mesh file.
Sphere, box, cylinder and capsule use the shared unit primitives (see RayraiGlobalAsset); size them with the set*Size() methods. Mesh loads
meshFilethroughassets(possibly asynchronously, see RayraiGlobalAsset::getMeshes()). Other shape types, a nullassetsor a missing file leave the visual invalid (isValid() false).- Parameters:
type – Raisim shape type to render.
name – Visual name.
assets – Global asset cache for primitive meshes.
meshFile – Mesh file path when type is Mesh.
Construct a visual from custom OpenGL meshes.
The shape type is Mesh and the list is shared, not copied. Automatic mesh LOD is enabled.
- Parameters:
name – Visual name.
meshes – Mesh list to render; null makes the visual invalid.
Construct a visual from custom OpenGL meshes.
- Parameters:
name – Visual name.
meshes – Mesh list to render; null makes the visual invalid.
automaticMeshLodEnabled – Generate and use automatic mesh LODs.
-
void setSphereSize(double radius)
Set sphere radius (uniform scale of the unit-radius sphere).
- Parameters:
radius – Sphere radius in metres.
-
void setBoxSize(double x, double y, double z)
Set box dimensions (scale of the unit cube).
- Parameters:
x – Full box length along local X, in metres.
y – Full box length along local Y, in metres.
z – Full box length along local Z, in metres.
-
void setCylinderSize(double radius, double height)
Set cylinder dimensions (scale of the unit cylinder, axis along local Z).
- Parameters:
radius – Cylinder radius in metres.
height – Cylinder height in metres.
-
void setCapsuleSize(double radius, double height)
Set capsule dimensions.
For a Capsule visual this regenerates a private capsule mesh (only when the size changes) and resets the scale to 1; for other types it sets the scale to (radius, radius, height).
- Parameters:
radius – Capsule radius in metres.
height – Height of the cylindrical section (excluding the caps), in metres.
-
void setMeshScale(double x, double y, double z)
Set mesh scale factors (applied in the mesh’s local frame).
- Parameters:
x – Scale in X.
y – Scale in Y.
z – Scale in Z.
-
void setDefaultPrimitivePbrEnabled(bool enabled)
Toggle High/Ultra default PBR shading for built-in primitive meshes.
Edits the material of the shared primitive mesh, so every visual using the same primitive is affected. No-op for mesh visuals.
- Parameters:
enabled – True to allow the PBR pass.
-
inline raisim::Shape::Type shapeType() const
- Returns:
Shape type this visual was created with (or set via setShapeType()).
-
inline void setShapeType(raisim::Shape::Type type)
Change the recorded shape type without touching the meshes; it affects shading type, bounds estimation and LOD eligibility.
- Parameters:
type – New shape type.
-
void configureGroundMaterial(bool reflective, float roughness, float metallic, bool proceduralChecker = false, const RayraiWindow *terrainTextures = nullptr)
Configure this visual’s mesh material as a reflective/non-reflective ground, like RaisimObject::configureGroundMaterial(). Used for ground visuals created over the TCP path which don’t go through RaisimObject. Differences: a reflective ground here gets IBL and environment strength 0 (planar reflection only), and a Ground-type visual stops casting shadows. HeightMap visuals only get the terrain material reapplied, with the heightmap terrain textures of
terrainTextureswhen it has any. Edits the mesh materials in place.- Parameters:
reflective – Use a reflective PBR ground with planar reflection.
roughness – Roughness, clamped to [0.04, 1] (reflective only).
metallic – Metallic factor, clamped to [0, 1] (reflective only).
proceduralChecker – Draw a procedural checker instead of the texture.
terrainTextures – Renderer whose heightmap terrain textures a HeightMap visual takes (see RayraiWindow::applyHeightmapTerrainTextures()), or nullptr.
-
void setPosition(double x, double y, double z)
Set position from components.
- Parameters:
x – X position in world coordinates (m).
y – Y position in world coordinates (m).
z – Z position in world coordinates (m).
-
void setPosition(const glm::vec3 &pos)
Set position from a vector.
- Parameters:
pos – Position in world coordinates (m).
-
void setOrientation(double w, double x, double y, double z)
Set orientation from wxyz quaternion.
The quaternion is used as given (not normalized); pass a unit quaternion.
- Parameters:
w – Quaternion w.
x – Quaternion x.
y – Quaternion y.
z – Quaternion z.
-
void setOrientation(const glm::vec4 &ori)
Set orientation from wxyz quaternion vector.
- Parameters:
ori – Quaternion (w, x, y, z): ori.x is w and ori.w is z, the same layout getOrientation() returns. The identity is glm::vec4(1, 0, 0, 0).
-
void setColor(double r, double g, double b, double a)
Set object color from components.
- Parameters:
r – Linear red channel in [0, 1].
g – Linear green channel in [0, 1].
b – Linear blue channel in [0, 1].
a – Alpha channel in [0, 1]; values below 1 route the visual to the transparent pass.
-
void setColor(const glm::vec4 &color)
Set object color from vector.
- Parameters:
color – Linear RGBA color in [0, 1].
-
inline void setUseMeshColor(bool use)
Use mesh-provided colors instead of object color.
Untextured meshes then use their own base color (or material base color); the visual’s alpha still multiplies the result.
- Parameters:
use – True to use mesh colors.
-
inline bool usesMeshColor() const
Check if mesh colors are used.
- Returns:
True if mesh colors are used.
-
inline void setFlatShading(bool enabled)
Force flat shading for this visual (overrides the shape’s shading type).
- Parameters:
enabled – True to use flat shading.
-
inline bool isFlatShading() const
Check if flat shading is forced.
- Returns:
True if flat shading is used.
-
inline void setTwoSided(bool enabled)
Disable face culling while drawing this visual.
- Parameters:
enabled – True to draw both sides of mesh triangles.
-
inline bool isTwoSided() const
Check if face culling is disabled for this visual.
- Returns:
True if both sides are drawn.
-
inline void setPbrEnvironment(unsigned int environmentMap, unsigned int brdfLut = 0, float strength = 1.0f)
Apply an image-based lighting environment to all PBR submeshes.
Same as the split overload with no irradiance or prefiltered map.
- Parameters:
environmentMap – GL cubemap id (0 clears).
brdfLut – Split-sum BRDF LUT texture id, or 0.
strength – Environment strength (Material::environmentMapStrength).
-
inline void setPbrEnvironment(unsigned int environmentMap, unsigned int irradianceMap, unsigned int prefilteredEnvironmentMap, unsigned int brdfLut, float strength = 1.0f, bool boxProjection = false, const glm::vec3 &probePosition = glm::vec3(0.0f), const glm::vec3 &boxMin = glm::vec3(0.0f), const glm::vec3 &boxMax = glm::vec3(0.0f))
Apply split image-based lighting maps to all PBR submeshes.
This mirrors the real-time IBL layout used by engines such as Filament: a display/environment cubemap, diffuse irradiance, prefiltered specular radiance, and a split-sum BRDF LUT. Supplying the full set gives whole-scene imported visuals the same high-fidelity path used by hand-built PBR meshes.
The ids are written into the materials of this visual’s meshes (and LOD meshes), material override, remaps and overlay, skipping materials that look like plain simple-shaded ones; a non-zero cubemap also switches those materials to Type::PBR. Mesh materials are edited in place, so other visuals sharing the same cached meshes see the change. Texture ids are not owned.
- Parameters:
environmentMap – Radiance/display cubemap id.
irradianceMap – Diffuse irradiance cubemap id, or 0.
prefilteredEnvironmentMap – Prefiltered specular cubemap id, or 0.
brdfLut – Split-sum BRDF LUT texture id, or 0.
strength – Environment strength (capped further for heightmap terrain).
boxProjection – Enable box-projected (parallax-corrected) reflections.
probePosition – Probe capture position in world coordinates.
boxMin – World-space minimum corner of the projection box.
boxMax – World-space maximum corner of the projection box.
-
inline void setPbrEnvironment(const PbrEnvironment &env)
Apply a PbrEnvironment bundle to all PBR submeshes.
Convenience overload that unpacks the four texture handles and the strength scalar from a single struct, eliminating the need for callers to juggle four raw GL ids in parallel.
- Parameters:
env – Environment bundle (also carries the box-projection settings).
Keep scene HDR cubemaps alive while this visual uses their texture ids.
-
inline void setCategory(VisualCategory category)
Set the render category used by capture/detection filters.
The category controls whether this user-created visual is included when a rayrai pass excludes non-detectable visualization objects, such as external camera scene-color renders, capture paths that reuse external-camera rendering, or picking/shadow candidate policies that request detectable custom visuals. The normal interactive viewer includes both categories by default.
This is render metadata only; it does not create collision, physics behavior, or a semantic label. New
Visualsdefault toVisualCategory::NotDetectable.See also
- Parameters:
category – New render category.
-
inline void setDetectable(bool detectable)
Convenience helper for toggling the visual render category.
- Parameters:
detectable – True to include this visual in detectable-only capture/detection render passes; false to keep it viewer-only for those passes.
-
inline glm::vec3 getPosition() const
Get current position.
- Returns:
Position in world coordinates.
-
inline glm::vec4 getOrientation() const
Get current orientation as a wxyz quaternion.
- Returns:
Quaternion with x holding w and w holding z.
-
inline glm::vec3 getScale() const
Get current shape or mesh scale.
- Returns:
Per-axis scale (for primitives this encodes the size set by set*Size()).
-
inline glm::vec4 getColor() const
Get current color.
- Returns:
Linear RGBA color in [0, 1].
-
inline VisualCategory getCategory() const
Get the render category used by capture/detection filters.
- Returns:
Current visual category.
-
inline bool isDetectable() const
Check whether detectable-only render passes include this visual.
- Returns:
True when the category is
VisualCategory::Detectable.
-
inline void setCastsShadows(bool castsShadows)
Enable or disable rendering this visual into shadow maps.
Large receiver-only helper surfaces can keep color rendering and shadow receiving while staying out of the shadow caster pass.
- Parameters:
castsShadows – True for ShadowCastingMode::On, false for Off.
-
inline bool castsShadows() const
- Returns:
True unless the shadow casting mode is Off.
-
inline void setShadowCastingMode(ShadowCastingMode mode)
- Parameters:
mode – New shadow casting mode.
-
inline ShadowCastingMode shadowCastingMode() const
- Returns:
Current shadow casting mode.
-
inline bool castsDoubleSidedShadows() const
- Returns:
True for ShadowCastingMode::DoubleSided.
-
inline void setColorPassVisible(bool visible)
Show or hide the visual in color passes without affecting shadow casting.
- Parameters:
visible – False hides it from color passes.
-
inline bool colorPassVisible() const
- Returns:
The flag set by setColorPassVisible().
-
inline bool visibleInColorPass() const
- Returns:
True when color-pass visible and not ShadowCastingMode::ShadowsOnly.
-
void setVisibilityRange(float begin, float end, float beginMargin = 0.0f, float endMargin = 0.0f, VisibilityRangeFadeMode fadeMode = VisibilityRangeFadeMode::Disabled)
Set renderer-side camera visibility range.
A zero begin/end disables that side of the range. Self fade uses the margins to alpha-fade this visual near the begin/end thresholds. Distances are measured from the camera to the visual’s bounds center, in metres; negative inputs are clamped to 0. Visuals with self fade are drawn in the transparent pass.
- Parameters:
begin – Hidden when closer than this.
end – Hidden when farther than this.
beginMargin – Half-width of the fade band around
begin(Self mode).endMargin – Half-width of the fade band around
end(Self mode).fadeMode – How the thresholds are applied.
-
inline float visibilityRangeBegin() const
- Returns:
Near visibility threshold in metres (0 = none).
-
inline float visibilityRangeEnd() const
- Returns:
Far visibility threshold in metres (0 = none).
-
inline float visibilityRangeBeginMargin() const
- Returns:
Fade half-width around the near threshold.
-
inline float visibilityRangeEndMargin() const
- Returns:
Fade half-width around the far threshold.
-
inline VisibilityRangeFadeMode visibilityRangeFadeMode() const
- Returns:
Current fade mode.
-
bool hasVisibilityRange() const
- Returns:
True when either threshold is non-zero.
-
bool visibilityRangeUsesSelfFade() const
- Returns:
True when Self fade is active with a non-zero margin on an enabled side.
-
float visibilityRangeAlpha(const glm::vec3 &viewPos) const
- Parameters:
viewPos – Camera position in world coordinates.
- Returns:
Visibility-range alpha in [0, 1] at
viewPos(1 without a range).
-
bool isVisibleAt(const glm::vec3 &viewPos) const
- Parameters:
viewPos – Camera position in world coordinates.
- Returns:
True when visibilityRangeAlpha() exceeds 0.001.
Override the visual’s draw material with a shared instance.
Ownership. The same
shared_ptr<Material>may be held by any number of other visuals —setMaterialOverridedoes not deep-copy. Mutating the pointed-to material from any holder is observed by every visual that shares it. If you want an in-place edit that affects only this visual, call theconst Material&overload (which copies into a new shared instance) or grab a fresh copy via*materialOverride()and push it back throughsetMaterialOverride(Material{...}).The override replaces the material of every submesh (and takes precedence over material remaps); the meshes’ own OpenGLMesh::textures are then ignored.
- Parameters:
material – Material to draw with; null clears the override.
-
void setMaterialOverride(const Material &material)
Override the visual’s draw material with a private copy.
Copies
materialinto a freshly allocated shared instance so later mutations affect only this visual. Prefer this overload when the material is going to be tweaked per-visual.- Parameters:
material – Material to copy.
-
void clearMaterialOverride()
Remove the material override; submeshes use their own (or remapped) materials again.
-
inline bool hasMaterialOverride() const
- Returns:
True when a material override is set.
-
inline const Material *materialOverride() const
- Returns:
The override material, or nullptr. Owned by this visual (possibly shared).
-
inline Material *mutableMaterialOverride()
Mutable accessor for the override material.
Honest companion to
setMaterialOverride(std::shared_ptr<Material>): if the material is shared with other visuals, edits made through this pointer are visible on all of them. Call notifyMeshMaterialsChanged() after editing so renderer caches are refreshed.- Returns:
The override material, or nullptr.
Replace the material of matching submeshes.
A submesh matches when its Material::name or OpenGLMesh::debugSourceMeshName equals
sourceName; the key “*” matches every submesh not matched by name. Ignored while a material override is set. The material is shared, not copied.- Parameters:
sourceName – Material or source-mesh name; empty is ignored.
material – Replacement material; null is ignored.
-
void setMaterialRemap(const std::string &sourceName, const Material &material)
Copying overload of setMaterialRemap().
-
void clearMaterialRemaps()
Remove all material remaps.
-
inline size_t materialRemapCount() const
- Returns:
Number of registered remap keys.
Draw every submesh a second time with this material on top of its normal material.
- Parameters:
material – Overlay material (shared, not copied); null clears it.
-
void setMaterialOverlay(const Material &material)
Copying overload of setMaterialOverlay().
- Parameters:
material – Material to copy.
-
void clearMaterialOverlay()
Remove the overlay material.
-
inline bool hasMaterialOverlay() const
- Returns:
True when an overlay material is set.
-
void setTransparency(float transparency)
Fade the whole visual: drawn alpha is multiplied by (1 - transparency). Values above 0 route the visual to the transparent pass; 1 skips drawing.
- Parameters:
transparency – Value clamped to [0, 1].
-
inline float transparency() const
- Returns:
Transparency in [0, 1].
-
void setCustomBounds(const glm::vec3 &localCenter, float localRadius)
Replace the culling bounds with a sphere given in the visual’s local (pre-scale) frame; it is scaled by the largest scale component.
- Parameters:
localCenter – Sphere center in local coordinates.
localRadius – Sphere radius; <= 0 disables custom bounds.
-
void clearCustomBounds()
Return to automatic bounds.
-
inline bool hasCustomBounds() const
- Returns:
True when custom bounds are active.
-
inline glm::vec3 customBoundsLocalCenter() const
- Returns:
Custom-bounds center in local coordinates.
-
inline float customBoundsLocalRadius() const
- Returns:
Custom-bounds radius in local units.
-
inline void setTransparentSortOffset(float offset)
Bias the transparent sort: the sort distance is reduced by
offset(clamped at 0), so a positive offset draws the visual later (as if closer).- Parameters:
offset – Distance offset in metres.
-
inline float transparentSortOffset() const
- Returns:
Transparent sort offset in metres.
-
inline void setTransparentSortUsesBoundsCenter(bool enabled)
- Parameters:
enabled – True (default) to sort by the bounds center, false to sort by getPosition().
-
inline bool transparentSortUsesBoundsCenter() const
- Returns:
Whether the transparent sort uses the bounds center.
-
glm::vec3 transparentSortCenter() const
- Returns:
World point used for transparent sorting.
-
float transparentSortDistanceSquared(const glm::vec3 &viewPos) const
- Parameters:
viewPos – Camera position in world coordinates.
- Returns:
Squared sort distance after applying the sort offset.
-
bool hasOpaqueDraws() const
- Returns:
True when some submesh is drawn in the opaque pass (false whenever the visual alpha, transparency or self fade makes it transparent).
-
bool hasTransparentDraws() const
- Returns:
True when some submesh is drawn in the transparent pass.
-
bool isTransparent() const
Check if visual is translucent based on alpha.
- Returns:
True if the color alpha is below 1, transparency is non-zero, self fade is active, or any draw material needs the transparent pass.
-
bool hasSpecialBlendMode() const
- Returns:
True when at least one draw material uses a blend mode other than Material::BlendMode::Mix.
-
int renderPriority() const
- Returns:
Highest material render priority across the visual’s draw materials (0 if none).
-
inline bool isValid() const
Check if the visual has valid mesh data.
- Returns:
True if a mesh list is assigned (it may still be empty while loading).
-
inline uint64_t renderRevision() const
Internal:
- Returns:
Counter bumped on every render-affecting change; used to invalidate frame caches.
-
inline const std::string &getName() const
- Returns:
The visual name used by the renderer.
-
float approximateRadius() const
- Returns:
Radius from approximateBounds(), or 0 for an invalid visual.
-
bool approximateBounds(glm::vec3 ¢er, float &radius) const
Conservative world-space bounds for coarse culling.
Uses custom bounds when set, mesh vertex bounds for Mesh/Ground/HeightMap visuals, and otherwise a scale-based estimate around getPosition().
- Parameters:
center – [out] Output sphere center.
radius – [out] Output sphere radius.
- Returns:
False for an invalid visual (outputs hold the scale-based estimate).
-
bool shadowGeometryWithinBounds() const
- Returns:
True when shadow depth draws keep every vertex inside approximateBounds(): no mesh, override, remap or overlay material uses billboards, fixed-size scaling or height displacement.
-
bool shadowDepthMayDiscard(bool transparentShadowDithering) const
- Returns:
False only when no mesh (at any LOD), override, remap or overlay material can make a shadow depth draw discard: none uses alpha mask, nor alpha blend while
transparentShadowDitheringis set.
-
uint64_t shadowMaterialSignature() const
Internal: hash of every material input of a shadow depth draw (mesh materials, textures and base colors, override, overlay and remap targets). OpenGLMesh::material and mutableMaterialOverride() are public and change no render revision, so cached shadow layers compare this too.
-
bool hasTextures() const
Check if any mesh has textures bound.
- Returns:
True if a mesh (or the override/overlay/remapped material) references a texture.
-
void setAutomaticMeshLodEnabled(bool enabled)
Enable automatic mesh LOD generation/selection for mesh visuals.
This affects visuals created from addVisualMesh()/addVisualCustomMesh(). Built-in primitive shapes keep their fixed authored meshes.
- Parameters:
enabled – True to generate (or fetch cached) LODs; false drops them.
-
inline bool automaticMeshLodEnabled() const
- Returns:
True when automatic mesh LOD is enabled for this visual.
-
void setAutomaticMeshLodBias(float bias)
Scale the projected size used for LOD selection; larger values keep finer LODs longer.
- Parameters:
bias – Multiplier, clamped to [0.01, 16] (default 1).
-
inline float automaticMeshLodBias() const
- Returns:
Current LOD bias.
-
size_t automaticMeshLodLevelCount() const
- Returns:
Number of available mesh LOD levels including the source mesh at level 0 (0 without meshes).
-
size_t automaticMeshLodTriangleCount(size_t level) const
- Parameters:
level – LOD level; 0 is the source mesh.
- Returns:
Triangle count for one mesh LOD level, or 0 for an invalid level.
-
float automaticMeshLodMaxUvClusterSpan(size_t level) const
- Parameters:
level – Generated LOD level (>= 1).
- Returns:
Largest UV span collapsed into one generated LOD vertex (diagnostics); 0 for level 0.
-
size_t selectAutomaticMeshLodLevel(const glm::vec3 &viewPos, float verticalFovDeg, int viewportHeight) const
Select the mesh LOD level that would be used for a camera.
-
void draw(Shader &shader, OpenGLMesh::RenderMode mode = OpenGLMesh::RenderMode::All) const
Draw the visual using a shader.
Always uses the source mesh (no LOD) and ignores the visibility range. Sets the
shadingType,modelandobjectColoruniforms and draws each submesh (plus the overlay material, if any) with OpenGLMesh::draw(). The shader must already be in use; requires a current GL context.- Parameters:
shader – Shader to use for drawing.
mode – Material filter (see OpenGLMesh::RenderMode).
-
inline void drawWithBoundShader(Shader &shader, OpenGLMesh::RenderMode mode = OpenGLMesh::RenderMode::All) const
Same as draw(); assumes the caller has already bound
shader.Currently equivalent to draw() because OpenGLMesh::draw also assumes the shader is bound. Kept as an API hook for callers that opt in via drawWithBoundShader.
- Parameters:
shader – Shader that is already in use.
mode – Material filter.
-
void draw(Shader &shader, const glm::vec3 &viewPos, float verticalFovDeg, int viewportHeight, OpenGLMesh::RenderMode mode = OpenGLMesh::RenderMode::All) const
Draw the visual using camera-aware automatic mesh LOD.
Like draw(Shader&, OpenGLMesh::RenderMode) but selects a LOD level and applies the visibility-range alpha for
viewPos.
-
inline void drawWithBoundShader(Shader &shader, const glm::vec3 &viewPos, float verticalFovDeg, int viewportHeight, OpenGLMesh::RenderMode mode = OpenGLMesh::RenderMode::All) const
Equivalent to the camera-aware draw(); kept for API parity.
-
void drawSorted(Shader &shader, const glm::vec3 &viewPos, OpenGLMesh::RenderMode mode = OpenGLMesh::RenderMode::All) const
Draw submeshes back-to-front relative to a camera position.
This is intended for transparent mesh visuals. It is more expensive than draw(), so rayrai only uses it on the transparent visual path. Submeshes are ordered by material render priority, then by distance (farthest first). Uses the source mesh (no LOD) and applies the visibility-range alpha.
-
bool drawsInMode(OpenGLMesh::RenderMode mode) const
Whether drawSorted() in this mode would rasterize anything. Transparent items are submitted once per shader, and a glass-only visual has nothing for the simple and non-transmissive passes; asking first avoids their program binds and per-object submission entirely.
- Parameters:
mode – Material filter.
- Returns:
True if some submesh (or overlay pass) would be drawn in
mode.
-
uint64_t materialSortKey(OpenGLMesh::RenderMode mode) const
Compact key for sorting opaque visual draws by material/texture state.
- Parameters:
mode – Render mode the draws will use.
- Returns:
Hash-like key combining the submeshes’ OpenGLMesh::materialSortKey(); sort only, not unique.
-
FrameCacheMaterialState frameCacheMaterialState(FrameCacheMaterialStateMemo *memo = nullptr) const
Internal: compute FrameCacheMaterialState in one traversal of the submeshes.
- Parameters:
memo – Optional memo to read/write (ignored for non-default PBR environments).
- Returns:
The summarized state.
Replace mesh data for this visual.
The list is shared, not copied. Automatic LODs are rebuilt, asset-level LOD caching is disabled for this visual, and the stored PBR environment is reapplied to the new meshes.
- Parameters:
meshes – New mesh list to render; null makes the visual invalid.
-
bool updateSingleMeshVertices(const std::vector<Vertex> &vertices)
Update the first mesh’s vertex buffer while preserving its index buffer.
Tangents are recomputed and generated LODs are dropped. The mesh is edited in place (shared users see it) and a GL context must be current.
- Parameters:
vertices – New vertex data for the existing mesh.
- Returns:
True when a single mesh was present and updated.
-
void notifyMeshMaterialsChanged()
Notify renderer caches after in-place material changes to existing meshes. Also reapplies the stored PBR environment.
-
size_t applyTextureFilteringQuality(float anisotropy, float mipLodBias) const
Apply sampler quality to all 2D material textures in this visual.
Includes generated LOD meshes; modifies the shared GL texture objects.
- Parameters:
anisotropy – Requested anisotropic filtering level.
mipLodBias – Mip LOD bias.
- Returns:
Number of texture ids updated (summed per mesh).
-
void collectMaterialTextureIds(std::vector<unsigned int> &textureIds) const
Append non-environment material texture ids used by this visual.
- Parameters:
textureIds – [inout] Ids are appended (duplicates are kept).
-
void accumulateGeometryDiagnostics(OpenGLMesh::GeometryDiagnostics &diagnostics, float tinyTriangleAreaThreshold) const
Accumulate CPU-side mesh geometry diagnostics for this visual.
- Parameters:
diagnostics – [inout] Totals to add to.
tinyTriangleAreaThreshold – Triangles with smaller (non-zero) area count as tiny.
-
void collectMeshDiagnostics(std::vector<OpenGLMesh::MeshDiagnostics> &diagnostics, float tinyTriangleAreaThreshold) const
Append per-mesh geometry/material diagnostics for this visual.
- Parameters:
diagnostics – [inout] One entry is appended per submesh.
tinyTriangleAreaThreshold – Triangles with smaller (non-zero) area count as tiny.
-
struct MaterialSortKeys
Internal: materialSortKey() for the three common render modes.
-
struct FrameCacheMaterialState
Summarize static frame-cache material state in one mesh traversal.
Internal: used by the renderer’s frame cache.
Public Members
-
bool cacheable
False (other fields default) when a material override, remap or overlay is set.
-
bool hasTextures
Some submesh has OpenGLMesh::textures.
-
bool hasPbrMeshes
Some submesh uses PBR shading.
-
bool transparent
Visual alpha/transparency/self fade, or a submesh needs the transparent pass.
-
bool specialBlendMode
Some submesh blend mode is not Material::BlendMode::Mix.
-
int renderPriority
Highest submesh render priority.
-
MaterialSortKeys sortKeys
Sort keys (simpleOnly equals all here).
-
bool cacheable
-
class FrameCacheMaterialStateMemo
Internal: memo keyed by mesh list, letting visuals that share meshes reuse frameCacheMaterialState() results.
-
bool hasPbrMeshes() const
-
class InstancedVisuals
Many copies of one shape or mesh drawn with GPU instancing.
Each instance has a position, wxyz orientation, scale and a color weight that blends between the two batch colors (getColor1(), getColor2()) (
mix(color1, color2, weight)). Appearance (colors, category, shadow flag) is shared by the whole batch. Instance edits are cheap CPU updates; the GPU instance buffer is refreshed lazily on the next draw, which requires a current GL context. Mesh batches may get automatic LODs prepared on a worker thread; such a batch draws nothing until that preparation has finished (see pollAsyncMeshPreparation()). Batches that look like foliage (alpha-masked or foliage materials, or a foliage-like file name) also enable shadow LOD, cluster culling and impostors by default.Draw-path diagnostics
Internal: results of the most recent draw, for tests and renderer diagnostics.
-
inline bool usedGpuInstanceCullingForDiagnostics() const
- Returns:
True if GPU instance culling was used.
-
inline bool usedGpuHizOcclusionForDiagnostics() const
- Returns:
True if Hi-Z occlusion culling was used.
-
inline size_t lastGpuInstanceCullCandidateCountForDiagnostics() const
- Returns:
Instances submitted to GPU culling.
-
inline uint32_t lastGpuInstanceCullSkipCodeForDiagnostics() const
- Returns:
0, or why GPU culling was skipped.
-
const char *lastGpuInstanceCullSkipReasonForDiagnostics() const
- Returns:
-
inline bool reusedVisibleInstanceFrameCacheForDiagnostics() const
- Returns:
True if the visible-instance list was reused from a previous frame.
-
inline bool visibleInstanceFrameCacheFallbackForDiagnostics() const
- Returns:
True if the visible-instance cache could not be used.
-
inline bool usedPersistentInstanceSourceBufferForDiagnostics() const
- Returns:
True if the persistent GPU instance source buffer was used.
-
inline bool persistentInstanceSourceBufferReadyForDiagnostics() const
- Returns:
True once the persistent GPU instance source buffer has been initialized.
-
inline size_t gpuSourceInstanceCapacityForDiagnostics() const
- Returns:
Capacity of the GPU instance source buffer, in instances.
-
inline size_t gpuSourceInstanceFullUploadCountForDiagnostics() const
- Returns:
Full uploads of the GPU instance source buffer.
-
inline size_t gpuSourceInstanceSubUploadCountForDiagnostics() const
- Returns:
Partial uploads of the GPU instance source buffer.
-
inline size_t compactInstanceFullUploadCountForDiagnostics() const
- Returns:
Full uploads of the compact instance buffer.
-
inline size_t compactInstanceSubUploadCountForDiagnostics() const
- Returns:
Partial uploads of the compact instance buffer.
-
inline bool usedMultiDrawIndirectForDiagnostics() const
- Returns:
True if multi-draw-indirect was used.
-
inline size_t lastMultiDrawIndirectCommandCountForDiagnostics() const
- Returns:
Indirect commands issued by the last multi-draw.
-
inline size_t multiDrawIndirectCommandUploadCountForDiagnostics() const
- Returns:
Uploads of the indirect command buffer.
-
inline uint32_t lastMultiDrawIndirectFallbackCodeForDiagnostics() const
- Returns:
0, or why multi-draw-indirect was not used.
-
const char *lastMultiDrawIndirectFallbackReasonForDiagnostics() const
- Returns:
Public Functions
Construct an instanced visual for repeated shapes/meshes.
Automatic mesh LOD is enabled. Primitive meshes are shared through
assets.- Parameters:
type – Shape type to instance.
name – Visual name.
size – Base scale of every instance (for primitives: sphere radius, full box lengths, or cylinder/capsule (radius, radius, height)).
color1 – Primary linear RGBA color in [0, 1] (color weight 0).
color2 – Secondary linear RGBA color in [0, 1] (color weight 1).
assets – Global asset cache for primitive meshes.
meshFile – Mesh file path when type is Mesh.
As above, choosing whether automatic mesh LOD is enabled.
- Parameters:
type – Shape type to instance.
name – Visual name.
size – Base scale of every instance.
color1 – Primary linear RGBA color.
color2 – Secondary linear RGBA color.
assets – Global asset cache for primitive meshes.
meshFile – Mesh file path when type is Mesh.
automaticMeshLodEnabled – Generate and use automatic mesh LODs.
Construct an instanced visual from an already-created mesh list.
- Parameters:
name – Visual name.
size – Base scale of every instance.
color1 – Primary linear RGBA color.
color2 – Secondary linear RGBA color.
meshes – Mesh list (shared, not copied).
As above, choosing whether automatic mesh LOD is enabled.
- Parameters:
name – Visual name.
size – Base scale of every instance.
color1 – Primary linear RGBA color.
color2 – Secondary linear RGBA color.
meshes – Mesh list (shared, not copied).
automaticMeshLodEnabled – Generate and use automatic mesh LODs.
-
std::shared_ptr<InstancedVisuals> cloneWithoutInstances(const std::string &name) const
Share prepared geometry, LODs and appearance with a new empty batch. Instance storage and GPU buffers remain independent. The source must have completed asynchronous preparation; use on its owning GL context. Meshes and materials are shared: edit instance appearance on the batch, and treat the prepared mesh/material objects as immutable while shared.
- Parameters:
name – Name of the new batch; must be non-empty.
- Throws:
std::invalid_argument – if
nameis empty or this is not a ready mesh batch.- Returns:
The new, empty batch.
-
inline size_t count() const
Get number of instances.
- Returns:
Instance count.
-
inline const std::string &getName() const
- Returns:
Batch name.
-
void clearInstances()
Clear all instances.
-
void resize(size_t count)
Resize instance storage.
Every instance (existing ones included) is reset to the origin, identity orientation, baseScale() and color weight 0.
- Parameters:
count – New instance count.
-
void reserveInstances(size_t capacity)
Reserve instance storage without changing the authored instance count.
- Parameters:
capacity – Number of instances to reserve room for.
-
void addInstance(const glm::vec3 &pos, const glm::vec4 &ori, const glm::vec3 &scale, float colorWeight = 0.f)
Add a fully specified instance.
- Parameters:
pos – Position in world coordinates (m).
ori – Orientation quaternion (wxyz): ori.x is w and ori.w is z.
scale – Per-instance scale, multiplied by baseScale().
colorWeight – Blend between color1 (0) and color2 (1).
-
inline void addInstances(std::span<const InstanceSpec> instances)
Add multiple fully specified instances and dirty the batch once.
- Parameters:
instances – Instance data to append.
-
void addInstances(const InstanceSpec *instances, size_t count)
Pointer/count form of addInstances(std::span<const InstanceSpec>).
- Parameters:
instances – Array of
countinstances.count – Number of instances to append.
-
void addInstance(const glm::vec3 &pos, const glm::vec4 &ori, float colorWeight = 0.f)
Add an instance with default scale (baseScale()).
- Parameters:
pos – Position.
ori – Orientation quaternion (wxyz).
colorWeight – Blend between color1 and color2.
-
void addInstance(const glm::vec3 &pos, float colorWeight = 0.f)
Add an instance at position with identity orientation and baseScale().
- Parameters:
pos – Position.
colorWeight – Blend between color1 and color2.
-
inline raisim::Shape::Type shapeType() const
- Returns:
Shape type of the batch.
-
void setPosition(size_t id, const glm::vec3 &pos)
Update position of an instance (ignored for an out-of-range
id).- Parameters:
id – Instance index.
pos – New position.
-
void setOrientation(size_t id, const glm::vec4 &ori)
Update orientation of an instance.
- Parameters:
id – Instance index.
ori – Orientation quaternion (wxyz).
-
void setScale(size_t id, const glm::vec3 &scale)
Update scale of an instance (ignored for an out-of-range
id).Unlike addInstance(),
scaleis stored as the instance’s total scale and is not multiplied by baseScale(); it matches what getScale() returns.- Parameters:
id – Instance index.
scale – New total scale.
-
void setColor(const glm::vec4 &color1, const glm::vec4 &color2)
Update the two base colors used for blending.
- Parameters:
color1 – Primary linear RGBA color in [0, 1].
color2 – Secondary linear RGBA color in [0, 1].
-
inline void setUseMeshColor(bool use)
Use mesh-authored colors for mesh instances instead of instance colors.
- Parameters:
use – True to use mesh colors (Mesh batches only).
-
inline bool usesMeshColor() const
- Returns:
True when mesh-authored colors are requested.
-
void setDefaultPrimitivePbrEnabled(bool enabled)
Toggle High/Ultra default PBR shading for built-in primitive meshes.
Edits the shared primitive mesh material, affecting every user of that primitive.
- Parameters:
enabled – True to allow the PBR pass.
-
void setColorWeight(size_t id, float weight)
Set per-instance blend weight.
- Parameters:
id – Instance index.
weight – Blend weight (0..1).
-
inline void setCategory(VisualCategory category)
Set the render category used by capture/detection filters.
The category is shared by all instances in this batch. It controls whether the instanced visual is included when a rayrai pass excludes non-detectable visualization objects, such as external camera scene-color renders, capture paths that reuse external-camera rendering, or picking/shadow candidate policies that request detectable custom visuals. The normal interactive viewer includes both categories by default.
This is render metadata only; it does not create collision, physics behavior, or per-instance semantic labels. New
InstancedVisualsdefault toVisualCategory::NotDetectable.See also
- Parameters:
category – New render category for the whole instanced batch.
-
inline void setDetectable(bool detectable)
Convenience helper for toggling the instanced visual render category.
- Parameters:
detectable – True to include this batch in detectable-only capture/detection render passes; false to keep it viewer-only for those passes.
-
glm::vec3 getPosition(size_t id) const
Get instance position.
- Parameters:
id – Instance index.
- Returns:
Position vector, or zero for an out-of-range
id.
-
glm::vec4 getOrientation(size_t id) const
Get instance orientation (wxyz).
- Parameters:
id – Instance index.
- Returns:
Quaternion vector, or all zeros for an out-of-range
id.
-
glm::vec3 getScale(size_t id) const
Get instance scale.
- Parameters:
id – Instance index.
- Returns:
Total scale (base scale already applied), or zero for an out-of-range
id.
-
float getColorWeight(size_t id) const
Get per-instance color blend weight.
- Parameters:
id – Instance index.
- Returns:
Weight, or 0 for an out-of-range
id.
-
inline const glm::vec3 &baseScale() const
- Returns:
Base scale (the constructor’s
size) applied by addInstance() and resize().
-
inline const glm::vec4 &getColor1() const
Get primary color.
- Returns:
Primary color.
-
inline const glm::vec4 &getColor2() const
Get secondary color.
- Returns:
Secondary color.
-
inline VisualCategory getCategory() const
Get the render category used by capture/detection filters.
- Returns:
Current category for the whole instanced batch.
-
inline bool isDetectable() const
Check whether detectable-only render passes include this batch.
- Returns:
True when the category is
VisualCategory::Detectable.
-
bool isTransparent() const
Check if any color is translucent.
- Returns:
True if either batch color has alpha < 1 or a mesh material needs the transparent pass.
-
bool hasSpecialBlendMode() const
- Returns:
True when at least one mesh uses a blend mode other than Material::BlendMode::Mix.
-
bool hasPlanarReflectionMeshes() const
- Returns:
True when any PBR mesh uses planar reflection.
-
int renderPriority() const
- Returns:
Highest material render priority across the instanced visual’s meshes.
-
void setCastsShadows(bool castsShadows)
Set whether this instanced visual casts shadows (enabled by default). Foliage materials and grass-patch configuration preserve this setting.
- Parameters:
castsShadows – True to render the batch into shadow maps.
-
bool castsShadows() const
- Returns:
True when this instanced visual should cast shadows.
-
inline bool isValid() const
Check if meshes are valid.
- Returns:
True if valid.
-
inline uint64_t renderRevision() const
Internal:
- Returns:
Counter bumped on render-affecting changes; used to invalidate frame caches.
-
bool approximateBounds(glm::vec3 ¢er, float &radius) const
Bounding sphere for all instances.
Each instance contributes a sphere at its position with radius equal to the length of its scale, so the result is only conservative for source geometry within the unit sphere.
- Parameters:
center – [out] Output center.
radius – [out] Output radius.
- Returns:
True if there are instances to bound.
-
bool shadowGeometryWithinBounds() const
- Returns:
True when shadow depth draws keep every vertex inside approximateBounds(): the source mesh fits the unit sphere, no material uses billboards, fixed-size scaling or height displacement, and neither wind nor the impostor policy applies.
-
bool approximateAabb(glm::vec3 &minCorner, glm::vec3 &maxCorner) const
Axis-aligned box version of approximateBounds() (same per-instance padding).
- Parameters:
minCorner – [out] Minimum corner in world coordinates.
maxCorner – [out] Maximum corner in world coordinates.
- Returns:
True if there are instances to bound.
-
bool sourceMeshLocalAabb(glm::vec3 &minCorner, glm::vec3 &maxCorner) const
Source mesh local-space AABB before per-instance transform.
- Parameters:
minCorner – [out] Minimum corner in mesh coordinates.
maxCorner – [out] Maximum corner in mesh coordinates.
- Returns:
False when there is no mesh or no usable vertex data.
-
inline void setMaxRenderedInstances(size_t maxInstances)
Cap drawn instances for simple single-threaded LOD. 0 means draw all.
- Parameters:
maxInstances – Only the first
maxInstancesinstances are drawn.
-
inline size_t maxRenderedInstances() const
- Returns:
Instance cap (0 = unlimited).
-
void setRenderedInstanceStride(size_t stride)
Set a stride for simple per-camera-independent LOD. 1 draws every instance.
- Parameters:
stride – Draw every
stride-thinstance; 0 is treated as 1.
-
inline size_t renderedInstanceStride() const
- Returns:
User-requested instance stride (>= 1).
-
inline void setFoliageDistanceFade(float start, float end, bool fadeIn)
Fade this batch across a camera-distance band. The complementary in/out modes let two representations overlap without a hard cell LOD switch. Zero (the default) disables distance fading.
-
inline void clearFoliageDistanceFade()
Disable the distance fade set by setFoliageDistanceFade().
-
void setProjectedLodPolicy(bool enabled, float minProjectedRadiusPixels = 2.0f, size_t maxStride = 8)
Enable camera-projected LOD for instanced visuals.
When enabled, the renderer increases the effective draw stride for far-away instances whose approximate per-instance radius projects below minProjectedRadiusPixels. The explicit rendered stride remains a lower bound, so user-requested LOD is preserved. Requires a camera-aware draw() overload (a positive viewport height).
- Parameters:
enabled – Enable the policy.
minProjectedRadiusPixels – Target projected instance radius in pixels (min 0.25).
maxStride – Largest stride the policy may choose (min 1).
-
inline bool projectedLodEnabled() const
- Returns:
True when projected LOD is enabled.
-
inline float projectedLodMinRadiusPixels() const
- Returns:
Projected-LOD target radius in pixels.
-
inline size_t projectedLodMaxStride() const
- Returns:
Projected-LOD maximum stride.
-
void setAutomaticMeshLodEnabled(bool enabled)
Enable automatic mesh LOD generation/selection for instanced mesh visuals.
- Parameters:
enabled – True to build (or fetch cached) LODs; false drops them.
-
void setFoliageMeshLodPixelError(float pixelError)
Set the projected geometric-error budget for authored foliage LODs. Smaller values keep finer meshes until they are farther from the camera. Zero restores the renderer default.
- Parameters:
pixelError – Error budget in pixels, in [0, 8].
- Throws:
std::invalid_argument – outside [0, 8] or for non-finite values.
-
inline float foliageMeshLodPixelError() const
- Returns:
Foliage LOD pixel-error budget (0 = renderer default).
-
bool pollAsyncMeshPreparation()
Finish worker-prepared LODs incrementally on the render thread. Starts the worker on the first call and uploads one prepared submesh per later call; draws also call it. Requires the batch’s GL context.
- Returns:
True on the call that installs the finished LODs.
-
bool pollAsyncMeshPreparation(std::chrono::steady_clock::time_point deadline)
Like pollAsyncMeshPreparation(), but uploads prepared submeshes until
deadlinepasses (at least one per call).- Parameters:
deadline – Time after which no further upload starts.
- Returns:
True on the call that installs the finished LODs.
-
bool hasPendingAsyncMeshPreparation() const
- Returns:
True while automatic LODs are still being prepared (the batch is not drawn).
-
inline bool automaticMeshLodEnabled() const
- Returns:
True when automatic mesh LOD is enabled for instanced mesh visuals.
-
size_t automaticMeshLodLevelCount() const
- Returns:
Number of available instanced mesh LOD levels including the source mesh.
-
size_t individualFoliageInstanceUploadCount() const
Internal (diagnostics):
- Returns:
Instance uploads made by the per-instance foliage LOD path.
-
size_t individualFoliageLodSelectionCount() const
Internal (diagnostics):
- Returns:
Number of submesh/pass visibility and LOD classifications (cache misses).
-
inline size_t sourceMeshCountForDiagnostics() const
- Returns:
Source mesh count for renderer regressions and diagnostics.
-
inline const std::string &sourceMeshCacheKey() const
- Returns:
Canonical source mesh cache key, empty for built-in primitive batches.
-
inline bool instanceAttributesBoundForDiagnostics() const
- Returns:
Whether per-instance vertex attributes are bound to the current mesh VAOs (diagnostics).
Install six authored LOD levels; source geometry remains level zero. Mesh lists may have different material/part counts. Every mesh must carry a finite nonnegative generatedLodRelativeError for projected selection. Authored levels use opaque/masked single-pass ordinary materials. Call on the GL render thread after loading; keep external textures alive. Replacement is atomic on validation failure. Disabling automatic LODs clears this chain; reinstall it to re-enable these authored levels.
- Parameters:
levels – Exactly six mesh lists (LOD 1..6).
- Throws:
std::invalid_argument – if the batch is not a ready mesh batch or a level is invalid.
-
inline const std::vector<std::shared_ptr<OpenGLMesh>> &preparedMeshLod(size_t level) const
Ready geometry for building static proxies. Shared meshes are immutable; the prototype and its GL context must outlive their use by the caller.
- Parameters:
level – LOD level; 0 or an unavailable level returns the source meshes.
- Returns:
Mesh list of that level.
-
size_t automaticMeshLodTriangleCount(size_t level) const
- Parameters:
level – LOD level; 0 is the source mesh.
- Returns:
Triangle count for one instanced mesh LOD level, or 0 for an invalid level.
-
float automaticMeshLodMaxUvClusterSpan(size_t level) const
- Parameters:
level – Generated LOD level (>= 1).
- Returns:
Largest UV span collapsed into one generated LOD vertex (diagnostics).
-
size_t selectAutomaticMeshLodLevel(const glm::vec3 &viewPos, float verticalFovDeg, int viewportHeight) const
Select the instanced mesh LOD level that would be used for a camera.
-
void configureGrassPatch(float patchWidth, float patchDepth, float densityPerSquareMeter, size_t drawBudget, float maxDrawDistance, float lodFadeStartDistance, float lodFadeEndDistance, uint32_t seed, float bladeRootHeight = 0.0f, float bladeTipHeight = 1.0f, float windStrength = 1.0f, float stiffness = 0.35f, float flutterWeight = 0.15f)
Mark this instanced visual as a grass patch and configure bounded draw/wind metadata.
Instances are still authored through addInstance()/resize() so callers keep full control over density masks and scatter placement. This method wires the batch into the generic foliage wind shader path, projected LOD, and render diagnostics.
Also caps drawn instances at
drawBudgetand enables projected LOD, shadow foliage LOD and hierarchical cluster culling with fixed defaults. Width, depth, density and seed are recorded for diagnostics only.- Parameters:
patchWidth – Patch width (m).
patchDepth – Patch depth (m).
densityPerSquareMeter – Blade density.
drawBudget – Maximum drawn instances (0 = unlimited).
maxDrawDistance – View depth at which blades have faded out (m); 0 = no limit.
lodFadeStartDistance – View depth where blades start fading (m).
lodFadeEndDistance – View depth where that fade ends (m).
seed – Scatter seed (metadata).
bladeRootHeight – Local height below which blades do not bend.
bladeTipHeight – Local height of full bend.
windStrength – Wind bend strength (>= 0).
stiffness – Bend stiffness, clamped to [0, 1].
flutterWeight – High-frequency flutter weight (>= 0).
-
void configureFoliageWind(float rootHeight, float tipHeight, float windStrength, float stiffness = 0.5f, float flutterWeight = 0.15f)
Configure generic wind bending for instanced foliage without grass-patch LOD.
Also enables impostors, shadow foliage LOD and hierarchical cluster culling.
- Parameters:
rootHeight – Local height below which geometry does not bend.
tipHeight – Local height of full bend.
windStrength – Wind bend strength (>= 0).
stiffness – Bend stiffness, clamped to [0, 1].
flutterWeight – High-frequency flutter weight (>= 0).
-
void setShadowFoliageLodPolicy(bool enabled, float minProjectedRadiusPixels = 2.5f, size_t maxStride = 16, float maxShadowDistance = 0.0f)
Configure a shadow-only foliage instance LOD policy.
This does not change the visible color pass. It only raises the instance stride used while rendering foliage into shadow maps.
- Parameters:
enabled – Enable the policy.
minProjectedRadiusPixels – Target projected instance radius in pixels (min 0.25).
maxStride – Largest shadow stride (min 1).
maxShadowDistance – Skip the batch in shadow passes when its nearest point is farther from the camera than this (m); 0 = no limit.
-
inline bool shadowFoliageLodPolicyEnabled() const
- Returns:
True when the shadow foliage LOD policy is enabled.
-
void setFoliageImpostorPolicy(bool enabled, float maxProjectedRadiusPixels = 1.15f, size_t minInstanceCount = 1024)
Configure distant foliage impostor rendering for instanced mesh foliage.
The visible color pass switches to a generated camera-facing quad only when the source mesh projects below maxProjectedRadiusPixels. This keeps close/mid-range authored foliage unchanged while preserving the authored instance count.
- Parameters:
enabled – Enable the policy.
maxProjectedRadiusPixels – Switch to impostors below this projected radius (min 0.05).
minInstanceCount – Only batches with at least this many instances qualify (min 1).
-
inline bool foliageImpostorPolicyEnabled() const
- Returns:
True when the foliage impostor policy is enabled.
-
void setHierarchicalFoliageClustersPolicy(bool enabled, size_t leafTargetInstances = 32, size_t minInstanceCount = 256, float minRejectionRatio = 0.08f)
Configure conservative BVH/quadtree-style foliage cluster culling.
Cluster culling only removes instances whose cluster bounds are outside the current view/shadow frustum. It does not reduce authored instance count or change material/mesh quality.
- Parameters:
enabled – Enable the policy.
leafTargetInstances – Target instances per leaf, clamped to [8, 1024].
minInstanceCount – Only batches with at least this many instances qualify (min 1).
minRejectionRatio – Minimum culled fraction for the cluster path to be used, clamped to [0, 0.95].
-
inline bool hierarchicalFoliageClustersEnabled() const
- Returns:
True when hierarchical cluster culling is enabled.
-
bool hasFoliageShadowLodMaterialForDiagnostics() const
Internal:
- Returns:
True when the batch is treated as foliage for shadow LOD (wind/grass configured or foliage-like materials).
-
bool supportsBasicFoliageShadowTransform() const
- Returns:
True when every possible shadow mesh uses ordinary instance transforms.
-
bool supportsFoliageColorBatch() const
Internal:
- Returns:
True when the batch can join the renderer’s batched foliage color draw.
-
bool hasDepthWritingMaterial() const
- Returns:
Whether a draw can override a surrounding pass’s disabled depth writes.
-
bool usesDefaultDepthAndStencilState() const
- Returns:
True when every mesh material uses default depth/stencil state.
-
bool hasAlphaMaskedFoliageMaterialForDiagnostics() const
Internal (diagnostics):
- Returns:
True when any mesh (source, LOD or impostor) uses an alpha-masked material.
-
inline const GrassPatchDiagnostics &grassPatchDiagnostics() const
Internal (diagnostics):
- Returns:
Grass-patch settings.
-
inline const FoliageWindDiagnostics &foliageWindDiagnostics() const
Internal (diagnostics):
- Returns:
Foliage wind settings.
-
inline const ShadowFoliageLodDiagnostics &shadowFoliageLodDiagnostics() const
Internal (diagnostics):
- Returns:
Last shadow foliage LOD decision.
-
const char *lastShadowFoliageLodFallbackReasonForDiagnostics() const
Internal (diagnostics):
- Returns:
-
inline const FoliageImpostorDiagnostics &foliageImpostorDiagnostics() const
Internal (diagnostics):
- Returns:
Last foliage impostor decision.
-
const char *lastFoliageImpostorFallbackReasonForDiagnostics() const
Internal (diagnostics):
- Returns:
Text for FoliageImpostorDiagnostics::fallbackCode.
-
inline const HierarchicalFoliageClusterDiagnostics &hierarchicalFoliageClusterDiagnostics() const
Internal (diagnostics):
- Returns:
Last cluster culling result.
-
const char *lastHierarchicalFoliageClusterFallbackReasonForDiagnostics() const
Internal (diagnostics):
- Returns:
Text for HierarchicalFoliageClusterDiagnostics::fallbackCode.
-
void requestAsyncFoliageClusterPreparation()
Start building the foliage cluster tree on a worker thread when the batch qualifies and the tree is out of date; no-op otherwise.
-
bool pollAsyncFoliageClusterPreparation()
Non-blocking check for a finished worker build.
- Returns:
True when a result was installed by this call.
-
inline const AsyncFoliageClusterPrepDiagnostics &asyncFoliageClusterPrepDiagnostics() const
Internal (diagnostics):
- Returns:
Asynchronous cluster preparation state.
-
void setDoubleBufferedInstanceUploads(bool enabled)
Enable double-buffering for full instance-buffer uploads.
Dirty-range updates remain on the single-buffer subdata path. Double-buffering helps when full rebuilds are frequent, for example after sorting or projected LOD stride changes.
- Parameters:
enabled – True to alternate between two instance buffers.
-
inline void setSortTransparentInstances(bool enabled)
Enable optional back-to-front CPU sorting for transparent instances.
This is disabled by default to keep RL visual workloads on the fast path.
- Parameters:
enabled – True to let the renderer call sortInstancesBackToFront() for this batch.
-
inline bool sortsTransparentInstances() const
- Returns:
True when transparent instance sorting is enabled.
-
void sortInstancesBackToFront(const glm::vec3 &viewPos)
Reorder the instances farthest-first by distance from
viewPos(stable). No-op unless setSortTransparentInstances(true), or when the instances are already in that order. Instance indices change.- Parameters:
viewPos – Camera position in world coordinates.
-
size_t applyTextureFilteringQuality(float anisotropy, float mipLodBias) const
Apply sampler quality to all 2D material textures in the instanced mesh.
Modifies the shared GL texture objects.
- Parameters:
anisotropy – Requested anisotropic filtering level.
mipLodBias – Mip LOD bias.
- Returns:
Number of texture ids updated (summed per mesh).
-
void collectMaterialTextureIds(std::vector<unsigned int> &textureIds) const
Append non-environment material texture ids used by this instanced visual.
- Parameters:
textureIds – [inout] Ids are appended (duplicates are kept).
-
void accumulateGeometryDiagnostics(OpenGLMesh::GeometryDiagnostics &diagnostics, float tinyTriangleAreaThreshold) const
Accumulate CPU-side mesh geometry diagnostics for this instanced visual.
- Parameters:
diagnostics – [inout] Totals to add to.
tinyTriangleAreaThreshold – Triangles with smaller (non-zero) area count as tiny.
-
void collectMeshDiagnostics(std::vector<OpenGLMesh::MeshDiagnostics> &diagnostics, float tinyTriangleAreaThreshold) const
Append per-mesh geometry/material diagnostics for this instanced visual.
- Parameters:
diagnostics – [inout] One entry is appended per source mesh.
tinyTriangleAreaThreshold – Triangles with smaller (non-zero) area count as tiny.
-
void draw(Shader &shader)
Draw all instances using instanced rendering.
No camera information, so projected LOD, mesh LOD selection and frustum culling are not applied. Sets the batch uniforms (
shadingType,color1,color2, wind parameters) and uploads dirty instance data; the shader must already be in use and a GL context current. Draws nothing while automatic LODs are still being prepared.- Parameters:
shader – Shader to use for drawing.
-
void draw(Shader &shader, const glm::vec3 &viewPos, float verticalFovDeg, int viewportHeight)
Draw all instances using camera-aware projected LOD.
-
void draw(Shader &shader, Shader *cullingShader, const glm::mat4 &viewProjection, const glm::vec3 &viewPos, float verticalFovDeg, int viewportHeight)
Draw all instances with optional GPU culling and indirect draws.
- Parameters:
shader – Material shader used for the final draw.
cullingShader – Optional compute shader. Null falls back to the CPU path.
viewProjection – Current projection * view matrix for frustum culling.
viewPos – Camera position in world coordinates.
verticalFovDeg – Camera vertical field of view in degrees.
viewportHeight – Viewport height in pixels.
-
void draw(Shader &shader, Shader *cullingShader, const GpuHizOcclusionConfig *gpuHizOcclusion, const glm::mat4 &viewProjection, const glm::vec3 &viewPos, float verticalFovDeg, int viewportHeight)
As above, with optional hierarchical-Z occlusion culling.
- Parameters:
shader – Material shader used for the final draw.
cullingShader – Optional instance-culling compute shader.
gpuHizOcclusion – Optional Hi-Z input; null disables occlusion culling.
viewProjection – Current projection * view matrix.
viewPos – Camera position in world coordinates.
verticalFovDeg – Camera vertical field of view in degrees.
viewportHeight – Viewport height in pixels.
-
void drawShadow(Shader &shader, Shader *cullingShader, const glm::mat4 &lightViewProjection, const glm::vec3 &viewPos, float verticalFovDeg, int viewportHeight)
Draw this instanced visual for a shadow map with shadow-only foliage LOD/culling.
- Parameters:
shader – Shadow depth shader that is already in use.
cullingShader – Optional instance-culling compute shader.
lightViewProjection – Light-space view-projection matrix.
viewPos – Main camera position (drives LOD distances).
verticalFovDeg – Main camera vertical field of view in degrees.
viewportHeight – Main viewport height in pixels.
-
void drawLinearDepth(Shader &shader, Shader *cullingShader, const glm::mat4 &viewProjection, const glm::vec3 &viewPos, float verticalFovDeg, int viewportHeight)
Draw this instanced visual into a linear-depth target.
Culls instances and selects mesh LODs for the camera as draw() does, except for foliage, which keeps its source meshes: simplified foliage drops leaf pieces, and a foliage impostor’s card holds the plant only in its color texture.
- Parameters:
shader – Linear-depth shader that is already in use.
cullingShader – Optional instance-culling compute shader.
viewProjection – Camera projection * view matrix.
viewPos – Camera position in world coordinates.
verticalFovDeg – Camera vertical field of view in degrees.
viewportHeight – Depth target height in pixels.
-
inline uint64_t instanceDataGeneration() const
Internal:
- Returns:
Counter bumped whenever instance data changes (cache key).
-
bool occlusionCandidatesPossible() const
Internal: whether addOcclusionCandidates() can add this batch: its draws take the bounds-culled path with enough geometry, before any frustum test.
-
void addOcclusionCandidates(rayrai_internal::InstancedOcclusion &occlusion)
Internal: adds the instances a colour or transparent draw for
occlusion'scamera would draw to its GPU depth-tile test, when this batch draws them through the bounds-culled path.
-
struct InstanceSpec
One instance for addInstances().
Public Members
-
glm::vec3 position
World position (m).
-
glm::vec4 orientation
wxyz: x holds w, w holds z
-
glm::vec3 scale
Multiplied by baseScale().
-
float colorWeight
0 = color1, 1 = color2 (clamped to [0, 1] by the shader).
-
glm::vec3 position
-
struct GrassPatchDiagnostics
Internal (diagnostics): grass-patch settings from configureGrassPatch().
Public Members
-
bool enabled
configureGrassPatch() was called.
-
size_t authoredInstanceCount
Instances in the batch.
-
size_t drawBudget
Instance cap (setMaxRenderedInstances()).
-
size_t drawStride
Active instance stride.
-
float patchWidth
Recorded patch width (m); metadata only.
-
float patchDepth
Recorded patch depth (m); metadata only.
-
float densityPerSquareMeter
Recorded blade density; metadata only.
-
float maxDrawDistance
View depth at which blades have faded out (m); 0 = no limit.
-
float lodFadeStartDistance
View depth where the blade fade-out starts (m).
-
float lodFadeEndDistance
View depth where the blade fade-out ends (m).
-
float bladeRootHeight
Local height below which blades do not bend.
-
float bladeTipHeight
Local height of full bend.
-
float windStrength
Wind bend strength.
-
float stiffness
Bend stiffness in [0, 1].
-
float flutterWeight
High-frequency flutter weight.
-
uint32_t seed
Recorded seed; metadata only.
-
bool enabled
-
struct FoliageWindDiagnostics
Internal (diagnostics): settings from configureFoliageWind().
Public Members
-
bool enabled
configureFoliageWind() was called.
-
float rootHeight
Local height below which geometry does not bend.
-
float tipHeight
Local height of full bend.
-
float windStrength
Wind bend strength.
-
float stiffness
Bend stiffness in [0, 1].
-
float flutterWeight
High-frequency flutter weight.
-
bool enabled
-
struct ShadowFoliageLodDiagnostics
Internal (diagnostics): last shadow-pass foliage LOD decision.
Public Members
-
bool enabled
The policy is enabled.
-
bool applicable
The batch qualified for the path in the last pass.
-
bool used
The path was used in the last pass.
-
size_t authoredInstanceCount
Instances in the batch.
-
size_t renderedInstanceCount
Instances after the setMaxRenderedInstances() cap.
-
size_t candidateInstanceCount
Instances left after the active stride.
-
size_t drawStride
Active instance stride.
-
uint32_t fallbackCode
0, or why the path was skipped (text via the matching last…ReasonForDiagnostics()).
-
bool enabled
-
struct FoliageImpostorDiagnostics
Internal (diagnostics): last foliage-impostor decision.
Public Members
-
bool enabled
The policy is enabled.
-
bool applicable
The batch qualified for the path in the last pass.
-
bool used
The path was used in the last pass.
-
size_t authoredInstanceCount
Instances in the batch.
-
size_t renderedInstanceCount
Instances after the setMaxRenderedInstances() cap; per-instance foliage draws report the instances they submit, before any occlusion test done on the GPU.
-
size_t candidateInstanceCount
Instances left after the active stride.
-
size_t sourceTrianglesPerInstance
Triangles per instance of the source mesh.
-
size_t impostorTrianglesPerInstance
Triangles per instance of the impostor.
-
float nearestDistance
Distance from the camera to the batch bounds (m).
-
float projectedRadiusPixels
Projected source-mesh radius in pixels.
-
uint32_t fallbackCode
0, or why the path was skipped (text via the matching last…ReasonForDiagnostics()).
-
bool enabled
-
struct HierarchicalFoliageClusterDiagnostics
Internal (diagnostics): last hierarchical foliage-cluster culling result.
Public Members
-
bool enabled
The policy is enabled.
-
bool applicable
The batch qualified for the path in the last pass.
-
bool used
The path was used in the last pass.
-
size_t authoredInstanceCount
Instances in the batch.
-
size_t renderedInstanceCount
Instances after the setMaxRenderedInstances() cap.
-
size_t candidateInstanceCount
Instances left after the active stride.
-
size_t visibleInstanceCount
Instances in visible clusters.
-
size_t nodeCount
Cluster tree nodes.
-
size_t leafCount
Cluster tree leaves.
-
size_t visitedNodeCount
Cluster nodes visited.
-
size_t visibleLeafCount
Visible cluster leaves.
-
uint32_t fallbackCode
0, or why the path was skipped (text via the matching last…ReasonForDiagnostics()).
-
bool enabled
-
struct AsyncFoliageClusterPrepDiagnostics
Internal (diagnostics): state of asynchronous foliage-cluster preparation.
Public Members
-
bool enabled
requestAsyncFoliageClusterPreparation() was called.
-
bool applicable
The batch qualified for asynchronous cluster building.
-
bool scheduled
A worker build was started.
-
bool active
A worker build is running.
-
bool ready
A worker result was collected.
-
bool committed
The worker result was installed.
-
bool synchronousFallback
Clusters were built synchronously instead.
-
size_t authoredInstanceCount
Instances in the batch.
-
size_t nodeCount
Cluster tree nodes.
-
size_t leafCount
Cluster tree leaves.
-
uint32_t fallbackCode
0, or why the asynchronous result was not used.
-
bool enabled
-
struct GpuHizOcclusionConfig
Internal: hierarchical-Z occlusion input for the GPU culling draw() overload.
Public Members
-
bool enabled
Use Hi-Z occlusion culling.
-
unsigned int depthPyramidTexture
GL 2D texture holding the depth pyramid (not owned).
-
int width
Width of pyramid level 0 in pixels.
-
int height
Height of pyramid level 0 in pixels.
-
int mipLevels
Number of pyramid levels.
-
float depthEpsilon
Depth tolerance for the occlusion test.
-
bool enabled
-
inline bool usedGpuInstanceCullingForDiagnostics() const
-
class OpenGLMesh : public std::enable_shared_from_this<OpenGLMesh>
Simple OpenGL mesh with indexed geometry and optional textures.
Keeps a CPU copy of the geometry plus a context-local VAO and (possibly shared) VBO/EBO. Constructors and every update/draw method require a current OpenGL context, except createCpuGeometry() and prepareGeometryAttributes(). Texture ids referenced by textures and material are not owned. Meshes are usually held by
std::shared_ptrand may be shared between objects (see RayraiGlobalAsset), so material edits on a shared mesh affect every user. Non-copyable and non-movable.Public Types
-
enum class RenderMode
Material filter applied by draw(); used to split a scene into shader passes.
Values:
-
enumerator All
Draw regardless of shading type, using the simple-shader uniform path.
-
enumerator SimpleOnly
Draw only meshes that do not use PBR shading.
-
enumerator PbrOnly
Draw only PBR meshes (all passes).
-
enumerator PbrNonTransmissiveOnly
PBR passes whose material is not transmissive.
-
enumerator PbrTransmissiveOnly
PBR passes whose material is transmissive (glass path).
-
enumerator All
-
enum class PrimitiveTopology
GL primitive used to interpret the index buffer.
Values:
-
enumerator Triangles
GL_TRIANGLES.
-
enumerator Lines
GL_LINES (width from setLineWidth()).
-
enumerator Points
GL_POINTS (size from setPointSize()).
-
enumerator Triangles
Public Functions
-
bool drawsInMode(RenderMode mode, const raisin::Material *materialOverride) const
Whether draw() with the same arguments would rasterize anything. It mirrors the mode and transmission filters draw() applies, including the nextPass chain, so a caller can skip a program bind and a whole submission instead of paying for a draw that returns immediately.
-
OpenGLMesh(const std::vector<Vertex> &vertices, const std::vector<unsigned int> &indices, const std::vector<Texture> &textures = {}, const glm::vec4 &baseColor = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), PrimitiveTopology primitiveTopology = PrimitiveTopology::Triangles)
Construct a mesh and upload it to the GPU.
Missing tangents are generated and an empty TexCoords2 set is filled from TexCoords. The material type is TEXTURED when
texturesis non-empty, else SIMPLE_COLOR. GPU indices stay 32-bit (see createWithCompactIndices()).- Parameters:
vertices – Vertex array.
indices – Index array.
textures – Optional texture list.
baseColor – Base color used when textures are absent.
primitiveTopology – How indices are assembled into primitives.
-
OpenGLMesh(std::vector<Vertex> &&vertices, std::vector<unsigned int> &&indices, const std::vector<Texture> &textures = {}, const glm::vec4 &baseColor = glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), PrimitiveTopology primitiveTopology = PrimitiveTopology::Triangles)
Construct a mesh by taking ownership of prepared CPU geometry.
Same as the copying constructor but moves
verticesandindices.- Parameters:
vertices – Vertex array (moved from).
indices – Index array (moved from).
textures – Optional texture list.
baseColor – Base color used when textures are absent.
primitiveTopology – How indices are assembled into primitives.
Freeze metadata before publishing to the asset cache. The template owns no VAO and remains immutable while worker-local materials are edited. Internal.
- Returns:
The cached snapshot, or nullptr for meshes that reference any texture or a material next-pass (those are never shared across contexts).
-
bool gpuGeometryVisibleInCurrentContext() const
- Returns:
True when this mesh’s VBO/EBO are visible in the current GL context.
-
size_t gpuGeometryBytes() const
- Returns:
Requested VBO + EBO allocation size for this mesh, in bytes.
-
void prepareGeometryAttributes()
Compute missing tangents and UV statistics without a GL context.
-
PreparedAttributes preparedAttributes() const
- Returns:
The attributes the last prepareGeometryAttributes() derived.
-
void restorePreparedGeometry(std::vector<Vertex> &&vertices, std::vector<unsigned int> &&indices, const PreparedAttributes &attributes)
Replace the CPU geometry with an already prepared copy, as prepareGeometryAttributes() would have left it. Internal: no GL calls; for caches of prepared meshes.
- Parameters:
vertices – Prepared vertex array.
indices – Triangle index array.
attributes – The attributes prepared with them.
-
void precomputeVertexSummaries() const
Compute what the first draws would otherwise scan vertices for: the local bounds and whether every vertex has the same color. Internal: no GL calls; workers call it before the render thread uses the mesh.
-
VertexSummaries vertexSummaries() const
- Returns:
The summaries of the current vertices and indices.
-
void adoptVertexSummaries(const VertexSummaries &summaries) const
Adopt summaries a cache stored for exactly these vertices and indices.
-
uint64_t contentDigest() const
Hash of vertices and indices; for summaries adopted from a cache of prepared geometry (until a method of this class changes the geometry), the digest stored with them. Internal: keys caches derived from the geometry.
-
void uploadPreparedGeometry(bool compactIndices = true)
Upload an already-prepared CPU mesh on the context-owning thread. No-op if the mesh already has a VAO or borrows another mesh’s buffers.
- Parameters:
compactIndices – Allow 16-bit GPU indices when lossless.
-
void uploadPreparedGeometry(bool compactIndices, const StagedGeometry &staged)
uploadPreparedGeometry() that copies the geometry on the GPU, from a staging buffer.
-
bool uploadsCompactIndices(bool compactIndices) const
- Returns:
Whether an upload allowed
compactIndicesstores 16-bit indices (triangles whose indices all fit).
-
void draw(const Shader &shader) const
Draw the mesh using the provided shader.
Same as
draw(shader, RenderMode::All). The shader is not bound here and must already be in use; the model matrix andobjectColorare the caller’s responsibility. Material depth/stencil/blend/cull state is applied around the draw call.- Parameters:
shader – Shader with expected texture uniforms.
-
void draw(const Shader &shader, RenderMode mode, const raisin::Material *materialOverride = nullptr) const
Draw the mesh if it matches the requested material render mode.
Non-PBR modes set the simple-shader material uniforms and bind the diffuse, specular and normal maps to units 0, 1 and 2 (white fallback when absent). PBR modes apply the full material (Material::applyTo()) and also draw its next-pass chain. The shader must already be in use.
- Parameters:
shader – Shader with expected material uniforms.
mode – Material filter for multi-pass rendering.
materialOverride – Optional material to use instead of the mesh material (the mesh’s textures are then ignored).
-
void drawInstanced(const Shader &shader, int instanceCount) const
Draw the mesh with instancing using the mesh’s own VAO.
Per-instance attributes must already be configured; usually prefer drawInstancedWithVao() with a VAO from instancedVaoForBuffer().
- Parameters:
shader – Shader with expected texture uniforms.
instanceCount – Number of instances to draw; <= 0 draws nothing.
-
void drawInstancedWithVao(const Shader &shader, int instanceCount, unsigned int vao) const
Draw the mesh with instancing using an explicit VAO variant.
- Parameters:
shader – Shader with expected texture uniforms.
instanceCount – Number of instances to draw.
vao – VAO from instancedVaoForBuffer(), or 0 for the mesh’s own VAO.
-
void drawInstancedIndirect(const Shader &shader, unsigned int indirectBuffer) const
Draw the mesh with an OpenGL DrawElementsIndirect command buffer.
- Parameters:
shader – Shader with expected texture uniforms.
indirectBuffer – Buffer containing a DrawElementsIndirectCommand.
-
void drawInstancedIndirectWithVao(const Shader &shader, unsigned int indirectBuffer, unsigned int vao, size_t commandOffsetBytes = 0) const
Draw an indirect instanced command using an explicit VAO variant.
- Parameters:
shader – Shader with expected texture uniforms.
indirectBuffer – Buffer containing a DrawElementsIndirectCommand; 0 draws nothing.
vao – VAO from instancedVaoForBuffer(), or 0 for the mesh’s own VAO.
commandOffsetBytes – Byte offset of the command in
indirectBuffer.
-
void drawInstancedMultiIndirect(const Shader &shader, unsigned int indirectBuffer, int commandCount, int commandStrideBytes) const
Draw several compatible DrawElementsIndirect commands against this mesh’s VAO.
- Parameters:
shader – Shader with expected texture uniforms.
indirectBuffer – Buffer containing tightly packed indirect commands.
commandCount – Number of commands in
indirectBuffer.commandStrideBytes – Stride between commands, or zero for tightly packed commands.
-
void drawInstancedMultiIndirectWithVao(const Shader &shader, unsigned int indirectBuffer, int commandCount, int commandStrideBytes, unsigned int vao) const
Draw several indirect commands using an explicit VAO variant.
- Parameters:
shader – Shader with expected texture uniforms.
indirectBuffer – Buffer containing the indirect commands.
commandCount – Number of commands; <= 0 draws nothing.
commandStrideBytes – Stride between commands, or zero for tightly packed commands.
vao – VAO from instancedVaoForBuffer(), or 0 for the mesh’s own VAO.
-
unsigned int instancedVaoForBuffer(unsigned int instanceBuffer) const
Return a VAO whose base mesh attributes plus instance attributes use
instanceBuffer.The instance buffer holds one 80-byte record per instance: a column-major
mat4model matrix (attributes 3-6) followed by avec4color (attribute 7). VAOs are created on first use and cached per buffer; call releaseInstancedVaoForBuffer() before deleting the buffer.- Parameters:
instanceBuffer – GL array buffer with instance records; 0 returns 0.
- Returns:
VAO id owned by this mesh, or 0 on failure.
-
unsigned int instancedVaoForBuffer(unsigned int instanceBuffer, bool compactFoliage) const
Internal: as above, optionally with the compact foliage vertex layout.
- Parameters:
instanceBuffer – GL array buffer with instance records.
compactFoliage – Use the packed foliage vertex stream when available.
- Returns:
VAO id owned by this mesh, or 0 on failure.
-
void releaseInstancedVaoForBuffer(unsigned int instanceBuffer) const
Drop cached VAO variants that reference
instanceBuffer.- Parameters:
instanceBuffer – Instance buffer about to be deleted or replaced.
-
inline void drawWithBoundShader(const Shader &shader) const
Same as draw(), but assumes the caller has already bound
shader. Currently equivalent to draw() (kept as an API hook for callers that used to pay a redundant shader bind cost; preserved for callers that opt in via OpenGLMesh::drawWithBoundShader).- Parameters:
shader – Shader that is already in use.
-
inline void drawInstancedWithBoundShader(const Shader &shader, int instanceCount) const
Equivalent to drawInstanced(); kept for API parity with drawWithBoundShader().
- Parameters:
shader – Shader that is already in use.
instanceCount – Number of instances to draw.
-
inline size_t drawIndexCount() const
- Returns:
Number of indices issued per draw (the view range for range views).
-
size_t indexElementBytes() const
GPU element width (2 or 4 bytes); CPU indices remain unsigned int. Raw VAO users must choose GL_UNSIGNED_SHORT or GL_UNSIGNED_INT accordingly.
- Returns:
2 or 4.
-
inline size_t drawFirstIndex() const
- Returns:
First index of the draw range in the GPU index buffer (non-zero for range views).
-
inline int drawBaseVertex() const
- Returns:
Base vertex added to each index when drawing (non-zero for range views).
-
inline void setPrimitiveTopology(PrimitiveTopology topology)
Set the OpenGL primitive topology used by this mesh.
- Parameters:
topology – New topology; the index buffer is reinterpreted, not rebuilt.
-
inline PrimitiveTopology primitiveTopology() const
- Returns:
The OpenGL primitive topology used by this mesh.
-
inline void setLineWidth(float width)
Set GL line width for PrimitiveTopology::Lines meshes.
- Parameters:
width – Width in pixels, clamped to the driver’s supported range when drawing.
-
inline void setPointSize(float size)
Set GL point size for PrimitiveTopology::Points meshes.
- Parameters:
size – Point size in pixels.
-
bool usesPbrShading() const
- Returns:
True when this mesh should be rendered by the PBR shader (Material::usesPbrShading(), cached until invalidateMaterialCache()).
-
uint64_t materialSortKey(RenderMode mode = RenderMode::All, const raisin::Material *materialOverride = nullptr) const
Compact key for ordering opaque draws by material/texture state.
- Parameters:
mode – Render mode the draws will use.
materialOverride – Material to key on instead of material, or nullptr.
- Returns:
Hash-like key mixing the PBR flag, texture ids and state flags; sort only, not unique.
-
void updateMesh(const std::vector<Vertex> &vertices, const std::vector<unsigned int> &indices)
Update mesh data on the GPU.
Recomputes tangents. A mesh sharing buffers with others is first given its own private buffers, so other users are unaffected.
- Parameters:
vertices – New vertex data.
indices – New index data; an empty vector keeps the current indices.
-
void updateIndices(const std::vector<unsigned int> &indices)
Replace the triangle index buffer, including clearing it with an empty vector.
- Parameters:
indices – New indices into the current vertex buffer.
-
bool localBoundingSphere(glm::vec3 ¢er, float &radius) const
Conservative local sphere, cached until geometry is uploaded again. Returns false when GPU-only uploads have detached the CPU geometry.
- Parameters:
center – [out] AABB center in object space.
radius – [out] Half-diagonal of the AABB.
- Returns:
False if there are no vertices, a position is non-finite, or the GPU data no longer matches vertices.
-
bool localBoundingBox(glm::vec3 ¢er, glm::vec3 &halfExtents) const
Object-space axis-aligned bounds, same caching and failure cases as localBoundingSphere().
- Parameters:
center – [out] AABB center.
halfExtents – [out] AABB half extents.
- Returns:
False when bounds are unavailable.
-
void updateVertices(const std::vector<Vertex> &vertices)
Update only vertex data on the GPU, keeping the existing index buffer.
Same as
updateVertices(vertices, true).- Parameters:
vertices – New vertex data.
-
void updateVertices(const std::vector<Vertex> &vertices, bool recomputeTangents)
Update only vertex data on the GPU, optionally preserving caller-provided tangents.
- Parameters:
vertices – New vertex data.
recomputeTangents – True to rebuild tangents from the index buffer.
-
inline glm::vec4 vertexDisplacementUvStats() const
Mesh-average UV metrics consumed by heightmap vertex displacement: xy = |dP/du|, |dP/dv| in object units per raw UV unit (area weighted), zw = mean raw-UV edge length. Zero when the mesh has no usable UVs.
- Returns:
The packed statistics.
-
bool updateVertexRange(size_t firstVertex, const Vertex *vertices, size_t count)
Update a contiguous vertex range while preserving the index buffer.
Updates both the CPU copy and the GPU buffer; tangents are not recomputed.
- Parameters:
firstVertex – Index of the first vertex to replace.
vertices – Replacement vertices.
count – Number of vertices.
- Returns:
False (nothing changed) if the range is empty or out of bounds.
-
void uploadVertices(const Vertex *vertices, size_t count)
Upload vertex data without copying it into the CPU-side mesh cache.
Unless
verticesis vertices itself, CPU-based bounds become unavailable (see localBoundingSphere()).- Parameters:
vertices – Pointer to vertex data.
count – Number of vertices.
-
size_t applyTextureFilteringQuality(float anisotropy, float mipLodBias) const
Apply sampler quality to all 2D textures owned by this mesh/material.
Modifies the GL texture objects, so other meshes using the same textures are affected.
- Parameters:
anisotropy – Requested anisotropic filtering level.
mipLodBias – Mip LOD bias.
- Returns:
Number of unique texture ids updated.
-
void collectMaterialTextureIds(std::vector<unsigned int> &textureIds) const
Append non-environment 2D material texture ids used by this mesh.
Environment/IBL maps are renderer resources and are reported separately by RayraiWindow diagnostics.
- Parameters:
textureIds – [inout] Non-zero ids are appended (duplicates are kept).
-
void accumulateGeometryDiagnostics(GeometryDiagnostics &diagnostics, float tinyTriangleAreaThreshold) const
Accumulate CPU-side triangle statistics for diagnostics.
- Parameters:
diagnostics – [inout] Totals to add to.
tinyTriangleAreaThreshold – Triangles with smaller (non-zero) area count as tiny.
-
void collectMeshDiagnostics(std::vector<MeshDiagnostics> &diagnostics, float tinyTriangleAreaThreshold) const
Append per-mesh geometry/material diagnostics for structured JSON output.
- Parameters:
diagnostics – [inout] One entry is appended.
tinyTriangleAreaThreshold – Triangles with smaller (non-zero) area count as tiny.
-
inline void invalidateMaterialCache() const
Refresh cached material-derived flags after direct material edits.
Call after changing material or textures in place so usesPbrShading() and the texture-slot cache are re-evaluated.
Public Members
-
std::vector<Vertex> vertices
Vertex list for the mesh.
-
std::vector<unsigned int> indices
Index list for the mesh, interpreted per primitiveTopology().
-
std::vector<Texture> textures
List of textures associated with the mesh.
Used by the simple shader path: the first “texture_diffuse” entry also becomes Material::albedoMap at construction, and a “texture_specular” entry is bound to unit 1.
-
glm::vec4 baseColor
Base color used when textures are not present.
Copied into Material::baseColorFactor at construction. draw() does not upload it; callers such as RaisimObject read it to set
objectColor.
-
std::string debugSourceMeshName
Source mesh name and imported primitive counts used by optional diagnostics.
-
size_t debugImportedFaceCount
Internal: face count reported by the importer.
-
size_t debugImportedIndexCount
Internal: index count reported by the importer.
-
float debugGeneratedLodMaxUvClusterSpan
Internal: largest UV span merged by LOD simplification.
-
float generatedLodRelativeError
Actual normalized quadric/attribute error reported by the simplifier; -1 means unknown.
-
unsigned int VAO
OpenGL vertex array object handle (context-local; owned unless this is a view).
Public Static Functions
-
static inline bool isPbrRenderMode(RenderMode mode)
- Parameters:
mode – Render mode to test.
- Returns:
True for the three PBR-only render modes.
Create a CPU-metadata view into
owner'sindexed GPU buffers.The returned mesh has its own material/CPU geometry metadata but shares
owner'sVAO/EBO/VBO and draws the requested index range. It does not own or delete the shared GL handles, and holds ashared_ptrtoownerso the borrowed GL handles cannot dangle.Taking the owner as an explicit
std::shared_ptrmakes shared ownership a compile-time requirement (noshared_from_this/bad_weak_ptrfallback that could silently return a non-owning view), and the view is built without any throwaway GL upload — it never allocates its own VAO/VBO/EBO. Returns null ifowneris null.- Parameters:
owner – Mesh whose GPU buffers are borrowed.
localVertices – CPU vertices for this view (bounds/diagnostics only).
localIndices – CPU indices for this view; their count is the draw count.
firstIndex – Offset, in indices, into
owner'sindex buffer.baseVertex – Value added to each index when drawing.
viewMaterial – Material of the view.
viewBaseColor – Base color of the view.
debugName – Diagnostics name; empty inherits
owner's.
- Returns:
The view, or nullptr.
Create a context-local mesh wrapper that reuses another mesh’s GPU buffers.
Buffer objects and textures are shared by OpenGL context share groups, while vertex array objects are context-local. This factory copies the CPU/material metadata, retains the shared VBO/EBO allocation, and creates a VAO in the caller’s current context.
- Parameters:
owner – Source mesh; its buffers must be visible in the current context.
- Returns:
The view, or nullptr if
owneris null, has no shareable buffers, or is not visible from the current context.
-
static std::shared_ptr<OpenGLMesh> createCpuGeometry(const std::vector<Vertex> &vertices, const std::vector<unsigned int> &indices, const std::vector<Texture> &textures, const glm::vec4 &baseColor, bool prepareAttributes = true)
Prepare geometry on a worker without issuing any OpenGL calls. Call uploadPreparedGeometry() on the GL thread before drawing.
- Parameters:
vertices – Vertex array.
indices – Triangle index array.
textures – Texture list (ids are only recorded).
baseColor – Base color.
prepareAttributes – Also run prepareGeometryAttributes().
- Returns:
New mesh with no GL objects.
-
static std::shared_ptr<OpenGLMesh> createCpuGeometry(std::vector<Vertex> &&vertices, std::vector<unsigned int> &&indices, const std::vector<Texture> &textures, const glm::vec4 &baseColor, bool prepareAttributes = true)
createCpuGeometry() that takes over the vertex and index arrays instead of copying them.
-
static std::shared_ptr<OpenGLMesh> createWithCompactIndices(const std::vector<Vertex> &vertices, const std::vector<unsigned int> &indices, const std::vector<Texture> &textures = {}, const glm::vec4 &baseColor = glm::vec4(1.f))
Construct a new owned mesh with lossless compact GPU indices when possible. Generic constructors retain uint32 buffers for existing raw-VAO clients.
- Parameters:
vertices – Vertex array.
indices – Triangle index array.
textures – Optional texture list.
baseColor – Base color used when textures are absent.
- Returns:
The new mesh (requires a current GL context).
-
struct GeometryDiagnostics
Aggregated triangle statistics (see accumulateGeometryDiagnostics()). Non-triangle meshes count toward meshCount only.
Public Members
-
size_t meshCount
Meshes visited.
-
size_t triangleCount
Triangles with valid indices and finite area.
-
size_t tinyTriangleCount
Triangles with 0 < area < threshold.
-
float minTriangleArea
Smallest triangle area (object units squared).
-
float maxTriangleArea
Largest triangle area (object units squared).
-
size_t meshCount
-
struct MeshDiagnostics
Internal: per-mesh geometry/material record for structured diagnostics output (see collectMeshDiagnostics()). Most fields mirror the Material setting named in their comment.
Public Members
-
std::string sourceMeshName
-
std::string materialName
Material::name.
-
size_t vertexCount
CPU vertex count.
-
size_t indexCount
CPU index count.
-
size_t triangleCount
-
size_t tinyTriangleCount
-
float minTriangleArea
-
float maxTriangleArea
-
size_t materialTextureReferenceCount
Non-zero texture ids from collectMaterialTextureIds() (with duplicates).
-
std::vector<std::string> textureSlots
Types of textures entries and names of bound Material texture slots.
-
size_t perTextureUvTransformCount
Material::perTextureUvTransformCount().
-
std::vector<std::string> uvTransformSlots
Slots with an authored per-texture UV transform.
-
std::string shaderVariant
“pbr” or “simple”.
-
std::string alphaMode
Material::alphaMode as text.
-
std::string blendMode
Material::blendMode as text.
-
int renderPriority
Material::renderPriority.
-
bool hasNextPass
Material::nextPass is set.
-
size_t nextPassCount
Length of the Material::nextPass chain.
-
std::vector<std::string> nextPassMaterials
Names of the next-pass materials.
-
std::string detailBlendMode
Material::detailAlbedoBlendMode as text.
-
std::string cullMode
Material::cullMode as text.
-
std::string textureRepeatMode
Material::textureRepeatMode as text.
-
std::string textureFilter
Material::textureFilter as text.
-
bool albedoTextureForceSrgb
Material::albedoTextureForceSrgb.
-
bool albedoTextureMsdf
Material::albedoTextureMsdf.
-
float msdfPixelRange
Material::msdfPixelRange.
-
float msdfOutlineSize
Material::msdfOutlineSize.
-
std::string emissionOperator
Material::emissionOperator as text.
-
bool heightmapInvert
Material::heightmapInvert.
-
float heightmapVertexDisplacementScale
Material::heightmapVertexDisplacementScale.
-
float heightmapVertexDisplacementMidlevel
Material::heightmapVertexDisplacementMidlevel.
-
std::string billboardMode
Material::billboardMode as text.
-
bool billboardKeepScale
Material::billboardKeepScale.
-
int particlesAnimHFrames
Material::particlesAnimHFrames.
-
int particlesAnimVFrames
Material::particlesAnimVFrames.
-
bool particlesAnimLoop
Material::particlesAnimLoop.
-
float particlesAnimFrameProgress
Material::particlesAnimFrameProgress.
-
bool particleTrailsEnabled
Material::particleTrailsEnabled.
-
float particleTrailLength
Material::particleTrailLength.
-
float particleTrailTaper
Material::particleTrailTaper.
-
glm::vec3 particleTrailWorldDirection
Material::particleTrailWorldDirection.
-
bool fixedSize
Material::fixedSize.
-
bool usePointSize
Material::usePointSize.
-
float pointSize
Material::pointSize.
-
bool useZClipScale
Material::useZClipScale.
-
float zClipScale
Material::zClipScale.
-
bool useFovOverride
Material::useFovOverride.
-
float fovOverrideDegrees
Material::fovOverrideDegrees.
-
size_t secondaryUvCount
Vertices whose TexCoords2 differs from TexCoords.
-
bool detailUsesUv2
Material::detailUvLayer is Uv2.
-
bool aoUsesUv2
Material::aoUsesUv2.
-
bool emissiveUsesUv2
Material::emissiveUsesUv2.
-
bool lightmapUsesUv2
Material::lightmapUsesUv2.
-
bool uv2TriplanarEnabled
Material::uv2TriplanarEnabled.
-
bool uv2TriplanarWorldSpace
Material::uv2TriplanarWorldSpace.
-
float uv2TriplanarSharpness
Material::uv2TriplanarSharpness.
-
size_t vertexColorCount
Vertices with a non-white Color.
-
bool vertexColorAsAlbedo
Material::useVertexColorAsAlbedo.
-
bool doubleSided
Material::doubleSided.
-
bool unlit
Material::unlit.
-
bool normalMapped
Any normal, bent-normal, detail-normal or clearcoat-normal map is set.
-
std::string tangentSource
How tangents were obtained (e.g. imported/generated).
-
size_t validTangentCount
Vertices with a usable tangent.
-
size_t fallbackTangentCount
Vertices that needed a fallback tangent.
-
bool generatedTangents
tangentSource mentions “generated”.
-
bool importedTangents
tangentSource mentions “imported”.
-
bool decal
Material::decalDepthBias is non-zero.
-
bool tinySurfaceDetail
Material::tinySurfaceDetail.
-
bool transmission
Transmission factor > 0 or map set.
-
bool refraction
Refraction factor > 0 or map set.
-
bool volume
Any volume thickness/attenuation setting is non-default.
-
bool subsurfaceSkinMode
Material::subsurfaceSkinMode.
-
bool clearcoat
Clearcoat factor > 0 or any clearcoat map set.
-
bool sheen
Any sheen setting is non-default.
-
bool anisotropy
Anisotropy factor non-zero or map set.
-
bool specularIor
Specular factor/color or IOR is non-default.
-
bool planarReflection
Planar reflection enabled or strength > 0.
-
bool environmentIbl
Any per-material environment/IBL map is set.
-
bool materialRenderFlags
Any of the shadow/ambient/fog/specular-occlusion opt-out flags is set.
-
bool thinTwoSidedLighting
Material::thinTwoSidedLighting.
-
bool thinTransmission
Material::thinTransmissionStrength > 0.
-
bool subsurface
Subsurface strength > 0 or a subsurface map set.
-
bool backlight
Backlight color non-zero or map set.
-
bool foliage
Material::foliageType is not None.
-
bool foliageTwoSidedLighting
Foliage with two-sided lighting.
-
bool foliageTransmission
Foliage with transmission strength > 0.
-
bool foliageWeatherResponse
Foliage with a non-zero wet or snow response.
-
bool weatherAffectsWetness
Material::weatherAffectsWetness.
-
bool weatherAffectsSnow
Material::weatherAffectsSnow.
-
bool weatherPuddleEligible
Material::weatherPuddleEligible.
-
bool weatherSnowEligible
Material::weatherSnowEligible.
-
bool weatherMaskMapped
Material::weatherMaskMap is set.
-
float weatherPorosity
Material::weatherPorosity.
-
std::string weatherSkipReason
Why weather may be skipped or reduced, or “eligible”.
-
std::string depthTestMode
Material::depthTest as text.
-
bool depthTestOverride
Material::hasDepthTestOverride().
-
bool depthWriteOverride
Material::hasDepthWriteOverride().
-
bool depthTestResolved
Material::resolveDepthTest(true).
-
bool depthWriteResolved
Material::resolveDepthWrite(true).
-
bool stencilOverride
Material::hasStencilOverride().
-
bool stencilRead
Material::stencilRead.
-
bool stencilWrite
Material::stencilWrite.
-
bool stencilWriteDepthFail
Material::stencilWriteDepthFail.
-
std::string stencilCompare
Material::stencilCompare as text.
-
int stencilReference
Material::stencilReference.
-
unsigned int stencilMask
Low 8 bits of Material::stencilMask.
-
std::string stencilEffectMode
Material::stencilEffectMode as text.
-
glm::vec4 stencilEffectColor
Material::stencilEffectColor.
-
float stencilOutlineThickness
Material::stencilOutlineThickness.
-
bool pbr
-
std::string sourceMeshName
-
struct PreparedAttributes
What prepareGeometryAttributes() derives besides the vertex attributes. Internal: caches of prepared meshes store it.
Public Members
-
std::string tangentSource
How tangents were obtained.
-
size_t validTangentCount
Vertices with a usable tangent.
-
size_t fallbackTangentCount
Vertices that needed a fallback tangent.
-
glm::vec2 uvDensity
See vertexDisplacementUvStats() (xy).
-
glm::vec2 uvEdgeLength
See vertexDisplacementUvStats() (zw).
-
std::string tangentSource
-
struct VertexSummaries
What precomputeVertexSummaries() and contentDigest() find. Internal: for caches of prepared geometry, which store it with the vertices.
Public Members
-
bool bounds
localBoundingSphere() succeeds.
-
glm::vec4 sphere
Its center (xyz) and radius (w).
-
glm::vec3 halfExtents
localBoundingBox() half extents.
-
bool uniformColor
Every vertex has the first one’s color.
-
uint64_t contentDigest
-
bool bounds
-
struct StagedGeometry
Where staging buffers (persistently mapped, OpenGL 4.4) hold this mesh’s vertices and indices as uploadPreparedGeometry() stores them. Internal.
-
enum class RenderMode
-
namespace assimp
Functions
-
bool isUsdModelFile(const std::string &path)
- Returns:
True for .usd, .usda, .usdc and .usdz paths (case-insensitive extension).
-
std::future<AsyncModelLoadResult> loadModelSceneAsync(const std::string &path)
Run the Assimp import of
pathon a new thread (no GL calls). USD files are not handled here; use loadModel() for them.
-
bool importedTexturesDecoded(const AsyncModelLoadResult &imported)
True when the texture files an import queued for background decoding are all decoded (or were never queued), so finishing it decodes no image on the calling thread. Never waits.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> finishImportedModelScene(AsyncModelLoadResult &imported)
Convert an import into meshes, resolving materials/textures and merging compatible meshes. Needs the render context.
- Throws:
std::runtime_error – if the import failed or is empty.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> prepareImportedModelScene(AsyncModelLoadResult &imported)
Like finishImportedModelScene() but defers geometry preparation to prepareImportedModelGeometry(). Material/texture resolution requires the render context; geometry remains CPU-only.
Worker stage: optimize geometry, compute tangents, and merge compatible meshes.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> loadModel(const std::string &path)
Load a model synchronously (Assimp formats and USD).
- Throws:
std::runtime_error – if the file cannot be loaded.
-
std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> loadModel(const std::string &path, std::vector<ModelSourceFile> &sourceFiles)
loadModel(), also returning the files the import read (just the model for USD).
-
std::vector<AdditionalLight> loadSceneLights(const std::string &path, float intensityScale = 1.0f)
Read authored lights (glTF KHR_lights_punctual, a rayrai light sidecar, or Assimp scene lights) as viewer lights. Lights are not added automatically.
- Parameters:
path – Model file.
intensityScale – Multiplier applied to light intensities.
- Throws:
std::runtime_error – if a binary glTF envelope is malformed.
- Returns:
Converted lights (empty if none).
-
struct FallbackMaterial
- #include <AssimpMeshLoader.hpp>
Material read from an OBJ’s sibling .mtl file, used when Assimp provides none.
-
struct ModelSourceFile
- #include <AssimpMeshLoader.hpp>
A file a model import read (or looked for), as it was at that point.
Public Functions
-
bool changed() const
- Returns:
True if the file was created, removed, resized or modified since.
Public Members
-
std::string path
File path.
-
bool exists
False for an optional companion that was missing.
-
std::uintmax_t size
Size in bytes.
-
std::filesystem::file_time_type time
Last modification time.
Public Static Functions
-
static ModelSourceFile current(const std::string &path)
- Returns:
pathas it is now.
-
bool changed() const
-
struct AsyncModelLoadResult
- #include <AssimpMeshLoader.hpp>
Assimp import produced by loadModelSceneAsync(), before GL resources exist.
Public Members
-
std::string path
Model file path.
-
std::string directory
Directory used to resolve relative texture paths.
-
std::string unsupportedGltfExtensionsNote
Note appended to every mesh’s Material::importReport for unsupported glTF extensions.
-
std::vector<std::string> gltfBaseColorTextureFallbacks
Per-material glTF base-color texture paths.
-
const aiScene *scene
Imported scene, or null on failure.
-
FallbackMaterial fallback
OBJ .mtl fallback.
-
bool stlDiffuseAlphaDefaultsOpaque
Binary STL whose header leaves color alpha undefined; diffuse alpha is forced to 1.
-
std::vector<ModelSourceFile> sourceFiles
The model and every other file the import read (glTF buffers, an OBJ material library, …), as they were when read.
-
std::shared_ptr<void> texturePrefetch
Background decodes of the texture files the materials reference, started by the import; finishing the import uploads them, and this drops the rest.
-
std::shared_ptr<ImportedGeometry> geometry
The meshes the scene’s nodes draw, in the order the model’s meshes are built, with what the import measured of their vertices. Internal.
-
std::string path
-
bool isUsdModelFile(const std::string &path)
Scene helpers
-
class PointCloud
Simple point cloud renderer.
Stores positions and colors on the CPU; nothing reaches the GPU until one of the update methods is called. GL buffers are created lazily on the first upload and released in the destructor, so construction needs no GL context but every update/draw call and the destructor (once uploaded) do.
Public Functions
-
PointCloud()
Construct an empty point cloud.
-
~PointCloud()
Destroy the point cloud and release GPU resources.
-
inline void setCategory(VisualCategory category)
Set the render category used by capture/detection filters.
Point clouds are visible in the normal interactive viewer regardless of this category. External-camera and generated-capture passes can request only detectable point clouds, in which case clouds left as
VisualCategory::NotDetectableare skipped. This lets debug lidar traces, helper samples, and temporary overlays remain visible to a human operator without appearing in external-camera or generated capture images.This is render metadata only; it does not create collision, physics behavior, or semantic labels. New
PointCloudinstances default toVisualCategory::NotDetectable.See also
- Parameters:
category – New render category.
-
inline void setDetectable(bool detectable)
Convenience helper for toggling the point cloud render category.
- Parameters:
detectable – True to include this cloud in detectable-only capture/detection render passes; false to keep it viewer-only for those passes.
-
inline VisualCategory getCategory() const
Get the render category used by capture/detection filters.
- Returns:
Current point cloud category.
-
inline bool isDetectable() const
Check whether detectable-only render passes include this point cloud.
- Returns:
True when the category is
VisualCategory::Detectable.
-
inline bool enabled() const
- Returns:
True when rendering is enabled.
-
inline uint64_t renderRevision() const
Internal:
- Returns:
Counter bumped on every render-affecting change, used by the renderer to invalidate cached frames.
-
void updatePointBuffer()
Upload positions and colors to the GPU (or free the buffers if empty).
Also recomputes the bounding sphere. Does nothing (and logs an error) when
colors.size() != positions.size().
-
void updatePointPositionsBuffer()
Streaming variant for point clouds whose colors stay unchanged. Updates bounds + position VBO only and reuses the initialized color buffer.
-
void updatePointRange(size_t begin, size_t count)
Upload a changed point range of positions and colors in place.
No-op unless the buffers were already uploaded with matching sizes; the range is clamped to the uploaded capacity. Bounds are not recomputed, so call updatePointBuffer() if points moved outside the previous bounds.
- Parameters:
begin – Index of the first changed point.
count – Number of changed points.
-
void draw(Camera &camera, Shader &shader)
Draw the point cloud.
- Parameters:
camera – Active camera (unused but kept for consistency).
shader – Shader to use for drawing; must already be in use (only the
pointSizeuniform is set here).
-
bool approximateBounds(glm::vec3 ¢er, float &radius) const
Bounding sphere (centroid + max distance) of the last uploaded positions.
- Parameters:
center – [out] Sphere center in world coordinates.
radius – [out] Sphere radius.
- Returns:
False (outputs untouched) when positions is empty.
-
inline void setMaxRenderedPoints(size_t maxPoints)
Cap drawn points for simple single-threaded LOD.
- Parameters:
maxPoints – Maximum number of points drawn per frame; 0 draws all.
-
inline size_t maxRenderedPoints() const
- Returns:
Point cap set by setMaxRenderedPoints() (0 = unlimited).
-
void setRenderedPointStride(size_t stride)
Draw every Nth point for cheap point-cloud LOD.
- Parameters:
stride – Point stride; 0 is treated as 1 (draw contiguous points).
-
inline size_t renderedPointStride() const
- Returns:
Current point stride (>= 1).
-
inline void enable(bool enable)
Enable or disable rendering.
- Parameters:
enable – True to enable.
-
inline void notifyDataChanged()
Bump the render revision after a direct mutation of
positionsorcolors.setCategory(),enable(),setMaxRenderedPoints()already bump the revision themselves; this method is for the publicpositions/colorsvectors, which the setter pattern does not cover.
Public Members
-
std::vector<glm::vec3> positions
Point positions in world space.
-
std::vector<glm::vec4> colors
Per-point colors (must match positions size).
RGB in [0, 1]. The built-in point shader draws opaque round points and ignores alpha; a black (zero) color falls back to the shader’s
uPointColoruniform.
-
float pointSize
Rendered point size in pixels; values <= 0 render at 2 px.
-
PointCloud()
-
class CoordinateFrame
Render helper for visualizing multiple coordinate frames.
Public Functions
Construct a coordinate frame visualizer.
- Parameters:
asset – Shared asset cache; the shared unit-cylinder axis mesh is fetched from it once here.
-
void draw(Shader &shader)
Draws all coordinate frames in poses without culling.
Each axis is drawn as a cylinder (X red, Y green, Z blue) by setting the
modelandobjectColoruniforms. The shader is not bound here, soshadermust already be in use. Requires a current OpenGL context.- Parameters:
shader – The shader program to use for rendering.
-
void draw(Shader &shader, const glm::mat4 &viewProjection, bool boundShader)
Variant that also frustum-culls poses against
viewProjection.- Parameters:
shader – Shader that must already be in use.
viewProjection – Camera view-projection matrix; an all-zero matrix disables culling.
boundShader – Unused; kept for API parity (neither overload binds the shader).
-
inline void enable(bool enable)
Enables or disables rendering of this coordinate frame set.
- Parameters:
enable – True to enable, false to disable.
-
inline bool enabled() const
- Returns:
True when this frame set is rendered.
Public Members
-
double frameSize
Axis length in world units; the axis radius is 3% of this value.
-
struct Pose
Pose definition for a single coordinate frame.
positionis in world units (typically metres).quaternionis a glm unit quaternion using glm’s (w, x, y, z) component order.
-
class CameraFrustum
Visual helper that renders camera frustum edges.
The frustum mesh is updated from either a rayrai Camera or a raisim DepthCamera and rendered using a Visuals instance.
Public Functions
Construct a frustum helper with a visual and mesh.
- Parameters:
visual – Visuals object used for rendering.
mesh – OpenGL line mesh representing the frustum edges.
-
void updateFromCamera(const Camera &camera)
Update frustum mesh from a rayrai camera.
Handles both perspective (vertical FOV from Camera::zoom) and orthographic (Camera::orthoScale) projections. The drawn far distance is clamped to 10 m. Requires a current OpenGL context (the mesh is re-uploaded).
- Parameters:
camera – Source camera.
-
void updateFromDepthCamera(raisim::DepthCamera &depthCam)
Update frustum mesh from a raisim depth camera.
Calls
depthCam.updatePose()first. The sensor’s horizontal FOV is read as radians, or as degrees when it exceeds pi. The drawn far distance is clamped to 10 m. Requires a current OpenGL context.- Parameters:
depthCam – Source depth camera.
-
void updatePerspective(const glm::vec3 &position, const glm::quat &orientation, float horizontalFov, float aspect, float nearDistance, float farDistance)
Update a perspective frustum from an explicit world-space sensor pose.
The sensor convention is local +X forward and local +Z up, matching RaiSim RGB and depth cameras.
- Parameters:
position – Sensor position in world coordinates.
orientation – Sensor-to-world orientation (normalized internally; identity if degenerate).
horizontalFov – Horizontal field of view in radians, clamped to (0, ~179 deg).
aspect – Image width divided by image height.
nearDistance – Near-plane distance.
farDistance – Far-plane distance used to size the visualization.
-
void setColor(const glm::vec4 &color)
Set the frustum color.
- Parameters:
color – RGBA color.
-
void setDetectable(bool detectable)
Set the capture/detection render category on the frustum visual.
Camera frustums are usually viewer-only helpers and should normally remain non-detectable so they do not appear in external-camera or generated capture images. Set this to true only when the frustum helper itself should be included by detectable-only visualization passes.
See also
- Parameters:
detectable – True to include the frustum visual in detectable-only render passes; false to keep it viewer-only for those passes.
-
enum class raisin::VisualCategory
Render-category flag for user-created visuals and point clouds.
VisualCategoryis render metadata. Rayrai uses it when a render policy asks for only capture/detection-visible helper geometry, for example external camera renders, capture paths that reuse external-camera rendering, detectable-only point-cloud rendering, and picking or shadow candidate passes that explicitly require detectable visualization objects.This flag does not create a physics body, collision shape, dynamics object, or semantic label, and it does not hide an object from the normal interactive viewer. User-created
Visuals,InstancedVisuals,PointCloud, and helpers built on top ofVisualsdefault toNotDetectableso debug overlays, camera frustums, axes, labels, and other viewer-only aids do not contaminate external-camera or generated capture images.Set a visual to
Detectablewhen it should be included in those capture/detection render passes. RaiSim world objects are not controlled by this enum; they follow their own wrapper visibility and the active render pass policy. The RaiSim RGB/depth sensor-camera overloads intentionally disable custom visualization objects and point clouds regardless of this flag.Values:
-
enumerator NotDetectable
Viewer-only by default; excluded from detectable-only render passes.
-
enumerator Detectable
Included when a rayrai render policy asks for detectable custom visuals.
-
enumerator NotDetectable
Rendering and materials
-
class Light
Simple light with optional shadow map support.
Supports all LightType models and owns the shadow-map framebuffer and depth textures used by the renderer. GL resources are created lazily by the shadow pre-pass methods (which need a current OpenGL context) and released in the destructor when the creating context is current; otherwise the ids are dropped without deletion. Non-copyable and non-movable.
Color terms
Linear RGB multipliers (not clamped; values above 1 brighten). The ambient term is added without distance attenuation.
-
glm::vec3 ambient
Constant term added regardless of surface orientation.
-
glm::vec3 diffuse
Lambertian term.
-
glm::vec3 specular
Highlight term.
Attenuation
Inverse-quadratic falloff for point, spot and area lights:
intensity / (constant + linear*r + quadratic*r^2)whereris in metres (never less than radius). Ignored for directional lights. Use setRange() for a more ergonomic alternative.-
float constant
Constant denominator term.
-
float linear
Coefficient of
r(1/m).
-
float quadratic
Coefficient of
r^2(1/m^2).
Projector (light cookie)
Optional 2D texture that tints the light; not applied to point lights.
-
unsigned int projectorMap
GL 2D texture id; 0 disables. Not owned by the light.
-
float projectorStrength
Blend toward the projector color, [0, 1]; 0 disables.
-
glm::vec4 projectorUvScaleOffset
Projector UV transform:
uv * xy + zw.
Camera-distance fade
When enabled, non-directional lights fade out smoothly over [distanceFadeBegin, distanceFadeBegin + distanceFadeLength] of camera distance.
-
bool distanceFadeEnabled
Enable the camera-distance fade.
-
float distanceFadeBegin
Metres from camera.
-
float distanceFadeShadow
Metres from camera at which the shadow starts fading.
-
float distanceFadeLength
Metres of fade band.
Internal shadow state
Public for the renderer; prefer the setters above.
-
unsigned int shadowFbo_
Shadow framebuffer id (shared by the 2D and cubemap passes).
-
unsigned int shadowDepthTex_
2D shadow depth texture (directional/spot/area).
-
unsigned int shadowCubeDepthTex_
Point-light cubemap depth texture.
-
int shadowRes_
Requested shadow-map resolution (set via setShadowResolution()).
-
int shadowAllocatedRes_
Allocated 2D depth texture size; 0 when unallocated.
-
int shadowCubeAllocatedRes_
Allocated cubemap face size; 0 when unallocated.
-
glm::mat4 lightSpaceMatrix_
World-to-light-clip matrix from the last updateShadowMatrix()/pre-pass.
-
std::array<glm::mat4, 6> pointLightSpaceMatrices_
Per-face matrices from pointShadowPrePassFace().
-
bool shadowsEnabled_
Set via setShadowsEnabled().
-
float shadowBias_
Set via setShadowParams().
-
float shadowStrength_
Set via setShadowParams().
-
float shadowPCFRadius_
Set via setShadowParams() (texels).
-
float shadowOrthoHalfSize_
Set via setShadowOrtho() (m).
-
float shadowNear_
Set via setShadowOrtho() (m).
-
float shadowFar_
Set via setShadowOrtho() (m).
-
glm::vec3 shadowCenter_
Set via setShadowCenter().
-
glm::vec3 shadowPosition_
Set via setShadowPosition().
-
bool shadowUseCustomPosition_
Set via setShadowPosition().
Public Functions
-
inline Light()
Default constructor creates a directional light.
No GL resources are created here; the shadow framebuffer is allocated on first use, so construction does not need a GL context.
-
inline void setAsDirectional(const glm::vec3 &dir, const glm::vec3 &diffColor = {0.85f, 0.85f, 0.85f})
Configure as a directional light.
- Parameters:
dir – Direction pointing from the light toward the scene (normalized here).
diffColor – Diffuse color (linear RGB).
-
inline void setAsPoint(const glm::vec3 &pos, const glm::vec3 &diffColor = {0.85f, 0.85f, 0.85f})
Configure as a point light.
- Parameters:
pos – Light position in world coordinates.
diffColor – Diffuse color (linear RGB).
-
inline void setSpotAngles(float innerDeg, float outerDeg)
Set the spotlight cone half-angles in degrees.
Convenience wrapper around the raw cosine fields. The inner cone is the fully-lit region; intensity falls off smoothly between
innerDegandouterDeg. Pass any values; they are clamped so thatinnerDeg <= outerDeg.- Parameters:
innerDeg – Half-angle in degrees where falloff begins.
outerDeg – Half-angle in degrees where light reaches zero.
-
inline void setRange(float rangeMeters)
Set the attenuation of a point, spot or area light from its range in metres.
Sets the inverse-quadratic coefficients 1, 4.5/range and 75/range^2: full intensity at the source, about 1% (1/80.5) at the range, and still decreasing beyond it (it never reaches zero, and the range does not limit which objects the light shades). Use this instead of writing
constant/linear/quadraticby hand. radius, the source size, is not changed.- Parameters:
rangeMeters – Distance at which the light contribution falls to about 1%.
-
bool ensureShadowFramebuffer()
Create or resize the shadow framebuffer and 2D depth texture.
Requires a current OpenGL context. Resources created in a different context are discarded and recreated.
- Throws:
std::runtime_error – (via the framebuffer completeness check) if the framebuffer is incomplete; resources are discarded in that case.
- Returns:
Always true.
-
bool shadowPrePass()
Prepare for 2D shadow depth rendering.
Ensures the framebuffer, updates lightSpaceMatrix_, binds the FBO, sets the viewport, clears depth, enables polygon offset and disables face culling (restored by shadowPostPass()). Requires a current GL context.
- Returns:
Always true; failures throw as in ensureShadowFramebuffer().
-
bool shadowPrePassInto(unsigned int framebuffer, bool clearDepth)
Prepare 2D shadow depth rendering into another framebuffer.
Same as shadowPrePass() but binds
framebuffer, whose depth attachment must match the allocated shadow map size, and clears depth only whenclearDepthis set. Call ensureShadowFramebuffer() first.- Parameters:
framebuffer – Framebuffer to render into.
clearDepth – Clear the depth attachment before rendering.
- Returns:
Always true.
-
void updateShadowMatrix(int snapResolution)
Recompute lightSpaceMatrix_ (used by standalone shadow maps and atlas tiles).
Directional lights use an orthographic box (see setShadowOrtho()) around the shadow center; spot lights a perspective frustum fitted to the outer cone; area lights a 150 degree frustum; point lights a 90 degree frustum.
- Parameters:
snapResolution – Shadow-map resolution in texels used to snap directional shadows to the texel grid (reduces shimmering).
-
bool pointShadowPrePassFace(int face)
Prepare one face of a point-light cubemap shadow render.
Updates lightSpaceMatrix_ and the face’s entry in
pointLightSpaceMatrices_, then binds that cubemap face for depth rendering. Requires a current GL context.- Parameters:
face – Cubemap face index in OpenGL order [0, 5] (clamped).
- Returns:
Always true; failures throw std::runtime_error.
-
void shadowPostPass()
Restore the caller’s face-cull state, disable polygon offset and bind the default framebuffer after shadow rendering.
-
void setShadowResolution(int res)
Set shadow-map resolution.
Releases existing shadow resources when the value changes; they are recreated at the new size on the next pre-pass.
- Parameters:
res – Shadow map size in pixels (min 64; also capped at the driver’s maximum texture size on allocation).
-
inline void setShadowsEnabled(bool e)
Enable or disable shadow sampling.
- Parameters:
e – True to enable shadows.
-
inline void setShadowParams(float bias, float strength, float pcfRadius)
Set shadow bias and filtering parameters.
- Parameters:
bias – Depth bias to reduce acne.
strength – Shadow darkening strength.
pcfRadius – PCF filter radius in shadow-map texels.
-
inline void setShadowOrtho(float halfSize, float zNear, float zFar)
Configure the shadow projection volume.
- Parameters:
halfSize – Half-size of the orthographic box (directional lights only), in metres.
zNear – Near plane in metres (all light types).
zFar – Far plane in metres (all light types).
-
inline void setShadowCenter(const glm::vec3 ¢er)
Set the center point used for directional shadow projection.
- Parameters:
center – World-space center.
-
inline void setShadowPosition(const glm::vec3 &pos, bool enable = true)
Override the light position used for directional shadow projection.
- Parameters:
pos – World-space light position.
enable – True to use the custom position, false to revert to auto position.
Public Members
-
LightType type
Active light type.
-
glm::vec3 position
World-space light position (point, spot and area lights).
-
glm::vec3 direction
Direction the light travels, i.e. pointing from the light toward the scene (directional, spot and area lights). Need not be unit length.
-
float spotInnerCos
Cosine of the inner spotlight cone half-angle (use setSpotAngles() to set in degrees).
-
float spotOuterCos
Cosine of the outer spotlight cone half-angle (use setSpotAngles() to set in degrees).
-
float radius
Light source size in metres. It is not a cutoff: the attenuation distance is clamped to at least this value (area lights use a quarter of it, min 0.1 m), and for area lights it also softens specular highlights.
-
glm::vec3 areaRight
Area-light width axis in world space (normalized by the shader).
-
glm::vec3 areaUp
Area-light height axis in world space (normalized by the shader).
-
bool negative
Subtract this light’s contribution instead of adding it.
-
bool temperatureEnabled
Tint the color terms by temperatureKelvin (normalized to D65).
-
float temperatureKelvin
Kelvin.
-
glm::vec3 ambient
-
class Material
A general-purpose material class supporting PBR, textured, and simple color models.
Plain data: every field is public and read when the material is drawn. usesPbrShading() decides the shader: a material whose type is SIMPLE_COLOR or TEXTURED and whose other fields keep their defaults is drawn by the cheaper simple mesh shader, while Type::PBR (the default) or any PBR-only feature selects the PBR shader; forceSimpleShading overrides both. Texture fields hold OpenGL texture ids that the material does not own (0 = unused). Colors are linear RGB(A) in [0, 1] unless noted.
Public Types
-
enum class TextureSlot
Material texture slots, indexing textureUvTransforms and textureSlotInfo().
Values:
-
enumerator Albedo
-
enumerator Normal
-
enumerator BentNormal
-
enumerator Metallic
-
enumerator Roughness
-
enumerator MetallicRoughness
-
enumerator Ao
-
enumerator Emissive
-
enumerator Clearcoat
-
enumerator ClearcoatRoughness
-
enumerator ClearcoatNormal
-
enumerator SheenColor
-
enumerator SheenRoughness
-
enumerator Transmission
-
enumerator Refraction
-
enumerator Thickness
-
enumerator Subsurface
-
enumerator SubsurfaceTransmittance
-
enumerator Backlight
-
enumerator Anisotropy
-
enumerator WeatherMask
-
enumerator Rim
-
enumerator Height
-
enumerator DetailMask
-
enumerator DetailAlbedo
-
enumerator DetailNormal
-
enumerator Lightmap
-
enumerator TextureBlend
-
enumerator Count
Number of slots (not a valid slot).
-
enumerator Albedo
-
enum class Type
Defines the user-facing type of material for easier configuration.
Only Type::PBR forces the PBR shader by itself; SIMPLE_COLOR and TEXTURED use the simple mesh shader unless a PBR-only feature is set (see usesPbrShading()).
Values:
-
enumerator SIMPLE_COLOR
Basic diffuse material with a solid color.
-
enumerator TEXTURED
A simple textured material (uses albedoMap).
-
enumerator PBR
Full PBR material with metallic/roughness properties.
-
enumerator SIMPLE_COLOR
-
enum class NormalMapConvention
Tangent-space normal-map convention.
Values:
-
enumerator OpenGL
+Y/green-up normal maps.
-
enumerator DirectX
-Y/green-down normal maps, common in Unreal assets.
-
enumerator OpenGL
-
enum class AlphaMode
glTF-style alpha handling for imported materials.
Values:
-
enumerator Opaque
Alpha ignored.
-
enumerator Mask
Discard texels with alpha below alphaCutoff.
-
enumerator Hash
Stochastic (dithered) alpha test, scaled by alphaHashScale.
-
enumerator Blend
Alpha-blended in the transparent pass.
-
enumerator Opaque
-
enum class BlendMode
Godot-style transparent compositing mode.
Values:
-
enumerator Mix
-
enumerator Add
-
enumerator Subtract
-
enumerator Multiply
-
enumerator PremultipliedAlpha
-
enumerator Mix
-
enum class AlphaAntiAliasing
Godot-style alpha-edge smoothing for masked materials.
Values:
-
enumerator Off
-
enumerator AlphaToCoverage
-
enumerator AlphaToCoverageAndToOne
-
enumerator Off
-
enum class DistanceFadeMode
Godot-style distance fade behavior.
Values:
-
enumerator Disabled
-
enumerator PixelAlpha
-
enumerator PixelDither
-
enumerator ObjectDither
-
enumerator Disabled
-
enum class DiffuseMode
Godot-style direct diffuse BRDF mode.
Values:
-
enumerator Burley
-
enumerator Lambert
-
enumerator LambertWrap
-
enumerator Toon
-
enumerator Burley
-
enum class SpecularMode
Godot-style direct specular BRDF mode.
Values:
-
enumerator SchlickGgx
-
enumerator Toon
-
enumerator Disabled
-
enumerator SchlickGgx
-
enum class ShadingModel
Higher-level shading-model selection.
Collapses the three orthogonal
DiffuseMode/SpecularMode/unlitcontrols that the underlying material exposes for fine-grained control into the small set of choices most callers actually want. UsesetShadingModel()to write the corresponding low-level fields andshadingModel()to read back a best-effort classification.Values:
-
enumerator Standard
Burley diffuse + GGX specular (default PBR look).
-
enumerator Lambert
Lambert diffuse + GGX specular (cheaper PBR).
-
enumerator Toon
Toon diffuse + Toon specular (stylized).
-
enumerator Unlit
Skip lighting entirely; emissive-style flat color.
-
enumerator Standard
-
enum class DetailBlendMode
Detail albedo compositing mode.
Values:
-
enumerator SoftMultiply
-
enumerator Mix
-
enumerator Add
-
enumerator Subtract
-
enumerator Multiply
-
enumerator SoftMultiply
-
enum class TextureChannel
Godot-style channel selector for scalar texture maps.
Values:
-
enumerator Red
-
enumerator Green
-
enumerator Blue
-
enumerator Alpha
-
enumerator Gray
-
enumerator Red
-
enum class DepthState
Optional per-material OpenGL depth-state override.
Inherit keeps the current render-pass state, which is the default and preserves existing Fast/Ultra behavior. Enabled/Disabled are explicit material-level overrides for decals, overlays, special transparent surfaces, and authored inspection assets.
Values:
-
enumerator Inherit
Keep the render pass’s state.
-
enumerator Enabled
Force on.
-
enumerator Disabled
Force off.
-
enumerator Inherit
-
enum class StencilCompare
Godot-style stencil comparison operator.
Values:
-
enumerator Always
-
enumerator Less
-
enumerator Equal
-
enumerator LessOrEqual
-
enumerator Greater
-
enumerator NotEqual
-
enumerator GreaterOrEqual
-
enumerator Always
-
enum class StencilEffectMode
Automatic stencil-based highlight effects (PBR path).
Values:
-
enumerator Disabled
No automatic effect.
-
enumerator Outline
Draw the mesh, then a grown overlay shell where the stencil differs.
-
enumerator Xray
Draw the mesh, then an overlay without depth test where the stencil differs.
-
enumerator Custom
Use the raw stencil fields as authored.
-
enumerator Disabled
-
enum class CullMode
Per-material face-culling mode.
Values:
-
enumerator Back
-
enumerator Front
-
enumerator Disabled
-
enumerator Back
-
enum class TextureRepeatMode
Shader-side material texture repeat override.
Values:
-
enumerator Inherit
-
enumerator Repeat
-
enumerator Disabled
-
enumerator Mirror
-
enumerator Inherit
-
enum class TextureFilter
Godot-style per-material texture filtering mode.
Inherit preserves the texture object’s current sampler state. The remaining modes explicitly apply nearest/linear and optional mipmap/anisotropic filtering.
Values:
-
enumerator Inherit
-
enumerator Nearest
-
enumerator Linear
-
enumerator NearestWithMipmaps
-
enumerator LinearWithMipmaps
-
enumerator NearestWithMipmapsAnisotropic
-
enumerator LinearWithMipmapsAnisotropic
-
enumerator Inherit
-
enum class EmissionOperator
Godot-style emission texture compositing operator.
Values:
-
enumerator Add
-
enumerator Multiply
-
enumerator Add
Public Functions
-
Material(std::string name = "DefaultMaterial")
Construct a new Material object.
- Parameters:
name – A unique name for the material.
-
inline bool isTransmissive() const
Optical transmission of this pass (does not traverse nextPass).
- Returns:
True if transmission or refraction factor is positive or its map is set.
-
bool hasTransmissivePass() const
- Returns:
True when this pass or any nextPass isTransmissive().
-
bool hasProximityFadePass() const
- Returns:
True when this pass or any nextPass enables proximity fade.
-
bool usesDefaultDepthAndStencilState() const
- Returns:
True when this pass and every nextPass render with the pass’s own depth test/write and no stencil or decal depth handling.
-
void applyTo(Shader &shader) const
Applies the material’s properties to a shader.
This method binds the necessary textures and sets all material-related uniforms on the provided shader before a draw call. It also makes
shaderthe active program. Requires a current GL context.- Parameters:
shader – The shader to which the properties will be applied.
-
inline void setShadingModel(ShadingModel model)
Write
diffuseMode,specularMode, andunlitfrom a high-level model.Helper for the common case where callers want “PBR/Lambert/Toon/Unlit” rather than picking a
DiffuseMode+SpecularModepair and remembering to clear theunlitflag.Unlitonly sets unlit and leaves the BRDF modes unchanged.- Parameters:
model – Desired shading model.
-
inline ShadingModel shadingModel() const
Read back a best-effort high-level shading model classification.
Returns
Unlitwhen theunlitflag is set, otherwise picks the closestStandard/Lambert/Toonbased on the currentdiffuseMode/specularMode. A Toon diffuse or specular mode yieldsToon; Burley diffuse yieldsStandard; anything else yieldsLambert.- Returns:
The classification.
-
inline AlphaSettings alphaSettings() const
Bundle the three alpha-related enums into a single struct view.
The returned struct is a snapshot; round-trip it via
setAlphaSettings()to write back into the underlying fields.- Returns:
Copy of the alpha fields.
-
inline void setAlphaSettings(const AlphaSettings &s)
Write
alphaMode,blendMode,alphaAntialiasingfrom one struct.- Parameters:
s – Values to write.
-
inline FoliageSettings foliageSettings() const
- Returns:
Copy of the foliage fields.
-
inline void setFoliageSettings(const FoliageSettings &f)
Write all foliage fields at once.
- Parameters:
f – Values to write.
-
inline ParallaxSettings parallaxSettings() const
- Returns:
Copy of the parallax fields.
-
inline void setParallaxSettings(const ParallaxSettings &p)
Write all parallax fields at once.
- Parameters:
p – Values to write.
-
inline VertexDisplacementSettings vertexDisplacementSettings() const
- Returns:
Copy of the vertex-displacement fields.
-
inline void setVertexDisplacementSettings(const VertexDisplacementSettings &p)
Write both vertex-displacement fields.
- Parameters:
p – Values to write.
-
bool usesPbrShading() const
Decide between the simple and the PBR shader.
- Returns:
False when forceSimpleShading is set; otherwise true for Type::PBR, a next pass, or any field that only the PBR shader implements.
-
bool canUseCorePbr() const
- Returns:
True when this material (and every next pass) can be drawn by the compact core PBR shader without losing authored features.
-
bool canUseFoliageFastPbr() const
- Returns:
True when this material (and every next pass) can use the compact alpha-masked foliage PBR shader.
-
bool receivesActiveWeather() const
True when this material actually picks up weather (wetness/snow).
Mirrors the per-material weather gate in the full PBR fragment shader: a non-PBR or non-porous material, or one that opts out of both wetness and snow, receives no weather effect — so it does not require the weather-capable full shader even when weather is globally enabled. Used by the scene-level shader selection so a per-material weather opt-out actually preserves the core/foliage-fast path (it previously did not).
- Returns:
True when any pass in the chain receives weather.
-
bool canUseCompactPbr() const
- Returns:
True when either compact PBR shader can reproduce this material.
-
bool requiresHighFidelityPbr() const
- Returns:
True when this PBR material (or a next pass) uses transmission, volume, subsurface, backlight, anisotropy, iridescence or sheen, which benefit from the high-fidelity PBR shader.
-
bool needsTransparentPass() const
- Returns:
True when this material or a next pass must be sorted and rendered by the transparent pass.
-
inline bool hasDepthTestOverride() const
- Returns:
True when this material explicitly overrides the current depth-test state.
-
inline bool hasDepthWriteOverride() const
- Returns:
True when this material explicitly overrides the current depth-write state.
-
inline bool usesInvertedDepthTest() const
- Returns:
True when this material wants an inverted depth comparison.
-
inline bool hasStencilOverride() const
- Returns:
True when stencilReference is non-negative.
-
inline bool resolveDepthTest(bool passDefault) const
Resolve material depth-test override against a render-pass default.
- Parameters:
passDefault – Depth-test state of the current pass.
- Returns:
Whether depth testing is enabled (Inverted counts as enabled).
-
inline bool resolveDepthWrite(bool passDefault) const
Resolve material depth-write override against a render-pass default.
- Parameters:
passDefault – Depth-write state of the current pass.
- Returns:
Whether depth writes are enabled.
-
inline bool usesTwoSidedLighting() const
- Returns:
True when back-facing fragments should use two-sided lighting (doubleSided or CullMode::Disabled).
-
UvTransform &textureUvTransform(TextureSlot slot)
- Parameters:
slot – Texture slot; must not be TextureSlot::Count (not bounds-checked).
- Returns:
Mutable reference into textureUvTransforms.
-
const UvTransform &textureUvTransform(TextureSlot slot) const
- Parameters:
slot – Texture slot; must not be TextureSlot::Count (not bounds-checked).
- Returns:
Reference into textureUvTransforms.
-
bool hasPerTextureUvTransforms() const
- Returns:
True when any slot has an authored UV transform.
-
size_t perTextureUvTransformCount() const
- Returns:
Number of slots with an authored UV transform.
Public Members
-
Type type
Material type hint; see usesPbrShading() for how it selects the shader.
-
bool forceSimpleShading
Force this material through the simple mesh shader even when PBR fields are set.
-
glm::vec4 baseColorFactor
Base color factor (albedo tint).
This is the base color if no texture is used, or a tint factor otherwise.
-
bool useVertexColorAsAlbedo
Multiply base albedo and opacity by mesh vertex colors.
-
bool vertexColorIsSrgb
Decode vertex color RGB from sRGB before applying it as albedo.
-
float textureBlendFactor
Strength for blending textureBlendMap over the base albedo. The blend map alpha is the mask.
-
float metallicFactor
Metallic factor (0 for dielectric, 1 for metal).
-
float roughnessFactor
Roughness factor (0 smooth, 1 rough); the PBR shader clamps to [0.04, 1].
-
glm::vec3 emissiveFactor
Emissive color factor in linear RGB.
-
float iblStrength
Strength of the simple procedural image-based lighting approximation.
-
float environmentMapStrength
Blend amount for the optional environment cubemap.
-
bool environmentBoxProjection
Enable box-projected parallax correction for local reflection probes.
-
glm::vec3 environmentProbePosition
Local reflection probe capture position in world space.
-
glm::vec3 environmentBoxMin
World-space minimum corner of the box-projected reflection volume.
-
glm::vec3 environmentBoxMax
World-space maximum corner of the box-projected reflection volume.
-
float normalStrength
Strength of tangent-space normal-map perturbation.
-
float normalMapYScale
Tangent-space normal-map Y scale. Use -1 for DirectX-style normal maps.
-
float bentNormalStrength
Strength for bent-normal ambient/specular-occlusion direction.
-
NormalMapConvention normalMapConvention
Named normal-map convention. This is applied before normalMapYScale.
-
AlphaMode alphaMode
Material alpha mode. Masked and fully transparent texels discard before depth writes.
-
BlendMode blendMode
Transparent compositing mode used when the material is drawn in the transparent pass.
-
int renderPriority
Godot-style render priority. Higher priority transparent materials draw later.
-
std::shared_ptr<Material> nextPass
Optional Godot-style material pass rendered immediately after this material.
The renderer walks a small bounded chain of next passes. This is intended for outline shells, X-ray overlays, and other lightweight multi-pass material effects.
-
float alphaCutoff
Alpha cutoff used for masked materials.
-
float alphaHashScale
Alpha-hash noise scale. Higher values create finer dither.
-
AlphaAntiAliasing alphaAntialiasing
Smooth alpha-tested edges. The shader approximates coverage when MSAA is unavailable.
-
float alphaAntialiasingEdge
Width of the smoothed alpha-test edge.
-
DistanceFadeMode distanceFadeMode
Distance fade mode for Godot-style material fade-out.
-
bool proximityFadeEnabled
Fade transparent pixels as they approach already-rendered opaque geometry.
-
float proximityFadeDistance
View-space distance over which proximity fade reaches full opacity.
-
float aoStrength
Ambient-occlusion texture strength. 0 ignores the AO map, 1 uses it fully.
-
float aoLightAffect
Godot-style amount of ambient occlusion applied to direct lighting.
0 keeps AO on indirect/ambient light only, 1 also attenuates direct lights.
-
float emissiveStrength
Multiplier for emissive texture/factor contribution.
-
EmissionOperator emissionOperator
Combine emissiveFactor and emissiveMap by addition or multiplication.
-
float specularFactor
glTF-style dielectric specular strength multiplier.
-
glm::vec3 specularColorFactor
glTF-style dielectric specular color multiplier.
-
DiffuseMode diffuseMode
Direct diffuse BRDF selector. Lambert preserves RayRai’s legacy default.
-
SpecularMode specularMode
Direct specular BRDF selector.
-
float ior
Index of refraction used to derive dielectric F0.
-
float transmissionFactor
Optical transmission strength for thin panes and authored-thickness volumes.
-
float refractionFactor
Godot-style screen refraction strength independent of physical transmission.
-
float volumeThicknessFactor
Authored optical path length in world units; zero denotes a thin sheet.
-
int dielectricPriority
Geometry-refraction overlap precedence: larger values win. This is not renderPriority. Use distinct priorities for overlapping different media.
-
unsigned int dielectricVolumeId
Nonzero explicitly joins submeshes/visuals into one dielectric volume. Zero gives each visual (or articulated visual body) its own volume.
-
float volumeAttenuationDistance
Distance over which volume attenuation reaches the authored color.
-
glm::vec3 volumeAttenuationColor
Tinted volume attenuation color for thick glass approximation.
-
float subsurfaceScatteringStrength
Godot-style subsurface scattering strength.
-
glm::vec3 subsurfaceTransmittanceColor
Tint for subsurface transmittance through thin/soft materials.
-
float subsurfaceTransmittanceDepth
Approximate material depth used to damp subsurface transmittance.
-
float subsurfaceTransmittanceBoost
Extra gain for subsurface transmittance from back-facing light.
-
bool subsurfaceSkinMode
Use a Godot-style skin diffusion profile for subsurface transmittance.
-
glm::vec3 backlightColor
Additive backlight tint for thin materials.
-
TextureChannel metallicTextureChannel
Channel sampled from metallicMap.
-
TextureChannel roughnessTextureChannel
Channel sampled from roughnessMap.
-
TextureChannel aoTextureChannel
Channel sampled from aoMap.
-
TextureChannel refractionTextureChannel
Channel sampled from transmission/refraction map.
-
glm::vec4 uvScaleOffset
UV transform as scale.xy and offset.zw.
-
float uvRotation
UV rotation in radians.
-
glm::vec4 uv2ScaleOffset
Secondary UV transform as scale.xy and offset.zw.
-
float uv2Rotation
Secondary UV rotation in radians.
-
TextureRepeatMode textureRepeatMode
Shader-side repeat behavior for material texture coordinates.
-
TextureFilter textureFilter
Explicit sampler filtering mode for all 2D textures used by this material.
-
float textureFilterAnisotropy
Requested anisotropy level for anisotropic textureFilter modes.
-
bool albedoTextureForceSrgb
Decode albedo texture samples as sRGB in shader for linear-format authored maps.
-
bool albedoTextureMsdf
Interpret the albedo texture as a multi-channel signed-distance field.
-
float msdfPixelRange
Source-pixel distance range encoded by the albedo MSDF texture.
-
float msdfOutlineSize
Optional MSDF outline expansion in source pixels.
-
BillboardMode billboardMode
Rotate the rendered material geometry toward the active camera.
-
bool billboardKeepScale
Preserve the model scale when billboardMode is enabled.
-
int particlesAnimHFrames
Horizontal frame count for Godot-style particle atlas animation.
When billboardMode is Particles, UV1 is remapped into the selected atlas cell.
-
int particlesAnimVFrames
Vertical frame count for Godot-style particle atlas animation.
-
bool particlesAnimLoop
Wrap particle atlas frame progress instead of clamping at the last frame.
-
float particlesAnimFrameProgress
Normalized atlas animation progress. Godot sources this from INSTANCE_CUSTOM.z.
-
bool particleTrailsEnabled
Stretch particle billboards into renderer-side trail quads.
Godot’s particle trail render mode is driven by particle history buffers. RayRai exposes the renderer-side deformation directly so callers can author trail visuals without an engine particle system.
-
float particleTrailLength
Extra tail length in world/local units for particle trail billboards.
-
float particleTrailTaper
Tail width multiplier. Values below one taper the trail toward the end.
-
glm::vec3 particleTrailWorldDirection
Optional world-space trail direction. Zero uses the billboard’s local down axis.
-
bool fixedSize
Scale the material by camera depth so its apparent size stays stable.
-
float fixedSizeScale
Multiplier for fixed-size material scaling.
-
bool usePointSize
Render GL point primitives with an authored material point size.
-
bool useZClipScale
Apply Godot-style clip-space Z compression toward the near plane.
-
float zClipScale
Clip-space Z scale. Values below 1 pull the material toward the near plane.
-
bool useFovOverride
Override the apparent camera FOV for this material in degrees.
-
float fovOverrideDegrees
Vertical FOV used when useFovOverride is enabled.
-
bool triplanarEnabled
Project primary material textures from three axes instead of mesh UVs.
This matches Godot-style triplanar materials for terrain, rocks, walls, and procedural assets where ordinary UVs would stretch or create visible seams.
-
bool triplanarWorldSpace
Use world-space coordinates for triplanar projection. False uses local mesh space.
-
glm::vec3 triplanarScale
Triplanar projection scale along local/world XYZ.
-
glm::vec3 triplanarOffset
Triplanar projection offset along local/world XYZ.
-
float triplanarSharpness
Blend sharpness for triplanar axis weights. Godot clamps this to 0..150.
-
bool uv2TriplanarEnabled
Triplanar projection for textures that explicitly use secondary UVs.
-
bool uv2TriplanarWorldSpace
Use world-space coordinates for UV2 triplanar projection.
-
glm::vec3 uv2TriplanarScale
UV2 triplanar projection scale along local/world XYZ.
-
glm::vec3 uv2TriplanarOffset
UV2 triplanar projection offset along local/world XYZ.
-
float uv2TriplanarSharpness
UV2 triplanar blend sharpness.
-
std::array<UvTransform, static_cast<size_t>(TextureSlot::Count)> textureUvTransforms
Authored UV transforms per texture slot.
glTF KHR_texture_transform belongs to each textureInfo. The material-wide uvScaleOffset/uvRotation fields remain as fallback for legacy/simple paths.
-
float clearcoatFactor
Optional clearcoat layer strength.
-
float clearcoatRoughnessFactor
Optional clearcoat roughness.
-
float iridescenceFactor
Thin-film iridescence strength (0..1). Adds soap-bubble/oil-slick rainbow shift to the Fresnel highlight. Combine with iridescenceThickness to control which wavelengths constructively interfere.
-
float iridescenceThickness
Thin-film thickness in nm. Typical soap bubble ~400nm; oil film 200..600nm; insect wings ~300nm.
-
float sheenFactor
Optional cloth/fabric sheen strength.
-
glm::vec3 sheenColorFactor
Optional cloth/fabric sheen color.
-
float sheenRoughnessFactor
Optional cloth/fabric sheen roughness.
-
float anisotropyFactor
Optional anisotropic specular strength for brushed materials.
-
float anisotropyRotation
Tangent-frame anisotropy rotation in radians.
-
bool unlit
Render base color without scene lighting, for glTF KHR_materials_unlit.
-
bool proceduralGroundChecker
Use an analytically filtered world-space checker for default ground.
-
bool usePlanarReflection
Whether this material samples the renderer’s planar reflection texture.
-
float planarReflectionStrength
Blend strength for planar reflections on this material.
-
bool dontReceiveShadows
Godot-style flag that skips shadow attenuation on this material.
-
bool disableAmbientLight
Godot-style flag that disables ambient and image-based lighting.
-
bool disableFog
Godot-style flag that disables fog compositing for this material.
-
bool disableSpecularOcclusion
Godot-style flag that keeps ambient specular from being occluded.
-
bool shadowToOpacity
Godot-style flag that converts received shadow into material opacity.
-
bool doubleSided
Disable back-face culling for this material.
-
bool thinTwoSidedLighting
Use generic two-sided lighting for thin non-foliage surfaces.
This is separate from doubleSided: doubleSided controls culling, while this controls diffuse/back-light response for paper, curtains, decals-on-cards, and thin shells.
-
float thinBackDiffuseScale
Back-side diffuse contribution scale for generic thin-surface lighting.
-
float thinTransmissionStrength
Thin-surface backlight/transmission strength for non-foliage materials.
-
glm::vec3 thinTransmissionColor
Tint for generic thin-surface transmitted light.
-
FoliageType foliageType
Explicit foliage category. None disables foliage-specific rendering behavior.
-
float foliageWindStrength
Per-material wind response multiplier for viewer-side foliage animation.
-
float foliageRootHeight
Local-space height where foliage deformation starts. Vertices below this stay rooted.
-
float foliageTipHeight
Local-space height where foliage deformation reaches full strength.
-
float foliageStiffness
Per-material stiffness multiplier. Higher values reduce wind deformation.
-
float foliageFlutterWeight
High-frequency leaf/card flutter multiplier.
-
bool foliageTwoSidedLighting
Use foliage-specific two-sided diffuse lighting for thin leaves/cards.
-
int foliageDepthLodViewCount
Fixed depth-capture surfaces: select the nearest captured viewing angle in instanced scene/shadow shaders. Supported layouts: six axis views or eight azimuth views plus two poles (10). Zero uses ordinary geometry.
-
float foliageDepthLodBlendWidth
Screen-stable coverage blend between neighbouring capture directions. Alignment width in [0, .25]; zero retains the nearest-view selection. This smooths capture rotation, rather than changing the geometry LOD.
-
float foliageTransmissionStrength
Thin-leaf direct and indirect transmission strength for viewer PBR foliage. High-fidelity indirect lighting also gathers the opposite hemisphere.
-
glm::vec3 foliageTransmissionColor
Linear RGB tint of base color for thin-leaf transmitted light.
-
bool foliageWeatherResponse
Allow weather wetness/snow load to alter foliage color, roughness, and wind damping.
-
float foliageWetResponse
Per-material rain/wetness response multiplier for foliage.
-
float foliageSnowResponse
Per-material snow accumulation/load response multiplier for foliage.
-
bool weatherAffectsWetness
Allow the runtime weather layer to darken/lower roughness for rain wetness.
-
bool weatherAffectsSnow
Allow the runtime weather layer to accumulate snow on this material.
-
float weatherPorosity
Relative porous weather response. 0 disables absorption; 1 is the default.
-
bool weatherPuddleEligible
Allow flat/up-facing areas of this material to receive procedural puddle masks.
-
bool weatherSnowEligible
Allow this material to receive snow accumulation after slope/opacity filtering.
-
float rimFactor
View-dependent rim-light strength, matching Godot-style material rim.
-
float rimTint
Blend between neutral rim light and rimColor/texture tint.
-
float rimPower
Rim falloff exponent. Higher values keep the rim closer to the silhouette.
-
glm::vec3 rimColor
Authored rim-light tint color.
-
bool growEnabled
Extrude vertices along their local normals before rendering this material.
-
float growAmount
Local-space grow extrusion distance.
-
float heightmapScale
Height-map parallax scale. Values follow Godot’s percent-style convention.
-
float heightmapVertexDisplacementScale
Local-space vertex displacement distance driven by heightMap.
This moves existing vertices along their normals before rendering. It does not create tessellation; dense meshes show the effect more clearly than coarse meshes.
-
float heightmapVertexDisplacementMidlevel
Height value treated as the neutral vertex-displacement surface.
-
bool heightmapDeepParallax
Enable iterative parallax occlusion sampling instead of a single offset sample.
-
int heightmapMinLayers
Minimum layer count for deep parallax at near-facing views.
-
int heightmapMaxLayers
Maximum layer count for deep parallax at grazing views.
-
glm::vec2 heightmapFlip
Tangent/binormal direction flips for assets authored with inverted height-map axes.
-
bool heightmapInvert
Invert sampled height-map values before parallax displacement.
-
float detailAlbedoBlend
Blend amount for detail albedo texture.
-
DetailBlendMode detailAlbedoBlendMode
Detail albedo compositing mode. SoftMultiply preserves RayRai’s legacy detail look.
-
float detailNormalStrength
Strength for detail tangent-space normal map.
-
bool aoUsesUv2
Sample the ambient-occlusion texture from secondary UVs.
-
bool emissiveUsesUv2
Sample the emissive texture from secondary UVs.
-
bool lightmapUsesUv2
Sample the baked lightmap texture from secondary UVs.
-
float lightmapStrength
Baked diffuse-indirect lightmap strength.
-
glm::vec3 lightmapTint
Optional tint/multiplier for baked lightmap texels.
-
bool decalDepthBias
Render after ordinary opaque surfaces with decal-style depth handling.
-
bool tinySurfaceDetail
Very small albedo-only imported surface detail such as book covers.
-
DepthState depthTest
Optional override for whether this material participates in depth testing.
-
DepthState depthWrite
Optional override for whether this material writes to the active depth buffer.
-
int stencilReference
Stencil reference value. Negative disables per-material stencil state.
-
bool stencilRead
Compare existing stencil values against stencilReference before drawing.
-
bool stencilWrite
Replace stencil values with stencilReference when depth and stencil tests pass.
-
bool stencilWriteDepthFail
Replace stencil values with stencilReference when the stencil test passes but depth fails.
-
StencilCompare stencilCompare
Stencil comparison operator used when stencilRead is enabled.
-
unsigned int stencilMask
Bit mask used for stencil reads and writes.
-
StencilEffectMode stencilEffectMode
Godot-style automatic stencil effect. Custom uses the raw stencil fields above.
-
glm::vec4 stencilEffectColor
Overlay color for automatic stencil outline and X-ray effects.
-
float stencilOutlineThickness
Normal-direction expansion used by stencil outline mode.
-
unsigned int albedoMap
Base color texture (OpenGL id, 0 if unused).
-
bool foliageTextureAtlasApplied
True after the foliage atlas path has remapped this material’s UVs.
-
glm::vec4 foliageTextureAtlasUvRect
UV atlas rectangle used by the foliage atlas path: offset.xy, scale.zw.
-
unsigned int textureBlendMap
Optional second base-color texture. RGB is the layer color, alpha is the blend mask.
-
unsigned int terrainSplatAlbedoMap
Optional secondary albedo layer used by terrain splat blending.
-
unsigned int terrainSplatControlMap
Optional control texture (R = primary-vs-secondary weight) for terrain splat blending.
-
float terrainSplatPrimaryUvScale
World-space UV tiling rate (1/metres) for the primary albedo layer.
-
float terrainSplatSecondaryUvScale
World-space UV tiling rate (1/metres) for the secondary albedo layer.
-
glm::vec4 terrainSplatControlBounds
Control-map bounds in world space (x, y, sizeX, sizeY) used to sample the splat control texture.
-
bool hasTerrainSplat
When true the splat blending path runs; false keeps the existing single-layer behaviour.
-
unsigned int normalMap
Tangent-space normal map (OpenGL id, 0 if unused).
-
unsigned int bentNormalMap
Optional bent normal map for ambient/specular occlusion direction.
-
unsigned int metallicMap
Metallic map (OpenGL id, 0 if unused).
-
unsigned int roughnessMap
Roughness map (OpenGL id, 0 if unused).
-
unsigned int metallicRoughnessMap
Combined glTF metallic-roughness map (G=roughness, B=metallic, 0 if unused).
-
unsigned int ormMap
Godot-style ORM map (R=ambient occlusion, G=roughness, B=metallic).
Uses the metallicRoughness UV transform because it shares the same sampler path in the PBR shader.
-
unsigned int aoMap
Ambient occlusion map (OpenGL id, 0 if unused).
-
unsigned int emissiveMap
Emissive color texture (OpenGL id, 0 if unused).
-
unsigned int clearcoatMap
Optional clearcoat intensity texture, red channel.
-
unsigned int clearcoatRoughnessMap
Optional clearcoat roughness texture, red channel.
-
unsigned int clearcoatNormalMap
Optional clearcoat tangent-space normal texture.
-
unsigned int sheenColorMap
Optional sheen color texture, RGB channels.
-
unsigned int sheenRoughnessMap
Optional sheen roughness texture.
-
unsigned int transmissionMap
Optional transmission texture, red channel.
-
unsigned int refractionMap
Optional screen refraction texture.
-
unsigned int thicknessMap
Optional volume thickness texture.
-
unsigned int subsurfaceMap
Optional subsurface scattering strength texture.
-
unsigned int subsurfaceTransmittanceMap
Optional subsurface transmittance color texture.
-
unsigned int backlightMap
Optional backlight color texture.
-
unsigned int anisotropyMap
Optional anisotropy texture.
Red and green encode the tangent-frame highlight direction. By default blue scales strength for glTF KHR_materials_anisotropy; enable anisotropyMapAlphaStrength for Godot-style flow maps that store strength in alpha.
-
bool anisotropyMapAlphaStrength
Read anisotropy strength from anisotropyMap alpha instead of blue.
-
unsigned int weatherMaskMap
Optional weather response mask. Red channel scales wetness, green channel scales snow.
-
unsigned int rimMap
Optional rim mask/tint texture. Red masks rim strength, green tints toward rimColor.
-
unsigned int heightMap
Optional height map for tangent-space parallax offset.
-
unsigned int detailMaskMap
Optional detail mask. Red channel controls detail albedo/normal blend.
-
unsigned int detailAlbedoMap
Optional detail albedo texture.
-
unsigned int detailNormalMap
Optional detail tangent-space normal texture.
-
unsigned int lightmapMap
Optional baked diffuse-indirect lightmap.
-
unsigned int environmentMap
Optional radiance/environment cubemap (OpenGL cubemap id, 0 if unused).
-
unsigned int irradianceMap
Optional diffuse irradiance cubemap for high-fidelity IBL.
-
unsigned int prefilteredEnvironmentMap
Optional prefiltered specular cubemap for high-fidelity IBL.
-
unsigned int brdfLut
Optional split-sum BRDF LUT texture for high-fidelity IBL.
-
std::string importReport
Human-readable import notes for debugging material differences.
Public Static Functions
-
static Material pbr(std::string name, const glm::vec4 &baseColor, float metallic = 0.0f, float roughness = 0.5f)
Build a metallic/roughness PBR material with sensible defaults.
Sets
type = Type::PBR, the albedo tint, metallic, and roughness factors; leaves all texture slots empty. Provide an IBL environment separately viaVisuals::setPbrEnvironment(...)if you want indirect lighting.- Parameters:
name – Material name.
baseColor – Linear RGBA albedo tint.
metallic – Metallic factor in [0, 1].
roughness – Roughness factor in [0, 1].
- Returns:
The configured material.
-
static Material glass(std::string name = "Glass", float thickness = 0.0f, const glm::vec3 &tint = glm::vec3(1.0f), float attenuationDistance = 1.0f, float roughness = 0.04f, float indexOfRefraction = 1.5f)
Dielectric glass. Zero thickness represents a thin window; positive thickness is an authored world-space optical path length for a solid. Tint is the transmitted color after attenuationDistance world units. Keep alpha at one: transmission, not coverage, makes glass transparent. Enable RenderQualitySettings::screenSpaceRefraction for scene transmission. Sets transmissionFactor = 1 and metallic = 0; a thin pane (thickness <= 0) is also made double-sided.
- Parameters:
name – Material name.
thickness – Optical path length in world units (clamped to >= 0).
tint – Transmitted color, clamped to [0, 1].
attenuationDistance – Distance at which
tintis reached (min 1e-4).roughness – Surface roughness.
indexOfRefraction – IOR, clamped to [1, 3].
- Returns:
The configured material.
-
static Material unlitColor(std::string name, const glm::vec4 &color = glm::vec4(1.0f))
Build an unlit material that ignores scene lighting.
Useful for HUD elements, debug visuals, holograms, light-emitting decals. Named
unlitColorrather thanunlitto avoid colliding with thebool unlitdata member. Sets unlit, which selects the PBR shader’s unlit path.- Parameters:
name – Material name.
color – Linear RGBA color.
- Returns:
The configured material.
-
static Material simpleColor(std::string name, const glm::vec4 &color)
Build a simple-color (non-PBR) material that responds to lighting.
Routes through the simple mesh shader (sets forceSimpleShading). Cheaper than
pbr()and appropriate for primitives that do not need metallic/roughness or IBL.- Parameters:
name – Material name.
color – Linear RGBA color.
- Returns:
The configured material.
-
static Material foliage(std::string name, FoliageType foliageKind, const glm::vec4 &baseColor)
Build a foliage material with the given type and base color.
Sets foliageType, a PBR type with roughness 0.85 and metallic 0, and doubleSided (no culling, two-sided lighting). Other foliage fields keep their defaults; in particular foliageWindStrength stays 0, so there is no wind deformation until it is set.
- Parameters:
name – Material name.
foliageKind – Foliage category.
baseColor – Linear RGBA albedo tint.
- Returns:
The configured material.
-
static Material defaultGround(std::string name = "GroundMaterial")
Build a neutral PBR ground material (mid-grey, rough, non-metallic).
Convenient default for the world’s ground plane / heightmap when no authored material is supplied. Base color 0.55 grey, roughness 0.9, metallic 0.
- Parameters:
name – Material name.
- Returns:
The configured material.
-
static const std::array<TextureBindingInfo, 32> &textureBindingTable()
Stable material sampler binding table used by Material::applyTo().
- Returns:
Static table with one entry per bindable map (including IBL cubemaps).
-
static const char *textureSlotName(TextureSlot slot)
- Parameters:
slot – Texture slot.
- Returns:
Slot name (e.g. “albedo”), or “unknown” for out-of-range values.
-
static const TextureSlotInfo &textureSlotInfo(TextureSlot slot)
Look up metadata for a texture slot by enum.
- Parameters:
slot – Texture slot.
- Returns:
Metadata describing the slot.
Countis invalid and returns an entry named “unknown” with both flags false.
-
struct UvTransform
Per-texture UV transform (glTF KHR_texture_transform style).
Public Members
-
glm::vec4 scaleOffset
scale.xy, offset.zw.
-
float rotation
Rotation in radians.
-
bool authored
Only authored transforms are used; others fall back to uvScaleOffset / uvRotation.
-
glm::vec4 scaleOffset
-
struct TextureBindingInfo
One row of textureBindingTable(): how applyTo() binds a material texture.
Public Members
-
const char *slot
Slot name, e.g. “albedo”.
-
const char *samplerUniform
Sampler uniform, e.g. “material.albedoMap”.
-
const char *presenceUniform
Bool uniform telling the shader the map is bound.
-
const char *target
“2D” or “cubemap”.
-
int textureUnit
Texture unit (preferred unit for some slots).
-
const char *slot
-
struct AlphaSettings
Grouped alpha-handling configuration.
Bundles the three orthogonal alpha-related enums that otherwise live as flat fields. It holds copies: read it with alphaSettings() and write it back with setAlphaSettings().
Public Members
-
AlphaAntiAliasing antiAliasing
-
AlphaAntiAliasing antiAliasing
-
struct FoliageSettings
Grouped foliage wind/weather authoring fields.
Wraps the ~12
foliage*fields scattered through the flat layout. Read withfoliageSettings(), write back withsetFoliageSettings().
-
struct ParallaxSettings
Grouped tangent-space heightmap / parallax controls.
Wraps the
heightmap*fields.scale == 0keeps parallax disabled regardless ofdeepParallax.
-
struct VertexDisplacementSettings
Grouped height-map vertex-displacement controls.
-
struct TextureSlotInfo
Static per-slot metadata for the TextureSlot enum.
Bundles the data that would otherwise live as parallel tables in Material.cpp: human-facing name, whether the slot carries sRGB color (so loaders pick the right internal format), and whether the slot is tracked in
textureUvTransforms[]so callers can iterate slots without a hardcoded list.Public Members
-
const char *name
Same as textureSlotName().
-
bool isSrgb
Color data that should be uploaded as sRGB.
-
bool hasUvTransform
Slot has an entry in textureUvTransforms.
-
const char *name
-
enum class TextureSlot
-
struct RenderQualitySettings
Explicit runtime quality settings for viewer rendering.
The struct stores its fields as a flat layout for historical reasons; the flat fields are the source of truth. For authoring, new code may use the grouped sub-config accessors —
shadows(),bloom(),depthOfField(),fog(),toneMapping(),temporalAa()— and the matchingset*()writers, which copy to and from the flat fields.Use
RenderQualitySettings::preset(RenderQualityPreset)to start from a known-good configuration, then apply withRayraiWindow::setRenderQualitySettings(). That call clamps many fields to the ranges noted on them and throwsstd::invalid_argumentfor invalid temporal-AA parameters; the remaining noted ranges are applied when the value is uploaded to the shaders.Background and main light
The main light is directional. Struct defaults are what Fast and Custom start from; in the simple-shading path there is no IBL, so a moderate ambient keeps smooth/metallic surfaces from going black.
-
glm::vec4 backgroundColorRgb255
Clear color, RGBA in 0..255 (shown where no sky/environment is drawn).
-
glm::vec3 mainLightAmbient
Main light ambient color (linear RGB); also the sky fill on the simple-shading path.
-
glm::vec3 mainLightDiffuse
Main light diffuse color/intensity (linear RGB); also tints the procedural sky sun.
-
glm::vec3 mainLightSpecular
Main light specular color (linear RGB).
-
glm::vec3 mainLightDirection
Direction the main light travels (from the light toward the scene); normalized on apply, ignored if zero.
Main directional shadow
The shadow box is an orthographic volume of half-size shadowOrthoHalfSize centered shadowCenterOffset metres in front of the camera. Ranges in brackets are applied by RayraiWindow::setRenderQualitySettings().
-
int shadowResolution
Main shadow-map edge length, texels (at least 256); additional shadow maps scale from it.
-
float shadowBias
Depth bias against shadow acne.
-
float shadowStrength
Shadow darkening, 0 = none, 1 = full.
-
float shadowPcfRadius
PCF filter radius, shadow-map texels.
-
float directionalShadowSoftnessDegrees
Sun angular diameter, degrees, [0, 4]; 0 keeps plain PCF.
-
float directionalShadowSoftnessMaxRadius
Upper bound of the blocker-based filter radius, shadow-map texels, [1, 16].
-
bool shadowContactHardening
Scale the PCF radius with receiver depth (harder near contact).
-
float shadowContactHardeningMinRadius
Smallest contact-hardening filter radius, texels, [0, 16].
-
float shadowContactHardeningMaxRadius
Largest contact-hardening filter radius, texels, [min radius, 32].
-
float shadowContactHardeningDepthScale
Depth-to-radius scale for contact hardening, [0, 4].
-
bool shadowDebugOverlayEnabled
Show the ImGui shadow debug overlay in the viewer.
-
float shadowOrthoHalfSize
Half-size of the main directional shadow box, metres.
-
float shadowNear
Shadow projection near plane, metres.
-
float shadowFar
Shadow projection far plane, metres (also the default cascade distance).
-
float shadowCenterOffset
Distance ahead of the camera where the shadow box is centered, metres.
Fog
Distance fog, exponential height fog and raymarched volumetric fog. With weather enabled, the weather densities are combined with these by max().
-
float fogDensity
Distance fog: transmittance = exp(-(distance * fogDensity)^2), 1/m.
-
bool fogColorOverrideEnabled
Use fogColor instead of the background color (backgroundColorRgb255) for fog.
-
glm::vec3 fogColor
Distance/height fog color when fogColorOverrideEnabled (linear RGB, >= 0).
-
bool heightFogEnabled
Enable exponential height fog (in addition to distance fog).
-
float heightFogDensity
Height-fog extinction at heightFogBaseHeight, 1/m.
-
float heightFogBaseHeight
World Z where heightFogDensity applies, metres.
-
float heightFogFalloff
Exponential density falloff per metre above the base height.
-
bool volumetricFogEnabled
Enable raymarched volumetric fog in the post-process pass.
-
float volumetricFogDensity
Volumetric fog density, [0, 1].
-
float volumetricFogNoiseScale
Spatial frequency of the fog noise, [0.001, 128].
-
float volumetricFogNoiseStrength
Noise modulation of the fog density, [0, 1].
-
glm::vec3 volumetricFogColor
Volumetric fog color (linear RGB, >= 0).
-
float volumetricFogAnisotropy
Henyey-Greenstein phase g, [-0.85, 0.85]; > 0 scatters forward.
-
float volumetricFogAnimationTimeSeconds
Time driving the fog noise animation, seconds (>= 0).
-
glm::vec2 volumetricFogWindDirection
Fog drift direction in world XY (normalized; zero becomes +X).
-
float volumetricFogWindSpeed
Fog drift speed, [0, 80].
-
float volumetricFogTurbulenceSpeed
Fog noise evolution speed, [0, 20].
Volumetric lighting
-
bool volumetricLightingEnabled
Enable volumetric (in-scattered) main-light shafts through the fog.
-
float volumetricLightStrength
Volumetric light intensity, [0, 8].
-
float volumetricLightDecay
Volumetric light decay, [0, 0.99].
-
int volumetricLightSamples
Volumetric light ray samples, [4, 32].
Shading, tone mapping and color
Shading path selection, tone curve, exposure and post-process color controls.
-
float gamma
Display gamma: output = pow(color, 1 / gamma); at least 0.01.
-
bool highFidelityPbr
Use the full PBR shader path (IBL, environment maps, PBR tone curves).
-
bool forceSimpleMaterialShading
Render every mesh with the simple (non-PBR) shader.
-
bool pbrToneMapping
Apply the colorMode tone curve with pbrExposure (high-fidelity PBR / linear HDR paths).
-
ViewerColorMode colorMode
Tone curve used when pbrToneMapping is on.
-
float pbrExposure
Exposure multiplier applied before the tone curve.
-
bool autoExposureEnabled
Adapt exposure from the average brightness of the previous frame.
-
float autoExposureKey
Target average luminance of the displayed frame (approximately linear).
-
float autoExposureSpeed
Fraction of the remaining exposure error corrected per frame, [0, 1].
-
float autoExposureMinFactor
Lower bound of the auto-exposure multiplier.
-
float autoExposureMaxFactor
Upper bound of the auto-exposure multiplier.
-
glm::vec3 viewerWhiteBalance
Per-channel RGB gain applied in the post-process pass (>= 0).
-
float viewerSaturation
Post-process saturation, 1 = unchanged, 0 = grayscale (>= 0).
-
ColorGradePreset viewerColorGradePreset
Color-grade look applied at the end of the post chain.
-
float viewerColorGradeStrength
Blend between ungraded and graded color, [0, 1].
Environment lighting and sky
Image-based lighting and the procedural sky. Environment mips are chosen as clamp(maxLod * r * (2 - r) + bias, 0, maxLod) for roughness r.
-
float pbrEnvironmentMaxLod
Highest environment mip used for rough reflections; 0 always samples mip 0.
-
float pbrEnvironmentMipLodBias
Bias added to the roughness-based environment mip, [-1, 2].
-
float pbrEnvironmentRotation
Rotation of environment maps and the sky about world +Z, radians.
-
float pbrEnvironmentIntensity
Image-based lighting intensity multiplier (high-fidelity PBR).
-
glm::vec3 pbrEnvironmentLightingTint
Linear RGB illumination for the procedural fallback, independent of the visible sky/fog palette. HDR environment maps retain their captured color.
-
glm::vec3 pbrEnvironmentSkyTint
Tint of the upper sky in the background and procedural environment.
-
glm::vec3 pbrEnvironmentHorizonTint
Tint of the horizon band.
-
glm::vec3 pbrEnvironmentGroundTint
Tint of the lower hemisphere (ground).
-
float pbrEnvironmentHorizonStrength
Width/strength of the horizon band, [0, 1].
-
glm::vec3 environmentBackgroundTint
Tint applied to the drawn sky/environment background (>= 0).
-
float environmentBackgroundExposureScale
Brightness multiplier of the drawn sky/environment background (>= 0).
-
bool proceduralSkyBackgroundEnabled
Draw the procedural sky when no environment map is set.
-
float proceduralSkySunStrength
Brightness of the procedural sun disk (>= 0).
-
float proceduralSkySunSize
Angular radius of the procedural sun disk, radians.
Procedural clouds
-
bool proceduralCloudLayerEnabled
Draw the procedural cloud layer (also requires cloudQuality != Off).
-
float proceduralCloudCoverage
Fraction of sky covered by clouds, [0, 1].
-
float proceduralCloudDensity
Cloud opacity, [0, 1].
-
float proceduralCloudScale
Cloud noise scale.
-
float proceduralCloudSoftness
Cloud edge softness.
-
glm::vec2 proceduralCloudOffset
Offset in cloud-noise space; animate it to move the clouds (no automatic drift).
-
glm::vec3 proceduralCloudTint
Cloud color (linear RGB, >= 0).
-
CloudQuality cloudQuality
Cloud quality path. Off disables clouds entirely; Texture uses the cheap 2D path; Volumetric uses raymarched 3D noise. Set by the presets.
-
bool cloudShadowProjectionEnabled
Project procedural cloud shadows onto the scene.
-
float cloudShadowStrength
Cloud-shadow darkening, [0, 1].
-
float cloudShadowScale
Cloud-shadow noise scale.
Material response and reflective ground
-
float pbrKeyLightIntensity
Main (key) light intensity multiplier in the PBR shaders (>= 0).
-
bool specularAntiAliasing
Reduce specular aliasing on high-frequency normals (PBR).
-
float specularAntiAliasingStrength
Specular anti-aliasing strength, [0, 2].
-
bool reflectiveGround
Render the default ground as a planar-reflective material.
-
float reflectiveGroundRoughness
Roughness of the reflective ground.
-
float reflectiveGroundMetallic
Metallic factor of the reflective ground.
Lens character, stylized effects and shading extras
Mostly screen-space effects applied in the post-process pass, plus detail normals and subsurface wrap in the PBR shaders. All are off by default; strengths are clamped to the noted ranges when uploaded.
-
bool fxaaEnabled
Enable FXAA in the post-process pass.
-
float viewerVignetteStrength
Radial darkening, [0, 1].
-
float viewerChromaticAberrationStrength
RGB channel offset, [0, 1].
-
float viewerFilmGrainStrength
Animated luma noise, [0, 1].
-
bool aerialPerspectiveEnabled
Apply atmospheric aerial perspective to distant geometry (needs the atmosphere volume).
-
float aerialPerspectiveStrength
Aerial-perspective strength multiplier.
-
bool detailNormalEnabled
Add procedural world-space micro-normal detail (high-fidelity PBR).
-
float detailNormalScale
World-space noise frequency, 1/m (>= 0.001).
-
float detailNormalStrength
Detail strength, [0, 1]; small values look natural.
-
float viewerSubsurfaceWrap
Diffuse wrap amount, [0, 1]; 0 = standard Lambert.
-
glm::vec3 viewerSubsurfaceTint
Tint of the wrapped light (>= 0); default is warm.
-
bool lightShaftsEnabled
Enable screen-space sun light shafts (god rays).
-
float lightShaftsStrength
Additive shaft intensity (>= 0).
-
float lightShaftsDecay
Per-step radial decay, [0.5, 0.999].
-
float lightShaftsDensity
Sample step density (effective range [0.1, 2]).
-
float lensFlareGhostStrength
Intensity of the ghost chain (>= 0); 0 disables.
-
float lensFlareStreakStrength
Intensity of the horizontal streak (>= 0); 0 disables.
-
glm::vec3 lensFlareTint
Ghost/streak color; default is a cool blue.
-
bool contactShadowsEnabled
Enable screen-space contact shadows.
-
float contactShadowsLength
Raymarch length, metres, [0, 0.5].
-
float contactShadowsStrength
Darkening, [0, 1].
-
float contactShadowsThickness
Linear-depth tolerance, metres (>= 0.01).
-
bool motionBlurEnabled
Enable the directional motion-blur post effect.
-
glm::vec2 motionBlurDirection
Blur vector in screen-UV units, scaled by motionBlurStrength.
-
float motionBlurStrength
Motion-blur amount, [0, 1].
-
bool ssrEnabled
Enable screen-space reflections.
-
float ssrStrength
Reflection blend amount, [0, 1].
-
int ssrSteps
Raymarch steps, [4, 64].
-
float ssrMaxDistance
Maximum reflection ray length, metres.
-
float ssrThickness
Depth tolerance for a ray hit, metres.
-
bool lensDistortionEnabled
Enable radial lens distortion.
-
float lensDistortionStrength
Signed, [-2, 2]: positive = barrel, negative = pincushion.
-
glm::vec2 lensDistortionCenter
Distortion center in screen UV.
-
bool pixelateEnabled
Enable pixelation.
-
int pixelateBlockSize
Block size, pixels, [1, 64].
-
bool nightVisionEnabled
Enable the night-vision filter.
-
float nightVisionStrength
Blend amount, [0, 1].
-
float nightVisionGain
Luminance gain before the phosphor curve (>= 0.05).
-
bool ditherEnabled
Enable output dithering.
-
float ditherStrength
Noise amplitude, [0, 0.05] (about 1/255 by default).
-
bool thermalEnabled
Enable the thermal (heat-map palette) filter.
-
float thermalStrength
Blend amount, [0, 1].
-
float thermalGain
Luminance gain before the palette lookup (>= 0.05).
-
bool scanlineEnabled
Enable CRT scanlines.
-
float scanlineStrength
Scanline darkening, [0, 1].
-
float scanlineFrequency
Lines per frame height (>= 20).
-
bool letterboxEnabled
Enable letterbox bars.
-
float letterboxAspect
Target aspect ratio; bars appear when it is wider than the frame.
-
glm::vec3 letterboxColor
Bar color (linear RGB).
-
bool underwaterEnabled
Enable the underwater overlay.
-
glm::vec3 underwaterTint
Water color (linear RGB).
-
float underwaterCausticStrength
Caustic intensity (>= 0); 0 disables caustics.
-
float underwaterCausticScale
Caustic pattern scale.
-
float underwaterDepthExtinction
Depth-based fade toward the water color (>= 0).
-
bool heatHazeEnabled
Enable heat-haze distortion.
-
float heatHazeStrength
Distortion amount, [0, 1].
-
float heatHazeFrequency
Ripple frequency (>= 0.5).
-
float heatHazeSpeed
Ripple animation speed (>= 0).
-
float heatHazeMaxY
Screen-UV height (0 = bottom) above which there is no haze, [0, 1].
-
bool zoomBlurEnabled
Enable radial zoom blur.
-
float zoomBlurStrength
Blur amount, [0, 1].
-
glm::vec2 zoomBlurCenter
Blur center in screen UV.
-
float zoomBlurInnerRadius
Sharp radius around the center in UV units, [0, 1].
-
bool posterizeEnabled
Enable color posterization.
-
int posterizeLevels
Levels per channel, [2, 32].
-
bool starburstEnabled
Enable sun diffraction spikes.
-
float starburstStrength
Spike intensity (>= 0).
-
int starburstSpikes
Number of spikes, [1, 16].
-
float starburstAngleOffset
Spike rotation, radians.
-
float starburstRadius
Spike length in screen UV, [0.01, 1].
-
glm::vec3 starburstTint
Spike color (linear RGB).
Bloom
Applied in the post-process pass.
-
bool bloomEnabled
Enable bloom (off in every preset; presets still tune the parameters below).
-
float bloomThreshold
Brightness where bloom starts.
-
float bloomStrength
Bloom intensity.
-
float bloomRadius
Blur radius scale (in source texels).
-
float bloomKnee
Soft-threshold width above bloomThreshold.
-
int bloomQuality
1 or less: 12-tap gather; 2: 24 taps; 3 or more: 4-level downsample/upsample chain.
-
float bloomSourceClamp
Clamp on bloom source color to suppress fireflies; <= 0 disables.
-
float bloomAnamorphic
Horizontal stretch of the bloom, [0, 1].
-
float bloomDirtStrength
Lens-dirt modulation of the bloom, [0, 1].
-
float bloomDirtScale
Lens-dirt pattern scale, [0.05, 32].
-
unsigned int bloomDirtTexture
Optional GL 2D lens-dirt texture; 0 = none.
-
GlowBlendMode bloomBlendMode
How bloom is combined with the scene.
-
float bloomMix
Scene attenuation for GlowBlendMode::Mix, [0, 1].
Post-process debug
-
PostProcessDebugMode postProcessDebugMode
Replace the final image with a post-process debug view.
Ambient occlusion
Depth-based SSAO plus an optional short-range contact AO band.
-
bool screenSpaceAoEnabled
Enable screen-space ambient occlusion.
-
float screenSpaceAoRadius
AO sample radius: pixels, or metres when screenSpaceAoRadiusWorldSpace.
-
float screenSpaceAoStrength
AO darkening strength.
-
float screenSpaceAoBias
Minimum depth difference counted as occlusion.
-
int screenSpaceAoSamples
AO samples, [4, 24].
-
float screenSpaceAoFalloff
Depth range falloff relative to the radius.
-
bool screenSpaceAoRadiusWorldSpace
Interpret the AO radii in metres instead of pixels.
-
float screenSpaceAoMaxPixelRadius
Cap on the projected AO radius, pixels, [1, 256].
-
bool screenSpaceAoGeometryAware
Weight AO samples by the reconstructed surface normal and distance.
-
float contactAoRadius
Short-range AO radius (same units as screenSpaceAoRadius), >= 0.
-
float contactAoStrength
Short-range AO strength, >= 0.
-
int contactAoSamples
Short-range AO samples, [4, 24].
-
float contactAoFalloff
Short-range AO falloff, >= 0.001.
-
bool screenSpaceAoDenoiseEnabled
Apply a depth-aware blur to the AO.
-
float screenSpaceAoDenoiseStrength
Denoise blend amount, [0, 1].
-
int screenSpaceAoDenoiseRadius
1 = 4-tap, 2 = 8-tap denoise kernel.
-
float screenSpaceAoDenoiseDepthSigma
Depth tolerance relative to view depth, >= 0.001.
Screen-space indirect lighting
-
bool screenSpaceIndirectLightingEnabled
Enable screen-space one-bounce indirect lighting.
-
float screenSpaceIndirectLightingRadius
Gather radius, metres (>= 0).
-
float screenSpaceIndirectLightingStrength
Indirect lighting intensity, [0, 4].
-
int screenSpaceIndirectLightingSamples
Samples, [4, 24].
-
float screenSpaceIndirectLightingFalloff
Distance falloff exponent factor (>= 0.001).
-
float screenSpaceIndirectLightingNormalRejection
Reject samples whose surface faces away, [0, 1].
-
float screenSpaceIndirectLightingSaturation
Saturation of the gathered light, [0, 4].
Draw ordering and depth prepasses
-
bool opaqueDepthPrepass
Depth-only prepass for opaque geometry (skipped for scenes with 16 or fewer opaque draws).
-
bool frontToBackOpaqueInstancedOrdering
Sort opaque instanced batches front to back.
-
bool foliageAlphaDepthPrepass
Depth prepass for alpha-tested foliage (high-fidelity PBR only).
Depth of field
-
bool depthOfFieldEnabled
Enable depth of field.
-
float depthOfFieldFocusDistance
Focus distance from the camera, metres.
-
float depthOfFieldFocusRange
Width of the fully sharp band around the focus distance, metres.
-
float depthOfFieldMaxRadius
Maximum blur (circle of confusion) radius, pixels.
Texture filtering, anti-aliasing and resolution
-
float textureAnisotropy
Anisotropic filtering level for material textures.
-
float textureMipLodBias
Mip LOD bias for material textures (positive = blurrier).
-
int viewerMsaaSamples
Scene MSAA sample count (forced to 1 for reprojected TAA).
-
bool alphaToCoverage
Enable alpha-to-coverage when the scene renders with MSAA.
-
bool temporalAaEnabled
Enable temporal anti-aliasing.
-
float temporalAaBlend
Legacy method: history weight, [0, 0.95].
-
float temporalAaJitterScale
Scale of the sub-pixel projection jitter; 0 disables jitter.
-
TemporalAaMethod temporalAaMethod
Temporal AA algorithm.
-
float temporalAaCurrentWeight
New sample weight for Reprojected; smaller values accumulate more frames. Must be finite and in [0.02, 1] (setRenderQualitySettings() throws otherwise).
-
float temporalAaSharpness
Bounded output sharpening; the stored linear history stays unsharpened. Must be finite and in [0, 1] (setRenderQualitySettings() throws otherwise).
-
float viewerRenderScale
Viewer render resolution scale, [0.25, 1]; below 1 renders low-res then upscales.
-
ViewerUpscaleFilter viewerUpscaleFilter
Filter used when viewerRenderScale < 1.
Shadow budget, cascades and additional shadows
Additional lights get shadow maps in order of their score, up to shadowedLightBudget - 1. Ranges in brackets are applied by RayraiWindow::setRenderQualitySettings().
-
bool shadowsEnabled
Master switch for shadow rendering.
-
int shadowedLightBudget
Shadowed lights including the main light; budget - 1 additional lights get shadow maps (max 8).
-
PointShadowPolicy pointShadowPolicy
Whether point lights can receive shadow maps.
-
int maxPointShadowLights
Maximum point lights with shadow cubemaps, [0, 8].
-
float additionalShadowResolutionScale
Additional spot/directional/area shadow-map size relative to shadowResolution.
-
float pointShadowResolutionScale
Point-light cube face size relative to shadowResolution.
-
int minAdditionalShadowResolution
Lower bound for additional shadow-map sizes, texels.
-
float shadowSlopeBiasScale
Slope-scaled depth bias, [0, 4].
-
float shadowNormalOffset
Receiver normal offset for shadow lookups, metres, [0, 0.02].
-
int directionalShadowCascadeCount
Directional shadow cascades, [1, 4]; 1 = single shadow map.
-
float directionalShadowCascadeLambda
Split blend, [0, 1]: 0 = uniform, 1 = logarithmic.
-
float directionalShadowCascadeMaxDistance
Shadowed view distance, metres; 0 uses shadowFar.
-
std::array<float, 4> directionalShadowCascadeSplitOverrides
Explicit split distances (metres) between cascades; used only if strictly increasing within range.
-
float additionalShadowBiasScale
Additional (non-point) shadow bias = shadowBias * scale.
-
float additionalShadowStrengthScale
Directional extras: shadowStrength * scale; spot/area/point: used directly as strength, [0, 1].
-
float additionalShadowPcfRadiusScale
Additional shadow PCF radius = shadowPcfRadius * scale.
-
float additionalShadowNormalOffsetScale
Additional shadow normal offset relative to shadowNormalOffset, [0, 4].
-
bool additionalShadowAtlasPlanningEnabled
Pack additional 2D shadow maps into one atlas.
-
int additionalShadowAtlasResolution
Shadow atlas edge length, texels, [512, 16384].
-
int additionalShadowAtlasPadding
Gap between atlas tiles, texels, [0, 16].
-
float pointShadowBiasScale
Point-light shadow bias = shadowBias * scale.
-
float pointShadowFar
Point-light shadow far plane, metres.
-
bool updateShadowsEveryFrame
Re-render shadow maps every frame; otherwise only when the scene, light or camera moves enough.
Additional-light selection
-
int maxAdditionalLightsPerFrame
Additional lights shaded per frame, [0, 16], chosen by influence near the view.
-
float minAdditionalLightInfluence
Additional lights with an influence score at or below this are skipped.
-
float additionalLightContributionThreshold
Opt-in total scene-linear incident-radiance cutoff budget for local additional lights, before the material BRDF and exposure. Zero preserves unlimited lighting exactly. Not a bound on final HDR/specular pixel error. The budget is divided among uploaded lights; fade starts below that share.
Reflection probes and local irradiance
Probe filter sizes are used when a probe is captured with captureFilteredReflectionProbe() without explicit filter settings.
-
int maxReflectionProbesPerSelection
Reflection probes blended per object, [1, 2].
-
float minReflectionProbeWeight
Probes with a weight at or below this are ignored.
-
bool reflectionProbeDebugOverlayEnabled
Show the ImGui reflection-probe debug overlay.
-
bool reflectionProbeFilteringEnabled
Filter captured probes (irradiance, prefiltered specular, BRDF LUT) on the CPU.
-
int reflectionProbeIrradianceResolution
Probe irradiance face size, [0, 128]; 0 skips it.
-
int reflectionProbeIrradianceSamples
Samples per irradiance texel (>= 0).
-
int reflectionProbePrefilteredResolution
Probe prefiltered-specular face size, [0, 512]; 0 skips it.
-
int reflectionProbePrefilteredMipLevels
Prefiltered roughness mip levels (>= 0).
-
int reflectionProbePrefilteredSamples
Samples per prefiltered texel (>= 0).
-
int reflectionProbeBrdfLutSize
Probe BRDF LUT size, [0, 512]; 0 skips it.
-
int reflectionProbeBrdfLutSamples
Samples per BRDF LUT texel (>= 0).
-
float localDiffuseIrradianceIntensity
Intensity of local diffuse irradiance, [0, 4].
-
float localDiffuseIrradianceSaturation
Saturation of local diffuse irradiance, [0, 4].
Imported lights
-
bool autoSelectImportedShadowLight
Promote the dominant imported scene light to the main shadow caster on import.
Transparency and refraction
-
bool sortTransparentInstances
Sort transparent instances back to front.
-
bool weightedBlendedOit
Use weighted blended order-independent transparency (requires MSAA off).
-
bool transparentDepthPrepass
Depth prepass for transparent geometry.
-
bool transparentShadowDithering
Transparent casters write dithered (partial) shadows.
-
float transparentShadowOpacityScale
Opacity multiplier for transparent shadow casters, [0, 4].
-
bool screenSpaceRefraction
Opaque-scene transmission for glass. Resolves MSAA before sampling; HDR is recommended. Does not trace through other transparent layers or exit faces.
-
float screenSpaceRefractionStrength
Refraction offset strength, [0, 1].
-
float screenSpaceRefractionMaxPixels
Maximum refraction offset, pixels, [0, 96].
-
bool geometryRefraction
Opt-in portable triangle tracing. Positive material thickness denotes a closed volume, but distances come from geometry, not the thickness factor.
-
GeometryRefractionBackend geometryRefractionBackend
Automatic tries Vulkan hardware BVH traversal, then falls back to OpenGL. VulkanRayQuery explicitly requires that backend (errors do not silently fall back).
-
int geometryRefractionSamples
Paths per pixel per frame, 1..64.
-
int geometryRefractionMaxBounces
Physical scattering events, 1..128.
-
bool geometryRefractionProgressive
Accumulate samples over frames while the view and scene are unchanged.
-
int geometryRefractionMaxSamples
Per-pixel sample cap for progressive accumulation, [1, 1048576].
-
bool geometryRefractionLowDiscrepancy
Use quasi-Monte-Carlo sample sequences.
-
bool geometryRefractionAdaptive
Stop sampling converged pixels (needs geometryRefractionProgressive).
-
int geometryRefractionMinSamples
Samples before a pixel may stop adaptively, [16, 1048576].
-
float geometryRefractionRelativeError
Adaptive relative error target, [0.02, 1].
-
float geometryRefractionAbsoluteError
Adaptive absolute error target, [0.001, 1e6].
-
int geometryRefractionSeed
Random seed (>= 0).
-
unsigned int geometryRefractionRevision
Increment after editing a texture/environment in place to reset history.
-
bool transparentFogAlphaWeighted
Scale fog on transparent surfaces by their alpha.
-
float transparentFogStrength
Fog amount on transparent surfaces, [0, 1].
Weather materials
Wet and snow material overrides for PBR and foliage shaders. Weather overwrites these fields while it is enabled.
-
bool weatherWetMaterialEnabled
Enable wet-surface shading.
-
float weatherWetness
Wetness, [0, 1].
-
float weatherPuddleStrength
Puddle amount, [0, 1].
-
float weatherRainRippleStrength
Rain ripples in puddles, [0, 1].
-
float weatherRainRippleScale
Ripple pattern scale, [0.1, 128].
-
float weatherRainRipplePhase
Ripple animation phase; advance it to animate.
-
float weatherWetAlbedoDarkening
Albedo darkening when wet, [0, 0.85].
-
float weatherWetRoughnessScale
Roughness multiplier when wet, [0.04, 1].
-
float weatherWetSpecularBoost
Specular boost when wet, [0, 1].
-
bool weatherSnowMaterialEnabled
Enable snow-cover shading.
-
float weatherSnowCoverage
Snow coverage, [0, 1].
-
float weatherSnowAccumulationStrength
Snow accumulation strength, [0, 1].
-
float weatherSnowAlbedoBlend
Blend toward snow albedo, [0, 1].
-
float weatherSnowRoughness
Roughness of snow, [0.04, 1].
-
float weatherSnowMetallicScale
Metallic multiplier under snow, [0, 1].
-
float weatherSnowNormalSoftening
Normal-map softening under snow, [0, 1].
Foliage wind
-
bool foliageWindEnabled
Animate foliage vertices with wind.
-
glm::vec2 foliageWindDirection
Wind direction in world XY (normalized; zero becomes +X).
-
float foliageWindSpeed
Wind speed, [0, 80].
-
float foliageWindTimeSeconds
Wind animation time, seconds; see RayraiWindow::advanceFoliageWindTime().
-
float foliageWindGustStrength
Gust amplitude, [0, 4].
-
float foliageWindGustScale
Gust spatial scale, [0.001, 64].
-
float foliageWindBranchBend
Branch bending amount, [0, 2].
-
float foliageWindLeafFlutter
Leaf flutter amount, [0, 2].
Viewer fill lights
-
bool addViewerFillLights
Add a viewer fill light and a warm rim point light (as additional lights) when settings are applied.
Public Functions
-
inline ShadowsSettings shadows() const
Read a snapshot of the shadows sub-config from the flat fields.
- Returns:
Copy of the main shadow and cascade fields (additional-light shadow fields excluded).
-
inline void setShadows(const ShadowsSettings &s)
Write the shadows sub-config back into the flat fields.
- Parameters:
s – Values to store.
-
inline BloomSettings bloom() const
Read a snapshot of the bloom sub-config from the flat fields.
- Returns:
Copy of the bloom* fields.
-
inline void setBloom(const BloomSettings &b)
Write the bloom sub-config back into the flat fields.
- Parameters:
b – Values to store.
-
inline DepthOfFieldSettings depthOfField() const
Read a snapshot of the depth-of-field sub-config from the flat fields.
- Returns:
Copy of the depthOfField* fields.
-
inline void setDepthOfField(const DepthOfFieldSettings &d)
Write the depth-of-field sub-config back into the flat fields.
- Parameters:
d – Values to store.
-
inline FogSettings fog() const
Read a snapshot of the fog sub-config from the flat fields.
- Returns:
Copy of the distance/height/volumetric fog fields (wind and animation excluded).
-
inline void setFog(const FogSettings &f)
Write the fog sub-config back into the flat fields.
- Parameters:
f – Values to store.
-
inline ToneMappingSettings toneMapping() const
Read a snapshot of the tone-mapping and color sub-config from the flat fields.
- Returns:
Copy of the tone-mapping, auto-exposure and color-grade fields (colorMode excluded).
-
inline void setToneMapping(const ToneMappingSettings &t)
Write the tone-mapping and color sub-config back into the flat fields.
- Parameters:
t – Values to store.
-
inline TemporalAaSettings temporalAa() const
Read a snapshot of the temporal-AA sub-config from the flat fields.
- Returns:
Copy of the temporalAa* fields.
-
inline void setTemporalAa(const TemporalAaSettings &a)
Write the temporal-AA sub-config back into the flat fields.
- Parameters:
a – Values to store.
Public Static Functions
-
static RenderQualitySettings preset(RenderQualityPreset p)
Build a
RenderQualitySettingsfor the given preset.Companion to the existing
RenderQualityPresetenum so the type that names the presets can also produce them. Delegates toRayraiWindow::defaultRenderQualitySettings()(defined in RenderQualityDefaults.cpp). The result is not clamped until it is passed toRayraiWindow::setRenderQualitySettings().- Parameters:
p – Preset to build.
- Returns:
Struct defaults with the preset’s overrides applied.
-
struct ShadowsSettings
Main directional shadow and cascade controls (additional-light shadow fields are not included).
Public Members
-
bool enabled
Mirrors shadowsEnabled.
-
int resolution
Mirrors shadowResolution.
-
float bias
Mirrors shadowBias.
-
float strength
Mirrors shadowStrength.
-
float pcfRadius
Mirrors shadowPcfRadius.
-
bool contactHardening
Mirrors shadowContactHardening.
-
float contactHardeningMinRadius
Mirrors shadowContactHardeningMinRadius.
-
float contactHardeningMaxRadius
Mirrors shadowContactHardeningMaxRadius.
-
float contactHardeningDepthScale
Mirrors shadowContactHardeningDepthScale.
-
float orthoHalfSize
Mirrors shadowOrthoHalfSize.
-
float nearPlane
Mirrors shadowNear.
-
float farPlane
Mirrors shadowFar.
-
float centerOffset
Mirrors shadowCenterOffset.
-
int directionalCascadeCount
Mirrors directionalShadowCascadeCount.
-
float directionalCascadeLambda
Mirrors directionalShadowCascadeLambda.
-
float directionalCascadeMaxDistance
Mirrors directionalShadowCascadeMaxDistance.
-
bool updateEveryFrame
Mirrors updateShadowsEveryFrame.
-
float directionalSoftnessDegrees
Mirrors directionalShadowSoftnessDegrees.
-
float directionalSoftnessMaxRadius
Mirrors directionalShadowSoftnessMaxRadius.
-
bool enabled
-
struct BloomSettings
Bloom / glow controls.
Public Members
-
bool enabled
Mirrors bloomEnabled.
-
float threshold
Mirrors bloomThreshold.
-
float strength
Mirrors bloomStrength.
-
float radius
Mirrors bloomRadius.
-
float knee
Mirrors bloomKnee.
-
int quality
Mirrors bloomQuality.
-
float sourceClamp
Mirrors bloomSourceClamp.
-
float anamorphic
Mirrors bloomAnamorphic.
-
float dirtStrength
Mirrors bloomDirtStrength.
-
float dirtScale
Mirrors bloomDirtScale.
-
unsigned int dirtTexture
Mirrors bloomDirtTexture.
-
GlowBlendMode blendMode
Mirrors bloomBlendMode.
-
float mix
Mirrors bloomMix.
-
bool enabled
-
struct DepthOfFieldSettings
Depth-of-field controls.
-
struct FogSettings
Distance / height / volumetric fog controls.
Public Members
-
float density
Mirrors fogDensity.
-
bool colorOverrideEnabled
Mirrors fogColorOverrideEnabled.
-
glm::vec3 color
Mirrors fogColor.
-
bool heightEnabled
Mirrors heightFogEnabled.
-
float heightDensity
Mirrors heightFogDensity.
-
float heightBaseHeight
Mirrors heightFogBaseHeight.
-
float heightFalloff
Mirrors heightFogFalloff.
-
bool volumetricEnabled
Mirrors volumetricFogEnabled.
-
float volumetricDensity
Mirrors volumetricFogDensity.
-
float volumetricNoiseScale
Mirrors volumetricFogNoiseScale.
-
float volumetricNoiseStrength
Mirrors volumetricFogNoiseStrength.
-
glm::vec3 volumetricColor
Mirrors volumetricFogColor.
-
float volumetricAnisotropy
Mirrors volumetricFogAnisotropy.
-
float density
-
struct ToneMappingSettings
Tone-mapping + color-grade controls.
Public Members
-
bool pbrToneMappingEnabled
Mirrors pbrToneMapping.
-
float exposure
Mirrors pbrExposure (this struct default of 1.0 differs from pbrExposure’s 0.55).
-
bool autoExposureEnabled
Mirrors autoExposureEnabled.
-
float autoExposureKey
Mirrors autoExposureKey.
-
float autoExposureSpeed
Mirrors autoExposureSpeed.
-
float autoExposureMinFactor
Mirrors autoExposureMinFactor.
-
float autoExposureMaxFactor
Mirrors autoExposureMaxFactor.
-
glm::vec3 whiteBalance
Mirrors viewerWhiteBalance.
-
float saturation
Mirrors viewerSaturation.
-
ColorGradePreset gradePreset
Mirrors viewerColorGradePreset.
-
float gradeStrength
Mirrors viewerColorGradeStrength.
-
bool pbrToneMappingEnabled
-
struct TemporalAaSettings
Temporal antialiasing controls.
-
glm::vec4 backgroundColorRgb255
The per-render toggles passed to the external-camera, capture, and timing
APIs are the nested struct raisin::RayraiWindow::RenderOverrides,
documented with raisin::RayraiWindow above.
-
enum class raisin::RenderQualityPreset
Viewer-quality policy presets (
RenderQualitySettings::preset()).These presets affect interactive viewer rendering only. They do not change sensor world-object filtering or make sensor outputs include viewer-only visuals.
Values:
-
enumerator Fast
Simple (non-PBR) shading, texture clouds, no reflective ground.
-
enumerator Balanced
PBR + IBL with ACES tone mapping, texture clouds, reflective ground; no MSAA/SSAO/DoF/TAA.
-
enumerator High
Adds 2x MSAA, volumetric clouds, SSAO, DoF, FXAA, probe filtering, two shadowed lights.
-
enumerator Ultra
High plus 4x MSAA, AgX tone curve, TAA, larger shadow maps and probe filters.
-
enumerator Custom
Struct defaults plus texture clouds; also reported after any manual settings change.
-
enumerator Fast
-
enum class raisin::ViewerColorMode
Tone curve applied when
RenderQualitySettings::pbrToneMappingis enabled.With tone mapping disabled the mode has no effect.
Values:
-
enumerator FastLinear
Currently uses the same fitted ACES curve as AcesApprox.
-
enumerator AcesApprox
Fitted ACES filmic curve.
-
enumerator UnrealPreviewApprox
ACES with slight shadow lift and highlight desaturation.
-
enumerator FilmicApprox
Hejl/Burgess-Dawson style filmic curve.
-
enumerator AgXApprox
AgX-style log curve; hue-preserving and neutral.
-
enumerator FastLinear
-
enum class raisin::ColorGradePreset
ASC-CDL color grade presets applied at the end of the post-process chain.
These are stylistic; Neutral is a no-op. Strength is mixed with the ungraded color via
viewerColorGradeStrength.Values:
-
enumerator Neutral
No grading.
-
enumerator Warm
Warm highlights, slight teal shadows.
-
enumerator Cool
Cyan/blue cast.
-
enumerator Cinematic
Teal shadows, orange highlights.
-
enumerator Bleach
Low saturation, slight green push (bleach bypass).
-
enumerator Neutral
-
enum class raisin::PostProcessDebugMode
Debug views that replace the final post-processed image.
Values:
-
enumerator Final
Normal output.
-
enumerator BloomSource
Thresholded bloom source.
-
enumerator AmbientOcclusion
Denoised ambient occlusion.
-
enumerator AmbientOcclusionRaw
Ambient occlusion before denoising.
-
enumerator FogTransmittance
Fog transmittance.
-
enumerator FogDensity
Volumetric fog density.
-
enumerator FogScattering
Volumetric in-scattering.
-
enumerator WorldNormal
World normal reconstructed from depth.
-
enumerator DepthHeatmap
Linear depth as a heat map.
-
enumerator ScreenSpaceIndirectLighting
Screen-space indirect lighting term.
-
enumerator Final
-
enum class raisin::GeometryRefractionBackend
Tracing backend requested for opt-in geometry refraction (
RenderQualitySettings::geometryRefraction).Automatic: use Vulkan hardware ray queries when available; otherwise (or if they fail) trace in OpenGL.Portable: always use the portable OpenGL tracer.VulkanRayQuery: require Vulkan hardware ray queries; rendering throws instead of falling back.
Values:
-
enumerator Automatic
-
enumerator Portable
-
enumerator VulkanRayQuery
-
struct GeometryRefractionDiagnostics
State of the geometry-refraction tracer after the most recent frame (
RayraiWindow::geometryRefractionDiagnostics()).Public Members
-
size_t triangles
Triangle count of the traced dielectric scene.
-
size_t volumes
Closed dielectric volumes (positive material thickness) in the traced scene.
-
size_t bvhNodes
Node count of the BVH built over the traced triangles.
-
uint64_t sceneBuilds
Number of times the traced dielectric scene was rebuilt.
-
int accumulatedSamples
Scheduled samples per pixel accumulated in the progressive history (reset when the view, scene or settings change). Adaptive pixels can have fewer actual samples.
-
int activeCameraMedia
Number of dielectric media (volumes) that contain the camera position.
-
bool active
True when the tracer rendered the last frame.
-
GeometryRefractionBackend backend
Backend actually used (Portable or VulkanRayQuery).
-
std::string backendStatus
Human-readable backend status or fallback reason.
-
size_t triangles
-
struct GeometryRefractionSamplingStatistics
Per-pixel sample statistics of the geometry-refraction history (
RayraiWindow::geometryRefractionSamplingStatistics()).Without adaptive sampling every pixel holds the scheduled budget, so min/max/mean equal
GeometryRefractionDiagnostics::accumulatedSamplesand no GPU readback happens.Public Members
-
size_t pixels
Pixel count of the trace target.
-
size_t belowBudget
Pixels whose accumulated sample count is below the scheduled budget (adaptive sampling).
-
double meanSamples
Mean accumulated samples per pixel.
-
int minSamples
Smallest per-pixel sample count.
-
int maxSamples
Largest per-pixel sample count.
-
size_t pixels
Weather, scene effects, and reflections
-
struct WeatherSettings
Weather state applied on top of the renderer (
RayraiWindow::setWeatherSettings()).While
enabledis true the window re-derives its effective RenderQualitySettings from the last settings passed tosetRenderQualitySettings()every time weather changes: the main light (sun/moon direction and color), ambient, procedural sky and clouds, environment tints/intensity, exposure, cloud shadows and the wet/snow material fields are overwritten, while fog density, height fog and volumetric fog/lighting are combined with the user values (the larger density wins). Disabling weather restores the user settings.Values are clamped by
setWeatherSettings()(ranges noted per field). Several effects are driven bytimeOfDayHours, so advance it to animate lightning, cloud drift, rain ripples and volumetric fog.Public Members
-
bool enabled
Apply weather to the viewer render.
-
WeatherPreset preset
Preset these values came from (Fog/Snow/Storm also tweak some derived values).
-
WeatherQuality quality
Effect cost tier; see WeatherQuality.
-
uint32_t seed
Seed for precipitation particles and lightning strike placement.
-
float timeOfDayHours
[0, 24]. Local solar hours when the UTC offset is automatic; civil hours otherwise.
-
float latitude
Degrees, [-89.9, 89.9].
-
float longitude
Degrees, [-180, 180].
-
bool automaticUtcOffset
Derive the continuous solar offset as longitude / 15.
-
float utcOffsetHours
Explicit local civil time minus UTC, including DST, [-12, 14].
-
int year
Calendar date used for the solar position, [1900, 2500].
-
int month
Month, [1, 12].
-
int day
Day of month, [1, 31].
-
glm::vec3 windDirection
World-space wind direction (normalized; XY drives cloud and fog drift).
-
float windSpeed
Metres / second, >= 0. Slants precipitation (capped at 20) and drives volumetric fog drift.
-
float transitionSeconds
Seconds, >= 0. Stored and interpolated only; the transition length used is the argument of
RayraiWindow::transitionWeather().
-
bool affectSensors
Also draw weather screen effects in RaiSim RGB/depth sensor renders.
-
float cloudCoverage
Fraction of sky covered, [0, 1].
-
float cloudDensity
Cloud opacity, [0, 1].
-
float precipitationRate
Normalized rain/snow intensity, [0, 1] (presets use 0.45 to 1.0).
-
float rainOcclusionStrength
Shelter factor, [0, 1]: scales precipitation and wetness by (1 - value).
-
float fogDensity
Distance-fog density, 1/m, [0, 1]; combined with the user fogDensity by max() and also raises the height-fog density.
-
float visibilityMeters
Metres, >= 1. Below 5 km enables height fog with density about 3 / visibility.
-
glm::vec3 fogColor
Linear RGB color used for weather height/volumetric fog.
-
float fogAnisotropy
Henyey-Greenstein g for volumetric fog, [-0.85, 0.85].
-
float humidity
Normalized [0, 1]; raises wetness from precipitation and slows drying.
-
float wetness
Base surface wetness, [0, 1].
-
bool wetnessAccumulationEnabled
Accumulate and dry wetness over time in
RayraiWindow::updateWeather().
-
float wetnessAccumulationRate
Fraction of the remaining gap to the wet target closed per second, [0, 4].
-
float wetnessDryingRate
Wetness lost per second when drying (scaled down by humidity), [0, 4].
-
float snowCoverage
Snow cover on surfaces and ground tint, [0, 1]; above 0.2 precipitation renders as snow.
-
float lightningRate
Lightning strikes per minute, [0, 16]; requires High or Ultra quality.
-
bool lightningLocalPointLightEnabled
Add a transient point light near the camera target during a strike.
-
float lightningLocalPointDistance
Distance of that light from the camera target, metres, [2, 250].
-
float lightningLocalPointRadius
Influence radius of that light, metres, [1, 500].
-
float lightningLocalPointIntensity
Peak intensity of that light, [0, 12].
-
float thunderSpeedOfSound
m/s, [250, 420]; thunder delay = lightningLocalPointDistance / speed.
-
float airTurbidity
Atmospheric haze, [1, 12]; higher values give hazier, warmer horizons and sun color.
-
float groundAlbedo
Ground reflectance used for the lower-hemisphere environment tint, [0, 1].
-
bool useExplicitSunAngles
Use the two angles below instead of computing the sun from date, time and location.
-
float sunAzimuthDegrees
Degrees, wrapped to [0, 360). The main light then travels along (cos az * cos el, sin az * cos el, -sin el), azimuth measured from world +X toward +Y.
-
float sunElevationDegrees
Degrees above the horizon, [-8, 89].
-
float sunDiskSize
Angular radius of the drawn sun disk, radians, [0.001, 0.08].
-
float moonDiskSize
Moon disk size in the generated weather sky, [0.001, 0.08].
-
float cloudAltitudeMeters
Volumetric cloud base, metres, [20, 12000]; used only when above 900 m.
-
float cloudThicknessMeters
Volumetric cloud layer thickness, metres, [1, 4000]; used only when above 250 m.
-
float cloudShadowStrength
Cloud shadow darkening, [0, 1]; requires High or Ultra quality.
-
float cloudScale
Cloud noise scale for the sky layer and cloud shadows, [0.01, 2].
-
float cloudAnimationSpeed
Cloud drift: offset = windDirection.xy * timeOfDayHours * speed, [0, 200].
-
bool lensDropletsEnabled
Draw rain droplets on the lens (rain only, High or Ultra quality).
-
float lensDropletStrength
Lens droplet amount, [0, 1].
-
bool enabled
-
enum class raisin::WeatherPreset
Named weather configurations produced by
RayraiWindow::defaultWeatherSettings().Every preset except Custom enables weather at High quality, 13:00 local time (Snow 12:00, Storm 15:00, NightClear 22:00, NightRain 23:00) with wetness accumulation on, and sets cloud, fog, precipitation, wetness, wind and turbidity values for the named look.
Values:
-
enumerator Clear
Almost cloudless, no fog or precipitation.
-
enumerator Overcast
Full grey cloud deck, light fog.
-
enumerator Fog
Dense fog (160 m visibility).
-
enumerator Rain
Moderate rain, wet surfaces.
-
enumerator HeavyRain
Heavy rain, fully wet surfaces, stronger wind.
-
enumerator Snow
Snowfall with snow cover and bright ground albedo.
-
enumerator Storm
Heavy rain with lightning and strong wind.
-
enumerator NightClear
Clear night sky.
-
enumerator NightRain
Rain at night.
-
enumerator Custom
User-defined;
defaultWeatherSettings(Custom)returns weather disabled.
-
enumerator Clear
-
struct LocalFogVolume
Spherical local fog region evaluated in the post-process pass.
Values are sanitized by
RayraiWindow::addLocalFogVolume()(ranges noted per field).Public Members
-
glm::vec3 center
World-space center, metres.
-
float radius
Sphere radius, metres (>= 0.001).
-
glm::vec3 color
Linear RGB fog color (>= 0).
-
float density
Signed density. Positive values add local fog; negative values carve clearer regions from global/local fog in a bounded postprocess approximation. Clamped to [-1, 1].
-
float edgeFade
Fraction of the radius over which density fades out at the rim, [0.001, 0.99].
-
float noiseScale
Spatial frequency of the density noise, [0.001, 128].
-
float noiseStrength
Noise modulation amount, [0, 1]; 0 = uniform density.
-
glm::vec3 center
-
struct ProjectedDecal
Screen-space box decal blended over the opaque scene in the post-process pass.
The decal box is centered at
center, rotated byorientationand sized byhalfExtents(metres). Surfaces inside the box receive the decal. The decal projects along the box’s local +Z axis: the decal UV comes from local X/Y, and surfaces facing away from local +Z are faded out bynormalFade. Values are sanitized byRayraiWindow::addProjectedDecal()(ranges noted per field).Public Members
-
glm::vec3 center
World-space box center, metres.
-
glm::vec3 halfExtents
Box half-size per local axis, metres (abs, >= 0.001).
-
glm::mat3 orientation
Box rotation (columns = local axes); re-orthonormalized on add.
-
glm::vec4 color
Linear RGB tint (clamped to [0, 4]) and opacity in alpha ([0, 1]).
-
float edgeFade
Fraction of the box (in normalized local units) faded at its faces, [0.001, 0.95].
-
float normalFade
Facing fade: opacity ramps in as local-space normal Z goes 0..normalFade, [0.001, 1].
-
float upperFade
Extra fade toward the box’s local +Y face, as a fraction of the half-extent; 0 disables.
-
float lowerFade
Extra fade toward the box’s local -Y face, as a fraction of the half-extent; 0 disables.
-
unsigned int albedoMap
Optional GL 2D texture multiplied with
color; 0 = none.
-
unsigned int emissionMap
Optional GL 2D emission texture added to the decal color; 0 = none.
-
unsigned int normalMap
Optional GL 2D tangent-space normal map (approximate relief shading); 0 = none.
-
unsigned int ormMap
Optional GL 2D occlusion/roughness/metallic texture (R/G/B); 0 = none.
-
glm::vec4 textureUvScaleOffset
UV transform (scale.xy, offset.zw) applied to all decal maps.
-
float albedoMix
Blend from
colortoward albedoMap * color, [0, 1].
-
float emissionEnergy
Multiplier for emissionMap, >= 0.
-
float normalStrength
normalMap intensity, [0, 2].
-
float ormStrength
ormMap influence, [0, 1].
-
bool distanceFadeEnabled
Fade the decal out with camera distance to
center.
-
float distanceFadeBegin
Distance from the camera where the fade starts, metres.
-
float distanceFadeLength
Length of the smooth fade band, metres.
-
glm::vec3 center
-
struct IrradianceVolume
Oriented box that adds a constant diffuse irradiance to PBR surfaces inside it.
Used as a cheap local fill/bounce light: surfaces inside the box receive
color * strength * albedo * ao / piof extra diffuse lighting. Values are sanitized byRayraiWindow::addIrradianceVolume()(ranges noted per field).Public Members
-
glm::vec3 center
World-space box center, metres.
-
glm::vec3 halfExtents
Box half-size per local axis, metres (abs, >= 0.001).
-
glm::mat3 orientation
Box rotation (columns = local axes); re-orthonormalized on add.
-
glm::vec3 color
Linear RGB irradiance color, [0, 8].
-
float strength
Irradiance multiplier, [0, 8].
-
float edgeFade
Fade-in distance from the box faces in normalized local units, [0.001, 1].
-
float normalBias
0 = uniform; 1 = weight by how much the surface normal faces world +Z, [0, 1].
-
glm::vec3 center
-
struct ReflectionProbe
Static local reflection probe registered with
RayraiWindow::addReflectionProbe().Usually produced by
RayraiWindow::captureFilteredReflectionProbe(). A probe takes part in selection only when at least one of its cubemaps is non-zero. Its weight at a point isstrength * (1 - d / radius)(zero beyondradius), orstrength / (1 + d)whenradiusis 0, wheredis the distance toposition, or to the box when box projection is enabled and the box is non-degenerate (sodis 0 inside the box).Public Members
-
glm::vec3 position
Capture position, metres.
-
float radius
Influence radius, metres; 0 = unbounded inverse-distance falloff.
-
unsigned int environmentMap
Radiance cubemap (RGBA8 and mipmapped when captured by rayrai).
-
unsigned int irradianceMap
Filtered diffuse irradiance cubemap; 0 if not filtered.
-
unsigned int prefilteredEnvironmentMap
GGX-prefiltered specular cubemap; 0 if not filtered.
-
unsigned int brdfLut
Split-sum BRDF LUT texture; 0 if not generated.
-
float strength
Weight/intensity multiplier, >= 0.
-
bool boxProjection
Use box-projected (parallax-corrected) lookups and box-distance weighting.
-
glm::vec3 boxMin
Projection box minimum corner, world space, metres.
-
glm::vec3 boxMax
Projection box maximum corner, world space, metres.
-
glm::vec3 position
-
struct ReflectionProbeCaptureSettings
Explicit static reflection-probe capture settings.
Probe capture is never automatic. Applications call captureReflectionProbeCubemap() when they want a bounded real-time local reflection approximation. Custom visuals, instanced visuals, and point clouds are captured only when their draw toggles are enabled and they are marked detectable.
Public Members
-
int resolution
Cubemap face size in texels, clamped to [16, 512]. Faces are RGBA8 without post-processing.
-
bool drawVisualizationObjects
Draw custom visuals and instanced visuals that are marked detectable.
-
bool drawCoordinateFrames
Draw coordinate-frame gizmos into the probe.
-
bool drawPointClouds
Draw point clouds that are marked detectable.
-
bool doShadows
Run shadow passes for the capture.
-
bool includeEnvironmentBackground
Render environmentBackgroundMap behind the scene.
-
unsigned int environmentBackgroundMap
GL cubemap used when includeEnvironmentBackground is true.
-
float environmentBackgroundExposure
Exposure multiplier for environmentBackgroundMap.
-
int resolution
-
struct ReflectionProbeFilterSettings
Explicit CPU filtering settings for captured local reflection probes.
Filtering is a load-time/manual operation run by captureFilteredReflectionProbe(). When no filter settings are passed, they are derived from the
RenderQualitySettings::reflectionProbe*fields, which only the High and Ultra presets enable; otherwise every size is 0 and only the raw cubemap is captured. A zero resolution or sample count skips that output.Public Members
-
int irradianceResolution
Diffuse irradiance cubemap face size, [0, 128]; 0 skips it.
-
int irradianceSamples
Cosine-weighted samples per irradiance texel.
-
int prefilteredResolution
GGX-prefiltered specular cubemap mip-0 face size, [0, 512]; 0 skips it.
-
int prefilteredMipLevels
Roughness mip levels, clamped to the levels the resolution allows.
-
int prefilteredSamples
GGX importance samples per prefiltered texel.
-
int brdfLutSize
Split-sum BRDF LUT edge length, clamped to [16, 512]; 0 skips it.
-
int brdfLutSamples
Samples per BRDF LUT texel.
-
int irradianceResolution
-
struct ReflectionProbeBlend
Result of
RayraiWindow::selectReflectionProbeBlend()for one sample position.Picks the one or two highest-weight probes (count limited by
RenderQualitySettings::maxReflectionProbesPerSelection, probes at or belowminReflectionProbeWeightignored). When only one probe is selected the secondary entries repeat the primary probe with zero weight.Public Members
-
bool valid
False when no probe has a positive weight.
-
size_t primaryIndex
Index of the highest-weight probe.
-
size_t secondaryIndex
Index of the second probe (equals primaryIndex if none).
-
float primaryWeight
Normalized blend weight of the primary probe.
-
float secondaryWeight
Normalized blend weight of the secondary probe; primary + secondary = 1.
-
float strength
Sum of the raw weights, clamped to [0, 1].
-
bool primaryBoxProjection
Primary probe uses box projection.
-
bool secondaryBoxProjection
Secondary probe uses box projection.
-
glm::vec3 primaryProbePosition
Primary probe capture position.
-
glm::vec3 secondaryProbePosition
Secondary probe capture position.
-
glm::vec3 primaryBoxMin
Primary probe box minimum corner.
-
glm::vec3 primaryBoxMax
Primary probe box maximum corner.
-
glm::vec3 secondaryBoxMin
Secondary probe box minimum corner.
-
glm::vec3 secondaryBoxMax
Secondary probe box maximum corner.
-
bool valid
-
struct ReflectionProbePlacementSuggestion
Probe placement suggested from scene bounds (
RayraiWindow::suggestReflectionProbePlacementFromSceneBounds()).The bounds are the union of the bounding spheres of world objects (halfspaces and heightmaps excluded), custom visuals and instanced visuals.
Public Members
-
bool valid
False when no finite, non-degenerate bounds were found.
-
glm::vec3 position
Center of the scene bounds.
-
float radius
Half of the bounds diagonal, metres.
-
bool boxProjection
True when the bounds have non-zero extent on all three axes.
-
glm::vec3 boxMin
Scene bounds minimum corner.
-
glm::vec3 boxMax
Scene bounds maximum corner.
-
size_t boundedObjectCount
Objects and visuals that contributed to the bounds.
-
float boundsDiagonal
Length of the bounds diagonal, metres.
-
bool valid
Render quality, weather, capture, reflection-probe, and diagnostics helpers are
exposed through raisin::RayraiWindow and the public headers included by
rayrai/RayraiWindow.hpp. The sections above document the intended entry
points and the fast-path boundaries for those APIs.
RaiSim integration
-
class RaisimObject
Render state of one raisim::Object, built from physics snapshots.
RaisimObject owns the meshes, colors and world transforms of an object as of the last applied PhysicsObjectSnapshot. It never reads the source raisim::Object, so it stays usable after the object is removed; the snapshot’s object pointer is an identity key only.
Snapshot state
-
inline raisim::Object *sourceObject() const
- Returns:
The source object, as an identity key only; it may no longer exist.
-
inline uint64_t instanceId() const
- Returns:
An id no other RaisimObject in the process had, so a drawable built for another object at the same address is told apart.
-
inline uint64_t renderRevision() const
- Returns:
Revision that advances whenever the drawn state changes.
-
inline glm::vec3 worldPosition() const
- Returns:
World position of the object origin (the plane height for a ground).
-
inline glm::mat3 worldRotation() const
- Returns:
World rotation of the object frame.
Material queries
Internal: renderer pass-selection queries over all cached meshes.
-
bool hasPbrMeshes() const
- Returns:
True when any cached mesh needs the PBR shader.
-
bool hasHighFidelityPbrMeshes() const
- Returns:
True when any PBR mesh requires the high-fidelity PBR path (Material::requiresHighFidelityPbr()).
-
bool hasTransmissivePbrMeshes() const
- Returns:
True when any PBR mesh needs the transmission pass (Material::hasTransmissivePass()).
-
bool hasProximityFadePbrMeshes() const
- Returns:
True when any PBR mesh uses proximity fade (Material::hasProximityFadePass()).
-
bool usesDefaultDepthAndStencilState() const
- Returns:
True when every mesh uses default depth/stencil state (Material::usesDefaultDepthAndStencilState()).
-
bool hasFullPbrMeshes() const
- Returns:
True when any PBR mesh cannot use the compact PBR shader (Material::canUseCompactPbr()).
-
bool hasFoliageFastPbrMeshes() const
- Returns:
True when any mesh can use the foliage fast-PBR path (Material::canUseFoliageFastPbr()).
-
bool hasWeatherEligiblePbrMeshes() const
- Returns:
True when any mesh reacts to active weather (Material::receivesActiveWeather()).
-
bool hasSimpleMeshes() const
- Returns:
True when any mesh uses non-PBR (simple/textured) shading.
-
bool hasPlanarReflectionMeshes() const
- Returns:
True when any PBR mesh enables Material::usePlanarReflection.
-
bool hasTransparentMaterials() const
- Returns:
True when any cached mesh material must be rendered in the transparent pass.
-
bool hasSpecialBlendMode() const
- Returns:
True when any cached mesh uses a blend mode other than Material::BlendMode::Mix.
-
int renderPriority() const
- Returns:
Highest Material::renderPriority across cached meshes (0 if none).
Public Functions
Build the render state of a snapshot object.
Builds or fetches the geometry of every visual (articulated systems get both visual and collision meshes). Primitive and file meshes come from
assetand are shared with other objects; meshes of hidden capsules and mesh files load once the object is shown. Requires a current GL context.- Parameters:
snapshot – Object state, copied; it must have a description.
parent – Owning RayraiWindow (for shared textures and settings).
asset – Asset cache to load primitive/mesh geometry.
-
Changes apply(const PhysicsObjectSnapshot &snapshot)
Advance to a newer snapshot of the same object.
Uploads changed mesh vertices (a vertex delta when the snapshot provides one) and rebuilds meshes whose shapes changed. An unchanged revision costs a comparison. Requires a current GL context.
- Parameters:
snapshot – Object state with the same object identity, copied when it changed.
- Returns:
What changed.
-
void draw(Shader &shader, bool showCollisionBodies, OpenGLMesh::RenderMode mode = OpenGLMesh::RenderMode::All)
Draw the object using the provided shader.
Sets the
shadingType,modelandobjectColoruniforms per mesh; the shader must already be in use. No-op when hidden.- Parameters:
shader – Shader used for rendering.
showCollisionBodies – True to render collision geometry when available (articulated systems only).
mode – Which material passes of each mesh to draw.
-
bool isSelectable() const
Check if this object can be selected in the picker.
- Returns:
True if not hidden, and not a heightmap or ground plane.
-
void configureGroundMaterial(bool reflective, float roughness, float metallic, bool proceduralChecker = false)
Configure ground and heightmap terrain materials. No-op for other objects.
For a ground plane, resets its material and makes it PBR with planar reflection when
reflective, or simple/textured otherwise. For a heightmap, only the window’s terrain overrides are reapplied and the other arguments are ignored.- Parameters:
reflective – Use a reflective PBR ground.
roughness – PBR roughness, clamped to [0.04, 1] (reflective only).
metallic – PBR metallic factor, clamped to [0, 1] (reflective only).
proceduralChecker – Draw a procedural checker instead of the ground texture.
-
void setHidden(bool h)
Hide or show this object in rendering, independent of its appearance.
The object is drawn only while neither this nor a “hidden” appearance hides it.
- Parameters:
h – True to hide.
Check if object is hidden.
- Returns:
True if hidden by setHidden() or by its appearance.
-
inline glm::vec4 getColor() const
Get object color used for rendering.
- Returns:
RGBA color in [0, 1] parsed from the raisim appearance string (0.7 grey by default). A negative alpha on a mesh object means “use the mesh’s own colors”.
-
float approximateRadius(bool showCollisionBodies) const
Conservative bounding radius for coarse culling.
- Parameters:
showCollisionBodies – Measure collision instead of visual geometry.
- Returns:
Radius from approximateBounds(), or 1 when bounds are unavailable.
-
bool shadowGeometryWithinBounds() const
- Returns:
True when shadow depth draws keep every vertex inside approximateBounds(): no material uses billboards, fixed-size scaling or height displacement.
-
bool shadowDepthMayDiscard(bool showCollisionBodies, bool transparentShadowDithering) const
- Returns:
True when a shadow depth draw of this object can discard fragments: a mesh that draw() draws has an alpha-mask material, or an alpha-blend material while
transparentShadowDitheringis set. Deformable surfaces always report true.
-
bool approximateBounds(bool showCollisionBodies, glm::vec3 ¢er, float &radius) const
Conservative world-space bounds for coarse culling.
The center is allowed to differ from the raisim object origin for offset meshes, articulated links, and deformables.
- Parameters:
showCollisionBodies – Measure collision instead of visual geometry.
center – [out] Sphere center in world coordinates.
radius – [out] Sphere radius in metres.
- Returns:
False when the object has no geometry.
-
void cullingBounds(bool showCollisionBodies, glm::vec3 ¢er, float &radius) const
Bounds for coarse culling: approximateBounds(), or a unit sphere at the object origin when the object draws no geometry.
- Parameters:
showCollisionBodies – Measure collision instead of visual geometry.
center – [out] Sphere center in world coordinates.
radius – [out] Sphere radius in metres.
-
bool getPrimitiveBatchData(bool showCollisionBodies, glm::mat4 &model, raisim::Shape::Type &shape, glm::vec4 &color) const
Return transform/color data for simple single-body primitive batching.
- Parameters:
showCollisionBodies – Batching is refused when true.
model – [out] World model matrix including the primitive scale.
shape – [out] Primitive shape (sphere, box, cylinder or capsule).
color – [out] Object color.
- Returns:
True when this object can be drawn by the internal primitive batch path (visible, opaque, single sphere/box/cylinder/capsule).
-
bool getPrimitiveBatchTemplate(bool showCollisionBodies, raisim::Shape::Type &shape, glm::vec3 &scale, glm::vec4 &color) const
Pose-independent part of getPrimitiveBatchData().
- Parameters:
showCollisionBodies – Batching is refused when true.
shape – [out] Primitive shape.
scale – [out] Primitive scale.
color – [out] Object color.
- Returns:
True when this object is batchable.
-
void setDefaultPrimitivePbrEnabled(bool enabled)
Toggle High/Ultra default PBR shading for built-in primitive meshes.
Box/sphere/cylinder meshes come from the shared asset cache, so this changes their material for every object that shares them.
- Parameters:
enabled – True to use the default PBR primitive material.
-
void collectMaterialTextureIds(std::vector<unsigned int> &textureIds) const
Append non-environment material texture ids used by this object’s cached meshes.
- Parameters:
textureIds – [inout] Ids are appended (duplicates are not removed here).
-
void accumulateGeometryDiagnostics(OpenGLMesh::GeometryDiagnostics &diagnostics, float tinyTriangleAreaThreshold) const
Accumulate CPU-side mesh geometry diagnostics for this object.
- Parameters:
diagnostics – [inout] Totals to add to.
tinyTriangleAreaThreshold – Triangles below this area count as tiny.
-
void collectMeshDiagnostics(std::vector<OpenGLMesh::MeshDiagnostics> &diagnostics, float tinyTriangleAreaThreshold) const
Append per-mesh geometry/material diagnostics for this object.
- Parameters:
diagnostics – [inout] One entry is appended per mesh.
tinyTriangleAreaThreshold – Triangles below this area count as tiny.
-
inline size_t debugModelMatrixCacheRebuilds() const
- Returns:
Number of model-matrix rebuilds, for tests and diagnostics.
-
inline const std::vector<std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>>> &debugMeshLists() const
Internal:
- Returns:
The cached mesh lists (tests/diagnostics).
-
inline bool debugHasMeshGeometry() const
Internal:
- Returns:
True when any cached mesh list is non-empty (tests/diagnostics).
-
struct Changes
What apply() changed, for the renderer’s caches.
Public Members
-
bool revision
renderRevision() advanced: the pose, geometry or appearance changed.
-
bool candidate
Draw candidates are stale: appearance, visibility, shapes, body type, or a static pose.
-
bool shadow
Shadow maps are stale beyond what caster-motion tracking sees: visibility, shapes or heightmap vertices.
-
bool revision
-
inline raisim::Object *sourceObject() const