Skip to content

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 ​

Constructors & destructor ​

InstancedVisuals ​

cpp
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

ParameterDescription
typeShape type to instance.
nameVisual name.
sizeBase scale of every instance (for primitives: sphere radius, full box lengths, or cylinder/capsule (radius, radius, height)).
color1Primary linear RGBA color in [0, 1] (color weight 0).
color2Secondary linear RGBA color in [0, 1] (color weight 1).
assetsGlobal asset cache for primitive meshes.
meshFileMesh file path when type is Mesh.
cpp
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

ParameterDescription
typeShape type to instance.
nameVisual name.
sizeBase scale of every instance.
color1Primary linear RGBA color.
color2Secondary linear RGBA color.
assetsGlobal asset cache for primitive meshes.
meshFileMesh file path when type is Mesh.
automaticMeshLodEnabledGenerate and use automatic mesh LODs.
cpp
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

ParameterDescription
nameVisual name.
sizeBase scale of every instance.
color1Primary linear RGBA color.
color2Secondary linear RGBA color.
meshesMesh list (shared, not copied).
cpp
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

ParameterDescription
nameVisual name.
sizeBase scale of every instance.
color1Primary linear RGBA color.
color2Secondary linear RGBA color.
meshesMesh list (shared, not copied).
automaticMeshLodEnabledGenerate and use automatic mesh LODs.

~InstancedVisuals ​

cpp
~InstancedVisuals()

Public member functions ​

Draw-path diagnostics

Internal: results of the most recent draw, for tests and renderer diagnostics.

usedGpuInstanceCullingForDiagnostics ​

cpp
bool usedGpuInstanceCullingForDiagnostics() const

Returns True if GPU instance culling was used.

usedGpuHizOcclusionForDiagnostics ​

cpp
bool usedGpuHizOcclusionForDiagnostics() const

Returns True if Hi-Z occlusion culling was used.

lastGpuInstanceCullCandidateCountForDiagnostics ​

cpp
size_t lastGpuInstanceCullCandidateCountForDiagnostics() const

Returns Instances submitted to GPU culling.

lastGpuInstanceCullSkipCodeForDiagnostics ​

cpp
uint32_t lastGpuInstanceCullSkipCodeForDiagnostics() const

Returns 0, or why GPU culling was skipped.

lastGpuInstanceCullSkipReasonForDiagnostics ​

cpp
const char *lastGpuInstanceCullSkipReasonForDiagnostics() const

Returns Text for lastGpuInstanceCullSkipCodeForDiagnostics().

reusedVisibleInstanceFrameCacheForDiagnostics ​

cpp
bool reusedVisibleInstanceFrameCacheForDiagnostics() const

Returns True if the visible-instance list was reused from a previous frame.

visibleInstanceFrameCacheFallbackForDiagnostics ​

cpp
bool visibleInstanceFrameCacheFallbackForDiagnostics() const

Returns True if the visible-instance cache could not be used.

usedPersistentInstanceSourceBufferForDiagnostics ​

cpp
bool usedPersistentInstanceSourceBufferForDiagnostics() const

Returns True if the persistent GPU instance source buffer was used.

persistentInstanceSourceBufferReadyForDiagnostics ​

cpp
bool persistentInstanceSourceBufferReadyForDiagnostics() const

Returns True once the persistent GPU instance source buffer has been initialized.

gpuSourceInstanceCapacityForDiagnostics ​

cpp
size_t gpuSourceInstanceCapacityForDiagnostics() const

Returns Capacity of the GPU instance source buffer, in instances.

gpuSourceInstanceFullUploadCountForDiagnostics ​

cpp
size_t gpuSourceInstanceFullUploadCountForDiagnostics() const

Returns Full uploads of the GPU instance source buffer.

gpuSourceInstanceSubUploadCountForDiagnostics ​

cpp
size_t gpuSourceInstanceSubUploadCountForDiagnostics() const

Returns Partial uploads of the GPU instance source buffer.

compactInstanceFullUploadCountForDiagnostics ​

cpp
size_t compactInstanceFullUploadCountForDiagnostics() const

Returns Full uploads of the compact instance buffer.

