Epok Engine
Documentation/Build, run & ship

Native PSX performance

START WITH THE BIG PICTURE

What does this part of Epok do?

Performance work in Epok begins with counters and repeatable captures, not guesses. The guide explains which CPU, GPU and memory costs the runtime can measure.

  1. 01Capture a repeatable scene or route
  2. 02Read counters and compare output
  3. 03Change one bottleneck and measure again

What is happening under the hood?

  • Transform, visibility and retained-packet caches reduce repeated work.
  • Clipped, dropped and submitted geometry remain visible in statistics.
  • Deterministic profiling tools compare runtime and VRAM captures across changes.

Field note: Optimize the measured bottleneck. The console does not award points for making already-fast code emotionally faster.

epok::performance_stats contains the last completed frame. Timings use the runtime scanline counter (approximately 64 microseconds per unit), rather than Windows or editor FPS. epok::time.frame_microseconds measures the interval between runtime frames. GPU rasterization and presentation are not independently measured.

Counters and timing

Project Settings > Rendering > Geometry > Mesh Triangle Budget can cap the double-buffered mesh packet reservation, including retained geometry. Automatic keeps the scene-derived capacity used by existing projects. A limit of 512..8192 reduces main RAM use without changing mesh assets or resolution. Validate all camera views and encounters: geometry beyond the pool is counted in lighting_stats.dropped_triangles. Streaming retains its independent limit; when both apply, the smaller capacity wins. Changes apply on the next build.

Optional on-screen debug HUD

Project Settings > Debug has independent FPS, CPU, Geometry/GTE, GPU Command DMA and SPU Sample Memory toggles. Apply, then build/Play. They also apply to exports: turn them off for a clean shipping build. They default to off for both new and existing projects.

The bottom-left overlay is chained after the game HUD, fades and loading image. It shares the existing font/CLUT, uses fixed double-buffered packets (no heap), and allocates no extra VRAM texture. All five enabled use 1,136 bytes of packet/ state RAM in the tested MIPS build, plus initialization guard, code and stack. A compile-time assertion limits packet/state storage to 2 KiB. All disabled removes the overlay and its instrumentation; it is small, not zero-cost when on.

  • FPS counts rendered runtime frames over at least 30 NTSC vblanks, not host or editor frames. It updates about twice a second and initially reads zero.
  • CPU measures Scene::frame including any waits inside it, but excludes the overlay itself and the final GPU::flip wait.
  • GTE measures the mesh vertex preparation/projection path using the GTE, including CPU setup. Lighting and software projection are excluded. It is not a hardware busy-cycle percentage.
  • GPU measures command DMA observed from CPU-frame entry until completion or the overlay sample, whichever comes first. Transfers completed before entry are not counted. It is not GPU rasterizer utilization and can include stalls.
  • SPU shows the resident ADPCM bank plus the reserved 4 KiB, out of 512 KiB. It is neither SPU execution load nor XA streaming-buffer fill.

Time bars fill at one NTSC vblank budget (~263 scanlines / 16.7 ms), with red at or above budget. They overlap; do not add them. The 16-bit scanline timer wraps after ~4.2 seconds. Compare performance using matching overlay settings.

Instrumented counters

The counters cover simulation, world synchronization, collision synchronization, mesh rendering, vertex transformation/projection, polygon processing, shading, fog and emission.

Timings are nested: simulation includes its world/collision queries, collision includes world synchronization, rendering includes vertices and polygons, and polygons include shading/fog/emission. Do not sum nested fields. The 16-bit timer difference wraps after approximately 4.2 seconds per scope.

Work counters report simulation steps, synchronization calls, local/world matrix rebuilds, collider-bound rebuilds and GTE/software vertex counts. A synchronization call does not imply a matrix rebuild.

The general profiler also reads linked sequence_stats, effect_stats, particle_stats and actor_stats. Its playback report includes active/alive and peak counts, completed/cancelled work, skipped bindings/events, dropped effects/particles and diagnostic overflow. Unlinked services are reported as unavailable. Counts come from each sampled RAM snapshot; they are not separate completed-frame timers. The report separates current gauges from cumulative counters, preserves startup totals, reports capture deltas and flags observed resets and saturation. Sampled maxima can miss activity between samples; runtime peak counters retain their own high-water marks. A saturated drop counter cannot quantify further lost work.

