Streamed Worlds¶
A world that goes on for tens or thousands of kilometres – a road trip, a flight, an open map built tile by tile round the player – runs into two limits. The scene cannot hold it all, so it is streamed: tiles are built ahead of the camera and freed behind it. And a float, which is what the GPU and the scene graph store positions in, keeps a position to about a millimetre 8 km from the origin, to a centimetre at 100 km and to a metre at 10,000 km; far out, vertices shake and shadows swim. So the scene is kept near the origin with a floating origin: every so often the game moves the whole scene back under the camera, and the world goes on.
The environment modules are built for both. This page shows how a game streams its ground, its trees and its grass into the environment stack and moves its origin, with nothing changing on the screen.
The floating origin¶
Two frames of coordinates are in play:
the scene: positions as the scene graph holds them, under
render, near the camera;the true world: where things really are in the game’s world, in the same units (world units,
Environment(metres_per_unit=...)), with Python floats (doubles).
Environment.world_origin is where the scene’s origin lies in the true
world, so true = scene + world_origin. It is (0, 0, 0) until the game
moves it, and the two frames are the same.
When the camera has gone far enough from the scene’s origin, the game moves its scene back by (-dx, -dy, -dz) and tells the environment:
env.shift_origin(dx, dy) # dz too, for a world that climbs
world_origin grows by (dx, dy, dz), and every origin handler runs, in
the order they were added. Nothing changes on the screen.
Who moves what. The rule is ownership: each module moves the nodes it made, and the game moves its own.
The engine’s modules handle the shift themselves, each with an origin handler it adds in its constructor and removes in
destroy(). AForestmoves its root and its depth pre-pass root,Grassplaces each of its cells again,VolumetricFogmoves the fog volumes placed withpos=,SunShadowsmoves the frame its cascades are fitted in. The clouds place no nodes in the world. A game must not move any of these, nor the nodes they hang under: leave a forest’s and the grass’srootat the scene’s origin.The game moves everything else it put in the scene: its terrain meshes, its buildings, its vehicles, its lights, the fog volumes it hung on its own nodes (they ride on them), and the camera.
The engine’s modules keep their world-space state in the true world – the
weather, the fog’s noise, the trees, the canopy, the grass’s layout – and
the passes that keep a history of the view (the frame pipeline’s TAA, AO and
motion vectors, the clouds’ and the fog’s temporal passes) move their last
view with the scene instead of dropping it. The shadow cascades are kept:
their light frame rides with the scene and their matrices are moved with it,
so their texels stay where they were in the true world and nothing redraws
(only once the light frame is 8192 m from the scene’s origin does it come
back and every cascade redraw). A shift is not a cut: do not call
Environment.cut for it, which would
start every history afresh and soften a frame. Call it as well only when
the camera also jumped.
When in the frame. At any point of the frame before it renders –
before or after the environment’s update (its task, sort 45) – but the
scene first: move the scene and the camera, then call shift_origin in
the same frame, in the same piece of code. A shift made after the update
rewrites what the frame values already hold: the camera and view slots are
written again, last frame’s view moved, and each module moves what it handed
this frame’s shaders (Environment.frame_written tells a handler that the
values are written already).
A game’s own frame slots. A slot that only says where something is in
the scene (a lamp’s position, a window’s corner) is written by a view
writer, not a frame writer: add_view_writer()
(remove_view_writer takes it off) is called every frame after the frame
writers, and again after a shift made once the frame was written, so a late
shift leaves no slot behind. A view writer must give the same result when
it runs twice in a frame: no time step in it.
How far, how often. Any finite shift works, of any size. A shift every few kilometres keeps the scene within float precision; shifting by whole tiles keeps a tile streamer’s arithmetic simple.
Height. dz moves the scene’s z = 0 too. Environment.altitude is
the height above the sea of the true world’s z = 0, and
Environment.scene_altitude that of the scene’s (altitude plus the
origin’s z in metres), which is what the sky, the clouds and the fog work
from.
A game’s own handler. A game module that keeps something in the scene frame across frames (a trail of positions, a cached reprojection) adds a handler the same way:
def on_shift(dx, dy, dz):
trail[:] = [(x - dx, y - dy, z - dz) for x, y, z in trail]
env.add_origin_handler(on_shift)
...
env.remove_origin_handler(on_shift)
Gameplay queries keep taking scene positions: clouds.density_at(pos),
clouds.precipitation_at(pos) and the rest answer for the weather at the
true place (Clouds and Weather).
Patterns in a game’s own shaders¶
A pattern fixed in the world – a detail texture tiled over the ground, a
noise, a hash per cell – computed from the scene position would jump at
every shift. world.glsl gives the true position instead:
#include "world.glsl"
vec2 uv = true_world(v_world.xy) / 4.0; // a 4 m tile over the ground
true_world(p) adds the WORLD_ORIGIN frame slot to a scene position.
The slot holds the origin modulo a period (world_period(): 8192 m in
world units, Environment.world_period), so a float holds it to a
millimetre however far the world goes: a pattern whose period divides
8192 m (1, 2, 4 … 8192 m) is exact at any distance, and a hash of whole
cells repeats every 8192 m. WORLD_ORIGIN.z is the origin’s height, not
reduced. Shaders in the Environment lists the slot.
Coordinates¶
One rule says which frame an API takes: state the engine keeps is in the true world; per-frame queries are in the scene. What is planted, laid out or added stays put across a shift, so it is named where it really is; what is asked about this frame, or follows a node, is asked where it is now. The true world comes in two units, as the modules that keep it work:
API |
Frame |
Unit |
|---|---|---|
|
true world |
world units |
|
true world |
metres |
|
scene |
world units |
true = scene + Environment.world_origin in world units, and a true point
in metres is that times metres_per_unit (Grass.to_true(p) does both
for a point of the grass’s root). With metres_per_unit 1 and no shift
yet, all three are the same numbers.
Streaming trees¶
Forest.plant and
unplant() take true world coordinates, so a
tile names the same trees the same way before and after any shift. A tile
passes its corner as origin (doubles) and its trees’ positions relative
to it, which keeps the numbers small and exact:
tag = forest.new_tag() # this streamer's trees
# tile built: positions within the tile, the corner as the origin
forest.plant(oak, positions, origin=(x0, y0, 0.0), tag=tag)
# tile freed: the tile's true-world bounds
forest.unplant((x0, y0, x0 + size, y0 + size), tag=tag)
A tree’s size, yaw and tint are hashes of its true position, so a tile
streamed out and back in is the same trees. unplant takes out exactly
the trees in the bounds (with tag, only the ones this streamer planted)
and their crowns, and the others keep their levels and fades.
The forest keeps its trees as floats relative to an anchor near the camera
(Forest.anchor): set on the camera’s cell in the true world when the forest
is made, so a game that starts far out plants exactly from the first tree, and
moved by whole cells once the camera is anchor_distance metres away (8192 by
default) – a fraction of a millisecond, no replanting. Every tree’s true
position is also kept in doubles, from which each float is written again when
the anchor moves, so trees do not shake however far from the anchor they were
planted. It places its nodes at the anchor less the environment’s
world_origin and moves them at every shift: never move forest.root or
forest.depth_root.
The canopy map. The crowns’ top-down map that darkens the forest floor
under acron.pipeline is a window round the
camera: Forest(canopy_extent=2048.0) metres square at canopy_texel
(2 m) a texel, at most 2048 texels a side. As the camera goes, only the
strips coming into the window are painted; a planting or a cut repaints the
16 x 16-texel tiles under its crowns alone, at most canopy_budget
texels a frame (65536, about a quarter of a millisecond), the nearest
first, and only the pages that changed go to the GPU. It costs the same in
a world of any size. Trees and Forests has the details.
Streaming the ground¶
The grass and the ecosystem grow on an acron.ecosystem.Terrain, a
paged terrain: regions under keys, each a heightfield with its masks over
a rectangle of the true world, added as the game builds a tile and removed
as it frees it. Outside every region there is no ground: no grass, no
plants, height() is None.
from acron.ecosystem import Grass, Terrain
ground = Terrain()
grass = Grass(env, ground, density=48, build_budget=2,
ground=(0.07, 0.115, 0.035))
# tile built
ground.set_region((tx, ty), (x0, y0), size, heights, x_size=n, y_size=n,
roads=[(road_points, 6.0, 1.5)])
# tile freed
ground.remove_region((tx, ty))
The terrain works in true world metres, whatever the scene’s unit: with
metres_per_unit other than 1, convert the game’s true-world positions
(world units) by that factor.
set_region(key, origin, size, heights, ...) adds region key (any
hashable: a tile’s (tx, ty)), or replaces it whole, its old masks with
it. origin is its south-west corner and size its side (or (x, y)),
in metres; heights is an image or a texture (grey level x z_scale +
z_offset), x_size x y_size floats in rows from north to south,
or a number for level ground. The masks come with the region
(exclusion=, moisture=, water=) or later with
set_mask(); roads are paths painted into
this region’s exclusion mask, clipped to it (each (points, width) or
(points, width, verge), true world metres). Give each region its own
roads: paint_road() paints only the regions
there now, not those added later.
Regions should meet edge to edge, their border texels on their edges: the ground, its normals and its slopes are then seamless across them. Where two overlap, the one set last wins. A lookup costs the same however many regions there are.
The grass follows. A region added is grown into within the grass’s
build_budget (cells a frame, nearest first; at a density of 64 a cell takes
about 2 ms, so a fast vehicle wants 2 rather than the default 8); a region
removed takes the cells wholly inside it at once (those it only partly covered
are laid out again within the budget); a region replaced lays out only its own
cells again, drawing the old blades until then. The grass lays out in true
world metres, puts each cell’s node at the cell’s corner, and places its cells
again at every shift, so its blades, its wind waves and its trample map stay
where they were – exactly, at any distance from the true origin: the shaders
read each cell’s corner modulo 8192 m and noises that repeat over that period.
Press and read the trampling with Grass.stamp and Grass.flatness (true metres); grass.trample, the native
map, counts from an anchor of its own. Pass the far fade’s colour as an RGB
triple (ground=): a colour image covers one rectangle, not a streamed world.
The ecosystem follows too, over the same terrain: a tile asked for before
its ground has come waits (Ecosystem.waiting) and is simulated by a
later simulate_tiles() or
plant() once the ground covers it
(Ecosystem.is_ready(tx, ty); wait_for_halo=True waits for the
ground round it too). The grass under a tile simulated or forgotten later
is laid out again. A tile does not forget itself when its ground goes: the
game calls forget (Ecosystems and Grass).
A scene in one piece – a level, a test, a sample – needs no regions of
its own: Terrain.from_heights(heights, origin=, size=),
Terrain.flat(origin=, size=, z=) and Terrain.procedural(size, ...)
make a terrain of one region.
Weather and clouds¶
Nothing to do: the clouds, the rain, the lightning and the clouds’ shadows
stay where they are in the true world. CloudRenderer
gives the native weather field the environment’s world_origin
(WeatherField.world_offset, Clouds and Weather), which works in the true
world less whole weather tiles and is as precise 10,000 km out as at the
origin; the shadow map and the screen history move with the scene. The
fog’s noise is fixed in the true world (Volumetric Fog).
A tile streamer¶
Put together, in a world of metres (metres_per_unit 1), with tiles of
256 m kept round the camera and the origin moved back every 2 km:
from acron.ecosystem import Grass, Terrain
from acron.trees import Forest, Species
TILE = 256.0
KEEP = 3 # tiles each side of the camera's
SHIFT_AT = 2048.0 # how far the camera may go from the origin
class TileStreamer:
def __init__(self, base, env, shadows):
self.base, self.env = base, env
self.ground = Terrain()
self.forest = Forest(env, shadows=shadows)
self.grass = Grass(env, self.ground, density=48, build_budget=2,
ground=(0.07, 0.115, 0.035), shadows=shadows)
self.oak = Species.load("oak")
self.tag = self.forest.new_tag()
self.tiles = {} # (tx, ty) -> the tile's mesh node
base.task_mgr.add(self.update, "tile-streamer", sort=0)
def build(self, tx, ty):
x0, y0 = tx * TILE, ty * TILE # true world
heights, n = make_heights(tx, ty) # the game's own
self.ground.set_region((tx, ty), (x0, y0), TILE, heights,
x_size=n, y_size=n,
roads=roads_in(tx, ty))
trees = [(x - x0, y - y0, self.ground.height(x, y))
for x, y in tree_spots(tx, ty)] # in the tile
self.forest.plant(self.oak, trees, origin=(x0, y0, 0.0),
tag=self.tag)
node = make_tile_mesh(heights, n, TILE) # from the corner
node.reparent_to(self.base.render)
self.tiles[tx, ty] = node
self.place(tx, ty)
def free(self, tx, ty):
x0, y0 = tx * TILE, ty * TILE
self.ground.remove_region((tx, ty))
self.forest.unplant((x0, y0, x0 + TILE, y0 + TILE), tag=self.tag)
self.tiles.pop((tx, ty)).remove_node()
def place(self, tx, ty):
# the game's own node: true corner less the origin, in doubles
ox, oy, oz = self.env.world_origin
self.tiles[tx, ty].set_pos(tx * TILE - ox, ty * TILE - oy, -oz)
def update(self, task):
cam = self.base.camera
p = cam.get_pos(self.base.render)
if max(abs(p.x), abs(p.y)) > SHIFT_AT:
# the scene back under the camera, by whole tiles
dx = round(p.x / TILE) * TILE
dy = round(p.y / TILE) * TILE
cam.set_pos(p.x - dx, p.y - dy, p.z)
self.env.shift_origin(dx, dy)
for t in self.tiles:
self.place(*t)
p = cam.get_pos(self.base.render)
ox, oy, _ = self.env.world_origin
cx, cy = int((p.x + ox) // TILE), int((p.y + oy) // TILE)
wanted = {(cx + i, cy + j) for i in range(-KEEP, KEEP + 1)
for j in range(-KEEP, KEEP + 1)}
for t in set(self.tiles) - wanted:
self.free(*t)
for t in wanted - set(self.tiles):
self.build(*t)
return task.cont
make_heights, roads_in, tree_spots and make_tile_mesh are the
game’s: they work in true-world coordinates, and the mesh in metres from the
tile’s corner, so its vertices stay small numbers. A game without a mesh of
its own can take the terrain’s: ground.make_mesh(step=4,
region=(x0, y0, x0 + TILE, y0 + TILE), origin=(x0, y0)) gives vertices in
metres from origin, subtracted in doubles. The streamer moves only
what it owns – the camera (here parented to render; a camera on a
moving vehicle moves with the vehicle, which the game moves) and its tile
meshes, placed from doubles rather than moved by a large offset – and the
forest, the grass, the fog, the shadows and the clouds follow the shift by
themselves. It moves the scene and calls shift_origin in one place;
any sort would do. A real streamer
builds a tile or two a frame rather than all at once, and frees coarser
levels of detail beyond the grass’s reach (90 m by default) or the trees’.
Precision¶
The scene stays near the camera, so the engine’s float32 positions keep their millimetre.
True-world values the modules hold are doubles, or floats relative to something nearby: the forest’s anchor, a grass cell’s corner, the weather field’s tile, the canopy map’s window.
Shader patterns read
true_world(), exact for periods that divide 8192 m.The forest keeps every tree’s true position in doubles besides its floats.
The grass is exact at any distance: its shaders read cell corners and noises modulo 8192 m, and its trample map counts from an anchor held in doubles. The ecosystem’s tile tables are float32 in true metres (8 mm at 100 km: fine for placing trees).
Known limitations¶
The clouds’ layer stretch (the stratiform noise’s large-scale skew) is not periodic: after about 100 km of travel, or hours of wind, the stratiform noise can look compressed where the layer’s thickness varies.
The grass’s far fade takes one colour or one image over one rectangle, not a colour per region.
Ecosystem tiles are not forgotten when their ground is removed; the game calls
forget.The frame pipeline’s TAA may show isolated pixels one step different at hard edges on the frame of a shift (float rasterisation).