compactInstanceSubUploadCountForDiagnostics ​

cpp
size_t compactInstanceSubUploadCountForDiagnostics() const

Returns Partial uploads of the compact instance buffer.

usedMultiDrawIndirectForDiagnostics ​

cpp
bool usedMultiDrawIndirectForDiagnostics() const

Returns True if multi-draw-indirect was used.

lastMultiDrawIndirectCommandCountForDiagnostics ​

cpp
size_t lastMultiDrawIndirectCommandCountForDiagnostics() const

Returns Indirect commands issued by the last multi-draw.

multiDrawIndirectCommandUploadCountForDiagnostics ​

cpp
size_t multiDrawIndirectCommandUploadCountForDiagnostics() const

Returns Uploads of the indirect command buffer.

lastMultiDrawIndirectFallbackCodeForDiagnostics ​

cpp
uint32_t lastMultiDrawIndirectFallbackCodeForDiagnostics() const

Returns 0, or why multi-draw-indirect was not used.

lastMultiDrawIndirectFallbackReasonForDiagnostics ​

cpp
const char *lastMultiDrawIndirectFallbackReasonForDiagnostics() const

Returns Text for lastMultiDrawIndirectFallbackCodeForDiagnostics().

cloneWithoutInstances ​

cpp
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

ParameterDescription
nameName of the new batch; must be non-empty.

Returns The new, empty batch.

Exceptions

ExceptionDescription
std::invalid_argumentif name is empty or this is not a ready mesh batch.

count ​

cpp
size_t count() const

Get number of instances.

Returns Instance count.

getName ​

cpp
const std::string &getName() const

Returns Batch name.

clearInstances ​

cpp
void clearInstances()

Clear all instances.

resize ​

cpp
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

ParameterDescription
countNew instance count.

reserveInstances ​

cpp
void reserveInstances(size_t capacity)

Reserve instance storage without changing the authored instance count.

Parameters

ParameterDescription
capacityNumber of instances to reserve room for.

addInstance ​

cpp
void addInstance(
    const glm::vec3 &pos,
    const glm::vec4 &ori,
    const glm::vec3 &scale,
    float colorWeight=0.f)

Add a fully specified instance.

Parameters

ParameterDescription
posPosition in world coordinates (m).
oriOrientation quaternion (wxyz): ori.x is w and ori.w is z.
scalePer-instance scale, multiplied by baseScale().
colorWeightBlend between color1 (0) and color2 (1).
cpp
void addInstance(
    const glm::vec3 &pos,
    const glm::vec4 &ori,
    float colorWeight=0.f)

Add an instance with default scale (baseScale()).

Parameters

ParameterDescription
posPosition.
oriOrientation quaternion (wxyz).
colorWeightBlend between color1 and color2.
cpp
void addInstance(const glm::vec3 &pos, float colorWeight=0.f)

Add an instance at position with identity orientation and baseScale().

Parameters

ParameterDescription
posPosition.
colorWeightBlend between color1 and color2.

addInstances ​

cpp
void addInstances(std::span<const InstanceSpec> instances)

Add multiple fully specified instances and dirty the batch once.

Parameters

ParameterDescription
instancesInstance data to append.
cpp
void addInstances(const InstanceSpec *instances, size_t count)

Pointer/count form of addInstances(std::span<const InstanceSpec>).

Parameters

ParameterDescription
instancesArray of count instances.
countNumber of instances to append.

shapeType ​

cpp
raisim::Shape::Type shapeType() const

Returns Shape type of the batch.

setPosition ​

cpp
void setPosition(size_t id, const glm::vec3 &pos)

Update position of an instance (ignored for an out-of-range id).

Parameters

ParameterDescription
idInstance index.
posNew position.

setOrientation ​

cpp
void setOrientation(size_t id, const glm::vec4 &ori)

Update orientation of an instance.

Parameters

ParameterDescription
idInstance index.
oriOrientation quaternion (wxyz).

setScale ​

cpp
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

ParameterDescription
idInstance index.
scaleNew total scale.

setColor ​

cpp
void setColor(const glm::vec4 &color1, const glm::vec4 &color2)

