Skip to main content

Crate ponko

Crate ponko 

Source
Expand description

§Crabby Engine

A fast 2D engine for games with huge numbers of things on screen.

use ponko::*;

fn main() {
    Game::new("My Game", 800, 600).run(|ctx| {
        let crab = ctx.load_texture("crab.png");
        let mut pos = vec2(400.0, 300.0);

        move |ctx: &mut Ctx| {
            if ctx.key_down(Key::Right) { pos.x += 200.0 * ctx.dt(); }
            if ctx.key_down(Key::Left)  { pos.x -= 200.0 * ctx.dt(); }
            if ctx.key_pressed(Key::Escape) { ctx.quit(); }
            ctx.draw(&crab, pos);
        }
    });
}

Everything you need comes in with use ponko::*;.

§Features

  • window (default): a window and GPU rendering (winit + wgpu). Without it the engine is simulation only: Game::run_headless works, drawing calls do nothing, Game::run panics. For simulation servers and CI, with a much smaller build.
  • audio (default): sound through kira; without it sounds are silent.
  • inspector (default): the in-game inspector overlay (egui), opened with the backquote key. On in debug builds; see Game::inspector.
  • gamepad (default): gamepads through gilrs; without it Ctx::gamepads is always empty. On Linux it needs libudev headers.
  • profiling: per-system scopes for puffin_viewer. (Not needed for profile_scope!, Ctx::perf_report or CountingAllocator, which are always built in and cost one atomic load while profiling is off.)
  • hotpatch: change system code while the game runs, with dx serve --hot-patch --features hotpatch.
  • physics: 2D physics with rapier (Game::physics); physics-determinism for bit-identical results across platforms.
  • physics3d: 3D physics with rapier (Game::physics3d): bodies, colliders (heightfield terrain too), queries, a character controller and raycast-wheel vehicles.
  • steam: lockstep and byte messages over Steam’s relays and lobbies (Net::steam_host), with the steamworks crate re-exported.

Re-exports§

pub use steamworks;
pub use taffy as ui_layout;
pub use ponko_ecs as ecs_core;
pub use serde_json;

Macros§

json
JSON values used by reflection (re-exported from serde_json). Construct a serde_json::Value from a JSON literal.
profile_scope
Times the rest of the block as a scope called $name.

Structs§