actor_stats (epok::actor_stats, declared in runtime/actor_tables.hpp) reports the Object/Actor/Component model, in the playback report under the key actor:

Field Kind Meaning
alive gauge Registry slots in use (actors, components, the Level and the scene script).
peak gauge High-water mark of alive since boot.
rejected counter Spawns, component additions and attachments refused by a capacity, domain, cardinality or abstractness rule.
spawned counter Slot acquisitions since boot, including reused slots.
deferred counter Spawn/destroy requests queued because they were made inside a callback.
actors gauge Actors in the current level's table (the scene script is not in it).
components gauge Components owned by those actors.
scene_scripts counter SceneScriptActor instances created, one per bank load.
banks_loaded counter Cooked actor tables loaded, so a transition is visible in the counters.

The values are refreshed once per frame after audio_tick() and again on every bank load and unload. A build whose banks carry no actors still links the symbol, so the report is available: true with an empty level rather than missing; a build from before this phase has no symbol at all and reports available: false.

EPOK_OBJECT_REGISTRY_CAPACITY is the cooked slot-table size: the maximum over the scene banks of (actors + components) plus 32 dynamic slots. Exhausting it increments rejected, never overwrites memory. epok::level_actor_capacity (64) and epok::actor_component_capacity (8) bound one level and one actor respectively.

Additional fields report mesh chunks tested/visible, backfaces, clipped polygons, emitted triangles, frame work before and after mesh rendering (prepare, finish), retained triangles and retained-packet rebuilds. Skeletal fields report pose/decode skeletal_scanlines, evaluated skeletal_bone_matrices, CPU-skinned vertices and decoded baked vertices; a culled character contributes zero to all four. skeletal_decoded_vertices counts coordinates-per-vertex that a clip frame actually supplied: a baked character whose animator has no valid clip, or whose clip carries no encoded vertex frames, renders its bind pose without decoding anything and adds nothing to that counter, although the attempt still shows up in skeletal_scanlines. skeletal_bone_matrices and skeletal_cpu_vertices stay zero for baked characters, and skeletal_cpu_vertices stays zero for an all-unlit rigid character, which poses bones and projects each position once instead of skinning on the CPU. With EPOK_PROFILE_DETAIL=1, per-quad shade/fog/emit timers, chunk setup and camera/sprite/HUD timers are also populated. Release builds leave those detail fields at zero. Reading extra timers adds work, so detail-build timings are not release measurements.

Explicit gameplay skeletal queries have separate counters available through epok::ResourceLibrary::skeletal_queries(): calls, requested vertices, evaluated bones, decoded compressed/raw bytes and failures. Clear them with clear_skeletal_queries() around a measured interval. These counters are not renderer counters: an off-screen explicit query legitimately adds query work while the renderer remains at zero. A compressed baked single-vertex query uses a cooked 16-vertex seek sidecar and decodes at most one block; a rigid batch poses the bounded bone set once and never borrows renderer scratch.

The descriptive streamed_chunks counter is collected only with EPOK_PROFILE_DETAIL=1 (tools/profile_runtime.py --detail). Ordinary builds store UINT32_MAX in its existing field; profiler JSON exposes this as null (not collected), not zero streamed chunks. This preserves the runtime ABI. Read, failure, timeout and dropped-geometry counters remain active independently of this diagnostic. Compare builds with matching instrumentation; --detail adds timing and counter overhead and is not a release FPS measurement.

GTE validation counters are populated only with EPOK_VALIDATE_GTE=1. Validation compares GTE and software results within the runtime's coordinate and screen tolerances; its extra work also affects timing.

Compound collision queries

Compound static colliders, including generated dungeons, automatically use a spatial grid cooked from their collision boxes. Movement queries cover the whole swept box, camera rays cover their full segment, and triggers query their own footprint. Only candidate parts reach the existing collision solver; boxes outside the rendered view still collide normally. Candidate order is preserved, including contact ties and trigger event order.

The grid starts with eight-unit XZ cells and coarsens to keep its cell lists within 8 KiB per collider. It needs no per-frame rebuild or heap allocation and follows translated owners. Small colliders and layouts without a useful bounded grid retain the linear query path.