Update the two base colors used for blending.

Parameters

ParameterDescription
color1Primary linear RGBA color in [0, 1].
color2Secondary linear RGBA color in [0, 1].

setUseMeshColor ​

cpp
void setUseMeshColor(bool use)

Use mesh-authored colors for mesh instances instead of instance colors.

Parameters

ParameterDescription
useTrue to use mesh colors (Mesh batches only).

usesMeshColor ​

cpp
bool usesMeshColor() const

Returns True when mesh-authored colors are requested.

setDefaultPrimitivePbrEnabled ​

cpp
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

ParameterDescription
enabledTrue to allow the PBR pass.

setColorWeight ​

cpp
void setColorWeight(size_t id, float weight)

Set per-instance blend weight.

Parameters

ParameterDescription
idInstance index.
weightBlend weight (0..1).

setCategory ​

cpp
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

ParameterDescription
categoryNew render category for the whole instanced batch.

See also VisualCategory

setDetectable ​

cpp
void setDetectable(bool detectable)

Convenience helper for toggling the instanced visual render category.

Parameters

ParameterDescription
detectableTrue to include this batch in detectable-only capture/detection render passes; false to keep it viewer-only for those passes.

getPosition ​

cpp
glm::vec3 getPosition(size_t id) const

Get instance position.

Parameters

ParameterDescription
idInstance index.

Returns Position vector, or zero for an out-of-range id.

getOrientation ​

cpp
glm::vec4 getOrientation(size_t id) const

Get instance orientation (wxyz).

Parameters

ParameterDescription
idInstance index.

Returns Quaternion vector, or all zeros for an out-of-range id.

getScale ​

cpp
glm::vec3 getScale(size_t id) const

Get instance scale.

Parameters

ParameterDescription
idInstance index.

Returns Total scale (base scale already applied), or zero for an out-of-range id.

getColorWeight ​

cpp
float getColorWeight(size_t id) const

Get per-instance color blend weight.

Parameters

ParameterDescription
idInstance index.

Returns Weight, or 0 for an out-of-range id.

baseScale ​

cpp
const glm::vec3 &baseScale() const