ActionMap
Serializable bindings, ordered by name. Runtime state is never serialized. Unknown names and queries of the wrong kind return false/zero.
AllocCounts
Heap allocations made while profiling was on, from alloc_counts.
AllocReport
Heap allocations per frame, from PerfReport::allocs.
AmbientOcclusion
Ground-truth ambient occlusion. Radius is in world units; quality controls angular slices and horizon steps. Disabled by default to preserve scenes.
Animation
Plays frames of a SpriteSheet on an entity’s Sprite. The built-in animate_sprites system advances it every frame.
AnimationClip
Cheaply cloned, shared animation data. Sampling clamps time; for looping use time.rem_euclid(clip.duration()) when duration is positive. The first sample on each distinct joint list allocates a name mapping; later samples (including skeleton clones) allocate nothing. Source skeletons use indices directly. Missing joints and shortened pose entries are skipped.
AnimationEvent
A named event on a state’s normalized clock.
AnimationGraph
Immutable graph shared by animators with independent parameters and clocks.
AnimationLayer
An overlay with its own graph, parameters, events and clock. Layers run even at weight zero. Configure parameters/commands through animator; base-layer commands remain on the parent Animator. Nested layers are supported.
AnimationState
State playback settings. Use AnimationState::new for looping defaults.
AnimationTrack
A vector track (translation or scale), or a quaternion track stored as xyzw. Use AnimationTrack::new to validate times and value counts.
AnimationTransition
An ordered transition. The graph’s first matching transition wins, with at most one taken per update; any-state transitions ignore exit time and do not reenter their current target. Exit time is a minimum on the state’s unwrapped normalized clock, checked against the end of this update.
Animator
Animation component. The engine updates it every frame after the frame systems and before the draw systems: frame systems see the previous frame’s pose, draw systems and the renderer this frame’s. run_headless has no frames, so there (or to pose it at another point) set manual and call update yourself, e.g. from a sim system. Buffers allocate on first use or skeleton changes, never in steady state. Interruptions freeze the last displayed mixed pose as the new fade source; ordinary fades continue advancing the outgoing state. Only the destination emits events and tests transitions. Events accumulate until drained, up to 64 entries; excess events are dropped, retaining the earliest events.
AttachToJoint
Keeps this entity’s Transform3D on a joint of another entity’s Skeleton, moved by offset in the joint’s space: a gun in a hand, a hat on a head. The engine sets it just before drawing, so systems see last frame’s place; Skeleton::joint_matrix gives this frame’s.
Attached
Keeps this entity’s Transform2D position and rotation at an offset from another entity’s, updated by follow_attachments. Its own scale is left alone. When the entity it’s attached to is despawned, this one is despawned too. Attachments can be attached to attachments.
AudioBus
Named mixer bus, created once with Ctx::audio_bus. Handles belong to their creating context. The default handle selects the sfx bus.
AudioEffects
Per-voice Kira low-pass and shared reverb send settings. Invalid values become defaults; cutoff is clamped to 20–20,000 Hz and send to 0–1.
AudioListener3D
Where the ears are. By default they follow ctx.camera3d; set your own with Ctx::set_audio_listener. Velocity (for doppler) is estimated from frame to frame.
AudioSettings3D
Settings for a positional voice. Distances are in world units (metres for doppler); pitch is controlled by sound.speed. Invalid ranges are clamped.
AudioSource3D
A sound that plays from an entity, paired with Transform3D. It starts by itself and follows the entity every frame. Removing the component or the entity stops it. One-shots don’t restart after they finish.
Authority
Who owns an entity right now: an owner peer and an epoch counter. A handoff gives the entity to another peer and bumps the epoch; updates stamped with an older epoch are rejected, so a late packet from the previous owner can’t undo the handoff.
Budget
Limits for a PerfReport, checked with PerfReport::assert_within in tests and CI. Everything starts unlimited.
BudgetViolation
A limit in a Budget that the report went over.
Camera2D
Which part of the world the window shows: ctx.camera.
Camera3D
The 3D camera: where it is, which way it looks, and how wide it sees. One per game, at Ctx::camera3d.
CellStreamer
Which cells of a square grid on the ground (X and Z) to have loaded around a point, such as the camera: those within load_radius, started nearest first, and kept until they’re beyond keep_radius. The gap between the two keeps cells at the edge from loading and dropping over and over as the camera moves back and forth.
Character3D
A walking character (a player, a person): an upright capsule moved by its velocity that slides along walls, climbs slopes up to max_slope and steps up to step_height, stays on the ground going downhill, falls by gravity and pushes dynamic bodies. Needs a Transform3D, whose position is at its feet.
ClockSync
Maps a sender’s clock to ours. Every packet carries the sender’s time s and arrives at our time r; r - s is the clock offset plus the trip time. The trip time only ever adds, so the estimate follows the lower end of the recent samples (the fastest packets), which makes it robust against jitter and late packets, then smooths that to avoid steps. Needs no round trips, and works one way.
Collider
The solid shape of a body, and how it touches others.
Collider3D
The solid shape of a 3D body, its surface (friction, bounciness) and what it touches.
ColliderFocus
Keeps static colliders around an entity (the player, a vehicle) once Physics3D::stream_colliders is on: the colliders of fixed bodies and TerrainColliders within radius of it (on the ground, X and Z) are in the physics world, nearest first, and stay until they’re beyond keep_radius of every focus. The gap between the two stops a collider at the edge from coming and going as the focus moves back and forth.
CollisionGroups
Which colliders touch which: a collider is a member of the groups in memberships (one bit each, 32 groups) and touches colliders whose memberships share a bit with its filter. Both sides must agree. Queries use the same test against QueryFilter3D::groups.
CollisionMesh
A convex hull, triangle mesh or heightfield, built once with Physics3D::convex_hull, Physics3D::trimesh, Physics3D::heightfield or Physics3D::add_mesh and shared by any number of Collider3D::mesh colliders and TerrainColliders. A handle: copying it doesn’t copy the data. Handles are only meaningful in the game that made them.
CollisionMeshData
A convex hull, triangle mesh or heightfield built on the CPU, on any thread: the slow half of Physics3D::heightfield and friends. Build it in a Job with the rest of a streamed cell, then hand it to Physics3D::add_mesh on the game’s thread, which is quick.
CollisionStarted
Event: two colliders started touching (or overlapping, for sensors). Read with ctx.events.read::<CollisionStarted>().
CollisionStopped
Event: two colliders stopped touching.
Color
An RGBA color. Components are 0.0 to 1.0, in sRGB (the values you’d pick in a paint program or see in CSS).
Commands
The ECS: entities, components, queries, resources, commands. A list of world changes to apply later. Use it to spawn or despawn while a query is running, since the query holds the world.
ComponentId
The ECS: entities, components, queries, resources, commands. Identifies a component type inside one World.
Compute
A compute pass shader, made with Ctx::load_compute or Ctx::create_compute; a cheap handle. Run it by adding a ComputePass to Ctx::compute_passes.
ComputePass
One entry of Ctx::compute_passes: a shader, the render target it updates, and a material whose custom values and textures it reads.
ContactModifier3D
Changes how a body’s contacts behave. Put it on an entity with a Collider3D (the one-way side and the conveyor velocity are in that body’s own frame, so they turn with it):
ContactPair3D
The contacts between two bodies this step, as the custom contact hook sees them (see Physics3D::set_contact_hook). Changes affect this step only; the hook runs again the next.
Contributor
Something that cost time in a WorstFrame.
CountingAllocator
The system allocator, counting what it hands out while profiling is on.
Ctx
What every system gets: the world, commands, events, input, drawing, the clock, sound, the camera, physics and the network session. Systems are fn(&mut Ctx).
Decal3D
A box that paints an image onto the opaque surfaces inside it. The entity’s Transform3D places the box (its scale multiplies size). The image is projected along the box’s -Z (looking from +Z), its top along +Y, as with MeshData::decal; only surfaces turned towards +Z get it.
Desync
The peers’ worlds stopped matching: from tick on, they’re different games.
DrawParams
Optional settings for Ctx::draw_ex. Start from DrawParams::default() and change what you need.
Effect
A screen effect shader, made with Ctx::load_effect or Ctx::create_effect; a cheap handle. Run it by adding a ScreenEffect to Ctx::effects.
Entity
The ECS: entities, components, queries, resources, commands. A handle to a thing in the World. Cheap to copy and store.
Events
Messages between systems, by type: Ctx::events.
FarTerrain
Low-detail ground for the whole world, drawn beyond the terrain tiles that are loaded: a few large meshes made from a coarse grid of heights the game provides (the world’s heights, sampled every spacing world units), with the terrain material. Where a cell has its own tile, the far ground is cut away (FarTerrain::cut), so the two never overlap or fight over depth. A short skirt hangs down from every cut edge, and the tiles’ own skirts hang down beside it, so there’s no crack between the fine and coarse ground.
Field
One field of a component described with WorldReflect::reflect_fields.
FlowField
The way to the nearest goal from every cell of a NavGrid.
Font
A loaded font. Get one from Ctx::load_font; Font::DEFAULT is always there.
FrameStats
Frame-time statistics over the last few seconds, from Ctx::frame_stats. All times in milliseconds; the CPU and GPU parts are averages.
FrameTimes
Frame times, in milliseconds. In a headless run a frame is one tick.
FrictionCurve
How much grip a tyre has for how much it slips: a curve rising from 0 to its peak (extremum_slip, extremum_value), falling to (asymptote_slip, asymptote_value) and staying there, both pieces smooth and flat at their ends. The value times stiffness times the load on the wheel is the tyre’s force.
Game
A game: a window plus the loop that drives your code.
Gamepad
A connected gamepad, from Ctx::gamepads. It keeps its slot while connected, so pads[0] stays player one; a pad that reconnects takes the lowest free slot.
GlobalIllumination
Real-time global illumination: sunlight, sky light and lamp light bounced off the world’s surfaces onto others, at Lighting::gi. A red wall in the sun tints the floor beside it red, a room lit through a window is lit all over (and a closed one goes dark instead of taking the sky’s light), and it all follows the sun through a day.
GpuBuffer
A GPU array of vec4<f32>. Empty initial data creates zeroed elements.
GpuPass
One GPU pass of a frame, from Ctx::gpu_passes.
GraphicsQuality
The settings that decide how heavy the 3D picture is, in one place: the resolution it is drawn at, shadows, ambient occlusion, screen-space reflections, global illumination and antialiasing. low, medium, high and ultra are ready-made sets; apply one with Ctx::set_graphics_quality and read the current one back with Ctx::graphics_quality.
GridEntry
One entity in the grid: its handle, where it was at the last rebuild, and optional data stored with it (see SpatialGrid::rebuild_with_data).
Heightfield
A terrain tile’s heights, for finding the ground under a point on the CPU: where to put a tree, keep a camera above the hills, or stand a character. Heights between the grid points follow the same triangles the tile is drawn with, so what’s found is exactly what’s seen. Coordinates are from the tile’s corner, X and Z from 0 to its size.
Hit3D
What a ray or a shape cast hit.
InstanceBatch
A persistent batch. Handles are never recycled; freeing twice is harmless. Create one batch per streamed region and free it when that region unloads.
InstanceBatchOptions
Settings for a batch; materials come from the mesh’s parts.
Instant
A point in time for measuring how long something took, like std::time::Instant (which it is, on desktop), but also working in web builds, where std::time::Instant::now() panics. Re-exported from web-time.
Interest
Decides, tick by tick, which entities each peer receives and how often: rings of distance around each viewer (InterestConfig), a hysteresis at their edges, and a spatial grid so thousands of entities cost little.
InterestChange
An entity entering or leaving a peer’s interest, from Interest::changes.
InterestConfig
Rings of interest, from near to far, plus how sticky their edges are. Entities beyond the last ring are not sent at all.
InterestEntity
An entity in the world, for Interest::update. The id is yours (a network id), unique within one update.
InterestEntry
One entity a peer is interested in, from Interest::entries.
InterestTier
One ring of interest: entities up to radius from a viewer (and beyond the previous, smaller ring) are sent every every ticks.
InterestViewer
Somebody who looks at the world: a peer and where. A peer may have several (split screen, a camera apart from its avatar); an entity counts by its nearest.
Job
Work running on a worker thread, and its result once it’s done.
Joint
One joint of a Skeleton: its name, the joint it hangs from, and where it sits relative to that joint when nothing moves it (its rest pose).
Joint3D
Put this component on a separate entity to connect two bodies. Removing that entity/component or either body’s physics components removes the joint next step. Missing endpoints are retried on later steps. Multiple joint entities may share bodies. Changing this component rebuilds its joint and wakes both endpoints.
JointAnimation
Tracks for a joint, identified both by its source index and name. Missing tracks leave the corresponding pose property untouched.
JointDrive3D
A spring/damper drive. Zero stiffness gives a velocity motor. Rapier’s default acceleration motor model is used; targets use meters or radians.
JointMask
Joint indices selected for one skeleton layout. Build once, reuse each frame.
LatestWins
A “latest wins per entity” filter for unreliable state updates: accepts an update only if it is newer than everything already accepted for the same key, which drops duplicates, reordered packets and updates from a previous authority epoch.
Lighting
The light in the 3D world: a sun far away (one direction everywhere) and ambient light from all around. At Ctx::lighting.
Line3D
A line through points (in its entity’s space), drawn as a camera-facing strip width meters wide: laser beams, cables, ropes, power lines, paths. Change points any time; it’s rebuilt every frame it’s seen.
LodGroup
Levels of detail: the meshes this entity draws depend on how much of the screen it covers. Goes on an entity with a Transform3D (and no Model: the group draws instead).
LodLevel
One level of a LodGroup: the meshes drawn while the group is at least screen_height tall on screen.
LodRenderer
One mesh of a LodLevel, placed relative to the LodGroup’s transform.
LodSettings
Global settings for LodGroups, at Ctx::lod: what a graphics quality setting changes.
Mat4
3D and 4D vectors, rotation and 4x4 matrix, for 3D (re-exported from glam). A 4x4 column major matrix.
Material
How a surface looks: its color (and texture), how rough and how metallic it is, and light it gives off. Made with Ctx::create_material; a cheap handle.
MaterialDesc
What a Material is made from.
Mesh
A mesh on the GPU: triangles, split into parts that each have a Material. Made with Ctx::create_mesh or loaded with Ctx::load_mesh; a cheap handle.
MeshCost
What one mesh cost to draw in the last frame, from Ctx::mesh_costs.
MeshData
Triangles to make a Mesh from: corners with their normals and texture coordinates, and three indices per triangle (counter-clockwise seen from the front).
MessageStats
Cumulative transport counters, including handshake, heartbeat and resends.
Model
Draws a Mesh where the entity’s Transform3D is.
MorphAnimation
A named morph channel. Values use the track’s x component, in units where 1 is full weight. Cubic tangents use weight units per second.
MorphFrame
One frame of a piecewise linear morph channel. The channel’s weight is stored at channel in MorphWeights; target selects this frame’s deltas. Every participating target must belong to exactly one channel.
MorphTarget
One shape a mesh can blend toward (see MeshData::morph_targets): per corner, how far it moves and how its normal changes at full weight.
MorphWeights
How much of each of its mesh’s morph targets a Model shows: 0 none, 1 all of it (more or less than that exaggerates or inverts). By target index; missing ones are 0. A model without this component shows its mesh’s own weights (from its glTF file, else none). Animation clips with weight tracks set it.
MotionChild
A motion inside a tree; positive time scale multiplies seconds.
NavAgent3D
Agent component; its feet follow the surface, without gravity. Enable avoidance to use DetourCrowd instead of the original path follower. The original follower retains path storage and allocates only on replans. Crowd mode retains slots/corridors but the backend allocates query scratch.
NavBakeError
Invalid input, resource limits or a Recast/Detour failure. No partial mesh is returned.
NavBakeSettings
Bake clearances in world units, with slopes in degrees. +Y is up. Height/radius round up to cells; climb rounds down, so clearance is conservative.
NavGrid
A grid of walking costs: how hard each cell is to enter.
NavMesh3D
Tiled navmesh resource. Replace it with a new bake to invalidate agent paths. Queries reject partial or truncated paths. Same ordered inputs yield the same results; the backend’s libm feature removes platform libm differences.
NavObstacle3D
World-space axis-aligned blocking box component; no Transform3D is needed.
NavSource
World-space, counter-clockwise triangle soup; include walls and ceilings too.
Net
A lockstep session: ctx.net. Start one with Net::host, Net::join or Net::loopback and pass it to Game::lockstep. Without one, ctx.net is offline: one player whose input applies on the next tick, so the same game code runs alone and online.
NetMessages
A game-owned, explicitly polled message endpoint. Hosts talk to clients; clients talk to their host. For P2P, each peer can host a separate endpoint. No simulation barriers, background threads or async runtime. Poll and drain every frame, even when simulation is paused. Application messages allocate; Renet also allocates outgoing packet batches. Queues are bounded.
NetPose
Component: a remote entity’s incoming Pose snapshots, applied to its Transform3D by apply_net_poses. Push each decoded update from your message handler with ctx.time() as the arrival time.
NetStats
What a session has sent so far (Net::stats).
ParticleCurve
A piecewise linear size multiplier over normalized lifetime. Keys must be finite, strictly increasing, and in 0..=1; sampling clamps to the endpoints.
ParticleEmitter3D
A CPU particle pool component, paired with Transform3D. Simulation runs after frame systems; no meshes are required. run_headless skips this visual frame phase. Cloning copies the live particles and RNG state. Capped emission is discarded.
ParticleGradient
A piecewise linear RGBA gradient, interpolated in the supplied color space.
ParticleSettings3D
Settings copied into an emitter. Change settings by creating a new emitter. All numeric inputs must be finite; ranges must be ordered and nonnegative (rotation may be negative). Invalid settings panic in ParticleEmitter3D::new.
PassReport
One GPU pass, in RenderReport::gpu_passes.
PeerId
Opaque, session-local peer identifier. Clients address the host as HOST; hosts obtain client identifiers from connection events. IDs are not reused.
PerfReport
Where a game’s time and allocations go, over its last frames. It comes from Ctx::perf_report in a running game and Game::profile_headless in a headless run.
PerfWarning
A problem the report found, and what to do about it.
Physics
The physics world: ctx.physics. Add it to a game with Game::physics; then entities with RigidBody, Collider and Transform2D are simulated.
Physics3D
The 3D physics world: ctx.physics3d. Add it to a game with Game::physics3d; then entities with RigidBody3D, Collider3D and Transform3D are simulated, and entities with Character3D and Transform3D walk.
Playing
A sound that was started, to stop it later with Ctx::stop_sound.
PointLight3D
Omnidirectional light at its entity’s Transform3D::position. Scale is ignored. Intensity is linear radiant intensity; distance attenuation is inverse-square, softened within one world unit and smoothly windowed to zero at range. Invalid/nonpositive ranges or intensities disable the light.
Pose
A position and rotation, optionally with the velocity the owner was moving at. Interpolates position linearly, or along a cubic Hermite curve when both neighbouring snapshots carry a velocity (smoother through curves and at low send rates), and rotation with slerp. Extrapolation moves the position on at velocity, or at the speed seen between the last two snapshots when there is none; rotation is held.
Post
What happens to the lit 3D frame before it reaches the screen. Sprites and UI drawn on top are not changed.
ProfileScope
One named scope: where profile_scope! adds up the time spent inside it.
Quat
Rotation and 3D vector (re-exported from glam); also used by the replication helpers (Pose, Interest), which need no 3d feature. A quaternion representing an orientation.
Query
The ECS: entities, components, queries, resources, commands. A query over a World, created by World::query.
QueryFilter3D
Which colliders a query sees. The default sees every solid collider and no sensors.
Ragdoll3D
A skeleton in physics’ hands, on the entity with the Skeleton and Transform3D; made by Ctx::start_ragdoll, ended by Ctx::stop_ragdoll. While it lasts, the entity’s Animator is paused and the pose follows the bodies. Push it with Physics3D::apply_impulse on body. Stop it before despawning the entity: its bodies are entities of their own.
RagdollBone
One bone of a ragdoll: the skeleton joint it starts at, how thick it is, and how far its joint to the parent bone bends.
Random
Where a system’s random numbers come from this tick: from Ctx::random. Copy, so it can be used inside par_for_each.
RayHit
What a ray hit.
ReceivesDecals
Which decal layers a model takes (see Decal3D::layers). Models without it take every decal. Only the low 16 bits count.
Rect
An axis-aligned rectangle: min is the top-left corner, max the bottom-right (y grows downward, like window pixels).
ReflectionProbe3D
A local environment at an entity’s Transform3D::position. Rotation and scale are ignored. Four baked environments can be resident; zero content falls back to sky lighting. Capture excludes transparent objects.
Regression
Something that got slower between two reports, from PerfReport::regressions.
RenderReport
What drawing cost, in a windowed game’s PerfReport.
RenderStats
What drawing the last frame cost, from Ctx::render_stats.
RigidBody
Makes an entity a physics body. It also needs a Collider and a Transform2D.
RigidBody3D
Makes an entity a 3D physics body. It also needs a Collider3D and a Transform3D.
Rng
A small, fast random number generator (xoshiro256++). Same seed, same numbers, on every machine.
RootMotion
Horizontal translation in skeleton-local axes and yaw for the latest update. Vertical motion and pitch/roll stay in the pose. Apply translation using the entity’s pre-update orientation, then postmultiply its rotation.
ScopeGuard
Times the code until it is dropped. From profile_scope! or ProfileScope::enter.
ScopeReport
One profiling scope’s cost, from PerfReport::scopes.
ScopeTiming
One scope’s times, from Ctx::scope_timings.
ScreenEffect
One effect in Ctx::effects: its shader, and a material whose custom values and textures the shader reads (material.custom[0] to [3], custom_texture0, …).
Shader
A material shader written in WGSL: made with Ctx::load_shader or Ctx::create_shader; a cheap handle. See the 3D chapter of the guide for what a shader can do.
ShadowMesh
Draws a different mesh into the shadow maps than the entity’s Model shows: a cheap stand-in for a detailed model’s shadow (a simplified copy, a billboard), or None for no shadow from this entity. Without it, the model’s own mesh casts the shadow (unless Ctx::set_mesh_shadows turned that mesh’s shadows off).
Skeleton
A component that poses the skinned Model on the same entity (and the models whose SkinOf points at it): each joint’s pose is where it sits relative to its parent this frame, and the mesh’s corners follow the joints they’re weighted to. Loaded from a glTF file with Ctx::load_skeleton, or made in code with Skeleton::new. Cloning one is cheap: the joints are shared.
SkinOf
Poses this entity’s skinned Model with another entity’s Skeleton, and draws it where that entity is: clothes, hair and swappable parts made for the same skeleton. Joints are matched by name, so a part works on any skeleton that has its joints. The entity needs no Transform3D of its own.
Sky
The sky behind the 3D world, and the fog in front of it: ctx.sky.
SnapshotBuffer
Timestamped states of one entity, in time order, read back at any time: interpolated between two snapshots, predicted for a bounded time past the newest, then held. Times are the sender’s, in seconds on any timeline you like (for a remote entity use SnapshotStream, which also converts your local clock).
SnapshotConfig
Tuning for SnapshotBuffer and SnapshotStream.
SnapshotSample
A state read from a SnapshotBuffer or SnapshotStream.
SnapshotStream
A SnapshotBuffer plus a ClockSync: what you need per remote entity. Push each decoded snapshot with the sender’s timestamp and our clock; sample with our clock, once a frame.
Sound
A loaded sound. Cheap to copy. Get one from Ctx::load_sound or Ctx::create_sound.
SoundParams
Optional settings for Ctx::play_sound_ex.
SpatialGrid
A uniform grid over the whole (unbounded) world, rebuilt from scratch each tick: answers radius, rectangle and nearest-neighbor queries without checking every entity.
SpotLight3D
Cone light pointing along its entity’s rotated local -Z (its forward). Angles are cone half angles in radians, 0 <= inner <= outer < pi/2. Equal angles give a hard cone edge. Invalid angles disable the light. Position, intensity, range, scale and shadows follow PointLight3D; a shadowed spot light needs one shadow view.
Sprite
Makes an entity visible: drawn at its Transform2D by the built-in draw_sprites system.
SpriteSheet
A texture cut into equal frames on a grid, numbered left to right, top to bottom: an animation strip, a tileset, a texture atlas of icons.
SteamLobby
An asynchronously created/joined Steam lobby. Call poll each frame; id is None until Steam completes the request. Drop or leave leaves it. Metadata is cached by Steam; remote changes become visible after callbacks.
SystemReport
One system’s cost, from PerfReport::systems.
SystemTiming
How long one system took. See Ctx::system_timings.
TargetCamera
A camera drawing the 3D world into a render target each frame, before the main view: one entry of Ctx::target_cameras.
TerrainCollider
Makes an entity’s terrain tile solid: a fixed collider of a heightfield made from the tile’s heights, at the entity’s Transform3D (the tile’s corner), turned and scaled with it, so it matches the drawn ground triangle for triangle. Holes are open. Put it on the entity with the TerrainTile (not with a RigidBody3D): despawning the tile removes its collider, and giving it a new mesh after an edit swaps the collider at the next physics step.
TerrainMaterialDesc
What a terrain material is made from: ground layers (grass, dirt, rock, …) and a weight map saying how much of each shows where. Made into a Material with Ctx::create_terrain_material and used for Ctx::create_terrain_tile.
TerrainTile
A square of terrain from a grid of heights, made with Ctx::create_terrain_tile. Spawn it with a Transform3D at the tile’s corner, instead of a Model. The renderer picks a detail level by how far the camera is: the full grid nearer than lod_distance, then every 2nd height to twice that, every 4th to four times that, and every 8th beyond. Skirts hide the cracks where tiles of different detail meet.
TerrainTileData
The meshes of a terrain tile at every detail level, made on the CPU from its heights: build them on a worker thread with a Job, then Ctx::upload_terrain_tile on the game’s.
Text3D
Text in the world, drawn on its entity’s Transform3D: a shop sign, a name over a head, a damage number. It stays sharp at any size and distance, and can have an outline and a soft edge (for glows and shadows). Any loaded Font works, and one entity’s text can’t mix fonts; use several entities for that.
TextParams
Optional settings for Ctx::draw_text_ex.
Texture
A loaded image on the GPU. Cheap to copy: it’s just an id plus its size.
TextureArray
Several images of the same size in one texture, for materials that use many: terrain layers, foliage variants. Made with Ctx::create_texture_array or Ctx::load_texture_array; a cheap handle. Custom shaders read one through MaterialDesc::custom_arrays, and it gets mipmaps.
TileMap
A grid of tiles, each a frame of sheet or empty. Put it on an entity with a Transform2D: its position is the map’s top-left corner (the rotation and scale are ignored). The built-in draw_tilemaps system draws the tiles the camera can see, so maps can be huge.
Trail3D
A ribbon left behind its entity as it moves: tracers, sword swings, streaks behind cars or projectiles. It faces the camera, is widest where width says (over age, 0 at the entity, 1 at the end) and fades by color. Points are recorded in the world, so the ribbon stays where the entity went. Like particles, trails are only for show: headless runs don’t record them.
Transform2D
Where an entity is: position, rotation and scale.
Transform3D
Position, rotation and scale of a 3D entity.
Turns
Which entities update this tick, from Ctx::turns.
UVec2
Whole-number 2D vector, for tile coordinates (re-exported from glam). A 2-dimensional vector.
Ui
Owned UI tree and screen stack. Build once, then mutate node properties. Draining events avoids callbacks borrowing the game and UI together.
UiId
Stable node identity, never reused within a UI.
UiInput
Input snapshot in logical window coordinates. Ctx supplies this each frame; tests and custom hosts can call Ui::frame directly.
UiPaint
Visual style, independent of Taffy’s layout style. A texture with slice > 0 is drawn as nine patches; slice is the source border in pixels.
UiPanel3D
Retained UI shown on a quad in the world (Rust’s Ui on a surface): a computer screen, a shop terminal, a sign with buttons. Build ui like Ctx::ui_retained; its widgets are laid out in texture’s pixels.
UiStyle
Colors and sizes of the built-in UI: ctx.ui_style.
UpdateStamp
A state update’s place in time: the owner’s epoch (bumped on every authority handoff) and a seq counter that wraps and restarts per sender. A higher epoch always beats a lower one; within an epoch the newer seq wins.
Vec2
2D vector used for positions, sizes and velocities (re-exported from glam). A 2-dimensional vector.
Vec3
Rotation and 3D vector (re-exported from glam); also used by the replication helpers (Pose, Interest), which need no 3d feature. A 3-dimensional vector.
Vec4
3D and 4D vectors, rotation and 4x4 matrix, for 3D (re-exported from glam). A 4-dimensional vector.
Vehicle3D
A car, truck or any wheeled vehicle: up to MAX_WHEELS raycast Wheel3Ds holding up the entity’s chassis, which needs a dynamic RigidBody3D, a Collider3D and a Transform3D. The chassis faces its -Z.
Velocity
A body’s speed, in pixels and radians per second. Read it after a step; write it to set the speed (a jump, a thrown crate, a moving platform).
Velocity3D
A 3D body’s speed: meters per second, and radians per second around each axis. Read it after a step; write it to set the speed.
Wheel3D
One wheel of a Vehicle3D: where it’s mounted, its suspension and tyres (set these up once), what drives it this tick (yours to set), and what happened to it in the last physics step (read after the step).
World
The ECS: entities, components, queries, resources, commands. Holds everything in the simulation: entities, their components, and global resources.
WorstFrame
One of the slowest frames, from PerfReport::worst_frames.