Precomputed chunk visibility

Enable Precomputed Visibility under Project Settings > Engine > Rendering to add conservative chunk selection. It is experimental, disabled by default and may lower FPS. Camera and object transforms remain supported; the setting does not add occlusion or increase the visible range.

Retained HUD and geometry

Movement uses fixed 60 Hz simulation independently of rendering. Position interpolation can smooth entity/camera translations at mismatched rendering rates; it is a presentation feature, not an FPS optimization. It keeps gameplay transforms/collision matrices unchanged and adds up to one fixed step of visual latency. See Position Interpolation for its switch and limits.

The runtime reuses unchanged HUD and eligible static-mesh packets. Enable Retained Packets in Project Settings to use static geometry retention; it is on by default. Material, lighting, geometry and transform changes refresh the packets automatically. Skeletal meshes and scrolling textures use per-frame packets. Turning retention off provides a comparison and can save RAM.

Streaming bounds retention by the configured triangle budget. Objects that do not fit use per-frame packets. Monitor native frame timings when adjusting these options for a game.

Geometry streaming and frame budgets

Project Settings > Engine > Streaming controls geometry CD pages, the RAM pool, the per-frame triangle budget and preloading. Streaming is experimental, disabled by default and may lower FPS or stall frames. See Geometry streaming for usage and Project Settings for defaults and ranges. Lower triangle budgets save RAM but can omit triangles; inspect dropped-triangle counters when changing the budget.

For large worlds, World optimization techniques lists the build-time techniques (visibility tracks, static world, prepared packet order and others), when to use each and what they measured.

Skeletal characters

tools/benchmark_skeletal.py measures skeletal workloads repeatably. It builds one project per configuration (storage mode, texture assignment, material lighting, instance count, on screen or behind the camera), runs each build several times in the configured emulator, samples completed-frame performance_stats, and records the cooked // skeletal budget: line from the generated scene header, the .ps-exe size, the build's memory report and the texture VRAM allocation. Results land in a new timestamped directory under artifacts/performance/skeletal/, as results.json plus a report.md with the tables, the environment and the fixture hashes.

The report also records which optional query tables are present in each cooked scene (skin_portable_to_cooked, skin_vertex_seek, baked skin_bones and skin_tracks). A render-only game must contain none of the query-only tables. When vertex or bone operations are reachable, their bytes are included in the ordinary skeletal budget rather than hidden in a separate allocation.

Method, and what to keep if you write your own comparison: hold the camera, resolution, transforms and clip selection fixed and change one variable per pair; discard the first seconds of each run as warm-up; repeat each workload at least three times and report the median, the 95th percentile, the maximum and the sample count rather than one number. Compare storage modes with frame_scanlines and render_scanlines: rigid bone evaluation is timed inside the vertex scope while baked decoding is timed in visible-chunk setup, so vertex_scanlines is not comparable between them, and the scanline unit is about 64 microseconds, which is the resolution of any difference. Assert culling with the skeletal counters themselves (all four read zero for an off-screen character), not with a lower-bound validation flag.

Findings from the fixtures currently in resources/models, at 320x240 with up to eight instances, which are a small measured sample and not a general ranking:

  • Neither storage mode is simply faster. Baked vertex frames had the lower frame and render time than rigid bones in every controlled pair measured, by roughly a tenth at one instance and under a fifth at eight, while rigid bones stored far fewer bytes and its payload grew much more slowly with clip count. Treat the choice as a time-for-space trade and measure the model you ship.
  • Keep skeletal materials unlit. A lit material routes the model to the compatible CPU rigid path, which cost about half as much again per frame as the same model on the GTE path and was the only configuration that reported CPU-skinned vertices. That effect was larger than the storage-mode difference.
  • Characters placed outside the view cost nothing measurable: all four skeletal counters stayed at zero and the frame cost matched the scene without them.
  • Clip count changes size, not frame time, because one clip plays at a time.
  • In these workloads the limiting resource was frame CPU time, not RAM, executable size, VRAM or the primitive budget, and most of that time was per-vertex projection and per-polygon work rather than pose evaluation or decoding. Check which resource is actually limiting before optimizing one.

These are emulator measurements of specific scenes: they are not physical console timings, and the editor viewport's own frame rate is a host measurement that says nothing about runtime performance. Re-measure after runtime or cooker changes instead of relying on the recorded numbers.

