API reference
Scenes, entities, meshes and lights
A scene is a list of entities, cameras and lights. An entity puts a mesh into the world with a material and a Transform. You create each object with an Engine function, then add it to one or more scenes. The engine sends the changes to the GPU at the start of the next frame.
In short
createScene,createEntity,createLight, thenaddEntityToSceneandaddLightToScene.- Meshes come from files (
loadMesh, background) or from your own vertices (createMesh, at once). - An entity is drawn only when its mesh and all its textures are loaded. Until then it is silently skipped.
- Move entities with
updateTransform. Only the changed rows are uploaded. - Everything can be destroyed, and entities and lights can leave a scene; rows, ranges and indices are reused (deferred destruction).
1Scenes
SceneHandle createScene();
Creates an empty scene. Returns an invalid handle and logs a warning when MAX_SCENES is reached (15 scenes can exist, because handle indices start at 1).
void addEntityToScene(SceneHandle scene, EntityHandle entity);
Adds the entity to the scene. If the entity is ready, the scene's draw list is rebuilt at the next beginFrame and the entity is drawn in that frame. If its mesh or textures still load, it joins when they finish.
- scene
- Invalid: logs an error, nothing changes.
- entity
- Invalid or destroyed: logs an error. An entity already in the scene is not added again (a warning).
A scene holds at most MAX_ENTITIES_PER_SCENE entities (a warning is logged after that). removeEntityFromScene takes it out again.
void removeEntityFromScene(SceneHandle scene, EntityHandle entity);
The scene stops drawing the entity from the next frame on; the entity lives on, and can be added again or be in other scenes. The scene's draw list is rebuilt once, which also drops the entity from Scene::entities. An entity that is not in the scene logs a warning.
void removeLightFromScene(SceneHandle scene, LightHandle light);
The light stops lighting the scene from the next frame on, and a shadow made for it in that scene casts nothing. The light lives on. The scene's light list is rebuilt once.
void destroyScene(SceneHandle scene);
Destroys the scene: its entities and lights live on, in no scene, and its draw list and light list buffers are freed once the GPU is done with them. Its index goes to the next createScene.
errors Refused while a render graph draws a view of the scene, with an error that names the view and its camera: destroy that graph first, or let it go out of scope. The graph of render lets go by itself.
void addCameraToScene(SceneHandle scene, CameraHandle camera);
Records the camera in the scene's camera list (at most MAX_CAMERAS_PER_SCENE, 32; past it an error is logged). Drawing does not read this list today: render, its Views and addScenePasses take the camera as an argument, and any camera can draw any scene. Cameras are on camera.html.
void addLightToScene(SceneHandle scene, LightHandle light);
Adds the light to the scene. It shines from the next frame on. A scene can hold any number of lights; a light already in the scene is not added again (a warning). Adding a light rebuilds the scene's list of lights once, on the CPU; nothing walks the lights after that while they do not change.
struct Scene
{
SceneHandle handle;
std::vector<EntityHandle> entities;
std::vector<CameraHandle> cameras;
std::vector<LightHandle> lights;
SceneEnvironment environment;
};
The record the engine keeps for each scene. There is no getter for it; it is in the public header because Engine stores it.
struct ShadowDesc
{
LightHandle light;
uint32_t cascadeCount = 4;
uint32_t size = 2048;
float distance = 50.0f;
float splitLambda = 0.7f;
bool operator==(const ShadowDesc&) const = default;
};
What addShadowPasses makes, and what a View lists in shadows: a light's shadow. A directional light gets cascaded shadow maps, a spot light one perspective map along its cone, a point light a cube map (Spot and point light shadows).
- light
- The light to shadow, of any
LightType. It must be in the scene's lights to be shadowed: one taken out of the scene casts no shadow. - cascadeCount
- Directional lights only: maps, 1 to
MAX_SHADOW_CASCADES(4). Each is one slice of the camera's view and one scene view. More cascades: sharper far shadows, more passes. A spot light has one map, a point light one cube of 6 faces (6 scene views). - size
- Width and height of each map (each cube face) in texels. A 2048 map of 32-bit depth is 16 MiB; a 1024 cube is 24 MiB.
- distance
- How far the shadow reaches, in world units. Directional light: from the camera, beyond its near plane; farther points are lit, faded in over the last tenth. Spot and point light: from the light, finite and above 0; it is the map's far plane, and its near plane is distance / 200.
- splitLambda
- Directional lights only. Where the slices end: 0 splits the distance evenly, 1 logarithmically (each slice the same factor longer than the one before), in between a mix. Higher values give the near cascades more detail.
struct SceneShadow
{
LightHandle light;
RenderTargetHandle maps[MAX_SHADOW_CASCADES] = {};
uint32_t mapCount = 0;
float distance = 0.0f;
float splitLambda = 0.0f;
bool operator==(const SceneShadow&) const = default;
};
A light's shadow, as addShadowPasses returns it, for addScenePasses. Do not build one yourself: addScenePasses takes only a shadow that addShadowPasses made for the same scene and camera in the same graph. A view reads up to MAX_VIEW_SHADOWS (4), of different lights. See Shadow mapping.
- light
- The light it darkens, from
ShadowDesc::light. - maps
- The depth-only targets (
D32_SFLOAT, no color) of the firstmapCountmaps: a directional light's cascades, nearest first; a spot light's one map; a point light's one cube (RenderTargetDesc::cube). A pass of yours can read one withreadDepth, as the inset ofexamples/06_shadowsdoes with the cascades. - mapCount
- 0 when
addShadowPassesfailed. - distance, splitLambda
- From the
ShadowDesc; every view of the shadow builds the maps' matrices with them each frame.
2Entities
An entity is not drawn the moment you create it. It moves through these states. Each arrow happens inside beginFrame.
createMesh is ready at once, so its entity gets rows at the next beginFrame. A failed entity stays in its scenes but draws nothing. Its rows go back when it or its mesh is destroyed.EntityHandle createEntity(const std::string& name, MeshHandle mesh = MeshHandle{}, MaterialHandle material = MaterialHandle{}, Transform transform = Transform{});
Creates an entity. It appears once it is in a scene and its mesh and textures are loaded (diagram above). You can pass a mesh that is still loading.
- name
- A label for you; the engine only stores it.
- mesh
- What to draw. Without a mesh the entity is never drawn, and the mesh cannot be set later.
- material
- Used by every sub-mesh that has no material of its own (OBJ files,
createMesh, glTF primitives without one). Invalid: the default material (white, metallic 1, roughness 1). A glTF sub-mesh's own material always wins. - transform
- Position, rotation and scale in the world. Default: the origin, no rotation, scale 1. A negative scale (a mirror) works: the engine culls the other face.
Returns an invalid handle and logs a warning after 262,143 entities (MAX_ENTITIES). Each entity needs one row in the instance table per sub-mesh; when EngineConfig::maxInstances rows are used, new entities log an error and are not drawn.
// examples/03_instances: 10,000 cubes share one mesh and two materials.
for (int z = 0; z < GRID_SIZE; ++z)
{
for (int x = 0; x < GRID_SIZE; ++x)
{
const auto material = (x + z) % 2 == 0 ? warm : cool;
const auto transform = cubeTransform(gridPosition(x, z), 1.0f);
engine.addEntityToScene(scene, engine.createEntity("grid", cube, material, transform));
}
}
void updateTransform(EntityHandle entity, Transform transform);
Moves the entity. Its instance rows (one per sub-mesh) are marked changed and uploaded at the next beginFrame, so the next frame shows the new place. Only these rows are uploaded, so moving a few entities in a big scene is cheap. If the sign of the scale changes (mirroring on or off), the entity's scenes rebuild their draw lists.
- entity
- Invalid: logs "Invalid entity handle for updating transform." and does nothing.
- transform
- Replaces the whole transform.
rasm::Transform transform = engine.getTransform(bunny);
transform.rotate(glm::vec3(0.0f, 1.0f, 0.0f), glm::radians(0.01f));
engine.updateTransform(bunny, transform);
void destroyEntity(EntityHandle entity);
Destroys the entity. It leaves every scene from the next frame on, and its instance rows (one per sub-mesh) and, for an animated entity, its row and ranges of the animation buffers go to the next entity at once: each frame slot has its own copy of those tables. Its mesh and material stay. A destroyed handle logs an error. See Deferred destruction.
engine.destroyEntity(tile.groundEntity);
engine.destroyMesh(tile.ground);
engine.destroyMaterial(tile.material);
engine.destroyTexture(tile.texture);
From examples/17_streaming/main.cpp: a tile that leaves the view goes, entities first.
Transform getTransform(EntityHandle entity);
A copy of the entity's transform. Invalid handle: logs an error and returns a default Transform.
struct Entity
{
EntityHandle handle{};
std::string name;
MeshHandle mesh{};
MaterialHandle material{};
Transform transform{};
};
The record the engine keeps for each entity. Read the transform with getTransform; the other fields have no getter.
3Transform
| Field | Default | Meaning |
|---|---|---|
position | (0, 0, 0) | World position, in doubles: precise to the nanometre on a planet in Earth-centred coordinates (large worlds). The world is right-handed, +Y is up, and a camera looks along −Z. |
rotation | identity | A glm::quat. Note the constructor order glm::quat(w, x, y, z). |
scale | (1, 1, 1) | Per axis. Negative values mirror the object. |
struct Transform
{
glm::dvec3 position = glm::dvec3(0.0);
glm::quat rotation = glm::identity<glm::quat>();
glm::vec3 scale = glm::vec3(1.0f);
};
Used for entities and cameras. It is an aggregate, so designated initializers work and you can skip fields: Transform{.position = p, .scale = s}. A glm::vec3 converts to the glm::dvec3 position by itself; arithmetic that mixes the two needs a cast, for example glm::vec3(transform.position) - center. Each view draws in its camera's render space, so a scene far from the origin renders like one near it.
Transform rotate(const glm::vec3& axis, float radians);
Turns the transform by radians around axis, an axis in world space (the new turn is applied after the old rotation). It changes the transform itself and also returns the result, so it can be passed on directly. A zero axis changes nothing. The axis does not need to be normalized.
glm::dmat4 toMatrix() const;
The model matrix in doubles: scale first, then rotate, then translate (T * R * S). For a glTF sub-mesh the engine multiplies it with the sub-mesh's node matrix, in doubles: entity.toMatrix() * glm::dmat4(subMesh.transform). It converts to a glm::mat4 by itself, which keeps only float precision.
4Meshes
OBJ (loadMesh)
One sub-mesh: every shape of the file is merged. No material: the entity's material is used. Positions, normals and the first UV set are read; the UV v is flipped so textures are not upside down. The .mtl file is ignored.
glTF / GLB (loadMesh, loadGLTF)
One sub-mesh per triangle primitive of each mesh node of the default scene, with the node's world matrix. Up to 3 UV sets and tangents are read; missing normals are computed. Each glTF material becomes a Material with its textures (see materials.html).
MeshHandle loadMesh(const std::string& path);
Starts loading a .obj, .gltf or .glb file and returns its handle at once. An AssetLoader call; an Engine has it too, for its own loader. The loader's workers read and decode the file, each of its images on a worker of its own, and build its LODs when EngineConfig::meshLods is on (job systems). A later beginFrame uploads it to the geometry pool, then isLoaded becomes true and the entities that use it are drawn.
- path
- Relative to
EngineConfig::assetRoot(seeresolveAssetPath), or absolute. UTF-8. The extension is checked in lower case only.
loads in the background Loading the same path again returns the same handle; the file is read once.
| Problem | When you see it | Result |
|---|---|---|
| Unknown extension | at the call | "Unsupported mesh format" logged, invalid handle |
| File does not exist | at the call | "Mesh file not found" logged, invalid handle |
| File does not parse, or a glTF requires an extension RASM does not support | in a later beginFrame | error logged (naming the extensions), the handle stays valid but isLoaded is false; entities using it log a warning and are not drawn |
| Geometry pool full | in a later beginFrame | error naming the EngineConfig field to raise; nothing of the mesh is uploaded |
After a parse failure, calling loadMesh with the same path tries again on the same handle.
MeshHandle loadGLTF(const std::string& path);
The same as loadMesh; the file extension picks the importer. It reads POSITION, NORMAL, TANGENT, TEXCOORD_0 to _2 and COLOR_0, in floats or in the integer types of KHR_mesh_quantization, skins (JOINTS_n / WEIGHTS_n, Animation), morph targets (POSITION, NORMAL and TANGENT deltas, sparse accessors too, Morph targets), and the material extensions on the materials page. A file may require KHR_materials_unlit, KHR_materials_emissive_strength, KHR_texture_transform, KHR_mesh_quantization and KHR_texture_basisu; one that requires any other extension fails to load. Other extensions it only uses are ignored.
rasm::MeshHandle room = engine.loadGLTF("models/gltf/coffee-room/scene.gltf");
if (!room.isValid())
return 1;
rasm::Transform transform{.scale = glm::vec3(2.0f)};
rasm::EntityHandle entity = engine.createEntity("room", room, {}, transform); // {}: use the glTF materials
bool isLoaded(MeshHandle mesh) const;
True when the mesh is uploaded and ready to draw, with every texture its glTF import made filled. Those textures are filled a few per frame after the mesh is ready, so a big model is loaded a few frames after its geometry. False while it loads, after it failed, and for an invalid handle. A mesh from createMesh is loaded at once. You do not need to wait for it before creating entities.
void destroyMesh(MeshHandle mesh);
Destroys the mesh. Its ranges of the geometry pool, its rows of the geometry table and its range of the animation pool are freed once the GPU has finished the frames that may draw it, and then taken by later meshes, so map tiles or levels can stream in and out for ever.
- What its glTF import made goes with it: the materials and textures
loadMeshcreated for this file belong to the mesh. An entity that uses one of those materials as its own falls back as afterdestroyMaterial, and a material that uses one of those textures as afterdestroyTexture. - Entities that still use the mesh live on and draw nothing; their rows are freed. Destroy them first, and nothing has to be searched.
- A load that has not finished is dropped at once: a load still in the queue never runs, and a running one gives its result up.
loadMeshof the same path then loads it again, as a new mesh. A mesh whose load failed can be destroyed too, which frees its index.
MeshHandle createMesh(std::vector<Vertex> vertices, std::vector<uint32_t> indices, std::vector<uint32_t> colors = {});
Makes a mesh from your data, builds its LODs when EngineConfig::meshLods is on, and uploads it now (the copy reaches the GPU with the next frame). The mesh has one sub-mesh with no material, so its entities use their own material.
- vertices
- See
Vertex. Settangentto zero when you have none. - indices
- A triangle list, 3 per triangle, counting from 0 in
vertices. Front faces are counter-clockwise seen from outside. - colors
- Optional vertex colors: empty, or one per vertex, each made with
packVertexColor. They multiply the material's base color. A mesh without them uses no color memory.
Returns an invalid handle when colors is neither empty nor one per vertex, the index count is not a multiple of 3, an index is not below vertices.size(), or the geometry pool is full (all logged). A mesh that does not fit takes no handle index. A mesh with no vertices or no indices is accepted but its entities skip it with a warning.
// examples/03_instances: one quad per cube face, so each face has its own normal.
std::vector<rasm::Vertex> vertices;
std::vector<uint32_t> indices;
// ... per face: 4 vertices like this, 6 indices
vertices.push_back({.pos = corners[i] * 0.5f,
.normal = n,
.uv = {uvs[i], uvs[i], uvs[i]},
.tangent = glm::vec4(0.0f)});
// ...
rasm::MeshHandle cube = engine.createMesh(std::move(vertices), std::move(indices));
// examples/09_gltf_materials: the same cube with a color per vertex, dark at the bottom and light at the top.
colors.push_back(rasm::packVertexColor(glm::vec4(glm::mix(glm::vec3(0.25f), glm::vec3(1.0f), height), 1.0f)));
// ...
return engine.createMesh(std::move(vertices), std::move(indices), std::move(colors));
MeshBuild buildMesh(std::vector<Vertex> vertices, std::vector<uint32_t> indices, std::vector<uint32_t> colors = {}, const MeshBuildOptions& options = {});
MeshHandle createMesh(MeshBuild&& build);
The two halves of createMesh. buildMesh is a free function that touches no renderer, so any thread may call it: it checks the data as createMesh does (colors empty or one per vertex, whole triangles, indices in range; an error and an invalid build otherwise) and builds the LODs and meshlets the options ask for, the slow part of a big mesh. Renderer::createMesh(MeshBuild&&) then only uploads it, on the renderer's thread, and takes the build (invalid afterwards). An application that makes its tiles' meshes builds them on its own threads, and its frames only upload.
// On a worker thread:
rasm::MeshBuild build = rasm::buildMesh(std::move(vertices), std::move(indices));
// Later, on the renderer's thread:
const rasm::MeshHandle mesh = renderer.createMesh(std::move(build));
struct MeshBuildOptions
{
bool lods = true;
bool meshlets = true;
};
lods: simplified LODs. meshlets: meshlets for a sub-mesh of 1024 triangles or more. Leave both off for geometry the shader moves (vector features, which buildVectorMesh does).
class MeshBuild
{
public:
bool isValid() const;
};
A mesh's CPU data, ready to upload. Move-only. isValid is false when buildMesh refused the data, and after a createMesh took it.
struct SkinVertex
{
uint16_t joints[4];
uint16_t weights[4];
};
A skinned vertex's 4 largest influences: joints of its skin, and weights as UNORM16 that add up to 65535 exactly (the rounding's rest goes to the largest). 16 bytes, in the geometry pool's skin stream, so a vertex stays 64 bytes. The import keeps the 4 largest of JOINTS_n / WEIGHTS_n (one warning per primitive that has more), scales them to add up to 1, and drops a weight whose joint is past the skin's.
struct MorphDelta
{
glm::vec3 position;
uint32_t normalTangent[3];
};
constexpr uint32_t MAX_MORPH_TARGETS = 256;
A morph target's change to one vertex: 24 bytes, in the geometry pool's morph stream. The position is 3 floats; the normal and the tangent's xyz are 6 half floats, two per uint, the first in the low half (normal x y, normal z tangent x, tangent y z). A glTF primitive keeps at most MAX_MORPH_TARGETS targets (a warning says how many it drops), because the Skin pass keeps a group's weights in shared memory. See Morph targets.
uint32_t packVertexColor(const glm::vec4& linearColor);
Packs a linear RGBA color (each 0 to 1; values outside are clamped) into the 4 bytes of a vertex color: R in the lowest byte. RGB is stored sRGB-encoded, like a color texture, so 8 bits keep the dark shades; alpha stays linear. The shader decodes it back to linear. packVertexColor(glm::vec4(1.0f)) is white, 0xFFFFFFFF.
MeshSize getMeshByteSize(const MeshHandle& handle) const;
The bytes the mesh uses in the geometry pool: vertices × 64, plus 4 per vertex color, and indices × 4, LOD indices included, over all sub-meshes. While the mesh loads it returns zeros. Invalid handle: logs an error and returns zeros.
struct MeshSize
{
uint64_t verticesByteSize;
uint64_t indicesByteSize;
};
The result of getMeshByteSize, in bytes.
The vertex
geometryPoolVertices of 221 vertices takes 128 MiB. Vertex colors are not in it: a mesh that has them keeps them in a separate stream (createMesh), so the others do not pay for them. See the vertex pulling guide.struct Vertex
{
glm::vec3 pos;
glm::vec3 normal;
glm::vec2 uv[MAX_VERTEX_UV_SETS];
glm::vec4 tangent;
};
- pos
- Position in mesh space.
- normal
- Unit normal, used for lighting.
- uv
- Up to
MAX_VERTEX_UV_SETS(3) texture coordinate sets. A material picks a set per texture. (0, 0) when unused. - tangent
- glTF tangent: xyz is the tangent, w is the bitangent sign (±1). w = 0 means "no tangent": the shader builds one from the UVs for normal mapping.
Mesh records in the public header
These types are in rasm/mesh.h because Engine stores them. No public function returns them; they are listed so you know what they are.
struct SubMesh
{
MeshGeometry geometry;
glm::mat4 transform;
MaterialHandle material;
int32_t animatedNode = -1;
};
One drawable part of a mesh: its place in the geometry pool, its node matrix at rest (identity for OBJ and createMesh, and for a skinned glTF primitive, whose joints place it), its glTF material (invalid when it has none), and the node in AnimationRaw::nodes that moves it while a clip plays (−1 when no clip moves it, and for a skinned one, see Animation). Each sub-mesh of an entity is one draw and one instance row.
struct Mesh
{
MeshState state = MeshState::LOADING;
std::vector<SubMesh> subMeshes;
std::vector<AnimationClip> animations;
std::vector<std::string> morphTargetNames;
std::vector<MaterialHandle> ownedMaterials;
std::vector<TextureHandle> ownedTextures;
std::vector<MeshLabel> labels;
std::vector<uint16_t> pointOrder;
MeshHandle glyphShape;
uint32_t glyphChunks = 0;
uint32_t users = 0;
};
A mesh: its load state, its sub-meshes, its clips (getAnimations) and the name of each morph weight of its entities (getMorphTargetNames). ownedMaterials and ownedTextures are what its glTF import made, which destroyMesh destroys with it; users counts the entities made with it, so destroying a mesh no entity uses searches nothing. labels are a vector mesh's (addVectorLabels); pointOrder is a point cloud chunk's: for each point in drawn order, its index in the PointCloudChunkDesc (2 B a point), which picks report. glyphShape is a glyph chunk's shape (GlyphChunkDesc::shape), and glyphChunks counts the chunks that name this mesh as theirs: destroying a shape stops their entities from drawing.
enum class MeshState { LOADING, READY, FAILED };
READY is what isLoaded checks. FAILED means the file did not parse or did not fit in the geometry pool.
struct MeshGeometry
{
uint32_t firstVertex = 0;
uint32_t vertexCount = 0;
uint32_t firstIndex = 0;
uint32_t indexCount = 0;
uint32_t lodIndexCount = 0;
uint32_t firstColor = 0;
uint32_t colorCount = 0;
uint32_t firstSkin = 0;
uint32_t skinCount = 0;
uint32_t firstMorph = 0;
uint32_t morphCount = 0;
uint32_t morphTargetCount = 0;
uint32_t firstMeshlet = 0;
uint32_t meshletCount = 0;
uint32_t maxLodMeshlets = 0;
uint32_t firstMeshletData = 0;
uint32_t meshletDataCount = 0;
uint32_t firstPoint = 0;
uint32_t pointUnits = 0;
uint32_t pointCount = 0;
uint32_t glyphCount = 0;
uint32_t geometryIndex = 0;
glm::vec3 boundsCenter = glm::vec3(0.0f);
float boundsRadius = 0.0f;
bool allocated = false;
};
Where a sub-mesh sits in the geometry pool, its row in the geometry table (geometryIndex), and its bounding sphere in mesh space, which frustum and occlusion culling test. allocated is true while it holds ranges of the pool, which destroyMesh gives back.
- firstIndex, indexCount
- LOD 0, the full detail.
- lodIndexCount
- The indices of LOD 1 and coarser, together. They come right after LOD 0's in the pool.
- firstColor, colorCount
- The sub-mesh's vertex colors in the color pool;
colorCountis 0 without colors. - firstSkin, skinCount
- The sub-mesh's
SkinVertexes in the skin stream;skinCountis 0 when it is not skinned. - firstMorph, morphCount, morphTargetCount
- The sub-mesh's
MorphDeltas in the morph stream:morphCount=vertexCount·morphTargetCount, target by target. Both are 0 without morph targets. - firstMeshlet, meshletCount, maxLodMeshlets
- The sub-mesh's meshlets in the meshlet stream, of every LOD, and the most of one LOD (each instance keeps a visibility bit per meshlet of that LOD). 0 for a sub-mesh without meshlets.
- firstPoint, pointUnits, pointCount, glyphCount
- A point cloud chunk's or a glyph chunk's range of the point pool, in 8 B units, and its points or glyphs; both counts are 0 for a mesh of triangles. A glyph chunk has no indices: its
indexCountis its glyph count. - firstMeshletData, meshletDataCount
- Its
ObjRaw::meshletDatawords in the meshlet data stream, which the mesh shaders read. Taken only where the device has mesh shaders (RenderContext::hasMeshShaders), else 0; a sub-mesh whose data does not fit (EngineConfig::geometryPoolMeshletData) has no meshlets.
A mesh's data on its way in, before the geometry pool (ObjRaw with its MeshLods and Meshlets) and what a glTF import hands back (SubGLTFRaw, GLTFRaw, GltfImportCache), are private, in src/assets/meshData.h: an application passes plain arrays to createMesh, or a path to an AssetLoader. How the LODs and meshlets are built is in Mesh simplification and Meshlets.
5Terrain
A terrain tile is an entity on a grid every tile of its size shares, lifted on the GPU by the tile's heights (Terrain from height maps). The tile carries only two textures: its heights and its image. It goes through culling, shadows, TAA and MSAA like any mesh, and is a TileStreamer tile's content like any other.
TerrainTile createTerrainTile(const TerrainTileDesc& desc);
Makes a TERRAIN material from the desc (its terrain, the imagery as base color with imageryRect as its texture transform, metallic 0, the roughness) and an entity on getTerrainMesh with getTerrainTransform. The heights' width decides the cells: width − 3. The entity is in no scene yet. Both handles are invalid, with an error, when the heights are not a live R16_UNORM or R32_SFLOAT square texture of 4 to MAX_TERRAIN_CELLS + 3 samples a side, the size is not above 0, maxHeight is below minHeight, or a pool is full. An imagery texture without a bindless slot gets one that clamps. A texture keeps the sampler of its first slot, so an image another material used first (with repeat) bleeds its opposite edge into the tile's border: give tiles images of their own.
The entity draws once its textures are loaded. List the entity, the material and both textures in a tile's content, never the grid. To change the heights' range later, update the material's terrain (updateMaterial) and the entity's transform together.
// examples/24_map_tiles: a tile's heights (35 x 35 steps of 1/16 m) and image came from the server.
const rasm::TerrainTile terrain = engine.createTerrainTile({.center = tileOrigin(node.level, node.x, node.y),
.size = size,
.terrain = {.heights = heights,
.heightScale = static_cast<float>(HEIGHT_STEP),
.heightOffset = data.heightOffset,
.minHeight = data.minHeight,
.maxHeight = data.maxHeight,
.skirt = static_cast<float>(size * SKIRT)},
.imagery = image,
.roughness = 0.95f});
struct TerrainTileDesc
{
glm::dvec3 center = glm::dvec3(0.0);
glm::quat orientation = glm::quat(1.0f, 0.0f, 0.0f, 0.0f);
double size = 0.0;
TerrainMaterial terrain = {};
TextureHandle imagery;
TextureTransform imageryRect = {};
float roughness = 0.9f;
};
- center
- World space, in doubles: the middle of the tile's square, at height 0 of its frame.
- orientation
- The frame's axes in world space: x and z across the tile, y up. On a globe, the tile's local frame at its centre (Large worlds).
- size
- Metres across, along x and z.
- terrain
- The heights and how they map to metres:
TerrainMaterial. - imagery, imageryRect
- The base color, and where the tile is in it: the identity for the tile's own image, a quarter (scale 0.5, an offset) for its parent's. Invalid: white.
struct TerrainTile
{
EntityHandle entity;
MaterialHandle material;
};
What createTerrainTile made. Add the entity to a scene, or give both to a TileStreamer tile.
MeshHandle getTerrainMesh(uint32_t cells);
The grid every terrain tile of cells × cells shares: (cells + 1)² vertices in a unit box (x and z from −0.5 to 0.5, y = 1) and a skirt under each edge (y = 0), with no LODs and no meshlets. Made on the first call for that size and kept until the renderer goes; destroyMesh refuses it. Invalid for 0 or more than MAX_TERRAIN_CELLS (256), or a full geometry pool.
Transform getTerrainTransform(const TerrainTileDesc& tile);
The entity transform of a tile: the grid's unit box stretched to the tile's box, from minHeight (lowered by the skirt, and by the curvature at the corners, d² / 2R) to maxHeight, at least 1 mm high. So culling sees the lifted terrain's real bounds. A free function, safe on any thread.
struct TerrainHeights
{
const uint16_t* unorm16 = nullptr;
const float* floats = nullptr;
uint32_t width = 0;
};
A tile's samples on the CPU, as in its heights texture: width × width, row by row (row j along z), the R16_UNORM values or the R32_SFLOAT ones.
double sampleTerrainHeight(const TerrainHeights& heights, const TerrainMaterial& terrain, double u, double v);
The drawn height in metres in the tile's frame, before the curvature, at (u, v) from 0 to 1 across the tile (clamped). The shader's rule: a grid point is heightOffset + heightScale × its sample, in floats; a cell is two flat triangles split from (0, 1) to (1, 0). Use it to put objects, labels and cameras on the ground, and to check a picked point. 0 for a width under 4 or no samples. Safe on any thread.
glm::dvec3 getTerrainPosition(const TerrainTileDesc& tile, const TerrainHeights& heights, double u, double v);
The world position of the drawn surface at (u, v), in doubles: sampleTerrainHeight lowered by the curvature, put in the world by the tile's center and orientation.
// The ground under a landmark at (u, v) of its tile.
const glm::dvec3 ground = rasm::getTerrainPosition(tile, {.unorm16 = samples.data(), .width = 35}, 0.25, 0.6);
constexpr uint32_t MAX_TERRAIN_CELLS = 256;
The most cells per side of a terrain grid; a tile's heights have cells + 3 samples a side.
6Vector features
Lines, polygons and points from map data: a mesh built by the functions below, drawn with a VECTOR material on an entity at the features' origin (no rotation, scale 1). The vertices keep each feature's points and offsets; the shader spreads them by the material's width every frame (Vector lines, polygons and points). The functions touch no renderer, so any thread may call them, each on its own geometry.
struct VectorGeometry
{
std::vector<Vertex> vertices;
std::vector<uint32_t> indices;
std::vector<MeshLabel> labels;
std::vector<uint32_t> colors;
};
What the add functions append to; labels holds addVectorLabels' boxes, and colors a word per vertex once a line brings values (empty before: the vertices are white), which the mesh keeps as its vertex colors. Build it into a mesh with buildVectorMesh. The vertex layout is shaders/lib/vector.slang's; the bits of each vertex's feature id are in tangent.w (read them with std::bit_cast<uint32_t>), exact for any 32-bit id.
void addVectorLines(VectorGeometry& geometry, const glm::dvec3& origin, const glm::dvec3* points, const uint32_t* lineSizes, uint32_t lineCount, const LineShape& shape = {},
const VectorPlacement& placement = {}, const uint32_t* featureIds = nullptr, const uint32_t* colors = nullptr, const float* scalars = nullptr);
- origin
- The world position of the entity that will draw the mesh: the vertices are offsets from it in floats, so a map far from the world's origin keeps its precision.
- points, lineSizes, lineCount
- Every line's points, in doubles, one line after another,
lineSizes[i]for linei. A line of fewer than 2 distinct points is skipped. - shape
- Joins and caps, and for a draped road its width in metres (
LineShape). - placement
- At the points' own heights, or draped on a terrain tile (
VectorPlacement). - featureIds
- One per line, the id picking will report; null: the line's number.
- colors, scalars
- Data lines: a value per point of
points, colors or scalars, not both (both: an error, the colors are kept). Colors are RGBA8 with RGB sRGB-encoded (packVertexColor), multiplied by the material's color. Scalars go through the material's colormap when itscolorModeisSCALAR(VectorMaterial), interpolated along the line and mapped per pixel. Every vertex a point makes (its segment's corners, a join, a cap) takes its value; a draped line's cut points take the value between their segment's ends; a draped band (drapeWidth) takes none. Lines without values in the same geometry are white, and with aSCALARmaterial they and the geometry's labels, polygons and points keep the material's color.
const glm::dvec3 road[3] = {{0.0, 0.0, 0.0}, {120.0, 0.0, 40.0}, {260.0, 0.0, 10.0}};
const uint32_t size = 3;
rasm::VectorGeometry geometry;
rasm::addVectorLines(geometry, glm::dvec3(0.0), road, &size, 1, {.join = rasm::LineJoin::ROUND, .cap = rasm::LineCap::ROUND});
const rasm::MeshHandle mesh = engine.createMesh(rasm::buildVectorMesh(std::move(geometry)));
// examples/30_glyphs: streamlines, a speed per point, for a material whose vector.colorMode is SCALAR.
rasm::addVectorLines(lines, origin, points.data(), sizes.data(), lineCount, {.join = rasm::LineJoin::MITER}, {}, nullptr, nullptr, speeds.data());
void addVectorPolygons(VectorGeometry& geometry, const glm::dvec3& origin, const glm::dvec3* points, const uint32_t* ringSizes, const uint32_t* ringCounts, uint32_t polygonCount,
const VectorPlacement& placement = {}, const uint32_t* featureIds = nullptr);
Polygons with holes, cut into triangles by earcut. points holds every ring, one after another, ringSizes[r] points for ring r; polygon i has ringCounts[i] rings, its outline first, then its holes. Rings need not be closed nor wound a given way. Without a drape they are cut in the ground's plane through origin (perpendicular to placement.up) and keep their points' heights.
void addVectorPoints(VectorGeometry& geometry, const glm::dvec3& origin, const glm::dvec3* points, uint32_t pointCount, const VectorPlacement& placement = {},
const uint32_t* featureIds = nullptr, const glm::vec4* iconRects = nullptr);
Points or markers: a disc each, the material's width across, with its outline as a ring. With iconRects (u0, v0, u1, v1 per point, in the material's albedo texture) a square icon instead.
MeshBuild buildVectorMesh(VectorGeometry geometry);
buildMesh with no LODs and no meshlets, which the shader's offsets would break. Safe on any thread; upload the result with createMesh(MeshBuild&&).
struct LineShape
{
LineJoin join = LineJoin::ROUND;
LineCap cap = LineCap::BUTT;
float miterLimit = MAX_VECTOR_MITER;
float drapeWidth = 0.0f;
};
enum class LineJoin : uint32_t { MITER, BEVEL, ROUND };
enum class LineCap : uint32_t { BUTT, SQUARE, ROUND };
constexpr float MAX_VECTOR_MITER = 2.0f;
How segments meet and lines end. A miter longer than miterLimit half widths (1 to MAX_VECTOR_MITER, which culling's pad counts on) is beveled. A square cap reaches half a width past the end point.
drapeWidth (metres) is for a draped line (VectorPlacement::drapeTile): above 0 the line is built that wide and cut on the terrain's grid across its whole width, so all of it lies on the drawn ground; with 0 only its middle is draped and its width spreads in the plane under the middle, which the ground beside a road wider than a cell can cover. A line built this way is drawn that wide in the ground's plane whatever the material's width, widthUnit and facing say (its outline and dashes keep the material's unit), so changing its width takes a rebuild; give the material the same width so the two read alike. The band is cut at the tile's edges, so give each tile the lines within half the width of it and its neighbour draws the rest. Without a drape, or when it is not finite, it is ignored.
// A road 16 m wide, draped on a tile whose cells are 8 m.
rasm::addVectorLines(roads, origin, points.data(), sizes.data(), lineCount, {.join = rasm::LineJoin::ROUND, .drapeWidth = 16.0f}, placement);struct VectorPlacement
{
glm::vec3 up = glm::vec3(0.0f, 1.0f, 0.0f);
const TerrainTileDesc* drapeTile = nullptr;
TerrainHeights drapeHeights = {};
};
Without a drape, features sit at their points' heights on a ground whose up is up (world space). With drapeTile and drapeHeights (the tile's desc and the samples of its heights texture), they are placed across the tile, their own height ignored, cut where they cross the terrain's grid lines and cell diagonals, and lifted by sampleTerrainHeight's rule, so they lie exactly on the drawn ground. Draped features must lie within the tile; make them content of the same tile as its terrain, so both are drawn together.
Labels
Names at points of the world, drawn as text that faces the screen (Text and labels). addVectorLabels lays each label's text out into the geometry with a font's metrics; the mesh is drawn with a VECTOR material whose font is the atlas's createFont, its width the text's size and its outline the halo. Each frame, each shaded view places the labels of every entity it draws: the higher priority first, never two over each other, fading in and out over a quarter second. Like the other builders, it touches no renderer.
rasm::FontAtlas atlas;
engine.loadFont("fonts/Roboto-Medium.ttf", atlas);
const rasm::FontHandle font = engine.createFont(atlas);
const rasm::MaterialHandle names = engine.createMaterial(rasm::MaterialType::VECTOR);
rasm::Material style = engine.getMaterial(names);
style.vector = {.color = glm::vec4(0.1f, 0.1f, 0.1f, 1.0f), .width = 14.0f, .outlineColor = glm::vec4(1.0f), .outlineWidth = 2.0f, .font = font};
engine.updateMaterial(names, style);
const rasm::LabelDesc label = {.position = {120.0, 0.0, 40.0}, .text = "Harbour", .priority = 5.0f};
rasm::VectorGeometry geometry;
rasm::addVectorLabels(geometry, glm::dvec3(0.0), atlas, &label, 1);
const rasm::EntityHandle entity = engine.createEntity("names", engine.createMesh(rasm::buildVectorMesh(std::move(geometry))), names);
void addVectorLabels(VectorGeometry& geometry, const glm::dvec3& origin, const FontAtlas& font, const LabelDesc* labels, uint32_t labelCount,
const VectorPlacement& placement = {});
Each label's text decoded from UTF-8 (decodeUtf8), each codepoint's glyph (findGlyph, the font's fallback for one it lacks), kerned (getKerning), each line centred under the first. A glyph is a quad twice, its halo's first, in ems from the anchor; the label's box goes in VectorGeometry::labels (MeshLabel) for placement. A label with no text is left out. Shaping (ligatures, right-to-left, complex scripts) is not done (D46). Keep the text within MAX_LABEL_REACH ems of its anchor. Draped, an anchor lies on the drawn ground like a point.
struct LabelDesc
{
glm::dvec3 position = glm::dvec3(0.0);
const char* text = nullptr;
float priority = 0.0f;
LabelAnchor anchor = LabelAnchor::CENTER;
glm::vec2 offset = glm::vec2(0.0f);
uint32_t featureId = 0;
};
enum class LabelAnchor : uint32_t { CENTER, BOTTOM, TOP, LEFT, RIGHT };
- position
- The anchor, in world space, in doubles.
- text
- UTF-8, read during the call. A line feed starts a new line.
- priority
- Placement keeps the higher first; among equals, the one placed last frame, then the first built.
- anchor
- Where the text sits: its middle on the anchor (
CENTER), above it (BOTTOM), below it (TOP), right of it (LEFT) or left of it (RIGHT), a quarter em away. - offset
- Moves the text further, in ems, +y up.
struct MeshLabel
{
glm::vec3 anchor = glm::vec3(0.0f);
glm::vec2 center = glm::vec2(0.0f);
glm::vec2 halfSize = glm::vec2(0.0f);
float priority = 0.0f;
uint32_t featureId = 0;
};
A label of a mesh (Mesh::labels, and VectorGeometry::labels before the build): its anchor in the mesh's space, and its text's box on the screen, in ems from the anchor (+y up). Each entity drawn with the mesh holds one of the renderer's MAX_LABELS slots per label.
struct FontAtlas
{
std::string name;
std::vector<uint8_t> pixels;
uint32_t width = 0;
uint32_t height = 0;
float distanceRange = 16.0f;
float ascent = 0.8f;
float descent = 0.2f;
float lineHeight = 1.2f;
std::vector<GlyphMetrics> glyphs;
std::vector<KerningPair> kerning;
uint32_t fallback = '?';
};
struct GlyphMetrics
{
uint32_t codepoint = 0;
float advance = 0.0f;
glm::vec2 offset = glm::vec2(0.0f);
glm::vec2 size = glm::vec2(0.0f);
glm::vec4 uv = glm::vec4(0.0f);
};
struct KerningPair
{
uint32_t left = 0;
uint32_t right = 0;
float advance = 0.0f;
};
A font as a signed distance field atlas on the CPU: width × height bytes, each 0.5 + distance / distanceRange (atlas pixels, inside positive), and the metrics in ems (1 is the text's size). A glyph's quad sits offset from the pen on the baseline (its bottom-left corner, +y up), size large, at uv (u0, v0, u1, v1) in the atlas; the pen then moves by advance, plus a kerning pair's. glyphs is sorted by codepoint, kerning by left, then right. loadFont and buildFontAtlas build one from a font file; an application can bring its own, made by any tool with this contract. Keep it after createFont to lay labels out.
const GlyphMetrics* findGlyph(const FontAtlas& font, uint32_t codepoint); float getKerning(const FontAtlas& font, uint32_t left, uint32_t right);
The glyph of a codepoint, or its fallback's when the atlas lacks it, or null when it lacks both. The kerning of a pair in ems, 0 for none.
uint32_t decodeUtf8(const char* text, std::vector<uint32_t>& codepoints);
Appends the codepoints of UTF-8 text and returns how many. A malformed sequence (a stray byte, an overlong form, a surrogate, a value past U+10FFFF) becomes U+FFFD and takes one byte, so decoding goes on.
FontHandle createFont(const FontAtlas& atlas);
void destroyFont(FontHandle font);
struct Font
{
FontHandle handle;
TextureHandle atlas;
float distanceRange = 0.0f;
};
constexpr uint32_t MAX_FONTS = 64;
Renderer methods. createFont uploads the atlas as an R8_UNORM texture in its own bindless slot, sampled clamped, and returns its handle; invalid, with an error, for an atlas whose pixels are not one byte per texel, a range not above 0, or when MAX_FONTS are alive. destroyFont releases the texture through the release queue; materials that name the font lose it, and their labels draw nothing. Font is the renderer's record of it.
constexpr uint32_t MAX_LABELS = 1u << 16; constexpr float MAX_LABEL_REACH = 12.0f;
MAX_LABELS: label slots of a renderer, for the labels of every entity alive at once; an entity that finds none left draws no labels (one warning). MAX_LABEL_REACH: the ems a label's text may reach from its anchor; culling pads a label draw by this times its size, so text farther out may vanish with its draw near the screen's edge.
7Point clouds
A point cloud is drawn in chunks of up to 65 536 points near each other: each chunk is a mesh made by buildPointCloudChunk, drawn by an entity with a POINTS material, and placed by the entity's transform in doubles. Each point is a splat a few pixels or centimetres wide; a chunk small on screen draws only the first points of its order (Point clouds).
constexpr uint32_t MAX_POINT_CHUNK_POINTS = 1u << 16;
struct PointCloudChunkDesc
{
const glm::vec3* positions = nullptr;
const uint32_t* colors = nullptr;
const float* scalars = nullptr;
uint32_t count = 0;
float spacing = 0.0f;
};
- positions
- Offsets from the entity's origin, in metres. Keep a chunk small (tens of metres): its points are 16-bit steps of its box, and it is culled and given a level of detail as a whole.
- colors
- RGBA8 with RGB sRGB-encoded (
packVertexColor), one per point, forPointColorMode::COLOR; the alpha is not read (points are opaque); null: none. - scalars
- A value per point (height, intensity, ...), for a colormap (
PointColorMode::SCALAR); null: none. Stored as 16-bit steps of the chunk's range. - count
- 1 to
MAX_POINT_CHUNK_POINTS. - spacing
- The distance between neighbouring points, in the chunk's units, which an
ADAPTIVEsize grows to. 0: measured from the points, as the cell size at which they take half as many cells as there are points (1.2 times the mean spacing of a random sample, 1.4 times a grid's step).
MeshBuild buildPointCloudChunk(const PointCloudChunkDesc& desc);
Checks the points (a count in range, positions and scalars finite; an error and an invalid build otherwise) and builds the chunk, on any thread: the points in an order whose every prefix is an even sample (a Morton order read in bit-reversed steps), 8 B a point with no colors, 12 B with them. createMesh uploads it into the point pool (RendererConfig::geometryPoolPoints, made with the first chunk). A pick's PickHit::feature is the point's index in desc's arrays (PICK_HIT_POINT), mapped through the mesh the entity drew; a mesh destroyed before the pick's answer leaves no feature (PICK_HIT_FEATURE cleared). An entity that draws a chunk without a POINTS material draws nothing, with a warning.
// On a worker thread:
rasm::MeshBuild build = rasm::buildPointCloudChunk({.positions = points.data(), .scalars = heights.data(), .count = count});
// Later, on the renderer's thread:
const rasm::EntityHandle chunk = renderer.createEntity("chunk", renderer.createMesh(std::move(build)), pointMaterial, rasm::Transform{tileCorner});
renderer.addEntityToScene(scene, chunk);
struct PointChunkLod
{
float drawn = 1.0f;
float finer[8] = {};
};
- drawn
- The share of the points its level of detail keeps that the chunk draws, 0 to 1: a prefix of a prefix, so a chunk fades in and out as an even sample. 0 draws nothing.
- finer
- Per octant of the entity's space (x ≥ 0 adds 1, y ≥ 0 adds 2, z ≥ 0 adds 4), the drawn share of a finer chunk over that octant, 0 to 1. An
ADAPTIVEpoint there shrinks back toward the material'ssizeby it, as the finer chunk fills the gaps it closed.
void setPointChunkLod(EntityHandle entity, const PointChunkLod& lod);
Sets an entity's PointChunkLod (7 bits for drawn, 3 for each finer, in its instance row); an entity starts with all its points and no finer chunk. A value that did not change writes nothing; one that did rewrites the entity's rows, which the next frame draws. An octree's streamer sets it each frame for the nodes it fades (Fades).
Octrees of points
A point cloud larger than GPU memory streams as an octree (Streaming point clouds): each node a sample of its cube, its children the detail it lacks, each node a chunk on an entity at its cube's centre, and a TileStreamer tile with TileRefine::ADD. rasm/pointCloudOctree.h.
struct PointCloudOctreeDesc
{
const glm::dvec3* positions = nullptr;
const uint32_t* colors = nullptr;
const float* scalars = nullptr;
uint32_t count = 0;
uint32_t cells = 128;
uint32_t maxNodePoints = 16384;
};
- positions
- World positions in doubles: ECEF, a projection's metres, anything.
- colors, scalars
- As
PointCloudChunkDesc's; null: none. - cells
- A node keeps the point nearest the centre of each cell its points take, of a
cells³ grid over its cube (a power of two, 2 or more), and passes the others down. The grid is coarser for a node that would keep more thanmaxNodePoints. - maxNodePoints
- A node with no more points left is a leaf that keeps them all; 1 to
MAX_POINT_CHUNK_POINTS.
constexpr uint32_t POINT_NODE_NONE = UINT32_MAX;
struct PointCloudNode
{
glm::dvec3 center = glm::dvec3(0.0);
double halfSize = 0.0;
glm::dvec3 boundsCenter = glm::dvec3(0.0);
double boundsRadius = 0.0;
float spacing = 0.0f;
float geometricError = 0.0f;
uint32_t parent = POINT_NODE_NONE;
uint32_t children[8] = {POINT_NODE_NONE, POINT_NODE_NONE, POINT_NODE_NONE, POINT_NODE_NONE, POINT_NODE_NONE, POINT_NODE_NONE, POINT_NODE_NONE, POINT_NODE_NONE};
uint32_t firstPoint = 0;
uint32_t pointCount = 0;
uint32_t level = 0;
};
- center, halfSize
- Its cube. Its points are offsets from
center, where its entity goes, so its octants are those ofPointChunkLod::finer. - boundsCenter, boundsRadius
- A sphere around its points and its children's, inside its parent's: its tile's
TileDesc::centerandradius. - spacing
- Measured as a chunk's is, and never more than its parent's: a few points at the data's edge are no surface to grow over.
- geometricError
- Its spacing, 0 for a leaf: its tile's
TileDesc::geometricError, so its children are wanted while its spacing on screen passes the cut's error. - children
- By octant (x ≥ centre adds 1, y 2, z 4);
POINT_NODE_NONEwhere the node kept every point. - firstPoint, pointCount
- Its points in the octree's arrays: up to
maxNodePointsfor a node with children, up toMAX_POINT_CHUNK_POINTSfor a leaf.
struct PointCloudOctree
{
std::vector<PointCloudNode> nodes;
std::vector<glm::vec3> positions;
std::vector<uint32_t> colors;
std::vector<float> scalars;
std::vector<uint32_t> indices;
};
The root is nodes[0], each node before its children. The point arrays hold the nodes' points one node after the other (colors and scalars empty without them); indices gives each point's index in the desc, so a pick's PickHit::feature on a node's entity is the desc's point indices[firstPoint + feature]. About 24 B a point in CPU memory, 28 with colors.
bool buildPointCloudOctree(const PointCloudOctreeDesc& desc, PointCloudOctree& octree); PointCloudChunkDesc getPointCloudNodeChunk(const PointCloudOctree& octree, uint32_t node);
Builds the octree on any thread (6 M points a second in Release on one thread): the points sorted along a 63-bit Morton curve of the cube around them, then each node sampled from its run of that order. False, with an error, for no points, a point that is not finite or a bad grid. Points beyond MAX_POINT_CHUNK_POINTS at one place are left out with a warning. getPointCloudNodeChunk is a node's chunk desc, its arrays the octree's and its spacing the node's, for buildPointCloudChunk on a worker thread.
rasm::PointCloudOctree octree;
rasm::buildPointCloudOctree({.positions = cloud.positions.data(), .colors = cloud.colors.data(), .count = static_cast<uint32_t>(cloud.positions.size())}, octree);
for (uint32_t n = 0; n < octree.nodes.size(); ++n)
{
const rasm::PointCloudNode &node = octree.nodes[n];
tiles[n] = streamer.createTile({.parent = node.parent == rasm::POINT_NODE_NONE ? rasm::TileHandle{} : tiles[node.parent],
.center = node.boundsCenter,
.radius = node.boundsRadius,
.geometricError = node.geometricError,
.refine = rasm::TileRefine::ADD});
}
// A tile handed out: its chunk on a worker thread, then its mesh and entity on the renderer's thread.
rasm::MeshBuild build = rasm::buildPointCloudChunk(rasm::getPointCloudNodeChunk(octree, n));
8Glyphs
A glyph chunk draws one shape (an arrow, a sphere, a cube, or any mesh) once per data point: up to 65 536 glyphs, each with its own position, orientation, scale and color or scalar, on an entity with a GLYPHS material placed in doubles. A compute pass culls every glyph and picks its shape's LOD each frame, and one indirect draw draws the visible ones (Instanced glyphs). rasm/glyphs.h.
constexpr uint32_t MAX_GLYPH_CHUNK_GLYPHS = 1u << 16;
struct GlyphChunkDesc
{
MeshHandle shape;
const glm::vec3* positions = nullptr;
const glm::quat* orientations = nullptr;
const glm::vec3* scales = nullptr;
const uint32_t* colors = nullptr;
const float* scalars = nullptr;
uint32_t count = 0;
};
- shape
- The mesh every glyph draws: its first sub-mesh, with its LODs, front faces counter-clockwise. It may still load: the chunk's entities wait for it. Destroying it stops them.
- positions
- Offsets from the entity's origin, as floats: keep a chunk within a few kilometres and put its entity at its place in doubles.
- orientations
- A rotation per glyph (normalized, kept as four 16-bit numbers); null: the shape's own axes.
getGlyphOrientationturns +Y to a direction. - scales
- A stretch along the shape's three axes per glyph, above 0, kept as half floats (up to 65 504); null: 1.
- colors, scalars
- A color (RGBA8, sRGB-encoded,
packVertexColor) or a scalar per glyph, for the material'sCOLORorSCALARmode; not both. Null for both: white. - count
- 1 to
MAX_GLYPH_CHUNK_GLYPHS.
MeshBuild buildGlyphChunk(const GlyphChunkDesc& desc);
Checks the glyphs (a shape, a count in range, finite values, no zero orientation, scales above 0 that a half float holds, not colors and scalars both; an error and an invalid build otherwise) and builds the chunk on any thread: 16 B a glyph (its position and its value), 8 B more with orientations, 8 B more with scales. createMesh uploads it into the point pool (RendererConfig::geometryPoolPoints, which point clouds share). A pick's PickHit::feature is the glyph's index in desc's arrays, with PICK_HIT_GLYPH. Glyphs cast no shadow (D52).
// On any thread: an arrow per sample of a vector field.
rasm::MeshBuild build = rasm::buildGlyphChunk({.shape = arrow, .positions = positions.data(), .orientations = orientations.data(), .scales = scales.data(), .scalars = speeds.data(), .count = count});
// On the renderer's thread:
const rasm::EntityHandle chunk = engine.createEntity("glyphs", engine.createMesh(std::move(build)), glyphMaterial, rasm::Transform{blockCorner});
engine.addEntityToScene(scene, chunk);
enum class GlyphShape : uint32_t
{
ARROW,
SPHERE,
CUBE,
};
MeshBuild buildGlyphShape(GlyphShape shape, uint32_t segments = 16);
A shape to draw glyphs with, on any thread. ARROW runs along +Y from 0 to 1 (a shaft 0.1 across, a head from 0.68, 0.26 across); SPHERE has a diameter of 1, CUBE a side of 1, both around the origin. segments (3 to 64) go around an arrow or a sphere. Their LODs halve the segments while they divide them (16, 8, 4), on the same vertices; an arrow's last LOD leaves out its two caps. buildMesh builds no LODs for meshes this small, so the shapes bring their own.
glm::quat getGlyphOrientation(const glm::vec3& direction);
The rotation that turns +Y, an arrow's axis, to direction (any length above 0; zero gives no rotation). Exact also straight down.
9Colormaps
A colormap turns a value into a color: a 256 × 1 sRGB texture that a POINTS or GLYPHS material, or a VECTOR material of data lines, reads through its ScalarRange (Colormaps).
TextureHandle createColormap(const glm::vec4* colors, uint32_t count); TextureHandle createColormap(ColormapPreset preset);
Makes a texture of COLORMAP_SIZE entries in its own bindless slot with linear filtering: from 1 to COLORMAP_SIZE linear colors (with alpha), spread evenly from the first entry to the last and interpolated between them, or from a preset. Invalid for no colors or more than COLORMAP_SIZE. Destroy it with destroyTexture; a material that names it loses it.
constexpr uint32_t COLORMAP_SIZE = 256;
enum class ColormapPreset : uint32_t
{
VIRIDIS,
TURBO,
MAGMA,
INFERNO,
PLASMA,
CIVIDIS,
GRAY,
COUNT,
};
viridis, magma, inferno, plasma and cividis change lightness evenly (cividis also for color-blind viewers); turbo is a smooth rainbow; gray is lightness only. The tables are matplotlib's.
struct ScalarRange
{
float min = 0.0f;
float max = 1.0f;
bool log = false; // both ends above 0
bool clamp = true; // false: values outside are not drawn
};
A value becomes t = (value − min) / (max − min), or the same with the logarithms of all three when log is set and both ends are above 0; t = 0 is the colormap's first entry and 1 its last. Outside the range a value takes the nearest end with clamp, and its point is not drawn without it.
10Animation
A glTF model's clips move its nodes, and the GPU poses them (Keyframe animation). A skinned model's clips move its joints, and the GPU skins its vertices once per frame for every view (Skinning); it plays the same way. A morphed model's clips move its weights too (Morph targets). The application owns the clock: it calls setAnimationTime once per frame, and starts a clip on an entity with playAnimation. Nothing else runs per frame on the CPU, however many entities play.
const rasm::MeshHandle box = engine.loadGLTF("models/gltf/BoxAnimated/BoxAnimated.glb");
const rasm::EntityHandle entity = engine.createEntity("box", box);
engine.addEntityToScene(scene, entity);
engine.playAnimation(entity, rasm::AnimationPlay{.clip = 0});
double seconds = 0.0;
while (engine.running())
{
seconds += 1.0 / 60.0;
engine.setAnimationTime(seconds);
engine.render(scene, camera);
}
| The entity... | What playAnimation does |
|---|---|
| plays nothing | Starts the clip. The next frame draws its pose. |
| plays a clip | Replaces it: the new play starts over from its own startTime and clipTime, also for the same clip. That frame has no motion from the frame before, so TAA does not smear the jump. |
| waits for its mesh | Keeps the play (a later play replaces it) and starts it when the mesh is ready. A clip the mesh does not have is refused then, with an error. |
| has a mesh that failed, or no mesh | Refuses it with an error. |
| would be one too many | Refuses it with an error that names EngineConfig::maxAnimatedEntities. An entity takes its row at its first play and keeps it. |
void setAnimationTime(double seconds);
Sets the animation clock, which every playing entity reads. Call it once per frame, before render or RenderGraph::execute; the frame uses the last value. It may go back (to replay) and starts at 0. The engine never reads a wall clock for animation, so a frame with the same clock is the same on every run. A value that is not finite is refused. The GPU gets the seconds since a base that moves every 64 s, so the clip time stays exact to 0.1 ms after a day.
void playAnimation(EntityHandle entity, const AnimationPlay& play);
Plays a clip of the entity's mesh on that entity (table above). The clip time is play.clipTime + (clock − play.startTime) · play.speed, wrapped into the clip for a loop, held at the ends otherwise. Each entity of a shared mesh plays on its own.
void stopAnimation(EntityHandle entity);
Puts the entity back in its rest pose from the next frame, or cancels a play that waits for the mesh. Nothing happens when it plays nothing. A skinned mesh goes back to its skeleton's rest pose (the nodes' own translation, rotation and scale), with no motion from the frame before; one that never played stands in that pose from the start, also when its file has no clips.
std::vector<AnimationClip> getAnimations(MeshHandle mesh) const;
The mesh's clips, in the file's order: index i is AnimationPlay::clip = i. Empty while it loads, for a mesh without clips, and for a model whose clips move none of its meshes. Returned by value.
int32_t findAnimation(MeshHandle mesh, const std::string& name) const;
The index of the mesh's first clip with that name, or −1 (also while the mesh loads). A clip without a name in the file is called animation 0, animation 1, ... by its index. Check for −1: cast to a clip it is refused by playAnimation.
struct AnimationPlay
{
uint32_t clip = 0;
double startTime = 0.0;
float clipTime = 0.0f;
float speed = 1.0f;
bool loop = true;
};
- clip
- An index of
getAnimations, orALL_ANIMATION_CLIPS. - startTime
- The clock time at which the clip is at
clipTime. A start in the future holds the first pose until then (a looping clip wraps back instead). - clipTime
- Where in the clip to be at
startTime: a phase, so a crowd does not move in step. - speed
- Clip seconds per clock second. 0 holds
clipTime(pause, or scrub by playing again); below 0 plays backwards. - loop
- Wraps the time into the clip;
falseholds the first or the last pose past the ends.
constexpr uint32_t ALL_ANIMATION_CLIPS = UINT32_MAX - 1;
Plays every clip of the mesh at once, for files with one clip per part (Blender exports an action per object this way). A node moved by two clips follows the last one. Its length is the longest clip's.
struct AnimationClip
{
std::string name;
float duration = 0.0f;
};
A clip's name from the file and its length in seconds: its last key time.
struct AnimationRaw
{
std::vector<AnimationNode> nodes;
std::vector<AnimationClipRaw> clips;
std::vector<AnimationJoint> joints;
std::vector<float> morphWeights;
std::vector<std::string> morphTargetNames;
};
struct AnimationJoint
{
uint32_t node = 0;
glm::mat4 inverseBind = glm::mat4(1.0f);
};
struct AnimationNode
{
int32_t parent = -1;
glm::mat4 rest = glm::mat4(1.0f);
glm::vec3 translation = glm::vec3(0.0f);
glm::vec4 rotation = glm::vec4(0.0f, 0.0f, 0.0f, 1.0f);
glm::vec3 scale = glm::vec3(1.0f);
};
struct AnimationClipRaw
{
AnimationClip info;
std::vector<AnimationSampler> samplers;
std::vector<AnimationChannel> channels;
};
struct AnimationSampler
{
AnimationInterpolation interpolation = AnimationInterpolation::LINEAR;
std::vector<float> times;
std::vector<glm::vec4> values;
};
struct AnimationChannel
{
uint32_t node = 0;
AnimationPath path = AnimationPath::TRANSLATION;
uint32_t sampler = 0;
};
enum class AnimationPath : uint32_t { TRANSLATION, ROTATION, SCALE, WEIGHTS };
enum class AnimationInterpolation : uint32_t { STEP, LINEAR, CUBICSPLINE };
What the import keeps of a glTF file's animations, in GLTFRaw::animation. nodes holds only the nodes a clip can move, parents before children, with their rest pose (a node below static parents hangs below an extra node whose rest is their world matrix). Each sampler's values are vec4s: a quaternion x, y, z, w, or a translation or scale with w = 0; CUBICSPLINE stores an in-tangent, the value and an out-tangent per key. A sampler that does not parse is skipped with a warning, and its clip keeps its index. joints holds every skin a sub-mesh uses, one skin after another: each joint's node in nodes (a joint is always kept, moved or not) and its inverse bind matrix (the identity when the file has none). morphWeights holds the rest weights of every node that draws a morphed mesh, one node after another (the node's, else the mesh's, else 0), and morphTargetNames one name per weight. A glTF weights sampler becomes one sampler per target, its value in x, and one AnimationPath::WEIGHTS channel per weight, whose node is the weight's index in morphWeights.
11Morph targets
A glTF mesh with morph targets has a list of weights per entity. The GPU adds each target's deltas, times its weight, to the vertices once per frame, before the skin, for every view (Morph targets). A weight comes from the application when it set one, else from the playing clip's weights channel, else from the mesh's rest weights.
Animate pass makes this choice per weight, every frame. A weight that setMorphWeights did not set keeps following the clip.// examples/14_morph_targets: a cube that plays nothing; its first weight follows a sine.
const float drivenWeights[2] = {0.5f - 0.5f * static_cast<float>(std::cos(seconds * 3.14159265358979 * 0.5)), 0.0f};
engine.setMorphWeights(drivenCube, drivenWeights, 2);
void setMorphWeights(EntityHandle entity, const float* weights, uint32_t count);
Sets the entity's first count morph weights, in the order of getMorphTargetNames. They win over the clip from the next frame; the weights past count keep following the clip, or their rest weight. Each entity of a shared mesh has its own weights. The values are copied. Call it again to change them: a call writes one row per weight, and nothing runs per frame on the CPU after that.
| Case | What happens |
|---|---|
The first call, or the first after clearMorphWeights | A jump: that frame has no motion from the frame before, so TAA does not smear it. |
| The next calls | Smooth: the change is motion, as for a clip. |
| The mesh still loads | The weights are kept until the entity has its row. Then the ones past the mesh's weight count are dropped. |
Invalid entity, a weight that is not finite, or weights null with count > 0 | Refused with an error; the weights stay as they were. |
| The entity has no mesh, or its mesh failed | Refused with an error. |
count larger than the loaded mesh's weight count | Refused with an error that names both counts. |
void clearMorphWeights(EntityHandle entity);
Gives every weight of the entity back to its clip, or to its rest weight, from the next frame. That frame has no motion from the frame before. Nothing happens when the entity has no weights set. An invalid entity is refused with an error.
std::vector<std::string> getMorphTargetNames(MeshHandle mesh) const;
One name per morph weight of the mesh's entities, in the order setMorphWeights takes them: the weights of each glTF node that draws a morphed mesh, one node after another. The names come from the glTF mesh's extras.targetNames; without them a weight is called target 0, target 1, ... by its index. Empty while the mesh loads, for a mesh without morph targets, and for an invalid handle. Returned by value.
const std::vector<std::string> names = engine.getMorphTargetNames(face);
std::vector<float> weights(names.size(), 0.0f);
for (size_t i = 0; i < names.size(); ++i)
{
if (names[i] == "Smile")
weights[i] = 1.0f;
}
engine.setMorphWeights(entity, weights.data(), static_cast<uint32_t>(weights.size()));
An entity of a morphed mesh is posed every frame, with a clip or not, like a skinned one: it takes a row of the animated entity table (EngineConfig::maxAnimatedEntities), and its weights take rows of EngineConfig::maxMorphWeights. The Skin pass reads only the targets whose weight is not 0. The deltas take 24 B per vertex and target in the geometry pool (EngineConfig::geometryPoolMorphs).
12Lights
LightType::DIRECTIONAL
Like the sun: same strength everywhere. Uses direction (the way the light travels, from the light to the surface), color and intensity. position and range are ignored.
LightType::POINT
Like a bulb: light / distance². Uses position, color, intensity and range. With range > 0 the light fades smoothly to zero at range; 0 means no limit. direction is ignored.
LightType::SPOT
Like a flashlight: a point light that shines only in a cone around direction. Full light inside innerConeAngle, a smooth fade to zero at outerConeAngle (the glTF rule).
Lights shade PBR materials. UNLIT materials ignore them. A scene without an environment also gets a small fixed ambient term, so unlit sides are not fully black; with one, the environment's light replaces it.
Local: point or spot light with a range
Sorted into clusters: only the pixels near it pay for it. Thousands are fine.
Global: directional, or range 0
Reaches every point, so every pixel shades it. Hundreds of them cost like hundreds of lights without clusters.
Shadowed
Up to MAX_VIEW_SHADOWS per view (addShadowPasses). Every other light has no shadow.
A point or spot light needs a range to be clustered; with range 0 it is global. Each cluster holds at most MAX_CLUSTER_LIGHTS lights. The guide Many lights: clustered lighting explains how it works.
LightHandle createLight(LightType type, glm::vec3 color = glm::vec3(1.0f), glm::dvec3 position = glm::dvec3(1.0), glm::vec3 direction = glm::vec3(0.0f, -1.0f, 0.0f), float intensity = 1.0f, float range = 10.0f, float innerConeAngle = 0.0f, float outerConeAngle = SPOT_OUTER_CONE_ANGLE);
Creates a light. Add it to a scene with addLightToScene, and change or move it with updateLight.
- type
DIRECTIONAL,POINTorSPOT.- color
- Linear RGB, multiplied by
intensity. - position
- World position (point and spot lights), in doubles, like an entity's.
- direction
- Direction the light travels (directional lights), or the cone's axis (spot lights). Pass a unit vector.
- intensity
- Strength. Point and spot lights fall off with distance², so they need larger values (the examples use 25 to 900).
- range
- Point and spot lights: distance where the light reaches zero. 0 = no limit: the light reaches every pixel and is shaded at every pixel (a global light). Give lamps a range, so they are clustered.
- innerConeAngle, outerConeAngle
- Spot lights: angles from
direction, in radians. Full light inside the inner one, none outside the outer one. They must keep 0 ≤ inner < outer ≤ π/2; the defaults are 0 andSPOT_OUTER_CONE_ANGLE(π/4), as in glTF.
Returns an invalid handle and logs a warning when EngineConfig::maxLights lights exist (16384 by default). A spot light with angles outside the rule logs an error and also returns an invalid handle.
rasm::LightHandle lamp = engine.createLight(rasm::LightType::POINT,
glm::vec3(1.0f, 0.85f, 0.65f), // color
glm::vec3(0.0f, 3.0f, -7.0f), // position
glm::vec3(0.0f), // direction (unused)
40.0f, 18.0f); // intensity, range
engine.addLightToScene(scene, lamp);
// A spot light from above, pointing down: full light within 14 degrees, none past 22.
rasm::LightHandle spot = engine.createLight(rasm::LightType::SPOT, glm::vec3(1.0f), glm::vec3(0.0f, 8.0f, 0.0f), glm::vec3(0.0f, -1.0f, 0.0f), 900.0f, 40.0f, glm::radians(14.0f),
glm::radians(22.0f));
engine.addLightToScene(scene, spot);
struct Light
{
LightHandle handle;
LightType type;
float intensity = 1.0f;
float range = 10.0f;
glm::vec3 color = glm::vec3(1.0f);
glm::dvec3 position = glm::dvec3(1.0);
glm::vec3 direction = glm::vec3(0.0f, -1.0f, 0.0f);
float innerConeAngle = 0.0f;
float outerConeAngle = SPOT_OUTER_CONE_ANGLE;
};
The record the engine keeps for each light, read with getLight and changed with updateLight. The engine writes it into the GPU's light table only when it changes.
void destroyLight(LightHandle light);
Destroys the light: it leaves its scenes from the next frame on, a shadow made for it casts nothing, and its row of the light table goes to the next light at once (each frame slot has its own copy).
Light getLight(LightHandle light) const;
A copy of the light's values. An invalid handle logs an error and returns a default Light.
void updateLight(LightHandle light, const Light& values);
Changes the light: every field of values but handle. The type must stay the same, since a shadow's maps are made for it: another type logs an error and changes nothing. It writes one row of the light table, which reaches the GPU in the next frame. A light that gains or loses its range moves between the global and the clustered lights of its scenes. A spot light with angles outside the rule of createLight logs an error and changes nothing.
// Move a lamp along a circle, once per frame.
rasm::Light light = engine.getLight(lamp);
light.position = center + glm::dvec3(std::cos(angle), 0.0, std::sin(angle)) * radius;
engine.updateLight(lamp, light);
Moving thousands of lights costs the CPU a call each; lights that do not change cost nothing (examples/11_many_lights).
constexpr uint32_t MAX_CLUSTER_LIGHTS = 256;
The most lights one cluster of a view holds (rasm/light.h). Where more lights reach one small box of the view, the lights later in the scene's order are left out there: FrameStats::lightsDropped counts them, and the log warns. Use fewer lights there, or shorter ranges.
enum class LightType { DIRECTIONAL, POINT, SPOT };
The three light kinds. The order matches the shader's LightType in shaders/lib/core.slang.
constexpr float SPOT_OUTER_CONE_ANGLE = 0.785398163f;
π/4: the default outer angle of a spot light's cone, glTF's default (rasm/light.h).
13Environments
An environment is an HDR photo of the light all around a scene. It lights every PBR material from all directions (soft light from the sky, reflections on shiny surfaces) and shows behind the scene as the sky. The guide Image-based lighting explains how.
const rasm::EnvironmentHandle sunset = engine.loadEnvironment("environments/venice_sunset_2k.hdr");
engine.setSceneEnvironment(scene, rasm::SceneEnvironment{.environment = sunset, .intensity = 1.0f, .rotation = 1.15f});
// Later: back to no environment.
engine.setSceneEnvironment(scene, {});
EnvironmentHandle loadEnvironment(const std::string& path);
Loads an equirectangular (2:1 panorama) Radiance .hdr image, in the background like loadMesh. An AssetLoader call; an Engine has it too, for its own loader. A relative path starts from AssetLoaderConfig::assetRoot. The header is read at once; a missing file, another extension or an image that is not HDR logs an error and returns an invalid handle. A worker decodes the pixels. The next beginFrame after that creates the textures, and the frame after (or the same one) prepares the light on the GPU, before any pass: about 1 ms for a 2048 × 1024 image. Until then a scene that uses it looks as if it had none.
Each call loads the file again (no cache). destroyEnvironment frees one you no longer need, for example to change the sky with the time of day.
void destroyEnvironment(EnvironmentHandle environment);
Destroys the environment. Scenes that use it have none from the next frame on (a small constant ambient). Its image, its three cubes (about 17 MiB for a 2k image) and their four bindless slots are freed once the GPU is done with them. A load or a bake that has not finished is dropped.
bool isLoaded(EnvironmentHandle environment) const;
True once the environment's light is prepared, so scenes use it from this frame on. False while it loads, if it failed, and for an invalid handle.
void setSceneEnvironment(SceneHandle scene, const SceneEnvironment& environment);
Gives the scene an environment, or takes it away with an invalid handle (SceneEnvironment{}). The scene's views read it every frame, so a change shows in the next frame and needs no new render graph. An invalid scene, a handle loadEnvironment did not return, a negative or non-finite intensity, a non-finite rotation, or an orientation that is not finite logs an error and changes nothing; a zero orientation is the identity. Several scenes can share one environment.
struct SceneEnvironment
{
EnvironmentHandle environment;
float intensity = 1.0f;
float rotation = 0.0f;
bool sky = true;
glm::quat orientation = glm::identity<glm::quat>();
};
- environment
- From
loadEnvironment. Invalid: no environment, the small fixed ambient and the render target's clear color. - intensity
- Multiplies its light and its sky. 0 turns its light off and keeps a black sky.
- rotation
- Radians around +Y, counter-clockwise seen from above. Turn the photo so its sun lines up with a directional light (
examples/08_ibldoes). Costs nothing: the light is not prepared again. - sky
- Draw the environment behind the scene, where nothing else was drawn. false keeps the clear color but still lights the scene.
- orientation
- The frame the environment is placed in, after
rotation: its +Y becomes the sky's up. Identity keeps the world's +Y. On a globe, give it the local frame (east, up and south of a place), so the horizon of the photo lies on the local ground (examples/23_large_world, large worlds). It is normalized; it costs nothing either.
The environment's light is not shadowed: shadow maps darken only the lights (D23).
14When changes reach the GPU
| You call | What the engine writes | Visible in |
|---|---|---|
createEntity + addEntityToScene | instance rows, the scene's draw list | the frame of the next beginFrame, if mesh and textures are loaded |
updateTransform | the entity's instance rows (one per sub-mesh) | the next frame |
loadMesh | geometry pool, geometry table | a later frame, when the worker is done (up to 4 ms of uploads per frame) |
createMesh | geometry pool, geometry table | the next frame |
addLightToScene | nothing stored on the GPU; copied into the scene data | the next frame |
loadEnvironment | the image and three cube maps, prepared by compute before the frame's passes | a later frame, when the worker is done |
setSceneEnvironment | nothing stored on the GPU; copied into the scene data | the next frame |
setMorphWeights, clearMorphWeights | one morph weight override row per weight of the entity | the next frame |
updateMaterial | one material table row | the next frame (see materials.html) |
The engine keeps one copy of each table per frame slot. A changed row is uploaded to each copy once, in that copy's own frame, so the GPU never reads a row while the CPU writes it. The guide The GPU scene tables explains the details.
15Limits
| Constant / setting | Value | Usable | What it limits |
|---|---|---|---|
MAX_SCENES | 16 | 15 | scenes |
MAX_ENTITIES | 262,144 | 262,143 | entities in total |
MAX_ENTITIES_PER_SCENE | 262,144 | 262,144 | entity entries in one scene |
EngineConfig::maxLights | 16,384 | all | lights in total; a scene holds any of them |
MAX_CLUSTER_LIGHTS | 256 | 256 | lights that reach one cluster of a view |
MAX_CAMERAS_PER_SCENE | 32 | 32 | camera entries in one scene |
MAX_SCENE_VIEWS | 32 | 32 | scene views: (scene, camera, target) sets given to addScenePasses and held by render graphs at once; each shadow cascade, spot light map and cube face is one |
MAX_VIEW_SHADOWS | 4 | 4 | shadows one view reads (addScenePasses's shadowCount) |
MAX_SHADOW_CASCADES | 4 | 4 | cascades of one shadow (ShadowDesc::cascadeCount) |
MAX_VERTEX_UV_SETS | 3 | 3 | UV sets per vertex |
MAX_MESH_LODS | 8 | 8 | LODs per sub-mesh, LOD 0 included |
MAX_MORPH_TARGETS | 256 | 256 | morph targets per glTF primitive |
EngineConfig::maxInstances | 65,536 | all | sub-meshes of all entities together |
EngineConfig::geometryPoolVertices, geometryPoolIndices, geometryPoolSubMeshes | 221 / 224 / 214 | all | geometry of all meshes together: vertices, indices, and one row per sub-mesh. The number of meshes has no limit of its own. |
EngineConfig::geometryPoolColors, geometryPoolSkins, geometryPoolMorphs | 220 / 220 / 220 | all | vertex colors, skinned vertices' joints and weights, and morph target deltas (one per vertex and target), of all meshes together |
EngineConfig::geometryPoolMeshlets | 217 | all | meshlets of all meshes together, every LOD included |
EngineConfig::maxAnimatedEntities | 16,384 | all | entities that have played a clip, or of a skinned or morphed mesh (each keeps its row) |
EngineConfig::maxMorphWeights | 65,536 | all | morph weights of all posed entities together (each keeps its range) |
EngineConfig::animationPoolBytes | 16 MiB | all | the kept nodes, samplers and keys of all loaded meshes; a mesh that does not fit fails to load |
"Usable" is lower for limits that count handles, because handle indices start at 1. Every limit logs a message when it is reached. The full list is on Types, handles and limits.
Every object can be destroyed, and pool space, rows and handle indices are reused (Deferred destruction). The fixed counts above are compile-time constants (D15). A pool fragments: a mesh needs one free range per stream, so a full pool can refuse a mesh that would fit in its free space added up; the error names the largest free range.