Enums§

Action
An action’s kind and sources. Buttons OR together; axes select the source with greatest magnitude (first wins ties), avoiding doubled movement.
AnimationCondition
Transition predicates, all of which must hold.
AnimationParameter
Parameter defaults; indices in the graph identify parameters.
AntiAliasing
Antialiasing of the 3D frame. FXAA and SMAA work on the tone mapped image before sprites/UI; Taa works on the lit HDR frame.
AudioRolloff
Distance gain curve. Keyed curves use normalized distance and linear gain; keys must be sorted by distance. Values outside the keys use the nearest key.
AuthorityCheck
What to do with a state update, judged against an Authority.
Axis2Binding
A vector source. Keyboard diagonals are normalized; sticks use a radial deadzone and retain their direction. Y is positive down.
AxisBinding
A scalar source. Gamepad values inside the deadzone read zero; outside they are rescaled continuously to full range. Invalid deadzones read zero.
Blend
How a material covers what’s behind it.
BodyKind
How a body moves.
ButtonBinding
A digital source. Gamepad slots are stable while connected.
FieldType
The type of a field in WorldReflect::reflect_fields, and how it looks in JSON.
GamepadAxis
One axis of a gamepad: a stick’s x or y (-1.0..=1.0, y down is positive like screen coordinates) or a trigger (0.0..=1.0).
GamepadButton
A gamepad button, named by its position, so it means the same on every brand of controller.
GamepadStick
Which stick, for Ctx::gamepad_stick.
InputEvent
Raw input for headless tests and replay. Feed before querying actions.
InterestChangeKind
Whether an entity entered or left a peer’s interest.
Interpolation
Interpolation between keys. Cubic values are stored as incoming tangent, value, outgoing tangent for each key; tangents are derivatives per second.
JointAxis3D
The six axes in the joint’s local frames, translations followed by rotations.
JointMotion3D
Freedom on one joint axis; distances are meters, angles radians.
Key
A keyboard key, identified by its physical position on a US layout.
Lane
Delivery policy; ordering is independent in each direction and peer.
LayerBlend
How a layer combines with the lower pose.
LodPick
Which level or levels of a LodGroup are drawn, from LodGroup::pick.
LodShadow
What a LodLevel casts into the shadow maps.
MessageEvent
Connection changes and owned application payloads. Drain events every poll.
Motion
A recursive motion. Trees use seconds, with each child scaling its clock. Tree duration is the longest child duration divided by its time scale. 2D uses normalized inverse squared distance; an exact point selects only that child (the first if points coincide). Quaternion blends use ordered incremental slerp, so child order matters for more than two rotations.
MouseButton
A mouse button.
NetState
Where a session is.
ParticleBlend3D
Particle compositing, always depth tested with depth writes disabled.
ParticleShape3D
Emission volume in the entity’s coordinates; cone directions point along +Y.
ParticleSpace3D
Whether existing particles follow the emitter’s transform.
QualityLevel
Which of the GraphicsQuality presets some settings are.
ReflectError
Why a reflection call failed.
Shape
A collider’s shape, in pixels, centered on the entity (plus Collider::offset) and turned with it.
Shape3D
A collider’s shape, in world units (meters), centered on the entity (plus Collider3D::offset) and turned with it. Scale isn’t applied.
SnapshotPush
What happened to a snapshot given to SnapshotBuffer::push.
SnapshotState
How a SnapshotSample was produced.
SteamLobbyVisibility
Visibility of a Steam lobby (feature steam).
TextAlign3D
How the lines of a Text3D line up.
TextureFilter
How a texture looks when drawn bigger or smaller than its pixels: Ctx::set_texture_filter.
TextureKind
What a TextureArray’s pixels hold.
Tonemap
How HDR light (which can be far brighter than white) is mapped to the screen.
UiEvent
One semantic event; values are read from the node after Changed.
UiTextAlign
Text alignment within a node’s content box.
UiWidget
Built-in behavior; text, images and decoration are configured separately.
Value
JSON values used by reflection (re-exported from serde_json). Represents any valid JSON value.
WarningKind
What a PerfWarning is about.

