Drawables and SceneObjects
This is a reference for the visual side of BGE: every Drawable subclass, the SceneObject each one registers with the Renderer, and how the Renderer actually turns a scene full of SceneObjects into pixels every frame. Read Building a Game with BGE first if you haven't - this guide assumes you already know how a Drawable attaches to a GameEntity.
The pipeline, in one sentence
A Drawable doesn't draw itself. GameEntity.addDrawable(name, drawable) attaches it, and once per frame Drawable.addToRenderer(rendererObj) registers a matching SceneObject with the Renderer - from then on, the Renderer owns drawing it, not the Drawable. The Drawable still computes its own transformation matrix from offset/rotation/scale (see Drawable.computeTransformationMatrix), but the actual per-frame draw call, camera-relative positioning, and draw-mode handling all live on the SceneObject side.
A Drawable doesn't strictly need a GameEntity - pass invalid as its owner to draw it straight through a standalone Renderer, with no Game at all:
renderer = new BGE.Renderer(myBitmap)
box = new BGE.DrawableRectangle(invalid, 40, 20, {offset: BGE.Math.VectorOps.create(100, 50, 0)})
box.addToRenderer(renderer)
renderer.render()It then behaves as if owned by an entity at the world origin with no rotation and a scale of 1, so its offset is its world position. Anything that needs a Game quietly does nothing instead: logging, pausing an animation while the game is paused, and a DrawableOrientedSprite picking its facing from the game camera. A DrawableText with no font uses the system default font.
Every Drawable / SceneObject pair
| Drawable | SceneObject | What it draws |
|---|---|---|
Image | SceneObjectImage | A single bitmap region - the basic sprite. |
Sprite | SceneObjectImage | An Image subclass that indexes into a sprite sheet by frame number. |
AnimatedImage | SceneObjectImage | A Sprite that advances its own frame index over time. |
DrawableRectangle | SceneObjectRectangle | A filled and/or outlined rectangle. |
DrawableCircle | SceneObjectCircle | A filled and/or outlined circle - foreshortens into an ellipse when oriented in 3D. |
DrawableSphere | SceneObjectCircle | A DrawableCircle that always renders as an undistorted circle, regardless of camera angle. |
DrawableOrientedSprite | SceneObjectImage | A Sprite that swaps its active animation based on the camera's angle to the entity, faking a Doom-style billboard sprite. |
DrawablePolygon | SceneObjectPolygon | A filled (its convex hull, or as drawn with concave) or outlined polygon (see below). |
DrawableLine | SceneObjectLine | A single line segment between two points. |
DrawableText | SceneObjectText | Text rendered with a roFont. |
Model3d | SceneObjectModel | A triangle-mesh 3D model (loaded via Game.load3dModel, see STLParser). |
DrawablePlane | SceneObjectPlane | A textured ground/floor plane, rendered with a Mode-7-style perspective warp (see below). |
DrawableWalls | SceneObjectWalls | A level's walls as segments at any angle with their own heights - one textured strip per few screen pixels (see below). |
DrawableGridWalls | SceneObjectWalls | DrawableWalls built from a grid maze's map (see below). |
DrawableWall | SceneObjectWall | A freestanding upright wall between two floor points, its texture stretched or tiled (see below). |
DrawableParallaxLayer | SceneObjectParallaxLayer | A scrolling/tiling background (or foreground) layer that moves at a configurable fraction of the camera's movement. |
DrawableParticles | SceneObjectParticle | A whole emitter's worth of simulated particles (lines, rectangles, or images), drawn through one SceneObject for the entire emitter (see below). |
(billboard drawables, e.g. images used with directToCamera/directScaled draw modes) | SceneObjectBillboard | Always faces the camera regardless of its own rotation. |
Every SceneObject subclass lives under src/source/engine/renderer/sceneObjects/. If you're adding a new visual primitive, the pair goes together: a Drawable subclass that computes its own geometry/transform, and a SceneObject subclass whose addToRenderer call the Drawable invokes.
Rectangles
DrawableRectangle is the primitive to reach for when you want a solid block of color - a paddle, a brick, a health bar, a HUD panel. GameEntity.addRectangle builds and attaches one in a single call:
' a 150x20 white paddle, drawn from the entity's position
m.addRectangle("body", 150, 20, {color: BGE.ColorsRGB.White})color and outlineRGBA are packed RGB (0xRRGGBB), which is what every Drawable takes - BGE.ColorsRGB is the named-color enum in that format, and alpha is a separate field. That's a different format from the packed RGBA (0xRRGGBBAA) that the Renderer.draw* calls and BGE.Colors use, and mixing the two up gives you a plausible-looking wrong color rather than an error.
A rectangle is anchored at its top left corner by default (anchor (0, 0)) and extends right and downwards on screen, the same as an Image. Call setAnchor(x, y) with normalized 0-1 coordinates to pivot around a different point instead - setAnchor(0.5, 0.5) centers it on the entity's position, setAnchor(0.5, 1) plants its bottom edge there (handy for a sprite that should grow from the ground up rather than from its center). Every Drawable with a rectangular width/height (Image, Sprite/AnimatedImage, DrawableRectangle, DrawableText) supports this the same way. Without setAnchor(), nothing changes - offsetting the drawable by half its size to fake a centered anchor still works exactly as before:
cornerOffset = BGE.Math.VectorOps.create(-width / 2, height / 2)
m.addRectangle("body", width, height, {color: BGE.ColorsRGB.Yellow, offset: cornerOffset})
' a RectangleCollider covers the same area for the same offset, so the two line up
m.addRectangleCollider("body", width, height, cornerOffset.x, cornerOffset.y)To resize one later, call setSize(width, height) rather than assigning to width/height directly (they're deliberately not public). A resize isn't movement, so the renderer's dirty-checking can't see it - setSize calls Drawable.invalidateGeometry(), which bumps a geometryVersion the SceneObject compares against to know it must recompute projected geometry even though nothing moved. Any Drawable that changes shape in place should do the same.
Outlines
Setting outlineRGBA on any billboard drawable - a rectangle, a polygon, an image, text - strokes an outline around it. There's no separate on/off flag: a color means yes, invalid (the default) means no, and the renderer skips all outline work when there isn't one. outlineWidth sets the thickness in pixels.
' a lime rectangle with a 2px white border
m.addRectangle("brick", 112, 30, {
color: BGE.ColorsRGB.Lime,
outlineRGBA: BGE.ColorsRGB.White,
outlineWidth: 2
})
' outline only, no fill - needs an outline color, or nothing is drawn at all
m.addRectangle("frame", 200, 100, {filled: false, outlineRGBA: BGE.ColorsRGB.Cyan})The stroke lives on SceneObjectBillboard, which draws it over the top of the fill each frame along the object's canvas corner points. Two consequences worth knowing:
- The outline is stroked in canvas space, so it stays a constant width rather than warping with perspective in the
orienteddraw modes. For a 1-2px stroke that generally looks better than the alternative, but it does mean an outline isn't baked into the cached temp bitmap and is re-stroked on every frame - which is why it's opt-in viaoutlineRGBA. - A
SceneObjectwhose shape isn't a single quad has to opt out by returninginvalidfromgetOutlineCanvasPoints(), which is whatSceneObjectModeldoes - outlining a triangle mesh means thewireFramedraw modes, not this.SceneObjectPolygonoverrides the same hook to stroke along its own point list instead of the inherited quad.
In the wireFrame draw modes the outline is the entire drawing, so it's stroked once by drawToCanvas and skipped by the hook. Those modes fall back to the fill color when no outlineRGBA is set, which is why they look the same as they always did.
Texture columns for flat quads
Images, sprites, text, circles and filled rectangles in the oriented and solid draw modes draw as projected texture columns: one DrawTransformedObject per column of the texture, placed and sized in camera space, so the result is perspective correct with no scratch or temp bitmaps. On a Camera2d the same columns are projected orthographically. How many columns a quad gets comes from render quality (quadColumnsPerTexel, quadMinPixelsPerColumn), and a per-frame budget keeps the draw count under Roku's queue limit. A slab is drawn affine, so it's only wrong where depth changes across it: quadMaxAffineErrorPixels caps the columns at as many as keep that error under its pixel count. A quad at near constant depth (facing the camera, or any quad on a Camera2d) then draws as one slab; a wall seen edge on gets many. Ultra turns the cap off. It isn't applied to quads with per-corner tints, whose colour blends per column. Each column is a slab a power of two texels wide, drawn whole, so fewer columns don't drop texture detail. A quad seen mirrored (from behind) would need each slab mirrored within its column, and a negative scale can't be rotated on a real Roku, so it draws slabs from a flipped copy of the texture instead, made once (one extra texture-sized bitmap per texture seen from behind). Text, whose bitmap is redrawn in place, gets no copy and draws each column's middle texel alone, with no error cap. Textured model faces mirror the same way, from one copy shared by every face using the texture.
Columns go straight to the canvas only while the object moves relative to the camera. Once it's still, its columns are drawn once into its temp bitmap and that is blitted, since one blit is far cheaper than redrawing every column each frame.
A quad that comes out as a plain rotated rectangle on screen (facing the camera, rotated only about the view axis) still takes the one-call fast path, because a single draw beats any number of columns.
The column cuts (BGE.QuadColumnTexture) are made once and shared:
- A sprite's frames are cut through its
BGE.SpriteFrames(getColumnTexture(frameIndex)), so every sprite sharing those frames shares the cuts. The regions inSpriteFramesare never touched. - Other textures are cached by the renderer under their region id (
Renderer.getQuadColumnTexture()). - Filled rectangles use one shared white texture, tinted (
Renderer.getWhiteColumnTexture()).
How a rectangle is drawn, and why it's a billboard
SceneObjectRectangle extends SceneObjectBillboard, so a rectangle orients and foreshortens in 3D just like an image (see examples/3d's RectanglesScene, which cycles a ring of panels through every draw mode). But it's one flat color with no texture to sample, so DrawableRectangle never has to hold a bitmap of its own.
In the oriented and solid draw modes, a filled rectangle is drawn as texture columns: tinted columns of a shared white texture, projected straight onto the canvas while it moves (see Texture columns below). Once still, it fills a temp bitmap with two triangles and blits that, exactly like a polygon does. Filling a rotated quad is far too expensive to repeat every frame for something that hasn't moved - skipping the cache here cost examples/3d's RectanglesScene about two thirds of its frame rate (22 FPS vs 63) before it was put back. Whether a SceneObject caches a given draw mode is usesTempBitmap(drawMode), which SceneObjectRectangle overrides to also require filled - an outline-only rectangle has no fill worth caching.
In the direct (billboard) draw modes with no rotation - which is the 2D case, since a Camera2d resolves matchCamera to directToCamera - it takes a shorter path still, going out as a single DrawRect with no triangle rasterization and no bitmap at all. That's the path examples/breakout runs on for its paddle, ball and every brick.
Keeping the billboard base (rather than making a rectangle a 4-point DrawablePolygon) is what buys the rest: backface culling and per-face isShaded shading, both of which need the surface normal a quad has and an arbitrary polygon doesn't; the direct/billboard draw modes, which SceneObjectPolygon ignores entirely; and a frustum check over the 4 already-computed world corners instead of SceneObjectPolygon.getPositionsForFrustumCheck's scan-every-vertex bounding cube (whose 8 corners collapse to the same 4 points for a flat quad anyway - pure overhead here).
Circles and Spheres
DrawableCircle is a filled (and optionally outlined) circle. GameEntity.addCircle builds and attaches one the same way addRectangle does, just with a radius instead of a width/height:
' an 80-radius red circle with a white outline
m.addCircle("body", 80, {color: BGE.ColorsRGB.Red, outlineRGBA: BGE.ColorsRGB.White, outlineWidth: 2})Like a rectangle, a circle is anchored at the top left of its bounding square by default and extends radius * 2 right and down - setAnchor/setSize-style resizing works the same way too, via setRadius(radius) rather than assigning radius directly (a resize isn't movement, so it has to call invalidateGeometry() for the same reason DrawableRectangle.setSize does).
Where a circle differs from a rectangle is how it's drawn - it has no cheap way to fill itself, so it uses two different techniques for its fill and its outline:
- Fill: a texture blit, not a rasterized shape.
Renderer.getCircleResource()rasterizes a circle once (lazily, the first time anything asks for it) and everyDrawableCircle/DrawableSpherein thatRenderershares the same bitmap -SceneObjectCirclejust returns a region of it fromgetRegionWithIdToDraw(), exactly the waySceneObjectImagereturns a region of the bitmap itsImagewas constructed with. This gets the same pinned-corners warp, color-tinting, and temp-bitmap caching anImagegets in the oriented draw modes, for free. - Outline: computed fresh, not baked into the texture.
outlineSegments(default 24) points are placed around the ellipse inscribed in the object's own already-transformed quad -SceneObjectCircle.getOutlineCanvasPoints()derives the ellipse's two axes directly from the quad's own corner vectors, so the outline automatically foreshortens along with the fill in the oriented draw modes without a second world-to-canvas transform pass.
A texture-backed fill means a circle pays the same pinned-corners cost an Image pays in the oriented/solid draw modes - real per-pixel perspective warping, not the cheap flat 2-triangle fill DrawableRectangle/DrawablePolygon get away with, since neither of those has a texture to sample. SceneObjectCircle opts solid/solidDrawBackFace into the same temp-bitmap caching the oriented modes already get, by overriding usesTempBitmap() (the same extension point SceneObjectRectangle overrides for its own reason - skipping the cache for an unfilled rectangle), since - unlike DrawableRectangle, whose solid-mode fill is cheap enough not to need it - a circle's solid fill is exactly as expensive as its oriented fill.
DrawableSphere is a DrawableCircle that forces drawMode = SceneObjectDrawMode.directScaled in its own constructor, so it renders identically in every way except one: it never turns to face a direction and never foreshortens into an ellipse, because a sphere looks the same from every angle. No separate SceneObjectSphere class exists for this - SceneObject.getActualDrawMode() only resolves the matchCamera default through the camera, so any other explicit drawMode (this one included) is used exactly as given. examples/3d's CirclesScene puts a ring of alternating CirclePanel/SpherePanel entities side by side, so orbiting the camera shows the difference directly: the circles turn edge-on and thin out, the spheres next to them don't move at all.
DrawableOrientedSprite is a Sprite that fakes full 3D orientation the way classic Doom/Duke3D monster sprites do: instead of one animation per action, it registers one animation per (elevation band, angle bucket) via addOrientedAnimation()/ addElevationOrientedAnimation(), and every frame swaps which one is actually playing based on the angle between the camera and the entity - GameEntity.addOrientedSprite builds one. Bucket 0 (of numAngles, default 8) is the entity's front facing the camera, and buckets increase clockwise as viewed from above; numElevationBands (default 1, meaning no vertical distinction) optionally adds a second axis for a sheet that also draws a distinct top-down or bottom-up view. Every bucket needs its own real art, unless the character is roughly left/right symmetric: set mirrorBuckets = true before registering, give only buckets 0 (front) to numAngles / 2 (back), and the other side draws the matching bucket flipped (via scale.x), nearly halving the sheet. Weapons and shields swap hands in the mirrored directions. See examples/terrain's Guard entity for a runnable demo, and specs/2026-09-22-oriented-sprite-billboards-design.md for the full design.
For a sheet laid out one direction after another, addOrientedAnimationColumns() builds every bucket from the frame columns of one direction, and frame rates can be fractional. BGE.frameRateFor(frameCount, seconds) gives the rate that fits a set time:
' 16 directions, 24 frames each; the run is columns 4-11 of every direction
sprite.addOrientedAnimationColumns("run", [4, 5, 6, 7, 8, 9, 10, 11], 24, 9.5)
' a 3-frame windup that has to last exactly as long as the attack's 1.1s telegraph
sprite.addOrientedAnimationColumns("windup", [12, 13, 14], 24, BGE.frameRateFor(3, 1.1), BGE.SpritePlayMode.Forward)For a walk or run, BGE.frameRateForStride(frameCount, stride, speed) gives the rate that keeps the feet from sliding: one loop of the cycle per stride travelled. examples/thirdPerson plays its 8-frame run at BGE.frameRateForStride(8, World.metres(3.3), speed).
Both Sprite and DrawableOrientedSprite accept an array of sheet bitmaps instead of one, so a large character can be split across sheets that each fit the device's bitmap size limit (or by animation, loading only what a scene needs). Every sheet uses the same cell size, and frame numbers run across them in order:
' 16 frames in walk.png (0-15), then 16 in attack.png (16-31)
sheets = [m.game.getBitmap("walk"), m.game.getBitmap("attack")]
sprite = m.addOrientedSprite("body", sheets, 128, 128)When many entities use the same sheet, ask the game for its frames instead of passing the bitmap. Every sprite made from them shares one set of regions, so spawning another enemy doesn't slice the sheet again:
frames = m.game.getSpriteFrames("orc", 128, 128) ' cached until "orc" is unloaded
sprite = m.addOrientedSprite("body", frames, 0, 0, 16)A grid makes every cell as big as the biggest frame in any direction. A packed sheet stores each frame trimmed to its own pixels, with its rect and its offset inside the untrimmed cell, so it still lines up with the others. setAnchor() is measured on the untrimmed cell. Load a JSON atlas (tools/render-character.py --packed writes one) and its sheets with loader.loadSpriteAtlas(), then ask the game for its shared frames (see Sprite atlases):
' in GameScene.onLoad(): orc.json and the orc.png, orc_1.png, ... sheets it lists
loader.loadSpriteAtlas("orc", "pkg:/sprites/orc.json")
' then, once loaded
frames = m.game.getSpriteAtlasFrames("orc")
sprite = m.addOrientedSprite("body", frames, 0, 0, 16)The frames can also be given directly, as BGE.SpriteFrameRects ({sheet, x, y, width, height, offsetX, offsetY, sourceWidth, sourceHeight}): m.game.getSpriteFrames(["orcSheet", "orcSheet2"], 0, 0, frameRects).
Playing the animation that's already playing keeps its place, so you can call it every frame, and so does turning to another direction of it. To replay a one-shot from its first frame, such as a second attack in a combo, pass restart:
sprite.playOrientedAnimation("attack", true) ' Sprite.playAnimation() takes it tooAn animating sprite is redrawn and re-sorted every frame. For a crowd, give an animation a far stand-in, such as one frame of it, that plays past lodDistance from the camera (across x/z). The distance is rechecked every lodCheckSeconds (0.5), at a different moment for each sprite. Animations without a stand-in (a walk) carry on as they are:
sprite.addOrientedAnimationColumns("still", [0], 4, 1)
sprite.lodDistance = 320
sprite.setLodAnimation("idle", "still")
sprite.playOrientedAnimation("idle") ' plays "still" while the camera is over 320 away
' sprite.isLodFar() says which side it was last time, e.g. to only wander about where seenPolygons
DrawablePolygon fills (or, in the wireframe draw modes, strokes) a flat polygon from its points. By default the fill is the points' convex hull, whatever order they're in, so a chevron or a star comes out with its notches filled in. That's the cheapest fill: a big convex polygon is drawn as exact triangles.
Set concave = true to fill the outline as drawn. The points must then go round the outline in order (either way round):
arrow = new BGE.DrawablePolygon(m, [
BGE.Math.VectorOps.create(-40, -30, 0),
BGE.Math.VectorOps.create(40, 0, 0),
BGE.Math.VectorOps.create(-40, 30, 0),
BGE.Math.VectorOps.create(-10, 0, 0)
], {concave: true, color: BGE.ColorsRGB.Yellow})
m.addDrawable("arrow", arrow)For an outline that crosses itself, fillRule says what's inside: BGE.PolygonFillRule.nonZero (the default, as in SVG) fills a star drawn as one line solid; BGE.PolygonFillRule.evenOdd leaves its centre hollow.
A concave polygon is filled with one DrawRect per run of equal pixel bands (Renderer.drawConcavePolygonTo(), a scanline fill), banding across the shorter side of its bounding box. The bands never overlap, so a translucent polygon blends once everywhere, even where a self-crossing outline overlaps itself. There's no exact triangle fill to fall back on, so a big concave polygon costs more than its hull would: roughly one rect per pixel row, more where the row crosses several arms (a 300 px star is ~15 ms on a Roku Express). So once a concave polygon is still, in every draw mode, it's filled into a cached bitmap that is blitted while nothing changes: at rest it costs one blit a frame. While it (or the camera) moves, the cached bitmap is moved into place where it fits; otherwise it's filled straight onto the canvas, with coarser bands (RenderQualitySettings.triangleQuickDrawStep) once it's more than 48 px across its banded side. Either way it's redrawn exactly when it stops. Points that happen to be convex in order take the normal hull path, so the flag costs nothing on a convex shape.
Changing points, concave, fillRule or the color redraws the polygon. If a corner fails to project (behind a 3D camera), the polygon fills its hull for that frame, since dropping a corner would join two that aren't neighbours. A polygon is depth sorted by its hull, so an object in a notch may be ordered against it when it needn't be, but never wrongly, and polygons are never occluders (see "Occluders and visibility"), so a notch can't hide what's behind it.
SceneObjectDrawMode
Every SceneObject has a SceneObjectDrawMode, controlling how it reacts to the camera's rotation and perspective:
| Draw mode | Behavior |
|---|---|
matchCamera | Follows the camera's rotation/perspective like a normal 3D object. |
directToCamera | Always faces the camera (billboard), ignoring its own rotation. |
directScaled | Like directToCamera, but sized by camera distance - a Doom-style sprite. |
axisAligned | Stands upright in the world and turns to face the camera's yaw; foreshortens with pitch. |
oriented / orientedDrawBackFace | Respects its own rotation in 3D, optionally drawing back faces. |
wireFrame / wireFrameDrawBackFace | Outline-only rendering of the triangle mesh. |
solid / solidDrawBackFace | Filled triangle rendering. |
This is what gives a fundamentally 2D-raster engine its pseudo-3D/billboard capability (see examples/3d) - examples/rendererTest has a runnable demo per mode (DemoList.bs).
For a model, a face's front is the side it's wound counter-clockwise from - the usual .obj/.stl convention, so its outside. The modes without DrawBackFace draw only faces turned toward the camera, and isShaded shades each face - by how squarely it faces the camera, or by the scene's lights once it has some (see Lighting).
matchCamera, directToCamera and directScaled are the screen-aligned (billboard) modes - isScreenAlignedDrawMode() - and they keep an object square to the screen instead of turning it in 3D. directScaled is the Doom-sprite one: it faces the camera and its on-screen size comes from how far away it is, independently of its own rotation. That independence is the whole point, and it's why SceneObjectBillboard builds the quad from the camera's own right/up axes in world space and then projects it (updateCanvasPointsForCameraFacingQuad), rather than measuring the object's own projected quad - measuring the latter would fold the object's orientation into its size, so a sprite turned edge-on would squash. For the same reason a screen-aligned object is never backface culled: it has no face to turn away. axisAligned is the upright version of directScaled, for characters, trees and props standing on the ground. It turns to face the camera around the world's vertical axis only, so it never goes side-on, but it stays upright in 3D: as the camera looks further down on it, it gets shorter with the real perspective instead of leaning back at the camera like a cardboard cutout. Anchor it at its feet so they stay planted while the top tilts away. axisAlignedFullHeightPitch is the angle (degrees) the camera looks down from when it's drawn full height. Set it to the elevation your art was rendered from:
knight = m.addOrientedSprite("body", sheet, 128, 128)
knight.drawMode = BGE.SceneObjectDrawMode.axisAligned
' the sheet was rendered looking 12 degrees down on the character
knight.axisAlignedFullHeightPitch = 12
knight.setAnchor(0.5, 1)Unlike the other billboards it banks when the camera rolls, tilting with the ground it stands on (banksWithCameraRoll doesn't apply). examples/rendererTest's "axisAligned Billboards" demo shows it next to directScaled.
BGE.getDrawModeName(drawMode) gives you a mode's name, for debug overlays or for an example that lets you cycle through them (examples/3d's BaseScene displays it on screen).
Lighting
A drawable with isShaded = true (models are shaded by default) is darkened by how it's lit. With no lights, that's a headlight: each surface is as bright as it is square-on to the camera. Add lights to light the scene from fixed directions and positions instead, in color:
' a blue-ish sun, shining down and away from the camera (+y is up)
sun = new BGE.DirectionalLight(BGE.Math.VectorOps.create(-1, -1, -0.5), &h6080FF, 0.8)
game.addLight(sun)
' a red lamp that fades out 600 units away
lamp = new BGE.PointLight(BGE.Math.VectorOps.create(0, 60, 200), 600, BGE.ColorsRGB.Red, 1.5)
game.addLight(lamp)
' a little light everywhere, so nothing in shadow is flat black
game.addLight(new BGE.AmbientLight(BGE.ColorsRGB.White, 0.15))To aim a light from a point in the sky, BGE.Math.directionFromYawPitch(yaw, pitch) points at it (a heading, and radians above the horizon); negate it for the way the light travels:
towardMoon = BGE.Math.directionFromYawPitch(BGE.Math.DegreesToRadians(150), BGE.Math.DegreesToRadians(35))
game.addLight(new BGE.DirectionalLight(BGE.Math.VectorOps.scale(towardMoon, -1), &h9DB4F0, 0.75))There are three kinds:
| Light | Lights a surface by |
|---|---|
DirectionalLight | how squarely it faces into direction (the way the light travels) |
PointLight | how squarely it faces position, fading linearly to nothing at range (0 never fades) |
AmbientLight | nothing - every surface gets the same amount |
Colors are RGB (0xRRGGBB, BGE.ColorsRGB). Each light's color * intensity is added up per channel, capped at full brightness, and multiplied into the surface's own color, so a red light on a white wall makes it red, and on a blue wall leaves it as dark as ambientBrightness allows. Drawable.ambientBrightness still applies, now per channel: it's the darkest any channel gets, so lower it to 0 if your lights (an AmbientLight, say) should decide how dark shadows are.
Lights can be changed any time - move a lamp, change its color, set enabled = false - and the renderer notices and relights whatever they reach. game.removeLight(light) and game.clearLights() take them away again (clearing them all goes back to the headlight).
A light added with game.addLight() stays across scene changes until you remove it. For a light that belongs to a scene or an entity, add it with theirs instead:
' in a scene's onCreate(): removed when the game leaves the scene (after onDestroy())
m.addLight(new BGE.AmbientLight(&h3A4C8A, 0.7))
' in a torch entity's onCreate(): removed when the torch is destroyed
m.addLight(new BGE.PointLight(m.position, 300, &hFF9440, 1.6))entity.removeLight(light) removes one early, and entity.getLights() lists them.
Ground planes take lights too: set isShaded = true on a DrawablePlane. A plane is flat, so directional and ambient light it evenly - its cached drawing is just tinted as it's drawn, which costs nothing extra. On a tiledImage plane, a point light with a range casts a pool of light on the ground beneath it, as wide as its range reaches and fading out toward the edge. Pools are blended over the texture (Roku can't multiply one image into another), so a bright pool fades the texture toward the light's color; lightPoolOpacity (0.4 by default) caps how far, so the ground still shows through. While a pool is in view, a light change redraws the plane rather than just re-tinting it - see the cost note below. A staticImage plane draws its pools, and the rest of its lighting, into a lit copy of its texture: one extra bitmap the texture's size, rebuilt only when its tint or a pool on it changes, so it costs nothing per frame. A light that changes every frame near it, or a point light with no range (whose light depends on where the camera is), rebuilds it every such frame. Pools would show over a texture's transparent areas, so set bakesLightPools = false on a decal that has any. A color plane, and a point light with no range, fall back to measuring the light on the plane right under the camera, so the ground brightens as you walk toward a lamp instead. Unlike other drawables, a plane with no lights isn't shaded at all.
Billboard characters take lights the same way. A sprite in a camera-facing draw mode (axisAligned, directScaled, directToCamera) has no surface of its own, so with isShaded it's lit as a cut-out turned toward the camera, from the centre of what it draws. Without lights it's left as it is. Set lightWrap to let light reach round past the lit side, so a figure with the light behind it is dim rather than black:
m.sprite = m.addOrientedSprite("body", frames, 0, 0, 16, 1, {
drawMode: BGE.SceneObjectDrawMode.axisAligned,
isShaded: true,
' 0.5: lit halfway when edge-on to a light, unlit only from straight behind
lightWrap: 0.5,
' let the AmbientLight decide how dark the shadows are
ambientBrightness: 0
})Cost. Lights are free while they stay still: objects keep their cached drawings until something moves. A light that moves or changes every frame relights everything it reaches every frame. Nothing is re-projected, so this costs less than moving those objects, but their cached drawings are still redrawn, so keep animated lights to the few that need it. A model with
useImpostor(the default) keeps its drawing through small light changes - while each light has turned less than the quality level'smodelImpostorMaxAngleDegreesand changed brightness by less thanmodelImpostorMaxLightChangesince it was drawn - so a slowly moving lamp only redraws it now and then. A lamp that moves while its pool is on screen redraws the ground plane's pools and re-slices it, but not its texture, once the pool has drifted more than the quality level'splaneLightPoolMaxDriftPixelsor changed color by more thanplaneLightPoolMaxLightChange. Shading is per triangle, from each one's centre, so a point light very close to a large flat face can light its triangles noticeably differently. There's no shadowing: a surface facing a light is lit even when something stands in between.
examples/rendererTest's Lighting demo (--param demo=lighting) cycles through these lights over a sphere, a cube, a flat panel and a tiled ground plane.
Draw-distance fade
With a Camera3d, nothing past the camera's draw distance is drawn. Instead of popping out of view at that limit, objects fade out across the far end of it:
camera = new BGE.Camera3d()
camera.maxDrawDistance = 1000
' fade across the last 20% (800-1000) instead of the default 15%
camera.drawDistanceFadeFraction = 0.2
game.setCamera(camera)Set drawDistanceFadeFraction = 0 for a hard cut-off. The fade multiplies whatever Drawable.alpha you've set, so an image at alpha 128 halfway through the band draws at 64.
When the draw distance changes - a new render quality level, or your game changing maxDrawDistance - the camera eases to the new distance over drawDistanceTransitionSeconds (default 0.75), so distant objects fade in or out gradually. Call camera.snapDrawDistance() after a camera cut to skip the transition.
Ground planes, skyboxes and parallax layers don't fade: they have no single distance from the camera. Everything else fades by its nearest corner, so a long wall stays solid while its near end is well inside the draw distance. Set Drawable.fadesWithDistance = false to keep something drawn at full strength wherever it is - for example a mist layer that stands at a fixed distance ahead of the camera, inside the fade band, to hide where the scene ends.
Something that gives off light, like a torch flame or a lit window, should show through fog further than the things around it. Drawable.fadeDistanceScale fades a drawable (and stops drawing it) as if the draw distance were that many times as far: with 2, a flame is still glowing at 1.5x the draw distance, over the fog backdrop, after its post has gone.
A ground plane always reaches the farthest any quality level would draw objects (1.5x maxDrawDistance with the default presets), so objects fade out on the ground rather than past its edge, and the horizon doesn't move when the quality level changes. Past the default distance, the ground's texture gets a little softer instead of costing more memory.
Fog
Fog lets distant things sink into mist instead of fading to the sky, so a scene can use a shorter draw distance without looking like the world just ends. Turn it on with the camera's fog, and mark the big things that make the skyline with castsFogSilhouette:
camera.fog.enabled = true
camera.fog.color = &h1C2842 ' RGB, like Drawable.color
camera.fog.backdropHeight = 256 ' world units, at the draw distance
' optional: a white image stretched over the backdrop and tinted the fog colour, e.g. one
' that's clear at the top for a soft edge
camera.fog.backdropRegion = mistRegion
house = new BGE.DrawableModel(m, model, {isOccluder: true, castsFogSilhouette: true})
walls = new BGE.DrawableWalls(m, segments, textures, {castsFogSilhouette: true})That does three things:
- The backdrop. The strip of screen from where the ground ends up to
backdropHeightat the draw distance, or the horizon if that's lower, is filled with the fog colour, behind everything. Objects fading out across the fade band (see above) now fade into fog rather than sky. - Silhouettes. A drawable with
castsFogSilhouettekeeps blocking the sky past the draw distance, out tofog.silhouetteReachtimes it (default 2), as a fog-coloured shape. A model is outlined by its own points, split up its height where its footprint shrinks sharply, so a tower on a long nave doesn't block the sky beside the tower and a pointed roof stays pointed; the outline is filled with rects in stairs at mostfogSilhouetteBandpixels tall and across, which the render quality level sets. An image is outlined by its corners.fog.silhouetteHulls = falsedraws up to three screen boxes per model instead: fewer draws, a looser outline. Across the fade band the silhouette is drawn behind the object, making up the opacity it has lostfog.silhouetteOpacityLeadtimes over (default 1). At 1 a fading object and its fog are up to a quarter see-through mid-fade; for solid buildings outlined by their points, 4 keeps the sky from showing through. Keep it at 1 for see-through casters (a tree image) or box silhouettes, or the silhouette shows round them early in the fade. Meant for buildings, towers and big trees; small props aren't worth it. - Walls. Level walls (
DrawableWalls,DrawableGridWalls) withcastsFogSilhouettekeep their real outline past the draw distance as flat fog-coloured strips, with solid fog under them across the fade band, so a fading wall and its fog add up to fully opaque.
For fog that fades things out without a skyline - a dungeon fading to black, say - set fog.silhouetteReach = 1: fading objects and walls still fade into the fog colour, but nothing is drawn past the draw distance.
With fog on, the draw distance stays at the camera's maxDrawDistance at every render quality level, so the fog's edge, the skyline and every fade stay put while the level changes: the level only changes how cheaply things inside it are drawn. To have the draw distance shrink at lower levels again for the speed, set fog.followsQuality = true; changes then ease in over fog.qualityTransitionSeconds (default 4) instead of the camera's drawDistanceTransitionSeconds (unless that's 0, which still applies them at once), so the fog creeps in rather than jumps.
All fog is drawn before the objects it's behind. Lower fog.silhouetteStartAlpha (default 1) to start the boxes and the fog under walls later in the fade band: cheaper, but they appear with a step where they start.
The fog fields are read every frame, so you can change them live. examples/rendererTest's Fog demo (--param demo=fog) cycles fog off / backdrop / backdrop + silhouettes, and demo=fog-benchmark times each.
Cost: the backdrop is one rectangle. Silhouette boxes cost about what the screen area they fill costs, and are repeated without being worked out again while nothing moves. Walls walk out to the reach, so the far part of a level costs a walk while the camera moves, and its fog strips are merged four at a time. In thirdPerson's town on a Roku Ultra, fog cost about 5% at the same draw distance, and fog at 22 m ran faster than no fog at 30 m.
Occluders and visibility
A big opaque thing in a 3D scene (a building, a wall, a hill) hides whatever stands behind it. Mark its drawable isOccluder: true and the renderer stops drawing everything it fully hides:
class Chapel extends BGE.GameEntity
override sub onCreate(args as roAssociativeArray)
m.isStatic = true ' an occluder's owner never moves
model = m.game.get3dModel("chapel")
m.addDrawable("chapel", new BGE.DrawableModel(m, model, {
isOccluder: true,
drawMode: BGE.SceneObjectDrawMode.solid
}))
end sub
end classAn occluder that's fading out with distance only hides things while fog fills in behind it (castsFogSilhouette with camera.fog on), since otherwise it's drawn see-through. Even then it doesn't hide a drawable with fadeDistanceScale above 1, which is meant to show through fog.
Game code can ask what happened to an entity last frame, for example to skip purely visual work for a tree nobody can see:
override sub onUpdate(dt as float)
if not m.isOnScreen()
return ' hidden or off camera: skip the sway animation
end if
m.animateSway(dt)
end sub
' Or tell the reasons apart:
if m.getVisibility() = BGE.VisibilityState.occluded
' something solid is in front of it
end ifgetVisibility() (on GameEntity, Drawable and SceneObject) returns a BGE.VisibilityState: visible (drawn), occluded (hidden behind an occluder), offCamera (outside the camera's view) or unknown (no drawables, or not drawn yet). An entity with several drawables reports the most visible one, in the order visible > occluded > offCamera > unknown. isOnScreen() is true for visible and unknown. Nothing in the engine skips an entity's onUpdate() or collisions for you; this is only a signal.
To see what's going on, call game.debugDrawOcclusion(true) (it shades the canvas areas the occluders cover and draws a red box around each hidden object), and read renderer.getOccludedCountLastFrame(). The terrain example has a static chapel that hides the trees behind it, and OK toggles occlusion in its WorldScene.
A few things the renderer enforces, which are easy to trip over:
- The drawable must be fully opaque (an image with no transparent pixels, a model with no translucent colors). The engine can't check this, so anything behind a see-through occluder would vanish.
- The owner must be
isStatic, and the drawable's draw mode must be an oriented one (oriented,orientedDrawBackFace,solid,solidDrawBackFace). Screen-aligned modes (matchCamera,directToCamera,directScaled) are ignored as occluders, and so is any occluder under aCamera2d. isOccludercan be turned on or off at any time, e.g. when a wall becomes see-through.- A standalone
SceneObjectwith no owner registers itself withrenderer.markOccluder(). - Occlusion is conservative: an object is only hidden when it is clearly behind the occluders, with a small safety margin, so a borderline object still draws. Screen-aligned fixed-size objects and text are never hidden; a particle emitter is hidden only once every live particle is.
- An occluder draws like anything else, cached bitmaps and coarse fills included. While it (or the camera) moves, the area it claims to cover shrinks by the largest error those shortcuts can make this frame, so it rarely hides something it doesn't actually paint over (a non-convex model can still briefly over-claim near its silhouette). A model redrawing its faces while moving draws them exactly and doesn't shrink; one reusing its impostor shrinks by just that frame's fit error. An object near an occluder's edge can therefore stay drawn while the camera moves, and is hidden again once it stops.
renderer.occluderDrawPolicychanges that trade-off. The default,BGE.OccluderDrawPolicy.fastShrink, is the behaviour above.exactmakes occluders always draw exactly and claim their whole outline (slower to draw, hides the most).fastExactClaimkeeps the shortcuts but still claims the whole outline, so an object just behind an occluder's edge can vanish for a few frames while the camera moves.- Tuning knobs on the
Renderer:occlusionCullingEnabled(defaulttrue),occlusionBandCount(45 horizontal bands),maxOccluders(32, the largest on screen are kept) andocclusionMargin(2.0 pixels of safety around each object). With no occluders registered the whole feature costs nothing. - Occlusion has its own cost: while the camera moves, the occluders are re-projected and each object is re-judged every frame. It pays off when what it hides is expensive to draw (warped textures, models), and barely breaks even when the hidden objects are cheap sprites.
renderer.getOcclusionMsLastFrame()andrenderer.getOcclusionTestsLastFrame()(objects that needed the full test) show what it costs you; compare frame times withocclusionCullingEnabledon and off.
Camera pitch (Camera3d.pitchMode)
A Camera3d shows the pitch in its orientation (looking up or down) one of two ways:
"rotate"(default): the view turns, a true perspective. Looking down, vertical lines converge towards the bottom of the screen."shear": the view stays level and the image moves down (looking up) or up (looking down) byfocal length x tan(pitch), held to ±60°. Vertical lines stay vertical, as in old voxel and raycast games. It's the pitch a voxel terrain can draw exactly, so objects sit on its hills at any pitch.
Everything the renderer draws follows the mode: models, sprites, walls, ground planes, the skybox, fog and culling. orientation keeps the pitch either way; getViewForward() is the direction projections look along (level under shear) and getPitchShiftY() how far the image moved (0 under rotate). Shear only reads as looking up or down at modest angles.
How Renderer.render() actually draws a frame
Renderer.render() (engine/renderer/Renderer.bs) runs once per frame, per canvas (there's a separate Renderer for the game canvas and the UI canvas). It does three things, in order:
updateSceneObjects()- recomputes world positions and camera-distance for every registeredSceneObject(see "Per-object update", below).- Sort by depth - by
negSortDepth(a stable sort), so farther objects draw first and nearer objects draw over them (simple painter's algorithm, no z-buffer). That'snegDistanceFromCamera, the depth along the view, unlessCamera.sortsByGroundDistanceis on: then it's the distance ahead across the ground, ignoring height. Turn that on for a camera that tilts down at sprites standing among tall props (a chase camera): along a tilted view a higher point counts as nearer, so a tall prop's centre sorts in front of a sprite standing nearer than it. Overlap clusters (computeOverlapClusters) still order their primitives by view depth. - Draw in two passes: every
SceneObjectPlanefirst, then every other enabledSceneObjectwhosenegDistanceFromCamera < 0(i.e. in front of the camera). Planes are drawn first because they're meant to be a ground/floor - drawing them before anything else means normal painter's-algorithm depth sorting for everything else (which does sort against the camera distance) still looks correct sitting on top of the plane. Objects hidden behind an occluder are skipped before this point (see "Occluders and visibility").
Per-object update (SceneObject.update/draw)
SceneObject.update(cameraObj) and .draw(rendererObj) are called every frame for every object, but most of the expensive work is skipped unless something actually changed:
objMovedLastFrame(the drawable's and its owner'sMotionCheckers) -Drawable/Camerause aMotionChecker(utils/MotionChecker.bs) for dirty-checking; if neither the object nor the camera moved since last frame,update()skips recomputing the transformation matrix and world position entirely.isPotentiallyOnScreen(cameraObj)- a cheap frustum check gate indraw(). If the object drew last frame and nothing has moved since, it skips straight to drawing; if the frustum culled it last frame and nothing has moved since, it stays culled without re-checking, which is what makes a static off-screen object free. A moving object always re-checks the frustum either way. Only a genuine cull latches this way: a draw that was attempted and failed is retried on the very next frame, becausefindCanvasPosition()andperformDraw()are both transient-failure-prone and both already recover. A camera projection change - its frame size or field of view, neither of which counts as camera movement - lifts the latch too, viaCamera.projectionVersion. On aCamera3dthe frustum's sides meet at the camera whengetPositionsForFrustumCheck()gives the object's real extent (two or more points), so an object just off the edge of the screen is culled. A single anchor point can't say how big its object is, so it gets a wider margin.findCanvasPosition(rendererObj, drawMode)- only re-run whenobjMovedInRelationToCamera()is true (the object or camera moved), there's no valid canvas position yet, or the camera's projection changed (Camera.projectionVersion, same signal as above). This is where aSceneObjectsubclass computes whatever camera-relative geometry it needs before drawing (e.g.SceneObjectPlanecomputes the frustum-to-plane intersection here - see below).performDraw(rendererObj, drawMode)- the actual draw call. SeveralSceneObjectsubclasses (SceneObjectBillboard,SceneObjectPlane) cache a rendered bitmap and reuse it across frames when nothing's moved, rather than re-rasterizing from scratch every frame - drawing that cached bitmap is far cheaper than recomputing the object's projected geometry and re-drawing it.- Draw replay - images (including sprites and walls) and models go one step further. When a still frame's
performDraw()came down to a single blit,draw()keeps that blit and, on later frames, repeats it without running any of the steps above, for as long as nothing that shaped it has changed: the object, its owner and the camera are still; geometry, draw mode, projection, quality, lighting, distance fade and fill color are the same; and so is the animation frame (getDrawReplayKey()), unless the new frame is the same size and offset and can simply be swapped in. On a device, the dozens of method calls a draw normally makes cost far more than the blit itself, so this is most of a still scene's frame. A region swapped by hand still has to callinvalidateGeometry(), as before. An unshaded image inaxisAlignedordirectScaledalso repeats while it and the camera move together - its blit only depends on where it sits relative to the camera, the camera's pitch and roll, and its scale (getCameraLockedReplayPose()), so something that follows the camera, like a fog band, stays a single replayed blit as the camera turns.
One supporting piece worth knowing about if you're touching rendering performance:
ScratchBitmapPool(engine/renderer/ScratchBitmap.bs) hands out reusable off-screen bitmaps for intermediate rendering work (now only the mirrored-and-rotated blit), so it doesn't need to allocate a freshroBitmapevery frame. Pooled bitmaps are handed out as-is, not cleared - if you draw into one and don't cover its entire area, whatever was left over from its previous, unrelated use will still be there. AlwaysClear()a scratch region yourself before drawing into it unless you're certain your draw call will fully cover it.
The cluster draw contract (getPrimitiveCount/getPrimitiveDepth/drawPrimitive/participatesInOverlapDetection)
Renderer.computeOverlapClusters (off by default) opts a renderer into detecting when two or more SceneObjects' projected screen bounds actually overlap (BGE.DepthSort's sort-and-sweep broad phase plus a convex-hull narrow phase) and, for any multi-member cluster it finds, interleaving their draws by depth instead of drawing each object atomically. That interleaving is built on four small, overridable SceneObject methods:
getPrimitiveCount()- how many separately-orderable pieces this object currently has. The base-class default (1) is correct for every billboard-familySceneObject- a quad, circle, piece of text, etc. is always one piece regardless of draw mode.getPrimitiveDepth(index)- the depth to sort primitiveindexby. The base-class default returns the object's ownnegDistanceFromCamera, correct for the single-primitive case. Every override must stay on the same convention - negative in front of the camera, ascending sort = farthest-first (matchingnegDistanceFromCameraand the main scene's own painter's-algorithm sort) - or its primitives will sort backwards against every other object's.drawPrimitive(rendererObj, index)- draws primitiveindexnow. The base-class default delegates to the object's normalperformDraw(), so a solo object's cluster-path draw and its normal draw path are the same call, not a second implementation to keep in sync.participatesInOverlapDetection()- whether this object is worth including in cluster detection at all. The base-class default (true) is correct for anything with real area, which the narrow phase can test via a convex hull of 3+ points.
A solo cluster (an object nothing else overlaps - still the overwhelming common case) draws exactly as it does today: whole-object temp-bitmap caching, one draw() call, no primitive enumeration. Only a genuine multi-member cluster pays for getPrimitiveCount()/ getPrimitiveDepth()/drawPrimitive() at all - Renderer collects every deferred cluster member's primitives into one combined list (spanning every cluster drawn that frame, not scoped per-cluster - harmless, since non-overlapping clusters were never going to visually interact anyway), sorts it once by depth, and calls drawPrimitive() in that order.
SceneObjectModel is the one type that overrides all three draw-contract methods: it exposes its per-face list (m.modelCanvasFaces, already rebuilt every frame by updateCanvasPosition(), already correctly reflecting the resolved draw mode's backface-cull behavior) via getPrimitiveCount()/getPrimitiveDepth(), and drawPrimitive() draws one face directly through a shared drawFaceToCanvas() helper - deliberately bypassing its own whole-model temp-bitmap cache, which aggregates every face in the model's own internal order and can't represent this face being interleaved with a different object's primitives.
Fixed (was tracked as #112): updateCanvasPosition()'s internal face sort is now SortBy("priority", "r") (descending, farthest priority value first), matching getPrimitiveDepth()'s own farthest-first convention. The solo draw loop (straight iteration over modelCanvasFaces, unchanged) and the cluster path now agree: a model's self-overlapping faces paint farthest-first, nearest-last-on-top, whether it's drawn solo or as part of a multi-member overlap cluster that frame.
SceneObjectLine and SceneObjectPlane both override participatesInOverlapDetection() to return false. Neither is a correctness workaround - a line's bounding points are always exactly its two endpoints, and a plane's default bounding point is a single point; neither can ever reach the narrow phase's minimum of 3 hull points, so both were always going to fail cluster candidacy regardless. The override just skips paying the broad-phase setup cost (screen-bounds projection, hull construction, sort/sweep bookkeeping) for a check that was guaranteed to reject them anyway - this matters in practice for a scene built from many line segments (e.g. examples/3d's TreesScene, each tree a bundle of DrawableLine branches), which would otherwise dominate the cluster-candidate count for zero possible benefit.
See specs/2026-08-16-depth-sort-plan-2-design.md for the full design, and examples/depthsort's ClusterVisualizerScene for a runnable demo of interleaved draw order taking visible effect.
Building models in code (Model3dOps.boxFaces)
For greyboxing, or props with no art of their own, build a Model3d from flat-colored boxes. BGE.Model3dOps.boxFaces(center, size, rgba, options) returns an axis-aligned box's triangles, wound counter-clockwise from outside with outward normals, so back faces cull and lighting works:
' a 2 m bench standing on the floor: center is the box's middle, not its base
center = BGE.Math.VectorOps.create(0, 0.25, 0)
size = BGE.Math.VectorOps.create(2, 0.5, 0.6)
faces = BGE.Model3dOps.boxFaces(center, size, &h7A5A3AFF, {omit: ["bottom"]})
m.addDrawable("bench", new BGE.DrawableModel(m, new BGE.Model3d(faces)))omit leaves out sides you never see ("top", "bottom", "right"/"left" for ±x, "front"/"back" for ±z). Append several boxes' faces for one model, but note the renderer sorts a model by the centre of its bounds: give separate pieces (a bench in a hall, a doorway's posts) a model each, as thirdPerson's BoxProp and CryptDoorway do.
Textured 3D models (Model3d / OBJParser)
An .obj model can carry diffuse textures, sampled via UV coordinates. On a Camera3d, each textured face draws as texture columns, like a flat quad (see Texture columns), but cut to the triangle: each strip is a power of two texels wide and runs only as far as the face's UV triangle reaches. The cuts are made once per face and strip width (BGE.TriangleColumnCuts, via Model3dTexture.getColumnCuts()) and shared by every instance of the model, so drawing a face only projects its strips. A moving model draws its faces straight to the canvas, and a still one draws them once into its temp bitmap and blits that. With useImpostor (the default), only the model's own movement or turning counts: while just the camera moves, the impostor reuses its last capture. Its impostor* fields tune that; applyImpostorOptions() sets them from a bag of short names that can come straight from deep-link params (model.applyImpostorOptions(params.pick(["strips", "stripStep"])); see BGE.ImpostorOptions). A Camera2d projects the strips orthographically (rendererTest's camera2d-model demo). A face that crosses the camera's near plane has its strips cut back to it. A face columns can't draw (the per-frame column budget is spent, or its UV triangle has no area) is filled with its shaded color instead, and the model's cached drawing isn't reused until it redraws in full. Solid (untextured) faces are filled straight into the canvas or the temp bitmap the same way, with no per-face rasters: on a Roku Ultra that was 1.5-3x faster than drawing each into its own raster and blitting it (#452). Two ways to get textures onto a model:
- Materials: the
.objreferences amtllib <file>.mtl, and eachusemtl <name>line sets the material of the faces after it. Each material'smap_Kd <image>is its texture, resolved relative to the.mtlfile. Every distinct texture is loaded once.examples/3d'sCarScene(nine materials) andD20Scene(one) use this, as doesexamples/terrain's chapel. - Explicit override: pass
{texturePath: "pkg:/..."}as the third argument toGame.load3dModel(modelName, modelPath, options)- every textured face uses it instead of its material's texture. Handy for a model that carries UV data but ships its texture separately, with nomtllibat all.
' textures from the model's .mtl file:
game.load3dModel("car", "pkg:/models/car/car.obj")
' one texture for every face, whatever the .mtl says:
game.load3dModel("crate", "pkg:/models/crate.obj", {texturePath: "pkg:/sprites/crate.png"})UVs outside 0..1 repeat the texture, the usual .obj convention for tiling a small texture across a big face. A face with no texture of its own - no UV data on one of its corners, a material with no map_Kd, or a texture that can't be found or loaded (a warning is logged) - is filled flat, in its material's Kd color when it has one. The rest of the model stays textured; a load never fails over a texture. Other .mtl properties (map_Bump, Ks/Ns, d transparency, illum) are ignored.


Deep dive: SceneObjectPlane (DrawablePlane)
DrawablePlane/SceneObjectPlane render a textured, (mostly) infinite ground/floor plane - examples/terrain is a small, playable demo of it (drive a camera around above a Mario Kart track image, or toggle to a checkerboard). It works nothing like the other SceneObjects, which each draw one small object; a plane covers the camera's entire view of the ground, so the implementation is closer to a classic SNES "Mode 7" renderer than to a sprite draw call.
The technique
Each frame, SceneObjectPlane (in findCanvasPosition, via getPerspectivePointsByCamera):
- Casts a ray from each of the camera's four frustum corners and intersects each with the plane (
BGE.Math.intersectRayWithPlane) - this gives the four world-space points where the camera's view "hits the ground" at its corners. When the camera isn't rolled, these rays are built fresh each frame using a true (atan-derived) vertical field of view rather than reusingCamera3d.frustumRays(which uses a cheaper linear approximation - accurate enough for frustum culling, but not for this plane's own edges; see "Roll" below for the rolled case, which builds its own rays too). Corners whose rays don't hit the plane at all (pointing above the horizon), or that hit it farther away than the plane draws, are placed instead on the plane at the camera's draw distance straight ahead, the full width of the view at that depth - the same depth every other object is clipped at, so nothing stands past the ground's far edge. - Converts those four world points into texture pixel coordinates via
BGE.Math.worldPointToTexturePixel(see "Texture anchoring" below). populatePerspectiveBmp()un-warps the resulting quad: it rotates/translates the entire source texture region so the quad's corner lines up correctly, then scales that into a rectangular "pre-perspective" bitmap - effectively turning "camera looking at a trapezoid on the ground" into "looking straight down at a flat rectangle."drawPerspectiveBmpSlicesToByCamera()slices that pre-perspective bitmap into thin horizontal bands (RenderQualitySettings.planeSliceCount, 20-50 depending on the quality level), each drawn with one scaled blit. Each band's on-screen position comes from projecting its world-space boundary points through the camera's own perspective formula (the same mathCamera3d.worldPointToCanvasPointuses for every other 3D object) - bands near the camera land large near the bottom of the frame, bands near the horizon shrink toward it, which is what produces the perspective effect, and what keeps the ground aligned with any per-point-projected object (a billboard, say) at the same world position. Each band's source span is exactly the ground the camera shows across the frame at the band's mid depth. A single blit can't change its horizontal scale as depth changes, so a straight line on the ground is drawn as a short staircase whose steps grow toward the sides of the frame. The size of a band's step depends on how much deeper its far edge is than its near edge, so the bands are spaced to give every one the same far/near depth ratio. RaisingplaneSliceCountmakes the steps smaller, at the cost of one more native draw call per band.
Texture anchoring
The plane is mathematically infinite (y=0, extending forever in x/z), but by default (fillMode: staticImage) its texture is a single finite bitmap region with no tiling - see "Fill modes" below for tiledImage, which does tile. BGE.Math.worldPointToTexturePixel(worldPoint, textureCenterWorldPoint, textureWidth, textureHeight) anchors the texture's center pixel on wherever the plane actually sits in world space (textureCenterWorldPoint, the plane entity's own world position) rather than on world (0,0) - world points equal to the anchor map to the texture's center pixel, and points n units away map n pixels away from center (1 world unit = 1 texture pixel, no additional scaling).
Practical implication: driving/looking far enough away from the plane's anchor point runs off the edge of the texture. That's expected and handled correctly - SceneObjectPlane.findCanvasPosition uses BGE.Math.boundsOverlapRect to skip drawing entirely once the camera's view can't possibly overlap the texture at all (a cheap early-out), and for partial overlaps, the plane correctly shows real texture on the side that's in-bounds and the renderer's background (transparent/black) on the side that isn't - it does not wrap or repeat the texture to fill the screen.
Fill modes (DrawablePlane.fillMode)
DrawablePlane.fillMode (a BGE.PlaneFillMode) picks how the plane's surface is filled, and planes in different modes compose with each other through ordinary addDrawable() calls - stack a flat color base, a tiled texture over it, and a one-off decal on top of both:
groundPlaneDef = {normal: {x: 0, y: 1, z: 0}, point: {x: 0, y: 0, z: 0}}
' A flat green base layer - region is `invalid` since color fillMode ignores it
baseLayer = new BGE.DrawablePlane(m, invalid, groundPlaneDef, {fillMode: BGE.PlaneFillMode.color, color: BGE.ColorsRGB.Green})
m.addDrawable("GroundBase", baseLayer)
' A repeating grass tile on top of it
grassTile = CreateObject("roRegion", m.game.getBitmap("grass"), 0, 0, 64, 64)
grassLayer = new BGE.DrawablePlane(m, grassTile, groundPlaneDef, {fillMode: BGE.PlaneFillMode.tiledImage})
m.addDrawable("Grass", grassLayer)
' A one-off decal (e.g. a road) on top of both
roadRegion = CreateObject("roRegion", m.game.getBitmap("road"), 0, 0, 256, 256)
roadDecal = new BGE.DrawablePlane(m, roadRegion, groundPlaneDef, {fillMode: BGE.PlaneFillMode.staticImage})
m.addDrawable("Road", roadDecal)colorfills the plane withDrawable.color/alphaand ignoresregionentirely - no texture, so it never "runs out" the way the other two modes can. This makes it the natural base/backdrop layer to add first.tiledImagetreatsregionas a single repeating tile, seamlessly covering the ground out toCamera3d.maxDrawDistancein every direction - this is the tiling the "Texture anchoring" section above calls out as unavailable by default.staticImage(the default, and the only mode that existed beforefillModewas added) is the finite decal described above: a one-off texture anchored at the plane's own world position - correct for something like a map/track texture, wrong for anything meant to repeat.
Layering order for planes at the same depth follows addDrawable() insertion order (the same depth-sort tie-break every SceneObject uses) - add the base layer first, as in the example above, so later calls draw on top of it.
tiledImage builds and caches a "supertexture" bitmap the first time it draws (lazily, per DrawablePlane instance, and rebuilt only if Camera3d.maxDrawDistance changes afterward) by tiling region across a grid roughly 2 * maxDrawDistance / tileSize tiles per axis, where tileSize is the tile's own smaller dimension. That means the tile count built up front - and so the build cost and cached bitmap size - scales with (maxDrawDistance / tileSize)². Pick a tile size (and consider maxDrawDistance) with that in mind: a small tile paired with a large maxDrawDistance builds a much bigger cached bitmap than a coarser tile would.
Note that maxDrawDistance itself may be silently capped below whatever you set it to: Camera3d clamps it per-device (900 on the BrightScript Simulator and, pending real hardware testing, on SD/HD devices too; effectively unlimited on FHD) every frame, so a plane's actual far distance and supertexture size follow the capped value, not the requested one.
Texture scale
A plane draws one texture pixel per world unit by default. Set its scale to stretch the texture over more of the world: scale.x along world x and scale.y along world z (the texture's own y). A 600x600 layout image at scale (1.5, 2) covers 900x1200 world units:
mapDecal = new BGE.DrawablePlane(m, mapRegion, groundPlaneDef, {
fillMode: BGE.PlaneFillMode.staticImage,
scale: BGE.Math.VectorOps.create(1.5, 2, 1)
})
' a 64px grass tile repeating every 256 world units
grass = new BGE.DrawablePlane(m, grassTile, groundPlaneDef, {
fillMode: BGE.PlaneFillMode.tiledImage,
scale: BGE.Math.VectorOps.create(4, 4, 1)
})The device cap above limits the plane's bitmaps, which are sized in texture pixels, so a coarser plane draws the ground farther: up to the cap times the smaller of its two scales, if the camera asks for that much (Camera3d.getPlaneDrawDistanceForTexelScale()). Objects' draw distance doesn't change. A non-square scale stretches a staticImage into one extra copy of its texture (a square scale needs none). examples/rendererTest's "Plane Texture Scale" demo cycles through a few scales.
Roll
Camera3d.rollDegrees (rotation about the camera's own forward axis) can't be represented by this horizontal-band rasterizer directly - a tilted horizon isn't a stack of horizontal bands. Instead, whenever rollDegrees <> 0, every step above runs against an unrolled ("level") camera enlarged to cover the real frame's diagonal (SceneObjectPlane.getRollCanvasSize), using Camera3d.getLevelUpVector()/getLevelRightVector() and a true, atan-derived field of view (getFovDegreesForCanvasSize) for both axes. The resulting composite is then rotated by rollDegrees about its own center and cropped back down to the real frame (performDraw) - mathematically exact for a pure roll, since perspective division commutes with an in-plane rotation about the optical axis. See specs/2026-08-19-camera-roll-and-plane-horizon-design.md for the full design.
Gotchas if you touch this code
- Scratch bitmaps are pooled and not cleared (see the
ScratchBitmapPoolnote above) - this bit particularly hard here, because the visual symptom of not clearing looked exactly like the texture "wrapping/repeating" the further you got from its valid bounds. It wasn't a sampling-wrap bug at all:populatePerspectiveBmp()'s scratch region andprePerspectiveBmpare reused, uncleared pooled bitmaps, and once the camera's view moved mostly or entirely outside the texture's valid area, the rotated draw call landed off-canvas and left the previous, unrelated frame's leftover pixels showing through - which happened to look like the track's own curb pattern, because that's literally what it was. Both bitmaps must beClear()-ed before drawing into them each frame. - Slice seams: each ground band's two boundary points are projected to screen-space Y independently and rounded to whole pixels, so adjacent bands' rounded positions can disagree by a fraction of a pixel, leaving a thin black gap between them (worst near the bottom of the screen, where bands are tallest/nearest the camera). Each band is drawn a few pixels taller than its exact allotted position (
seamPadding) so neighbors overlap slightly instead of gapping. - Camera-orientation coupling: if you're building a "chase camera" or similar that follows a moving point, don't use
camera.setTarget(fixedPoint)every frame if you want the camera to turn the way a driver's/person's head turns -setTargetpoints the camera at that fixed point, which orbits the camera around it as its own position changes, rather than rotating the camera's own view. Setcamera.orientationdirectly from your desired look direction instead (seeexamples/terrain/src/source/Scenes/MainScene.bs'supdateCameraOrientation).
Skybox (DrawableSkybox / SceneObjectSkybox)
DrawableSkybox renders a 360-degree panoramic texture that surrounds the camera, giving the impression of a distant sky or environment infinitely far away. Unlike other drawables that move with the world, a skybox is always centered on the camera and rotates with it. Attach one to an entity the same way as any other drawable:
' Create a skybox with a 360-degree panoramic image
region = CreateObject("roRegion", bmp, 0, 0, bmp.getWidth(), bmp.getHeight())
owner.addDrawable("sky", new BGE.DrawableSkybox(owner, region, {
degreesPerFullWidth: 360.0,
verticalDegreesCovered: 90.0
}))The constructor takes an optional args object with two configurable fields:
degreesPerFullWidth(default360.0): how many degrees of view angle the texture's full width represents. Set to360for a complete 360-degree panorama, or a smaller value if the texture covers a narrower field of view (e.g.,120for a 120-degree wide-angle texture).verticalDegreesCovered(default90.0): how many degrees of vertical view angle the texture's full height represents. This controls how much of the sky above and below the horizon the texture fills.
SceneObjectSkybox renders in its own dedicated pass in Renderer.render(), before all other objects (including planes). This ensures the skybox always draws behind everything else. A skybox never participates in depth-sort or overlap-cluster detection—it's always drawn as a background layer.
Like SceneObjectPlane, SceneObjectSkybox handles Camera3d.rollDegrees (rotation about the camera's forward axis) by rendering against an unrolled camera view and then rotating the composite. See specs/2026-08-19-camera-roll-and-plane-horizon-design.md section D for the full mathematical details of this render-then-rotate trick—the mechanism is the same, applied to the skybox's spherical geometry instead of a planar ground.
Note: Camera2d does not support skyboxes; this feature is 3D-only (issue #65).
Note: unlike SceneObjectPlane, SceneObjectSkybox has no per-frame dirty-check caching yet—it recomputes and re-blits its visible band every frame even when yaw/pitch/roll haven't changed. Correct, just not optimized; tracked as a follow-up issue.
Level walls (DrawableWalls / SceneObjectWalls)
DrawableWalls draws a level's walls as leaning texture strips, one every few screen pixels, instead of a 3D model per wall. Each wall is a segment: two floor points, a foot and a top height, at any angle and length. Walls can be short or tall, and a grid maze converts straight from its map (see Grid mazes).
segments = [
' a 4-unit-high wall facing -z (one-sided walls face the left of start -> end, seen from above)
BGE.createWallSegment(BGE.Math.VectorOps.create(0, 0, 0), BGE.Math.VectorOps.create(512, 0, 0), 0, 128, "stone", {tileWidth: 64, tileHeight: 128})
' a low wall seen from both sides
BGE.createWallSegment(BGE.Math.VectorOps.create(100, 0, -200), BGE.Math.VectorOps.create(300, 0, -260), 0, 32, "stone", {tileWidth: 64, tileHeight: 32, twoSided: true})
]
walls = new BGE.DrawableWalls(invalid, segments, {stone: stoneRegion}, {isShaded: true})
walls.addToRenderer(renderer)Segments are in world space. Each texture is one copy as tiled on a wall: tileWidth world units across, and tileHeight up (rounded so a whole number of copies fits). Copies stacked up a wall are drawn into one tall column texture (at most maxColumnHeight pixels; taller walls stretch fewer copies), so a strip is always one draw. Far off, where one strip covers several of the texture's columns, it draws from a narrower copy whose columns average them, so the pattern doesn't shimmer as you move toward or away from a wall (mipmapped, on by default; it costs about twice the texture's memory). Replace walls with setSegments() (also after changing them in place) and textures with setTextures(). color, alpha and flash() work as on other drawables.
How it draws (BGE.WallsView): nothing is raycast. The segments go into a 2D BSP when set (BGE.WallsBsp; walls that cross are split where they meet). That happens in the constructor and setSegments(), not while drawing, so for a big level set the walls while loading. Each frame the camera moves, the BSP is walked front to back, skipping branches wholly behind the camera, outside the view or past the draw distance, and the segments facing the camera and projected onto a fan of rays across the screen, one strip per ray, wallStripWidth pixels apart (see Render quality). Each ray keeps an open window of elevation, and nearer walls narrow it. A wall standing on the floor closes it up to its top, and one reaching above the screen closes it down to its foot. A closed ray costs nothing more, and the walk stops once every ray is closed. So cost follows screen coverage, not the wall count, and a short wall lets taller walls behind it show. Strips draw far to near, leaning with the camera's pitch so wall feet stay planted on a DrawablePlane floor. With a still camera the walk is reused. Strips past wallLodDistanceFraction of the draw distance cover two rays each (see Render quality).
To draw your own floors and ceilings between the walls, set view.recordSurfaces = true on the walls' scene object (BGE.SceneObjectWalls) and call its prepareView(renderer) after Renderer.setupCameraForFrame(): the walk then also lists, per ray, the canvas rows of the floor in front of each wall standing below the eye (at that wall's foot height) and of the ceiling in front of each wall reaching above it (at its top), in runs of consecutive rays. render() reuses that walk. rendererTest's floors-benchmark draws them as textured row spans. It treats every wall's foot as floor and its top as ceiling, so it suits levels built that way (rooms and steps): a floating ledge or a lintel then hides what's below or above it too.
Grid mazes (DrawableGridWalls)
For a Wolfenstein-style maze, describe the grid as rows of characters, say which characters are walls, and attach a DrawableGridWalls. It's a DrawableWalls whose segments come from the map (GridWallsMap.toSegments(): one per straight run of a texture, facing the open cells):
map = new BGE.GridWallsMap([
"#######"
"#..#..#"
"#.....#"
"#######"
], {
cellSize: 192,
wallHeight: 128,
origin: BGE.Math.VectorOps.create(0, 0, 0),
solid: {"#": "stone"}
})
walls = new BGE.DrawableGridWalls(invalid, map, {stone: stoneRegion}, {isShaded: true})
walls.addToRenderer(game.gameRenderer)Row 0 is -z and column 0 is -x; origin is the -x/-z corner of cell (0, 0) and its y is the floor height. Anything outside the grid counts as solid, so an unclosed map still has walls (they use outsideTexture, defaulting to the first legend entry). A legend key is one character, and since the legend is an associative array, characters differing only by case ("a"/"A") collide. Each texture is an roRegion one cell wide and one wall height tall. To change the maze, pass the new map to walls.setMap(), or call it again with walls.map after changing that map in place. Unless you set hideTolerance, it follows the map's cell size.
Lights
Set isShaded: true and the walls are lit by the renderer's lights like any other shaded drawable (see Lighting), along each wall in buckets lightBucketLength world units long. A wall keeps its light until a light, the color, ambientBrightness or lightWrap changes, so with still lights a moving camera relights nothing. A change to lights alone relights the walls without walking them again.
With Renderer.profileStages on, the walls report wallsWalk, wallsShade and wallsStrips (the draw calls) within the walls stage.
Hiding what's behind a wall
Walls draw in their own walls stage, after planes and before the sorted objects. Every sorted object is tested against the walls, and anything behind a wall is skipped (or redrawn only where it is in front, for an object peeking round a corner). Something behind a short wall is hidden only where the wall covers it. The test includes objects that are off-screen, so one turning into view from behind a wall never flickers; such an object reports occluded rather than offCamera. Props hung on a wall (an alcove image a hair off the face) stay in front of it: an object counts as behind only if it is more than hideTolerance farther than the wall (8 world units, or a quarter cell for grid walls). Depth is measured forward along the camera, not radially.
Your own overlays need the same treatment. drawWorldBar(), drawWorldPolyline() and the shapes built on them (drawWorldCircle, drawWorldArc) already skip anything behind a wall. For other overlays ask the renderer:
if not renderer.isBehindWalls(enemy.position)
' draw the marker
end ifThe UI canvas is a separate renderer, so walls never hide UI.
What it expects
- A
Camera3d. Pitch is supported from about 15 degrees up to 35 degrees down; beyond that the ray count is capped (4 rays per strip width of screen), so strips get coarser. Camera roll is ignored. Wall tops aren't drawn, so keep the camera below them where it can look down on a wall. - Nothing may sit lower than the lowest wall foot: a wall standing on that floor closes the rays behind it.
- No collision: the walls are drawn, not solid. For a grid, use the same map (
map.isSolid(col, row),map.cellAt(x, z)) for your movement. - One walls drawable per renderer: a second one is ignored.
- No floors per area or doors yet.
examples/rendererTest has a Grid Walls demo (--param demo=grid-walls) with a tiled floor, a wall-hung alcove, a figure pacing behind a corner and torch flames (DrawableParticles) in and out of view, and a Segment Walls demo (demo=segment-walls, map=hall) with walls of mixed heights.
Freestanding walls (DrawableWall)
DrawableWall is an upright textured quad between two floor points, from bottom to top, at any length and angle. It's for a few walls in an open scene; for a level's walls use DrawableWalls. It stays a sorted object rather than a segment, so it works under a Camera2d and on any entity, moving ones included (a renderer has one walls view, Camera3d only). Set tileWidth/tileHeight (world units per copy of the texture) to repeat the texture instead of stretching it once. Tiles start at the wall's start point and foot, so a partial tile is at the far end or the top.
' in a static entity's onCreate()
m.isStatic = true
wall = new BGE.DrawableWall(m, brickRegion, BGE.Math.VectorOps.create(0, 0, 0), BGE.Math.VectorOps.create(400, 0, -200), 0, 120, {tileWidth: 64, tileHeight: 64})
m.addDrawable("wall", wall)Points are in the owner's space. Move a wall with setEnds() and change its tiling with setTileSize(), not by writing the fields. It's orientedDrawBackFace, isOccluder and isShaded by default; give the owner isStatic = true so it sorts through the static BSP and can occlude. It draws like an oriented image, as perspective-correct texture columns: one pass of columns that wrap the texture, in a band per repeat along their length (QuadColumnDrawer.drawTiledTo(), also reachable through Renderer.drawColumnTextureTo()'s repeatU/repeatV). A column can't span two repeats, so a wall gets at least one per tile. An untiled wall can still take the one-call rotated-rectangle fast path.
Limits:
- Cost grows with wall count: each wall is a sorted object with its own columns and temp bitmap, and every visible wall redraws its columns each frame the camera moves. Measure with rendererTest's
walls-benchmark. Watch texture memory on HD devices. - Hiding is whole-object (the span map) plus the painter's sort, with no per-strip hiding as with
DrawableWalls, so walls that cross, or something standing in a gap, can sort wrong. - No collision.
Parallax layers (DrawableParallaxLayer)
DrawableParallaxLayer scrolls a bitmap at a configurable per-axis fraction of the camera's movement (parallaxFactor, a BGE.Math.Vector): {1,1} (the default) behaves like an ordinary drawable, {0,0} pins it to the camera, 0 < factor < 1 gives a background layer that drifts slower than the world, and factor > 1 gives a foreground layer that scrolls faster. repeatX/repeatY (defaulting to true/false) tile the bitmap to cover the viewport along either axis.
Unlike every other billboard drawable, SceneObjectParallaxLayer extends SceneObject directly rather than SceneObjectBillboard - a parallax layer is always flat 2D and may draw several tiled copies in a single frame, so it skips the 3D/orientation/temp-bitmap machinery entirely and just issues one Renderer.drawObject()/drawScaledObject() call per visible tile. It also doesn't honor Drawable's anchor (setAnchor()), rotation, color/outline, or drawMode fields - SceneObjectParallaxLayer.performDraw() ignores all of them and always draws from a top-left-anchored canvas position.
Attach one to an entity the same way as any other drawable:
region = CreateObject("roRegion", bmp, 0, 0, bmp.getWidth(), bmp.getHeight())
owner.addDrawable("mountains", new BGE.DrawableParallaxLayer(owner, region, {
parallaxFactor: BGE.Math.VectorOps.create(0.3, 0.06),
repeatX: true,
repeatY: true
}))examples/parallax is a small, playable demo with several stacked background/foreground layers and a camera that follows the player (examples/parallax/src/source/Scenes/MainScene.bs).
SceneObjectParallaxLayer overrides three SceneObject methods to make this work: findCanvasPosition() does the actual parallax math and tile enumeration - the base SceneObject.draw()'s existing objMovedInRelationToCamera() check already re-triggers it whenever the camera moves (its default implementation already ORs in cameraObj.movedLastFrame()), so no change to the shared SceneObject/Drawable update machinery was needed for this part. isPotentiallyOnScreen() and getPositionsForFrustumCheck() correct the renderer's frustum-culling check, which otherwise tests distance from the owning entity's raw (un-shifted) position: a repeating layer (repeatX/repeatY) always returns true from isPotentiallyOnScreen() and is never culled, since a repeating axis re-tiles to cover the viewport regardless of how far the raw owning entity has drifted from the camera; a non-repeating layer is instead tested against its actual parallax-shifted screen position (via getPositionsForFrustumCheck()), not its raw owner position, so it stays correctly visible/hidden even once that raw position is far outside the frustum.
Draw order relies entirely on the ordinary distance-from-camera sort - give a background layer's owning entity a suitably negative Z (or positive, for a foreground layer) so it falls out of Renderer.render()'s existing sort with no renderer changes.
Particles (DrawableParticles)
DrawableParticles emits and simulates a population of lightweight particles - lines, rectangles, or images - with randomized velocity, constant acceleration, and lifetime-driven color/alpha/size interpolation. GameEntity.addParticles builds and attaches one the same way addRectangle/addCircle do, just with a shape name instead of a size:
emitter = m.fireworks.addParticles("fireworks", BGE.ParticleShape.Rectangle, {
lifetime: 1.0,
lifetimeSpread: 0.3,
velocitySpreadMagnitude: 300,
startColor: BGE.ColorsRGB.Cyan,
endColor: BGE.ColorsRGB.Magenta,
startAlpha: 255,
endAlpha: 0,
startSize: 10,
endSize: 2,
maxParticles: 500
})Nothing spawns until you call start() (continuous emission at spawnRate particles/second) or burst(count) (spawns count particles immediately, regardless of start()/stop() state - see examples/particles's BurstScene, which fires 50 at a time on a button press). stop() halts continuous emission, but particles already alive keep simulating and drawing until they expire naturally:
emitter.start() ' begin continuous emission at spawnRate/sec
emitter.stop() ' stop spawning new ones; live particles finish out their lifetime
emitter.burst(50) ' spawn 50 right now, independent of start()/stop()Each particle gets its own randomized lifetime (lifetime +/- lifetimeSpread) and initial velocity, spread around the emitter's base velocity by velocitySpreadAngleDegrees (direction) and velocitySpreadMagnitude (speed). If velocity is left at zero, particles instead radiate outward in a uniformly random direction at velocitySpreadMagnitude - the way to get a stationary explosion/burst effect rather than a directional spray. acceleration (e.g. gravity) is applied to every particle every frame. Over each particle's lifetime, startColor/endColor (packed RGB), startAlpha/endAlpha (0-255), and startSize/endSize all linearly interpolate by the particle's own age / lifetime - startSize/endSize mean a line's length, a rectangle's side length, or an image's scale multiplier (1.0 = native size), depending on shape. maxParticles caps the live population; once reached, further spawns (continuous or burst()) are silently dropped until a slot frees up via natural expiry - a safety net against a runaway or misconfigured emitter, not something you need to size exactly.
A line's length is in world units, but by default a rectangle's side is in canvas pixels and an image's scale is of its pixel size, so they stay the same size on the canvas whatever their distance, and cover more of the screen on a lower-resolution canvas. On a Camera3d, set sizeInWorldUnits: true to size them in world units instead (an image as one world unit per pixel, times its scale): they then shrink with distance and look the same at every canvas size, like the rest of the scene. On a Camera2d a world unit is a pixel, so it makes no difference there.
The velocity spread only fans out in x/y. For a 3D spray, burstCone() fires particles in a cone around any direction, with optional upward lift:
' 20 particles, up to 0.6 rad off the swing direction, 100 +/- 30 units/s, plus 80 +/- 20 up
emitter.burstCone(20, swingDirection, 0.6, 100, 30, 80, 20)For one-shot effects all over the world (hits, sparks, dust), add a BGE.ParticleBurstPool instead of an entity per effect. It reuses a few emitters, each moved to its burst, once the emitter's particles have faded:
m.bursts = new BGE.ParticleBurstPool(m.game)
m.game.addEntity(m.bursts)
m.bursts.play(hitPoint, swingDirection, {
shape: BGE.ParticleShape.Rectangle, count: 18,
startColor: &h8A1010, endColor: &h8A1010, startSize: 2, endSize: 0.6, sizeInWorldUnits: true,
lifetime: 0.5, spreadRadians: 0.6, speed: 100, speedSpread: 30, lift: 80,
acceleration: BGE.Math.VectorOps.create(0, -400, 0)
})BGE.ParticlePresets has ready-made styles for melee hits: blood(color), blockSparks() and parrySparks(). They're authored in metres, so pass your world's scale. Each call returns a new style, so change any field before playing it:
import "pkg:/source/engine/drawables/ParticlePresets.bs"
style = BGE.ParticlePresets.blood(&h306020, {unitsPerMetre: 32}) ' green slime
style.count = 30
m.bursts.play(hitPoint, awayFromAttacker, style)
m.bursts.play(hitPoint, awayFromAttacker, BGE.ParticlePresets.parrySparks({unitsPerMetre: 32}))In a 2D game whose y grows downward, add yDown: true so the lift and gravity point up the screen. examples/thirdPerson's fighters spray all three.
Procedural flame frames
A particle emitter costs about 1 ms a frame on a device, too much for a scene full of torches. BGE.ProceduralFrames.flame() draws a looping flame once into a strip bitmap instead (squares that rise, shrink, fade and cool from one colour to another) and returns its frames for an animated image, so every torch shares one bitmap and draws one image a frame:
import "pkg:/source/engine/drawables/ProceduralFrames.bs"
frames = BGE.ProceduralFrames.flame(m.game, "blueFlame", {startColor: &hE0F4FF, endColor: &h2050FF})
flame = m.addAnimatedImage("flame", frames, {drawMode: BGE.SceneObjectDrawMode.axisAligned, animationDurationMs: 560})
flame.setAnchor(0.5, 1)The strip is kept in the game under its name and reused by later calls with that name, so give each look its own name. BGE.FlameFrameOptions sets the frame count and size, how many squares are in flight, their sizes, alpha and sideways drift. drawFlameStrip() draws a strip without caching it. examples/thirdPerson's Torch draws its fire, spirit and grave flames this way.
Animated sprite-sheet particles (shape = BGE.ParticleShape.Image)
A BGE.ParticleShape.Image emitter can optionally animate each particle through a sprite sheet instead of drawing one static bitmap. Set cellWidth/cellHeight (pixels) alongside image, and each particle's current frame is driven by its own age / lifetime - mirroring Sprite's own row-major grid-slicing convention, just with time-since-spawn in place of an explicit frame index:
emitter = m.fireballs.addParticles("fireballs", BGE.ParticleShape.Image, {
spawnRate: 8,
lifetime: 1.2,
velocitySpreadAngleDegrees: 360,
velocitySpreadMagnitude: 60,
startSize: 0.5,
endSize: 0.5,
startAlpha: 255,
endAlpha: 0,
cellWidth: 128,
cellHeight: 128,
maxParticles: 40
})
emitter.image = m.game.getBitmap("fireball")
emitter.start()cellWidth/cellHeight default to 0, meaning image draws as a single static bitmap - existing BGE.ParticleShape.Image emitters are unaffected unless you opt in. getFrameRegions() slices image into its grid lazily on first use and caches the result, so a fade-style sheet (bright frame to a transparent one) reproduces its own fade with no extra frame-rate configuration - see examples/particles's AnimatedImageParticlesScene.
Every particle from one emitter draws through a single SceneObjectParticle - the emitter's own performDraw loop issues one drawLine/drawRectangle/drawRegion call per live particle directly, rather than each particle getting its own SceneObject. That's a deliberate departure from every other pair in this guide's table, made specifically so that spawning and expiring particles every frame (the normal case for continuous emission) never touches Renderer.addSceneObject/removeSceneObject, which would otherwise defeat the depth-sort skip-optimization (see "How Renderer.render() actually draws a frame" above) for the whole renderer, not just this emitter. See specs/2026-08-18-particle-system-design.md for the full reasoning, including the tradeoffs this accepts (particles from one emitter draw as a single atomic unit against the rest of the scene, and aren't depth-sorted against each other). Frustum culling accounts for this: it checks a bounding box over every live particle's position (not just the emitter's own anchor), and re-checks every frame while any particle is alive - so a stationary emitter whose particles drift on/off-screen still culls and un-culls correctly (see issue #114).