raisin::InstancedVisuals
class · #include <rayrai/Visuals.hpp>
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.
Nested classes
structAsyncFoliageClusterPrepDiagnostics — Internal (diagnostics): state of asynchronous foliage-cluster preparation.structFoliageImpostorDiagnostics — Internal (diagnostics): last foliage-impostor decision.structFoliageWindDiagnostics — Internal (diagnostics): settings from configureFoliageWind().structGpuHizOcclusionConfig — Internal: hierarchical-Z occlusion input for the GPU culling draw() overload.structGrassPatchDiagnostics — Internal (diagnostics): grass-patch settings from configureGrassPatch().structHierarchicalFoliageClusterDiagnostics — Internal (diagnostics): last hierarchical foliage-cluster culling result.structInstanceSpec — One instance for addInstances().structShadowFoliageLodDiagnostics — Internal (diagnostics): last shadow-pass foliage LOD decision.
Constructors & destructor
InstancedVisuals
InstancedVisuals(
raisim::Shape::Type type,
const std::string &name,
const glm::vec3 &size,
const glm::vec4 &color1,
const glm::vec4 &color2,
const std::shared_ptr<RayraiGlobalAsset> &assets,
const std::string &meshFile="")Construct an instanced visual for repeated shapes/meshes.
Automatic mesh LOD is enabled. Primitive meshes are shared through assets.
Parameters
| Parameter | Description |
|---|---|
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. |
InstancedVisuals(
raisim::Shape::Type type,
const std::string &name,
const glm::vec3 &size,
const glm::vec4 &color1,
const glm::vec4 &color2,
const std::shared_ptr<RayraiGlobalAsset> &assets,
const std::string &meshFile,
bool automaticMeshLodEnabled)As above, choosing whether automatic mesh LOD is enabled.
Parameters
| Parameter | Description |
|---|---|
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. |
InstancedVisuals(
const std::string &name,
const glm::vec3 &size,
const glm::vec4 &color1,
const glm::vec4 &color2,
const std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> &meshes)Construct an instanced visual from an already-created mesh list.
Parameters
| Parameter | Description |
|---|---|
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). |
InstancedVisuals(
const std::string &name,
const glm::vec3 &size,
const glm::vec4 &color1,
const glm::vec4 &color2,
const std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>> &meshes,
bool automaticMeshLodEnabled)As above, choosing whether automatic mesh LOD is enabled.
Parameters
| Parameter | Description |
|---|---|
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. |
~InstancedVisuals
~InstancedVisuals()Public member functions
Draw-path diagnostics
Internal: results of the most recent draw, for tests and renderer diagnostics.
usedGpuInstanceCullingForDiagnostics
bool usedGpuInstanceCullingForDiagnostics() constReturns True if GPU instance culling was used.
usedGpuHizOcclusionForDiagnostics
bool usedGpuHizOcclusionForDiagnostics() constReturns True if Hi-Z occlusion culling was used.
lastGpuInstanceCullCandidateCountForDiagnostics
size_t lastGpuInstanceCullCandidateCountForDiagnostics() constReturns Instances submitted to GPU culling.
lastGpuInstanceCullSkipCodeForDiagnostics
uint32_t lastGpuInstanceCullSkipCodeForDiagnostics() constReturns 0, or why GPU culling was skipped.
lastGpuInstanceCullSkipReasonForDiagnostics
const char *lastGpuInstanceCullSkipReasonForDiagnostics() constReturns Text for lastGpuInstanceCullSkipCodeForDiagnostics().
reusedVisibleInstanceFrameCacheForDiagnostics
bool reusedVisibleInstanceFrameCacheForDiagnostics() constReturns True if the visible-instance list was reused from a previous frame.
visibleInstanceFrameCacheFallbackForDiagnostics
bool visibleInstanceFrameCacheFallbackForDiagnostics() constReturns True if the visible-instance cache could not be used.
usedPersistentInstanceSourceBufferForDiagnostics
bool usedPersistentInstanceSourceBufferForDiagnostics() constReturns True if the persistent GPU instance source buffer was used.
persistentInstanceSourceBufferReadyForDiagnostics
bool persistentInstanceSourceBufferReadyForDiagnostics() constReturns True once the persistent GPU instance source buffer has been initialized.
gpuSourceInstanceCapacityForDiagnostics
size_t gpuSourceInstanceCapacityForDiagnostics() constReturns Capacity of the GPU instance source buffer, in instances.
gpuSourceInstanceFullUploadCountForDiagnostics
size_t gpuSourceInstanceFullUploadCountForDiagnostics() constReturns Full uploads of the GPU instance source buffer.
gpuSourceInstanceSubUploadCountForDiagnostics
size_t gpuSourceInstanceSubUploadCountForDiagnostics() constReturns Partial uploads of the GPU instance source buffer.
compactInstanceFullUploadCountForDiagnostics
size_t compactInstanceFullUploadCountForDiagnostics() constReturns Full uploads of the compact instance buffer.
compactInstanceSubUploadCountForDiagnostics
size_t compactInstanceSubUploadCountForDiagnostics() constReturns Partial uploads of the compact instance buffer.
usedMultiDrawIndirectForDiagnostics
bool usedMultiDrawIndirectForDiagnostics() constReturns True if multi-draw-indirect was used.
lastMultiDrawIndirectCommandCountForDiagnostics
size_t lastMultiDrawIndirectCommandCountForDiagnostics() constReturns Indirect commands issued by the last multi-draw.
multiDrawIndirectCommandUploadCountForDiagnostics
size_t multiDrawIndirectCommandUploadCountForDiagnostics() constReturns Uploads of the indirect command buffer.
lastMultiDrawIndirectFallbackCodeForDiagnostics
uint32_t lastMultiDrawIndirectFallbackCodeForDiagnostics() constReturns 0, or why multi-draw-indirect was not used.
lastMultiDrawIndirectFallbackReasonForDiagnostics
const char *lastMultiDrawIndirectFallbackReasonForDiagnostics() constReturns Text for lastMultiDrawIndirectFallbackCodeForDiagnostics().
cloneWithoutInstances
std::shared_ptr<InstancedVisuals> cloneWithoutInstances(const std::string &name) constShare 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
| Parameter | Description |
|---|---|
name | Name of the new batch; must be non-empty. |
Returns The new, empty batch.
Exceptions
| Exception | Description |
|---|---|
std::invalid_argument | if name is empty or this is not a ready mesh batch. |
count
size_t count() constGet number of instances.
Returns Instance count.
getName
const std::string &getName() constReturns Batch name.
clearInstances
void clearInstances()Clear all instances.
resize
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
| Parameter | Description |
|---|---|
count | New instance count. |
reserveInstances
void reserveInstances(size_t capacity)Reserve instance storage without changing the authored instance count.
Parameters
| Parameter | Description |
|---|---|
capacity | Number of instances to reserve room for. |
addInstance
void addInstance(
const glm::vec3 &pos,
const glm::vec4 &ori,
const glm::vec3 &scale,
float colorWeight=0.f)Add a fully specified instance.
Parameters
| Parameter | Description |
|---|---|
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). |
void addInstance(
const glm::vec3 &pos,
const glm::vec4 &ori,
float colorWeight=0.f)Add an instance with default scale (baseScale()).
Parameters
| Parameter | Description |
|---|---|
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
| Parameter | Description |
|---|---|
pos | Position. |
colorWeight | Blend between color1 and color2. |
addInstances
void addInstances(std::span<const InstanceSpec> instances)Add multiple fully specified instances and dirty the batch once.
Parameters
| Parameter | Description |
|---|---|
instances | Instance data to append. |
void addInstances(const InstanceSpec *instances, size_t count)Pointer/count form of addInstances(std::span<const InstanceSpec>).
Parameters
| Parameter | Description |
|---|---|
instances | Array of count instances. |
count | Number of instances to append. |
shapeType
raisim::Shape::Type shapeType() constReturns Shape type of the batch.
setPosition
void setPosition(size_t id, const glm::vec3 &pos)Update position of an instance (ignored for an out-of-range id).
Parameters
| Parameter | Description |
|---|---|
id | Instance index. |
pos | New position. |
setOrientation
void setOrientation(size_t id, const glm::vec4 &ori)Update orientation of an instance.
Parameters
| Parameter | Description |
|---|---|
id | Instance index. |
ori | Orientation quaternion (wxyz). |
setScale
void setScale(size_t id, const glm::vec3 &scale)Update scale of an instance (ignored for an out-of-range id).
Unlike addInstance(), scale is stored as the instance's total scale and is not multiplied by baseScale(); it matches what getScale() returns.
Parameters
| Parameter | Description |
|---|---|
id | Instance index. |
scale | New total scale. |
setColor
void setColor(const glm::vec4 &color1, const glm::vec4 &color2)Update the two base colors used for blending.
Parameters
| Parameter | Description |
|---|---|
color1 | Primary linear RGBA color in [0, 1]. |
color2 | Secondary linear RGBA color in [0, 1]. |
setUseMeshColor
void setUseMeshColor(bool use)Use mesh-authored colors for mesh instances instead of instance colors.
Parameters
| Parameter | Description |
|---|---|
use | True to use mesh colors (Mesh batches only). |
usesMeshColor
bool usesMeshColor() constReturns True when mesh-authored colors are requested.
setDefaultPrimitivePbrEnabled
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
| Parameter | Description |
|---|---|
enabled | True to allow the PBR pass. |
setColorWeight
void setColorWeight(size_t id, float weight)Set per-instance blend weight.
Parameters
| Parameter | Description |
|---|---|
id | Instance index. |
weight | Blend weight (0..1). |
setCategory
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 InstancedVisuals default to VisualCategory::NotDetectable.
Parameters
| Parameter | Description |
|---|---|
category | New render category for the whole instanced batch. |
See also VisualCategory
setDetectable
void setDetectable(bool detectable)Convenience helper for toggling the instanced visual render category.
Parameters
| Parameter | Description |
|---|---|
detectable | True to include this batch in detectable-only capture/detection render passes; false to keep it viewer-only for those passes. |
getPosition
glm::vec3 getPosition(size_t id) constGet instance position.
Parameters
| Parameter | Description |
|---|---|
id | Instance index. |
Returns Position vector, or zero for an out-of-range id.
getOrientation
glm::vec4 getOrientation(size_t id) constGet instance orientation (wxyz).
Parameters
| Parameter | Description |
|---|---|
id | Instance index. |
Returns Quaternion vector, or all zeros for an out-of-range id.
getScale
glm::vec3 getScale(size_t id) constGet instance scale.
Parameters
| Parameter | Description |
|---|---|
id | Instance index. |
Returns Total scale (base scale already applied), or zero for an out-of-range id.
getColorWeight
float getColorWeight(size_t id) constGet per-instance color blend weight.
Parameters
| Parameter | Description |
|---|---|
id | Instance index. |
Returns Weight, or 0 for an out-of-range id.
baseScale
const glm::vec3 &baseScale() constReturns Base scale (the constructor's size) applied by addInstance() and resize().
getColor1
const glm::vec4 &getColor1() constGet primary color.
Returns Primary color.
getColor2
const glm::vec4 &getColor2() constGet secondary color.
Returns Secondary color.
getCategory
VisualCategory getCategory() constGet the render category used by capture/detection filters.
Returns Current category for the whole instanced batch.
isDetectable
bool isDetectable() constCheck whether detectable-only render passes include this batch.
Returns True when the category is VisualCategory::Detectable.
isTransparent
bool isTransparent() constCheck if any color is translucent.
Returns True if either batch color has alpha < 1 or a mesh material needs the transparent pass.
hasSpecialBlendMode
bool hasSpecialBlendMode() constReturns True when at least one mesh uses a blend mode other than Material::BlendMode::Mix.
hasPlanarReflectionMeshes
bool hasPlanarReflectionMeshes() constReturns True when any PBR mesh uses planar reflection.
renderPriority
int renderPriority() constReturns Highest material render priority across the instanced visual's meshes.
setCastsShadows
void setCastsShadows(bool castsShadows)Set whether this instanced visual casts shadows (enabled by default). Foliage materials and grass-patch configuration preserve this setting.
Parameters
| Parameter | Description |
|---|---|
castsShadows | True to render the batch into shadow maps. |
castsShadows
bool castsShadows() constReturns True when this instanced visual should cast shadows.
isValid
bool isValid() constCheck if meshes are valid.
Returns True if valid.
renderRevision
uint64_t renderRevision() constInternal:
Returns Counter bumped on render-affecting changes; used to invalidate frame caches.
approximateBounds
bool approximateBounds(glm::vec3 ¢er, float &radius) constBounding 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
| Parameter | Description |
|---|---|
center (out) | Output center. |
radius (out) | Output radius. |
Returns True if there are instances to bound.
shadowGeometryWithinBounds
bool shadowGeometryWithinBounds() constReturns 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.
approximateAabb
bool approximateAabb(glm::vec3 &minCorner, glm::vec3 &maxCorner) constAxis-aligned box version of approximateBounds() (same per-instance padding).
Parameters
| Parameter | Description |
|---|---|
minCorner (out) | Minimum corner in world coordinates. |
maxCorner (out) | Maximum corner in world coordinates. |
Returns True if there are instances to bound.
sourceMeshLocalAabb
bool sourceMeshLocalAabb(glm::vec3 &minCorner, glm::vec3 &maxCorner) constSource mesh local-space AABB before per-instance transform.
Parameters
| Parameter | Description |
|---|---|
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.
setMaxRenderedInstances
void setMaxRenderedInstances(size_t maxInstances)Cap drawn instances for simple single-threaded LOD. 0 means draw all.
Parameters
| Parameter | Description |
|---|---|
maxInstances | Only the first maxInstances instances are drawn. |
maxRenderedInstances
size_t maxRenderedInstances() constReturns Instance cap (0 = unlimited).
setRenderedInstanceStride
void setRenderedInstanceStride(size_t stride)Set a stride for simple per-camera-independent LOD. 1 draws every instance.
Parameters
| Parameter | Description |
|---|---|
stride | Draw every stride-th instance; 0 is treated as 1. |
renderedInstanceStride
size_t renderedInstanceStride() constReturns User-requested instance stride (>= 1).
setFoliageDistanceFade
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.
Parameters
| Parameter | Description |
|---|---|
start | Camera distance where the fade band starts (m, > 0). |
end | Camera distance where it ends (m, > start). |
fadeIn | True to fade in across the band, false to fade out. |
Exceptions
| Exception | Description |
|---|---|
std::invalid_argument | for non-finite or out-of-order values. |
clearFoliageDistanceFade
void clearFoliageDistanceFade()Disable the distance fade set by setFoliageDistanceFade().
setProjectedLodPolicy
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
| Parameter | Description |
|---|---|
enabled | Enable the policy. |
minProjectedRadiusPixels | Target projected instance radius in pixels (min 0.25). |
maxStride | Largest stride the policy may choose (min 1). |
projectedLodEnabled
bool projectedLodEnabled() constReturns True when projected LOD is enabled.
projectedLodMinRadiusPixels
float projectedLodMinRadiusPixels() constReturns Projected-LOD target radius in pixels.
projectedLodMaxStride
size_t projectedLodMaxStride() constReturns Projected-LOD maximum stride.
setAutomaticMeshLodEnabled
void setAutomaticMeshLodEnabled(bool enabled)Enable automatic mesh LOD generation/selection for instanced mesh visuals.
Parameters
| Parameter | Description |
|---|---|
enabled | True to build (or fetch cached) LODs; false drops them. |
setFoliageMeshLodPixelError
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
| Parameter | Description |
|---|---|
pixelError | Error budget in pixels, in [0, 8]. |
Exceptions
| Exception | Description |
|---|---|
std::invalid_argument | outside [0, 8] or for non-finite values. |
foliageMeshLodPixelError
float foliageMeshLodPixelError() constReturns Foliage LOD pixel-error budget (0 = renderer default).
pollAsyncMeshPreparation
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: once its uploads began in one context, a call with another current gives the staged uploads back (see releaseStagedAsyncMeshUploads()) and throws std::logic_error; a draw there leaves the batch pending instead.
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 deadline passes (at least one per call).
Parameters
| Parameter | Description |
|---|---|
deadline | Time after which no further upload starts. |
Returns True on the call that installs the finished LODs.
hasPendingAsyncMeshPreparation
bool hasPendingAsyncMeshPreparation() constReturns True while automatic LODs are still being prepared (the batch is not drawn).
releaseStagedAsyncMeshUploads
void releaseStagedAsyncMeshUploads()Gives the staging space of the prepared submeshes waiting for upload back, from any context; they stage again, or upload directly, once polled in the batch's context. RayraiWindow calls it when polled in another context.
automaticMeshLodEnabled
bool automaticMeshLodEnabled() constReturns True when automatic mesh LOD is enabled for instanced mesh visuals.
automaticMeshLodLevelCount
size_t automaticMeshLodLevelCount() constReturns Number of available instanced mesh LOD levels including the source mesh.
individualFoliageInstanceUploadCount
size_t individualFoliageInstanceUploadCount() constInternal (diagnostics):
Returns Instance uploads made by the per-instance foliage LOD path.
individualFoliageLodSelectionCount
size_t individualFoliageLodSelectionCount() constInternal (diagnostics):
Returns Number of submesh/pass visibility and LOD classifications (cache misses).
sourceMeshCountForDiagnostics
size_t sourceMeshCountForDiagnostics() constReturns Source mesh count for renderer regressions and diagnostics.
sourceMeshCacheKey
const std::string &sourceMeshCacheKey() constReturns Canonical source mesh cache key, empty for built-in primitive batches.
instanceAttributesBoundForDiagnostics
bool instanceAttributesBoundForDiagnostics() constReturns Whether per-instance vertex attributes are bound to the current mesh VAOs (diagnostics).
setPreparedMeshLods
void setPreparedMeshLods(std::span<const std::shared_ptr<std::vector<std::shared_ptr<OpenGLMesh>>>> levels)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
| Parameter | Description |
|---|---|
levels | Exactly six mesh lists (LOD 1..6). |
Exceptions
| Exception | Description |
|---|---|
std::invalid_argument | if the batch is not a ready mesh batch or a level is invalid. |
preparedMeshLod
const std::vector<std::shared_ptr<OpenGLMesh>> &preparedMeshLod(size_t level) constReady geometry for building static proxies. Shared meshes are immutable; the prototype and its GL context must outlive their use by the caller.
Parameters
| Parameter | Description |
|---|---|
level | LOD level; 0 or an unavailable level returns the source meshes. |
Returns Mesh list of that level.
automaticMeshLodTriangleCount
size_t automaticMeshLodTriangleCount(size_t level) constParameters
| Parameter | Description |
|---|---|
level | LOD level; 0 is the source mesh. |
Returns Triangle count for one instanced mesh LOD level, or 0 for an invalid level.
automaticMeshLodMaxUvClusterSpan
float automaticMeshLodMaxUvClusterSpan(size_t level) constParameters
| Parameter | Description |
|---|---|
level | Generated LOD level (>= 1). |
Returns Largest UV span collapsed into one generated LOD vertex (diagnostics).
selectAutomaticMeshLodLevel
size_t selectAutomaticMeshLodLevel(
const glm::vec3 &viewPos,
float verticalFovDeg,
int viewportHeight) constSelect the instanced mesh LOD level that would be used for a camera.
Parameters
| Parameter | Description |
|---|---|
viewPos | Camera position in world coordinates. |
verticalFovDeg | Camera vertical field of view in degrees. |
viewportHeight | Viewport height in pixels. |
Returns Selected level (0 = source mesh).
configureGrassPatch
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 drawBudget and enables projected LOD, shadow foliage LOD and hierarchical cluster culling with fixed defaults. Width, depth, density and seed are recorded for diagnostics only.
Parameters
| Parameter | Description |
|---|---|
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). |
configureFoliageWind
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
| Parameter | Description |
|---|---|
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). |
setShadowFoliageLodPolicy
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
| Parameter | Description |
|---|---|
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. |
shadowFoliageLodPolicyEnabled
bool shadowFoliageLodPolicyEnabled() constReturns True when the shadow foliage LOD policy is enabled.
setFoliageImpostorPolicy
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
| Parameter | Description |
|---|---|
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). |
foliageImpostorPolicyEnabled
bool foliageImpostorPolicyEnabled() constReturns True when the foliage impostor policy is enabled.
setHierarchicalFoliageClustersPolicy
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
| Parameter | Description |
|---|---|
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]. |
hierarchicalFoliageClustersEnabled
bool hierarchicalFoliageClustersEnabled() constReturns True when hierarchical cluster culling is enabled.
hasFoliageShadowLodMaterialForDiagnostics
bool hasFoliageShadowLodMaterialForDiagnostics() constInternal:
Returns True when the batch is treated as foliage for shadow LOD (wind/grass configured or foliage-like materials).
supportsBasicFoliageShadowTransform
bool supportsBasicFoliageShadowTransform() constReturns True when every possible shadow mesh uses ordinary instance transforms.
supportsFoliageColorBatch
bool supportsFoliageColorBatch() constInternal:
Returns True when the batch can join the renderer's batched foliage color draw.
hasDepthWritingMaterial
bool hasDepthWritingMaterial() constReturns Whether a draw can override a surrounding pass's disabled depth writes.
usesDefaultDepthAndStencilState
bool usesDefaultDepthAndStencilState() constReturns True when every mesh material uses default depth/stencil state.
hasAlphaMaskedFoliageMaterialForDiagnostics
bool hasAlphaMaskedFoliageMaterialForDiagnostics() constInternal (diagnostics):
Returns True when any mesh (source, LOD or impostor) uses an alpha-masked material.
grassPatchDiagnostics
const GrassPatchDiagnostics &grassPatchDiagnostics() constInternal (diagnostics):
Returns Grass-patch settings.
foliageWindDiagnostics
const FoliageWindDiagnostics &foliageWindDiagnostics() constInternal (diagnostics):
Returns Foliage wind settings.
shadowFoliageLodDiagnostics
const ShadowFoliageLodDiagnostics &shadowFoliageLodDiagnostics() constInternal (diagnostics):
Returns Last shadow foliage LOD decision.
lastShadowFoliageLodFallbackReasonForDiagnostics
const char *lastShadowFoliageLodFallbackReasonForDiagnostics() constInternal (diagnostics):
Returns Text for ShadowFoliageLodDiagnostics::fallbackCode.
foliageImpostorDiagnostics
const FoliageImpostorDiagnostics &foliageImpostorDiagnostics() constInternal (diagnostics):
Returns Last foliage impostor decision.
lastFoliageImpostorFallbackReasonForDiagnostics
const char *lastFoliageImpostorFallbackReasonForDiagnostics() constInternal (diagnostics):
Returns Text for FoliageImpostorDiagnostics::fallbackCode.
hierarchicalFoliageClusterDiagnostics
const HierarchicalFoliageClusterDiagnostics &hierarchicalFoliageClusterDiagnostics() constInternal (diagnostics):
Returns Last cluster culling result.
lastHierarchicalFoliageClusterFallbackReasonForDiagnostics
const char *lastHierarchicalFoliageClusterFallbackReasonForDiagnostics() constInternal (diagnostics):
Returns Text for HierarchicalFoliageClusterDiagnostics::fallbackCode.
requestAsyncFoliageClusterPreparation
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.
pollAsyncFoliageClusterPreparation
bool pollAsyncFoliageClusterPreparation()Non-blocking check for a finished worker build.
Returns True when a result was installed by this call.
asyncFoliageClusterPrepDiagnostics
const AsyncFoliageClusterPrepDiagnostics &asyncFoliageClusterPrepDiagnostics() constInternal (diagnostics):
Returns Asynchronous cluster preparation state.
setDoubleBufferedInstanceUploads
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
| Parameter | Description |
|---|---|
enabled | True to alternate between two instance buffers. |
setSortTransparentInstances
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
| Parameter | Description |
|---|---|
enabled | True to let the renderer call sortInstancesBackToFront() for this batch. |
sortsTransparentInstances
bool sortsTransparentInstances() constReturns True when transparent instance sorting is enabled.
sortInstancesBackToFront
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
| Parameter | Description |
|---|---|
viewPos | Camera position in world coordinates. |
applyTextureFilteringQuality
size_t applyTextureFilteringQuality(
float anisotropy,
float mipLodBias) constApply sampler quality to all 2D material textures in the instanced mesh.
Modifies the shared GL texture objects.
Parameters
| Parameter | Description |
|---|---|
anisotropy | Requested anisotropic filtering level. |
mipLodBias | Mip LOD bias. |
Returns Number of texture ids updated (summed per mesh).
collectMaterialTextureIds
void collectMaterialTextureIds(std::vector<unsigned int> &textureIds) constAppend non-environment material texture ids used by this instanced visual.
Parameters
| Parameter | Description |
|---|---|
textureIds (in, out) | Ids are appended (duplicates are kept). |
accumulateGeometryDiagnostics
void accumulateGeometryDiagnostics(
OpenGLMesh::GeometryDiagnostics &diagnostics,
float tinyTriangleAreaThreshold) constAccumulate CPU-side mesh geometry diagnostics for this instanced visual.
Parameters
| Parameter | Description |
|---|---|
diagnostics (in, out) | Totals to add to. |
tinyTriangleAreaThreshold | Triangles with smaller (non-zero) area count as tiny. |
collectMeshDiagnostics
void collectMeshDiagnostics(
std::vector<OpenGLMesh::MeshDiagnostics> &diagnostics,
float tinyTriangleAreaThreshold) constAppend per-mesh geometry/material diagnostics for this instanced visual.
Parameters
| Parameter | Description |
|---|---|
diagnostics (in, out) | One entry is appended per source mesh. |
tinyTriangleAreaThreshold | Triangles with smaller (non-zero) area count as tiny. |
draw
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
| Parameter | Description |
|---|---|
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.
Parameters
| Parameter | Description |
|---|---|
shader | Instanced shader that is already in use. |
viewPos | Camera position in world coordinates. |
verticalFovDeg | Camera vertical field of view in degrees. |
viewportHeight | Viewport height in pixels (<= 0 disables 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
| Parameter | Description |
|---|---|
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
| Parameter | Description |
|---|---|
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. |
drawShadow
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
| Parameter | Description |
|---|---|
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. |
drawLinearDepth
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
| Parameter | Description |
|---|---|
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. |
instanceDataGeneration
uint64_t instanceDataGeneration() constInternal:
Returns Counter bumped whenever instance data changes (cache key).
occlusionCandidatesPossible
bool occlusionCandidatesPossible() constInternal: whether addOcclusionCandidates() can add this batch: its draws take the bounds-culled path with enough geometry, before any frustum test.
addOcclusionCandidates
void addOcclusionCandidates(rayrai_internal::InstancedOcclusion &occlusion)Internal: adds the instances a colour or transparent draw for occlusion's camera would draw to its GPU depth-tile test, when this batch draws them through the bounds-culled path.