Compilation and measurement

The editable-mesh cooker gives nonconforming opaque wall joins a small coverage margin (at most 1/2 unit for coplanar T joins and 1/8 unit for convex floor corners, capped to a quarter of panel width). The wider coplanar overlap covers integer edge disagreement at grazing views without adding faces or per-frame stitching. At convex joins the shared floor corner also extends just beneath the walls, with all copies kept coincident to avoid pinholes at their base. Authored meshes, face/corner order, UVs, normals, bake colors and collision data are retained. Open boundaries, translucent/scrolling materials, free-standing props and inward room corners do not receive this margin.

Software clipping preserves already projected corners, so the general renderer uses the same GTE screen coordinates as its unclipped neighbours. Shared clipping edges interpolate consistently from outside to inside, independent of winding. When either half of a quad needs software clipping, both surviving halves use the same clipping planes so their shared diagonal cannot bend apart.

Chunk bounds use native 32-bit products when each input fits the limit derived from the actual view coefficients, rather than a fixed 32-world-unit cutoff. A conservative rounding guard contains the previous wide bounds. Plane tests also use 32-bit arithmetic only when their coefficient and translation bounds prove it safe; larger transforms and unusual display ratios retain the wide path. This changes render traversal cost without changing geometry, lighting, draw distance or collision queries.

Release builds optimize the runtime's main.o with -O2; PsyQo and game scripts retain their configured options. EPOK_RUNTIME_OPT=-Os permits comparison. Rebuild main.o after changing optimization, detail or validation flags.

When using the editor, rebuild it after runtime source changes because it embeds those sources. Standalone C++ exports contain their own runtime snapshot and are rebuilt with their included Makefile.

Use the same scene, input sequence, resolution, build mode and instrumentation for comparisons. Track dropped simulation steps and primitives alongside timings, and inspect rendered frames for regressions. Changing camera position, visible geometry, HUD content or particles can change the measured workload.

Optional PC sampling is enabled with EPOK_RUNTIME_OPT="-O2 -DEPOK_PROFILE_SAMPLE". Its default uses Timer0 and a 32 KiB histogram: 8,192 bins of 128 bytes cover physical code addresses 0x10000..0x110000. Native-only sequence music uses Timer2 and can remain enabled; legacy sequence timing uses Timer0 and rejects this combination at compilation. The sampler starts after sequence-clock setup, which clears Timer0. Normal builds do not contain its state or interrupt handler.

Diagnostic builds can override EPOK_PROFILE_SAMPLE_BASE, EPOK_PROFILE_SAMPLE_SHIFT and EPOK_PROFILE_SAMPLE_BINS. A focused window at 0x70000, shift 6 and 2,048 bins covers 128 KiB at 64-byte resolution with an 8 KiB histogram. Choose the window from the matching ELF; instrumentation can move code. The compiler requires aligned RAM-code addresses, 1..8,192 bins and a shift of 2..16, with the whole window inside 2 MiB RAM. Samples outside the chosen window remain in the outside counter; they are not discarded or assigned to a function in that window.

Debugger tools can pause collection through epok::cpu_sample_enabled and read cpu_sample_layout, cpu_sample_bins and cpu_sample_outside. Clear the bins while collection is disabled and record the exact measurement window. The Complete-game verifier's --deterministic-route --capture-cpu-samples options collect frames 301 through 1,440 without removing music. They read the linked layout and verify its count against the ELF buffer size. This is a diagnostic build, and its timings do not certify normal-build performance.

Use tools/summarize_cpu_samples.py --samples <cpu-samples.json> --elf <matching.elf> --nm <mipsel-none-elf-nm> --out <report.json> to attribute samples. Only bins wholly inside one linked function are assigned to it. Boundary bins remain ambiguous, inlined work belongs to its containing function, and time spent with interrupts masked can defer sampling and underrepresent interrupt handlers. Always retain the matching executable and ELF alongside the report.

Capacity limits are not frame-rate guarantees. Emulator measurements describe the tested workload; physical-console timing and GPU/presentation costs require separate validation. No scene-specific benchmark results are bundled with this guide.

Documentation for v0.10.0 · View technical source · 6d01853