Constants§

DEFAULT_SEED
The seed games use unless Game::seed sets one, so runs are reproducible by default.
LIGHT_SHADOW_ATLAS_SIZE
Default width and height of the depth atlas every point and spot light shadow view is packed into, in texels (see Lighting::light_shadow_atlas).
LIGHT_SHADOW_SIZE
Default width and height of the largest point or spot light shadow view, in texels (see Lighting::light_shadow_resolution): what a light near the camera gets.
MAX_DECALS
The most decals drawn in a frame. When more are in view, the ones nearest the camera are kept.
MAX_DECALS_PER_CLUSTER
The most decals one screen cell blends (the screen is 16 x 9 cells, each split into 24 slices of depth). Where more overlap, the ones with the highest Decal3D::order are kept.
MAX_GAMEPADS
How many gamepads the engine tracks at once.
MAX_GI_PROBES
The most probes a GlobalIllumination grid has: a bigger extent at the same spacing is shrunk to fit.
MAX_GI_PROBES_PER_FRAME
The most probes updated in one frame (GlobalIllumination::probes_per_frame).
MAX_INPUT_BYTES
The most bytes one player’s input for one tick can have.
MAX_INTEREST_TIERS
The most tiers in an InterestConfig.
MAX_LIGHT_SHADOW_VIEWS
The most shadow views point and spot lights can share each frame (see Lighting::light_shadow_views, 12 by default): a shadowed spot light takes one, a shadowed point light six. Each view is a square tile of the lights’ shadow atlas.
MAX_MESSAGE_BYTES
Maximum application payload, in either lane (1 MiB).
MAX_PLAYERS
The most players in one session.
MAX_POLYGON_POINTS
Most corners a Shape::Polygon can have.
MAX_RENDER_SCALE
See MIN_RENDER_SCALE.
MIN_RENDER_SCALE
Smallest and largest Post::render_scale.
PHYSICS3D_HZ
The simulation rate Game::physics3d sets, unless the game picked its own with Game::fixed_hz: 50 steps per second.
SPATIAL_SORT_EVERY
How often (in ticks) the built-in grid also reorders entities in memory by spatial_key. Positions drift slowly, so occasional sorting keeps neighbors close in memory at a small amortized cost (1M entities: ~18 ms per sort, ~0.5 ms per tick).
TERRAIN_LAYERS
The most ground layers a terrain material blends.
TERRAIN_LODS
How many detail levels a TerrainTile has: every height, then every 2nd, 4th and 8th.

