Custom Drawing
Most visuals are components — sprites, tilemaps, particles. When you need something they can’t express — debug overlays, procedural shapes, custom geometry — the engine exposes its drawing layer directly.
Which API to use
Section titled “Which API to use”| API | Model | Reach for it when |
|---|---|---|
Draw |
Immediate, global — commands batch and clear every frame. | Debug overlays, gizmos, anything redrawn from scratch each frame. |
Graphics |
Retained path recorder — build once, replay through Draw with flush(). |
Vector shapes with paths/béziers/arcs you don’t want to re-tessellate per frame. |
ShapeRenderer / MeshRenderer |
Components — entities with sorting layers, materials, editor gizmos. | Shapes/meshes that are part of the scene (see Sprites). |
Rule of thumb: if the visual belongs to the scene (sorted, saved, inspectable), make it a component; if it belongs to a frame (debug, HUD-ish overlays, procedural effects), draw it in a callback.

The Drawing demo example, one picture per API: Draw (the radar), Graphics (the star) and a MeshRenderer ribbon.
Draw callbacks
Section titled “Draw callbacks”Register a callback and it runs inside the render pass every frame, with the camera’s view-projection already active — no setup, just draw:
import { registerDrawCallback, Draw } from 'esengine';
registerDrawCallback('debug-overlay', (elapsed) => { Draw.line({ x: 0, y: 0 }, { x: 100, y: 50 }, { r: 1, g: 0, b: 0, a: 1 }, 2); Draw.circleOutline({ x: 0, y: 0 }, aggroRadius, { r: 1, g: 1, b: 0, a: 0.5 });});Callbacks draw on top of the scene; registerPreSceneDrawCallback draws
under it (its callback receives { width, height, elapsed }). Remove one
with unregisterDrawCallback(id). All coordinates are world-space.
The Draw API
Section titled “The Draw API”Draw is an immediate-mode singleton — commands are batched automatically and
cleared every frame, so call it each frame you want the shape visible:
| Method | Draws |
|---|---|
line(from, to, color, thickness?) |
A line segment (thickness in px, default 1). |
rect(pos, size, color, filled?) / rectOutline(pos, size, color, thickness?) |
A rectangle — pos is the center. |
circle(center, radius, color, filled?, segments?) / circleOutline(…) |
A circle (default 32 segments). |
texture(pos, size, textureHandle, tint?) |
A textured quad. |
textureRotated(pos, size, rotation, textureHandle, tint?) |
Same, rotated (radians). |
triangles(mesh, { tint?, transform? }) |
Triangles with a colour a vertex (positions x, y pairs, indices, optional colors), moved by a 2D affine [xx, xy, yx, yy, tx, ty] and multiplied by tint, batched with the other primitives. What Graphics.flush() draws through. |
createTriangles(mesh) |
Puts a mesh on the GPU once and returns a buffer triangles() draws by reference: each copy is moved and tinted on the GPU, so it costs one 28-byte record, and consecutive copies of one buffer are one instanced draw. release() it when it is no longer drawn. |
trianglesMany(buffer, copies, count?) |
Many copies of one buffer in one call: 10 numbers a copy in copies (the affine xx, xy, yx, yy, tx, ty, then the tint r, g, b, a). The same picture as triangles() a copy, without a call into the engine a copy. |
drawMesh(geometry, shader, transform) / drawMeshWithMaterial(geometry, material, transform?) |
A custom mesh by handle (see the Geometry API below). |
setLayer(layer) / setDepth(depth) |
Sorting of subsequent commands. |
setBlendMode(mode) / setDepthTest(on) |
Blend / depth state for subsequent commands. |
withDepthState({ test, write }, draw) |
Run synchronous drawing with temporary depth testing and writes. Restores the native state even if drawing throws; returns false without invoking draw on older cores. |
getDrawCallCount() / getPrimitiveCount() |
Frame stats. |
Vector paths: Graphics
Section titled “Vector paths: Graphics”For shapes built from paths — polygons, polylines, béziers, arcs, rounded rects —
Graphics records them, turns them into triangles once, and draws those
triangles through Draw when you flush():
import { Graphics, registerDrawCallback } from 'esengine';
const g = new Graphics();g.lineStyle(2, { r: 1, g: 1, b: 1, a: 1 });g.beginFill({ r: 0, g: 0.5, b: 1, a: 1 });g.drawRoundRect(-50, -25, 100, 50, 8);g.endFill();g.moveTo(0, 0);g.curveTo(50, 80, 100, 0); // quadratic bézier
registerDrawCallback('hud-shape', () => g.flush());Path methods: moveTo / lineTo / closePath, curveTo (quadratic) /
cubicCurveTo, arc, and the shapes drawRect / drawRoundRect /
drawCircle / drawEllipse / drawPolygon(points); clear() starts over.
lineStyle(thickness, color, { join?, cap?, miterLimit? })sets the stroke: corners are joined ('miter'by default, or'round'/'bevel') and open ends capped ('butt','round','square'). A thickness of0draws no stroke.beginFill(color)/endFill()fill everything drawn between them: a path frommoveTo/lineToas much as a shape, concave outlines included.feather(a property, in the drawing’s units) fades every outer edge to transparent — anti-aliasing where the quality level draws without MSAA.
A path takes the style in force when it ends: a new moveTo, a change of
style, a shape, closePath() or a draw ends it, and a change of style part-way
along a line goes on from the same point.
The drawing is tessellated the first time it is drawn after a change, and
flush() is then one Draw.triangles call. The triangles go onto the GPU on
that first draw and stay there: a flush sends only where the copy is and how
faint, the GPU moves every vertex, and copies flushed one after another are
drawn together as one instanced draw. dispose() gives the GPU memory back
early (a Graphics nobody disposes of gives it back when it is collected). geometry() returns those
triangles, to hand to a MeshRenderer that should keep them.
One shape, drawn many times
Section titled “One shape, drawn many times”flush({ x, y, rotation, scale, alpha, tint }) draws the same triangles moved,
turned, scaled about the drawing’s own origin and faded. Build a shape once
and draw it wherever and however faint each copy should be: nothing is
rebuilt, and no texture is made. A hit flash that pops and fades is one
Graphics:
const hexagon = new Graphics();hexagon.lineStyle(2, { r: 1, g: 1, b: 1, a: 1 });hexagon.beginFill({ r: 1, g: 0.85, b: 0.4, a: 0.6 });hexagon.drawPolygon(Array.from({ length: 6 }, (_, i) => ({ x: Math.cos((i / 6) * Math.PI * 2) * 26, y: Math.sin((i / 6) * Math.PI * 2) * 26,})));hexagon.endFill();
registerDrawCallback('hit-flashes', () => { for (const hit of hits) { // however many there are this frame hexagon.flush({ x: hit.x, y: hit.y, scale: 0.7 + hit.age * 0.6, alpha: 1 - hit.age }); }});For hundreds of copies a frame, flushMany(copies, count?) draws them all in
one call. copies holds GRAPHICS_COPY_STRIDE (8) numbers a copy: x, y, rotation, scale, r, g, b, alpha. The picture is the same as a flush() a
copy; what it spares is a call into the engine a copy. Keep one array and fill
it each frame:
const copies = new Float32Array(MAX_HITS * GRAPHICS_COPY_STRIDE);
registerDrawCallback('hit-flashes', () => { let n = 0; for (const hit of hits) { copies.set([hit.x, hit.y, 0, 0.7 + hit.age * 0.6, 1, 1, 1, 1 - hit.age], n++ * GRAPHICS_COPY_STRIDE); } hexagon.flushMany(copies, n);});Do not bake opacity into a texture to fade a shape — drawing it to a canvas and uploading the result whenever its alpha changes makes a texture a frame, which is what a phone pays most for.
Filled polygons and joined strokes: setPath
Section titled “Filled polygons and joined strokes: setPath”Graphics draws in a draw callback, over the scene. For a shape that lives in the scene (it sorts with the other renderables, batches, and a
scene saves it), build the path’s geometry and let a MeshRenderer draw it:
import { setPath, circlePoints, cubicBezier } from 'esengine';
// A star with a round hole, filled orange and outlined with mitered corners.setPath(app, entity, starPoints, { fill: { color: [1, 0.55, 0.1, 1], holes: [circlePoints(0, 0, 14)] }, stroke: { color: [0.2, 0.1, 0.05, 1], width: 8, join: 'miter' }, closed: true,});
// An open curve with round caps and joins.setPath(app, other, cubicBezier(p0, p1, p2, p3), { stroke: { color: [0.2, 0.8, 0.9, 1], width: 14, join: 'round', cap: 'round' },});setPath gives the entity a MeshRenderer if it has none and uploads the geometry; call it again with new points to change the shape (the cost is the
tessellation, and nothing while the path stands still). buildPathGeometry(points, style) is the same without the entity, for building geometry of your own.
| Style | Meaning |
|---|---|
fill: { color, holes? } |
Ear-clipped fill of any simple polygon, concave ones included. holes are rings cut out of it. |
stroke: { color, width, join?, cap?, miterLimit? } |
join: 'miter' (default), 'round', 'bevel'; a miter longer than miterLimit (4) half-widths is bevelled. cap: 'butt' (default), 'round', 'square'. A stroke does not overlap itself at a corner, so a translucent one is even. |
closed |
Joins the last point to the first: the stroke has no caps. The fill always closes. |
feather |
A fade to transparent over this many units along every outer edge: anti-aliasing for a quality level without multisampling. Default 0. |
arcStep |
The angle one slice of a round join or cap may turn through, in radians (default 0.25). |
cubicBezier, quadraticBezier and circlePoints flatten curves into the points a path takes. Self-intersecting polygons are filled by their ear clip
(a figure-eight loses its crossing), and a hole must lie inside the outline.
Custom meshes: MeshRenderer
Section titled “Custom meshes: MeshRenderer”MeshRenderer is a component that renders an arbitrary indexed triangle list —
procedural terrain slices, radial health arcs, water surfaces. Author the
geometry on the component (positions as x,y pairs; optional per-vertex UVs and
colors):
cmds.spawn() .insert(Transform, { position: { x: 0, y: 0, z: 0 } }) .insert(MeshRenderer, { geometry: { positions: [0, 0, 100, 0, 50, 80], colors: [1,0,0,1, 0,1,0,1, 0,0,1,1], indices: [0, 1, 2], }, });The mesh shares the standard renderable surface: texture, color, layer,
lit, parallax, and material. Geometry set in a scene (or at spawn) uploads
automatically; to mutate it at runtime, go through the MeshRenderers resource —
setGeometry(entity, geometry) re-uploads (indices are validated engine-side),
getGeometry / clearGeometry round it out. Direct writes to the geometry
field alone are not change-detected.
Inline geometry is data code supplies while the game runs: it is not an inspector
field, set_field does not reach it, and the edit viewport does not show geometry a
script builds. For geometry an entity should keep, use the mesh field instead — a
built-in shape (builtin:cube, builtin:sphere, builtin:plane, …), an .esmesh
asset, or at run time a handle from assets.createMesh(data).
Cards that face the camera: Billboard
Section titled “Cards that face the camera: Billboard”A Billboard beside a MeshRenderer turns the mesh to each view that draws it: a sign, a sprite of a character in a 3D world, a
distant tree drawn on a card, a lens glint.
world.insert(card, MeshRenderer, { mesh: 'builtin:quad', texture: tree, lit: false });world.insert(card, Billboard, { mode: BillboardMode.Upright });- View plane (the default) lies flat in the view, the way a particle does: every card in a view faces the same way.
- Upright turns about world up only, so it stays standing as the camera looks down on it. It is the one for trees, signs and characters, which would otherwise tip back as the camera rises.
The mesh’s +Z is turned toward the viewer and its +Y up, which is how builtin:quad stands. The rotation is worked out by each
view as it draws, so two cameras each see the card face on, and the entity’s Transform is never written: scripts, physics and the
editor’s gizmo read the rotation that was authored. A shadow map is a view too, so a card turns to the light there and casts its
whole outline. A Billboard is not merged by static batching, and a set of placements
(MeshInstances) is not turned.
Custom geometry: the Geometry API
Section titled “Custom geometry: the Geometry API”Where MeshRenderer is the component path, Geometry is the immediate one: it
uploads an indexed vertex buffer and hands back a handle you draw yourself —
paired with a material via
Draw.drawMeshWithMaterial(geometry, material, transform?) (or a raw shader via
Draw.drawMesh(geometry, shader, transform)).
import { Geometry, Draw, Material, registerDrawCallback } from 'esengine';
const quad = Geometry.createQuad(120, 120); // 1 unit ≙ 1 design pxconst mat = Material.create({ shader }); // a compileShader material
registerDrawCallback('custom-mesh', () => { Draw.drawMeshWithMaterial(quad, mat); // identity transform});GeometryOptions
Section titled “GeometryOptions”| Field | Default | Description |
|---|---|---|
vertices |
— | Interleaved vertex data as one Float32Array (max 64K floats per upload). |
layout |
— | VertexAttributeDescriptor[] — one { name, type } per attribute, in buffer order. |
indices |
— | Uint16Array or Uint32Array triangle list (max 16K indices per upload). |
dynamic |
false |
Allocate for frequent updates via updateVertices. |
DataType names each attribute’s shape: Float, Float2, Float3, Float4,
Int, Int2, Int3, Int4.
Methods & helpers
Section titled “Methods & helpers”| Method | Does |
|---|---|
create(options) |
Uploads the mesh; returns a GeometryHandle (throws on failure or oversized data). |
updateVertices(handle, vertices, offset?) |
Rewrites vertex data on a dynamic geometry (offset in floats). |
release(handle) / isValid(handle) |
Free / probe a handle. |
createQuad(width?, height?) |
A centered quad (defaults 1×1), layout a_position + a_texCoord. |
createCircle(radius?, segments?) |
A triangle-fan circle (defaults 1, 32), same layout. |
createPolygon(points) |
A fan-triangulated polygon from {x, y} points, UVs from its bounding box. |
The helper meshes all use the two-attribute Float2 position + Float2 UV
layout, so they pair directly with fragment-only .esshader materials.
Offscreen targets: RenderTexture
Section titled “Offscreen targets: RenderTexture”For minimaps, portraits and mirrors, RenderTexture allocates an offscreen
render target. Wrap draw commands in begin/end to render into it; the
resulting texture is an ordinary texture handle usable anywhere (a
Sprite.texture, Draw.texture, a material texture param).
A whole scene goes into one by pointing a camera at it: set
Camera.renderTarget to the target’s render-target handle (rt._handle, not the rt.texture you put on a sprite) and that camera draws there instead
of the screen, before the screen cameras and without competing to be the main
view. Its own sorting layers (Camera.cullingMask) decide what it sees, so a
minimap camera and the player’s camera can look at the same world and show
different parts of it. A render target reaches a Sprite on both backends; the
pixel check of that path runs on WebGL2 only for now (on WebGPU a frame readback
comes back empty when one frame holds both an offscreen and a surface pass):
import { RenderTexture, Draw } from 'esengine';
const rt = RenderTexture.create({ width: 256, height: 256, filter: 'linear' });
RenderTexture.begin(rt, viewProjection); // an ortho view-projection you supplyDraw.circle({ x: 0, y: 0 }, 80, { r: 1, g: 0.5, b: 0, a: 1 });RenderTexture.end();
sprite.texture = rt.texture;RenderTextureOptions
Section titled “RenderTextureOptions”| Field | Default | Description |
|---|---|---|
width / height |
— | Target size in pixels (required). |
depth |
true |
Attach a depth buffer — turn off for pure 2D compositing to save memory. |
filter |
'nearest' |
Sampling filter when the result is drawn: 'nearest' or 'linear'. |
Methods
Section titled “Methods”| Method | Does |
|---|---|
create(options) |
Allocates the target; returns a handle with texture (resource-table handle for components), textureId (raw device id for low-level paths), width, height. |
begin(rt, viewProjection) |
Redirects subsequent draws into the target (you supply the matrix). |
end() |
Ends offscreen rendering, back to the screen. |
resize(rt, width, height) |
Releases and re-creates — returns a new handle (the texture handle changes). |
getDepthTexture(rt) |
The depth attachment as a sampleable texture handle. |
release(rt) |
Frees the target and its textures. |
This is a low-level surface: it doesn’t render the scene for you — it redirects
whatever you draw between begin/end, under a view-projection matrix you build.
Packing textures onto one canvas: TextureAtlas
Section titled “Packing textures onto one canvas: TextureAtlas”Sprites that share a texture draw in one batch. When your pictures arrive separately — icons
fetched from a server, a character built from parts, images a player picked — TextureAtlas.pack
draws them onto one canvas at run time and tells you where each one landed.

Each card above is a sprite cut from the same canvas (the small picture on the right is the canvas itself). The white square at a card’s top-left and the dark bar along its bottom show they came out the right way up.
import { TextureAtlas } from 'esengine';
// In a system in Schedule.Update — the canvas is painted in a pass of its own.const atlas = TextureAtlas.pack([iconA, iconB, iconC], { padding: 2 });if (!atlas) return; // the renderer is not up yet: try again next frame
world.insert(entity, Sprite, { ...atlas.sprite(iconB), size: { x: 64, y: 64 } });sources are texture handles (what Sprite.texture holds). atlas.sprite(source) returns
{ texture, uvOffset, uvScale } for a Sprite; atlas.get(source) returns the pixel rectangle
too (x, y from the top, width, height).
| Option | Default | Description |
|---|---|---|
maxSize |
2048 |
The largest canvas edge to try, in pixels. Packing throws if the textures do not fit. |
padding |
2 |
Transparent pixels kept between pictures, so a filtered edge does not pick up its neighbour. |
filter |
'linear' |
How the canvas is sampled: 'linear' or 'nearest' (pixel art). |
- The canvas is the smallest power-of-two size that holds everything. Pictures are copied as they are, with no blending, so their transparency is kept exactly.
- A handle given twice is packed once.
- Keep the source textures alive for as long as the atlas is in use. After a lost graphics device the canvas is drawn again from them, automatically.
atlas.repaint()draws the canvas again by hand (after changing a source);atlas.release()frees it. Neither touches the sources.- Like
RenderTexture, it can be shown on aSprite; the pixel check of that path runs on WebGL2 only for now (a WebGPU frame readback returns nothing when one frame holds an offscreen and a surface pass).
The Render Texture example
builds four cards and packs them (src/systems/atlas.ts).
Composing a picture at known positions: TextureCanvas
Section titled “Composing a picture at known positions: TextureCanvas”When you already know where each piece goes — a character built from parts, a card with an icon and a
frame — make a blank canvas, paste textures into it, and put the result on a Sprite. It is the same
idea as Unity’s Graphics.CopyTexture or drawing onto an Unreal render target.
import { TextureCanvas } from 'esengine';
// In a system in Schedule.Update — each draw is a pass of its own.const canvas = TextureCanvas.create(256, 256); // 1. a blank, transparent canvasif (!canvas) return; // the renderer is not up yet: try again next framecanvas.draw(body, 96, 100); // 2. paste: (x, y) is the picture's top-left cornercanvas.draw(head, 104, 46);canvas.draw(head, 190, 20, 24, 24); // optional width and height scale itworld.insert(entity, Sprite, { texture: canvas.texture, size: { x: 512, y: 512 } }); // 3. show itxandycount pixels from the canvas’s top-left, y pointing down. The picture is drawn at its own size unless you givewidthandheight.- Pictures blend over what is already there, in the order you paste them.
canvas.clear()makes it transparent again;canvas.release()frees it.- Keep the pasted textures alive. After a lost graphics device the canvas is drawn again from them, in the same order, automatically.
- The canvas is an ordinary texture — show it with no
flipY. For pictures you have no positions for,TextureAtlas.packlays them out for you.
The Texture Canvas example builds a small figure from seven pastes.
See also
Section titled “See also”- Sprites & Rendering — the component path for images and shapes.
- Materials & Shaders — custom shaders for any renderable.
- Camera — where the view-projection your callbacks draw under comes from.