Returns Base scale (the constructor's size) applied by addInstance() and resize().

getColor1 ​

cpp
const glm::vec4 &getColor1() const

Get primary color.

Returns Primary color.

getColor2 ​

cpp
const glm::vec4 &getColor2() const

Get secondary color.

Returns Secondary color.

getCategory ​

cpp
VisualCategory getCategory() const

Get the render category used by capture/detection filters.

Returns Current category for the whole instanced batch.

isDetectable ​

cpp
bool isDetectable() const

Check whether detectable-only render passes include this batch.

Returns True when the category is VisualCategory::Detectable.

isTransparent ​

cpp
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.

hasSpecialBlendMode ​

cpp
bool hasSpecialBlendMode() const

Returns True when at least one mesh uses a blend mode other than Material::BlendMode::Mix.

hasPlanarReflectionMeshes ​

cpp
bool hasPlanarReflectionMeshes() const

Returns True when any PBR mesh uses planar reflection.

renderPriority ​

cpp
int renderPriority() const

Returns Highest material render priority across the instanced visual's meshes.

setCastsShadows ​

cpp
void setCastsShadows(bool castsShadows)

Set whether this instanced visual casts shadows (enabled by default). Foliage materials and grass-patch configuration preserve this setting.

Parameters

ParameterDescription
castsShadowsTrue to render the batch into shadow maps.

castsShadows ​

cpp
bool castsShadows() const

Returns True when this instanced visual should cast shadows.

isValid ​

cpp
bool isValid() const

Check if meshes are valid.

Returns True if valid.

renderRevision ​

cpp
uint64_t renderRevision() const

Internal:

Returns Counter bumped on render-affecting changes; used to invalidate frame caches.

approximateBounds ​

cpp
bool approximateBounds(glm::vec3 &center, 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

ParameterDescription
center (out)Output center.
radius (out)Output radius.

Returns True if there are instances to bound.

shadowGeometryWithinBounds ​

cpp
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.

approximateAabb ​

cpp
bool approximateAabb(glm::vec3 &minCorner, glm::vec3 &maxCorner) const

Axis-aligned box version of approximateBounds() (same per-instance padding).

Parameters

ParameterDescription
minCorner (out)Minimum corner in world coordinates.
maxCorner (out)Maximum corner in world coordinates.

Returns True if there are instances to bound.

sourceMeshLocalAabb ​

cpp
bool sourceMeshLocalAabb(glm::vec3 &minCorner, glm::vec3 &maxCorner) const

Source mesh local-space AABB before per-instance transform.

Parameters

ParameterDescription
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 ​

cpp
void setMaxRenderedInstances(size_t maxInstances)

Cap drawn instances for simple single-threaded LOD. 0 means draw all.

Parameters

ParameterDescription
maxInstancesOnly the first maxInstances instances are drawn.

maxRenderedInstances ​

cpp
size_t maxRenderedInstances() const

Returns Instance cap (0 = unlimited).

setRenderedInstanceStride ​

cpp
void setRenderedInstanceStride(size_t stride)

Set a stride for simple per-camera-independent LOD. 1 draws every instance.

Parameters

ParameterDescription
strideDraw every stride-th instance; 0 is treated as 1.

renderedInstanceStride ​

cpp
size_t renderedInstanceStride() const

Returns User-requested instance stride (>= 1).

setFoliageDistanceFade ​

cpp
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

ParameterDescription
startCamera distance where the fade band starts (m, > 0).
endCamera distance where it ends (m, > start).
fadeInTrue to fade in across the band, false to fade out.

Exceptions

ExceptionDescription
std::invalid_argumentfor non-finite or out-of-order values.

clearFoliageDistanceFade ​

cpp
void clearFoliageDistanceFade()

Disable the distance fade set by setFoliageDistanceFade().

setProjectedLodPolicy ​

cpp
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

ParameterDescription
enabledEnable the policy.
minProjectedRadiusPixelsTarget projected instance radius in pixels (min 0.25).
maxStrideLargest stride the policy may choose (min 1).

projectedLodEnabled ​

cpp
bool projectedLodEnabled() const

Returns True when projected LOD is enabled.

projectedLodMinRadiusPixels ​

cpp
float projectedLodMinRadiusPixels() const

Returns Projected-LOD target radius in pixels.

projectedLodMaxStride ​

cpp
size_t projectedLodMaxStride() const

Returns Projected-LOD maximum stride.

setAutomaticMeshLodEnabled ​

cpp
void setAutomaticMeshLodEnabled(bool enabled)

Enable automatic mesh LOD generation/selection for instanced mesh visuals.

Parameters

ParameterDescription
enabledTrue to build (or fetch cached) LODs; false drops them.

setFoliageMeshLodPixelError ​

cpp
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

ParameterDescription
pixelErrorError budget in pixels, in [0, 8].

Exceptions

ExceptionDescription
std::invalid_argumentoutside [0, 8] or for non-finite values.

foliageMeshLodPixelError ​

cpp
float foliageMeshLodPixelError() const

Returns Foliage LOD pixel-error budget (0 = renderer default).

pollAsyncMeshPreparation ​

cpp
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.

cpp
bool pollAsyncMeshPreparation(std::chrono::steady_clock::time_point deadline)

Like pollAsyncMeshPreparation(), but uploads prepared submeshes until deadline passes (at least one per call).

Parameters

ParameterDescription
deadlineTime after which no further upload starts.

Returns True on the call that installs the finished LODs.

hasPendingAsyncMeshPreparation ​

cpp
bool hasPendingAsyncMeshPreparation() const

Returns True while automatic LODs are still being prepared (the batch is not drawn).

releaseStagedAsyncMeshUploads ​

cpp
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 ​

cpp
bool automaticMeshLodEnabled() const

Returns True when automatic mesh LOD is enabled for instanced mesh visuals.

automaticMeshLodLevelCount ​

cpp
size_t automaticMeshLodLevelCount() const

Returns Number of available instanced mesh LOD levels including the source mesh.

individualFoliageInstanceUploadCount ​

cpp
size_t individualFoliageInstanceUploadCount() const

Internal (diagnostics):

Returns Instance uploads made by the per-instance foliage LOD path.

individualFoliageLodSelectionCount ​

cpp
size_t individualFoliageLodSelectionCount() const

Internal (diagnostics):

Returns Number of submesh/pass visibility and LOD classifications (cache misses).

sourceMeshCountForDiagnostics ​

cpp
size_t sourceMeshCountForDiagnostics() const

Returns Source mesh count for renderer regressions and diagnostics.

sourceMeshCacheKey ​

cpp
const std::string &sourceMeshCacheKey() const

Returns Canonical source mesh cache key, empty for built-in primitive batches.

instanceAttributesBoundForDiagnostics ​

cpp
bool instanceAttributesBoundForDiagnostics() const

Returns Whether per-instance vertex attributes are bound to the current mesh VAOs (diagnostics).

setPreparedMeshLods ​

cpp
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

ParameterDescription
levelsExactly six mesh lists (LOD 1..6).

Exceptions

ExceptionDescription
std::invalid_argumentif the batch is not a ready mesh batch or a level is invalid.

preparedMeshLod ​

cpp
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

ParameterDescription
levelLOD level; 0 or an unavailable level returns the source meshes.

Returns Mesh list of that level.

automaticMeshLodTriangleCount ​

cpp
size_t automaticMeshLodTriangleCount(size_t level) const

Parameters

ParameterDescription
levelLOD level; 0 is the source mesh.

Returns Triangle count for one instanced mesh LOD level, or 0 for an invalid level.

automaticMeshLodMaxUvClusterSpan ​

cpp
float automaticMeshLodMaxUvClusterSpan(size_t level) const

Parameters

ParameterDescription
levelGenerated LOD level (>= 1).

Returns Largest UV span collapsed into one generated LOD vertex (diagnostics).

selectAutomaticMeshLodLevel ​

cpp
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.

Parameters

ParameterDescription
viewPosCamera position in world coordinates.
verticalFovDegCamera vertical field of view in degrees.
viewportHeightViewport height in pixels.

Returns Selected level (0 = source mesh).

configureGrassPatch ​

cpp
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

ParameterDescription
patchWidthPatch width (m).
patchDepthPatch depth (m).
densityPerSquareMeterBlade density.
drawBudgetMaximum drawn instances (0 = unlimited).
maxDrawDistanceView depth at which blades have faded out (m); 0 = no limit.
lodFadeStartDistanceView depth where blades start fading (m).
lodFadeEndDistanceView depth where that fade ends (m).
seedScatter seed (metadata).
bladeRootHeightLocal height below which blades do not bend.
bladeTipHeightLocal height of full bend.
windStrengthWind bend strength (>= 0).
stiffnessBend stiffness, clamped to [0, 1].
flutterWeightHigh-frequency flutter weight (>= 0).

configureFoliageWind ​

cpp
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

ParameterDescription
rootHeightLocal height below which geometry does not bend.
tipHeightLocal height of full bend.
windStrengthWind bend strength (>= 0).
stiffnessBend stiffness, clamped to [0, 1].
flutterWeightHigh-frequency flutter weight (>= 0).

setShadowFoliageLodPolicy ​

cpp
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

ParameterDescription
enabledEnable the policy.
minProjectedRadiusPixelsTarget projected instance radius in pixels (min 0.25).
maxStrideLargest shadow stride (min 1).
maxShadowDistanceSkip the batch in shadow passes when its nearest point is farther from the camera than this (m); 0 = no limit.

shadowFoliageLodPolicyEnabled ​

cpp
bool shadowFoliageLodPolicyEnabled() const

Returns True when the shadow foliage LOD policy is enabled.

setFoliageImpostorPolicy ​

cpp
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

ParameterDescription
enabledEnable the policy.
maxProjectedRadiusPixelsSwitch to impostors below this projected radius (min 0.05).
minInstanceCountOnly batches with at least this many instances qualify (min 1).

foliageImpostorPolicyEnabled ​

cpp
bool foliageImpostorPolicyEnabled() const

Returns True when the foliage impostor policy is enabled.

setHierarchicalFoliageClustersPolicy ​

cpp
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

ParameterDescription
enabledEnable the policy.
leafTargetInstancesTarget instances per leaf, clamped to [8, 1024].
minInstanceCountOnly batches with at least this many instances qualify (min 1).
minRejectionRatioMinimum culled fraction for the cluster path to be used, clamped to [0, 0.95].

hierarchicalFoliageClustersEnabled ​

cpp
bool hierarchicalFoliageClustersEnabled() const

Returns True when hierarchical cluster culling is enabled.

hasFoliageShadowLodMaterialForDiagnostics ​

cpp
bool hasFoliageShadowLodMaterialForDiagnostics() const

Internal:

Returns True when the batch is treated as foliage for shadow LOD (wind/grass configured or foliage-like materials).

supportsBasicFoliageShadowTransform ​

cpp
bool supportsBasicFoliageShadowTransform() const

Returns True when every possible shadow mesh uses ordinary instance transforms.

supportsFoliageColorBatch ​

cpp
bool supportsFoliageColorBatch() const

Internal:

Returns True when the batch can join the renderer's batched foliage color draw.

hasDepthWritingMaterial ​

cpp
bool hasDepthWritingMaterial() const

Returns Whether a draw can override a surrounding pass's disabled depth writes.

usesDefaultDepthAndStencilState ​

cpp
bool usesDefaultDepthAndStencilState() const

Returns True when every mesh material uses default depth/stencil state.

hasAlphaMaskedFoliageMaterialForDiagnostics ​

cpp
bool hasAlphaMaskedFoliageMaterialForDiagnostics() const

Internal (diagnostics):

Returns True when any mesh (source, LOD or impostor) uses an alpha-masked material.

grassPatchDiagnostics ​

cpp
const GrassPatchDiagnostics &grassPatchDiagnostics() const

Internal (diagnostics):

Returns Grass-patch settings.

foliageWindDiagnostics ​

cpp
const FoliageWindDiagnostics &foliageWindDiagnostics() const

Internal (diagnostics):

Returns Foliage wind settings.

shadowFoliageLodDiagnostics ​

cpp
const ShadowFoliageLodDiagnostics &shadowFoliageLodDiagnostics() const

Internal (diagnostics):

Returns Last shadow foliage LOD decision.

lastShadowFoliageLodFallbackReasonForDiagnostics ​

cpp
const char *lastShadowFoliageLodFallbackReasonForDiagnostics() const

Internal (diagnostics):

Returns Text for ShadowFoliageLodDiagnostics::fallbackCode.

foliageImpostorDiagnostics ​

cpp
const FoliageImpostorDiagnostics &foliageImpostorDiagnostics() const

Internal (diagnostics):

Returns Last foliage impostor decision.

lastFoliageImpostorFallbackReasonForDiagnostics ​

cpp
const char *lastFoliageImpostorFallbackReasonForDiagnostics() const

Internal (diagnostics):

Returns Text for FoliageImpostorDiagnostics::fallbackCode.

hierarchicalFoliageClusterDiagnostics ​

cpp
const HierarchicalFoliageClusterDiagnostics &hierarchicalFoliageClusterDiagnostics() const

Internal (diagnostics):

Returns Last cluster culling result.

lastHierarchicalFoliageClusterFallbackReasonForDiagnostics ​

cpp
const char *lastHierarchicalFoliageClusterFallbackReasonForDiagnostics() const

Internal (diagnostics):

Returns Text for HierarchicalFoliageClusterDiagnostics::fallbackCode.

requestAsyncFoliageClusterPreparation ​

cpp
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 ​

cpp
bool pollAsyncFoliageClusterPreparation()

Non-blocking check for a finished worker build.

Returns True when a result was installed by this call.

asyncFoliageClusterPrepDiagnostics ​

cpp
const AsyncFoliageClusterPrepDiagnostics &asyncFoliageClusterPrepDiagnostics() const

Internal (diagnostics):

Returns Asynchronous cluster preparation state.

setDoubleBufferedInstanceUploads ​

cpp
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

ParameterDescription
enabledTrue to alternate between two instance buffers.

setSortTransparentInstances ​

cpp
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

ParameterDescription
enabledTrue to let the renderer call sortInstancesBackToFront() for this batch.

sortsTransparentInstances ​

cpp
bool sortsTransparentInstances() const

Returns True when transparent instance sorting is enabled.

sortInstancesBackToFront ​

cpp
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

ParameterDescription
viewPosCamera position in world coordinates.

applyTextureFilteringQuality ​

cpp
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

ParameterDescription
anisotropyRequested anisotropic filtering level.
mipLodBiasMip LOD bias.

Returns Number of texture ids updated (summed per mesh).

collectMaterialTextureIds ​

cpp
void collectMaterialTextureIds(std::vector<unsigned int> &textureIds) const

Append non-environment material texture ids used by this instanced visual.

Parameters

ParameterDescription
textureIds (in, out)Ids are appended (duplicates are kept).

accumulateGeometryDiagnostics ​

cpp
void accumulateGeometryDiagnostics(
    OpenGLMesh::GeometryDiagnostics &diagnostics,
    float tinyTriangleAreaThreshold) const

Accumulate CPU-side mesh geometry diagnostics for this instanced visual.

Parameters

ParameterDescription
diagnostics (in, out)Totals to add to.
tinyTriangleAreaThresholdTriangles with smaller (non-zero) area count as tiny.

collectMeshDiagnostics ​

cpp
void collectMeshDiagnostics(
    std::vector<OpenGLMesh::MeshDiagnostics> &diagnostics,
    float tinyTriangleAreaThreshold) const

Append per-mesh geometry/material diagnostics for this instanced visual.

Parameters

ParameterDescription
diagnostics (in, out)One entry is appended per source mesh.
tinyTriangleAreaThresholdTriangles with smaller (non-zero) area count as tiny.

draw ​

cpp
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

ParameterDescription
shaderShader to use for drawing.
cpp
void draw(
    Shader &shader,
    const glm::vec3 &viewPos,
    float verticalFovDeg,
    int viewportHeight)

Draw all instances using camera-aware projected LOD.

Parameters

ParameterDescription
shaderInstanced shader that is already in use.
viewPosCamera position in world coordinates.
verticalFovDegCamera vertical field of view in degrees.
viewportHeightViewport height in pixels (<= 0 disables projected LOD).
cpp
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

ParameterDescription
shaderMaterial shader used for the final draw.
cullingShaderOptional compute shader. Null falls back to the CPU path.
viewProjectionCurrent projection * view matrix for frustum culling.
viewPosCamera position in world coordinates.
verticalFovDegCamera vertical field of view in degrees.
viewportHeightViewport height in pixels.
cpp
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

ParameterDescription
shaderMaterial shader used for the final draw.
cullingShaderOptional instance-culling compute shader.
gpuHizOcclusionOptional Hi-Z input; null disables occlusion culling.
viewProjectionCurrent projection * view matrix.
viewPosCamera position in world coordinates.
verticalFovDegCamera vertical field of view in degrees.
viewportHeightViewport height in pixels.

drawShadow ​

cpp
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

ParameterDescription
shaderShadow depth shader that is already in use.
cullingShaderOptional instance-culling compute shader.
lightViewProjectionLight-space view-projection matrix.
viewPosMain camera position (drives LOD distances).
verticalFovDegMain camera vertical field of view in degrees.
viewportHeightMain viewport height in pixels.

drawLinearDepth ​

cpp
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

ParameterDescription
shaderLinear-depth shader that is already in use.
cullingShaderOptional instance-culling compute shader.
viewProjectionCamera projection * view matrix.
viewPosCamera position in world coordinates.
verticalFovDegCamera vertical field of view in degrees.
viewportHeightDepth target height in pixels.

instanceDataGeneration ​

cpp
uint64_t instanceDataGeneration() const

Internal:

Returns Counter bumped whenever instance data changes (cache key).

occlusionCandidatesPossible ​

cpp
bool occlusionCandidatesPossible() const

Internal: whether addOcclusionCandidates() can add this batch: its draws take the bounds-culled path with enough geometry, before any frustum test.

addOcclusionCandidates ​

cpp
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.

RaiSim — physics for robotics and AI.