Traits§

Component
The ECS: entities, components, queries, resources, commands. Any Send + Sync + 'static type can be a component. No derive needed.
Interpolate
A state that can be blended between two snapshots and predicted past the last one. Implemented for f32, Vec2, Vec3, Quat and Pose; implement it for your own state to use SnapshotBuffer with it.
SetupResult
What setup may return: nothing, or a closure to run every frame.
WorldReflect
Reflection methods on World: read and write components by name as JSON.

Functions§

alloc_counts
The allocations counted so far (while profiling was on). Take two readings and subtract to count a stretch of code. All zero if CountingAllocator isn’t installed and nothing calls note_allocation.
animate_sprites
Built-in system: advances every Animation and shows its frame on the entity’s Sprite. Game runs it every frame, before draw_sprites.
apply_net_poses
System: sets the Transform3D position and rotation of every entity with a NetPose from its stream, sampled at ctx.time() (scale is left alone). Entities without snapshots stay where they are. Add it with Game::system, so entities move every frame whatever the simulation does; the stream’s timestamps are matched against ctx.time(), so push with that clock.
camera_controls
A ready-made system for looking around big worlds: drag with the right or middle mouse button to pan, scroll to zoom toward the mouse.
draw_sprites
Built-in system: draws every entity that has a Transform2D and a Sprite. Game runs it every frame by default.
draw_tilemaps
Built-in system: draws the visible tiles of every TileMap. Game runs it every frame, before draw_sprites.
follow_attachments
Moves every entity with Attached to its place next to the entity it follows, on all cores, and despawns those whose entity is gone. Add it as a simulation system after the ones that move things.
interpolate_physics3d
Draws moving bodies smoothly: between two physics steps, sets each moving body’s Transform3D to a blend of its last two poses, by how far the frame is between them (Ctx::fixed_alpha). Added as the first frame system by Game::physics3d, so camera code sees the blended pose too. Does nothing in headless runs, where frames and ticks line up. Transforms you changed since the last step are left alone (they teleport the body at the next step).
look_at_joint
Aims axis (joint-local) at a world point, limiting the correction angle in radians in the joint parent’s space, then applying weight (clamped 0..1). Call in parent-to-child order with separate weights to spread over a chain. Zero axes, coincident targets, invalid indices and singular transforms are ignored. Entity scale is handled by inverse transformation; non-uniform joint scales/shear make the angular limit approximate in world space.
note_allocation
Counts one allocation of bytes made by something that isn’t Rust’s allocator, such as C++’s operator new (see CRABBY_COUNT_CPP_ALLOCATIONS in crabby.hpp). Counts only while profiling is on.
rebuild_spatial_grid
Built-in system added by Game::spatial_grid: re-indexes every Transform2D entity into ctx.spatial. It runs first in every simulation tick, and every SPATIAL_SORT_EVERY ticks it also sorts entities by cell so neighbor queries stay cache-friendly.
scope_named
The scope called name, made the first time it is asked for. Names are kept for the life of the process.
seq_diff
Signed distance from b to a on a 16-bit circle: positive when a is ahead of b, negative when behind, zero when equal. Sequence numbers more than half the range (32768) apart are ambiguous; that exact distance yields i16::MIN.
seq_newer
Is a newer than b, with 16-bit wrap-around? Equal numbers are not newer. Exactly half the range apart (32768) is ambiguous: neither is newer.
spatial_key
Z-order (Morton) key of the grid cell containing position: points that are close in space usually get close keys. Sort entities by it so that neighbors sit next to each other in memory:
steam_lobby_from_args
The lobby of a Steam invite this game was launched with (Steam starts the game with +connect_lobby <id> when a friend accepts an invite while it isn’t running). Feature steam.
steam_wait_for_invite
Waits up to timeout for the player to accept a friend’s Steam invite to a lobby, while the game is running (Steam tells a running game instead of starting it). For a “join a friend” screen before the game starts; steam_lobby_from_args covers invites accepted while it wasn’t running. Feature steam.
step_navmesh3d
Register with Game::sim_system, just like the exposed physics step. No resource means no-op. Each tick gathers obstacle components, invalidates paths on mesh/obstacle/destination changes or teleports, then moves agents. Stalled agents retry when those inputs change. No window/GPU is required.
step_physics
Steps the physics world one simulation tick: picks up new, changed and removed bodies, simulates, writes positions and velocities back, and sends CollisionStarted / CollisionStopped events. Added by Game::physics; remove or reorder it like any other system.
step_physics3d
Steps the 3D physics world one simulation tick: picks up new, changed and removed bodies, moves characters, simulates, writes poses and velocities back, and sends CollisionStarted / CollisionStopped events. Added by Game::physics3d; remove or reorder it like any other system.
two_bone_ik
Rotates a direct parent-child-child chain toward a world target without changing translations or lengths. pole is a world-space bend direction. Weight is clamped to 0..1. Invalid indices, incomplete poses, singular transforms and zero-length bones are ignored. Collinear hints use a stable perpendicular. Targets outside reach use the closest reachable distance.
uvec2
Whole-number 2D vector, for tile coordinates (re-exported from glam). Creates a 2-dimensional vector.
vec2
2D vector used for positions, sizes and velocities (re-exported from glam). Creates a 2-dimensional vector.
vec3
Rotation and 3D vector (re-exported from glam); also used by the replication helpers (Pose, Interest), which need no 3d feature. Creates a 3-dimensional vector.
vec4
3D and 4D vectors, rotation and 4x4 matrix, for 3D (re-exported from glam). Creates a 4-dimensional vector.