Skip to content

Building a new scene

The overview of the level work, the decisions behind it, the knowledge base and the planned architecture are in docs/modding/levels/.

Level mods are now recipes: Level recipes is the format and tools/port/scene/build_level.py the builder, which drives the glTF builder below for the level and edits the base mission's briefing, debriefing and newspaper scenes (../levels/front-end-scenes.md). The specs on this page still build as before.

tools/port/scene/build_scene.py builds a scene that is not on the disc and writes it as a port mod. Three specs use it: a single room (specs/new_room.json), a small mission (specs/two_rooms.json, two rooms, guards and a worker on routes, two targets, a working exit) and that mission with its own logic, text and sound (specs/contract.json, three targets). The first one, tools/port/scene/specs/new_room.json, is a 12 × 12 × 4 m room with a tiled floor and four walls. It has its own collision, room trees, sound graph, navigation and lights, and 47 can walk around in it. The tool reads the player's disc each time it runs, so the repository holds only the tool, the spec and this page. The texture is generated by the tool. A level can also be modelled in Blender and exported as glTF: see Making a level in Blender (gltf_level.py, specs/showcase.json).

python -I tools/port/scene/build_scene.py tools/port/scene/specs/new_room.json --out <mods folder>/new_room [--iso ISO]

The member formats are described in scene.md and the pages it links to.

What comes from the disc and what is new

The spec names a base scene, SCENES/HIDEOUT/HIDEOUT_.ZIP (Scenes/hideout/hideout_main). It is the smallest disc scene with a playable 47: 3,975 geoms, against 10,000 to 13,000 in the missions. The tool keeps the base scene's non-world objects and replaces its world.

Kept from the disc (AllLevels content, not the level) Removed (remove rules in the spec) New (ours)
AllLevels/herosetup.zip: 47, his outfit and cloth, the cutscene groups the rats and the canary (Characters!*) the NewRoom ZROOM
AllLevels/mainsceneincludes.zip: camera setup, OSD, menus, map, post filters, dialogue, audio definitions, the AI script controllers the hideout's weapons and ammo on the racks and their lists (Items!*) the RoomShell mesh (floor and walls, 168 triangles) and its collision tree
AllLevels/equipment.zip: weapons, upgrades and dynamic items Hideout/Hideout_LOCATIONS.zip: all 3 rooms, 737 geoms of world geometry, lights and props a 128 × 128 RGBA texture of tiles
the CloneGroup_AllLevels/* clone pools Hideout/Hideout_Audio.zip, Hideout/Hideout_Effects.zip two ZENVIRONMENT lights and their prims
LevelControl with its ZHM3LevelControlHideout controller (empty) Fun!*, ActionExit and the hideout clone groups .RMC/.RMI room boxes, .SGP room, .GMS navigation
TrackLinkObjects, ZParticleController, the ZDefines the level control's hideout_levelcontrol script; ScriptCModule is set to "" 47's start position
.ANM, .SND, .LOC, .SUP, .ZGF, .SGD, the GUI XML files and .WAV/.WHD (animations, sounds, text)

1,456 geoms are removed and 2,523 remain. The removed world is also scrubbed from the members that kept its bytes:

  • .PRM: the vertex, UV, colour, chunk and strip-length blocks of 432 prim records that only removed geoms reach are zeroed (975 KB). The handles stay, so no reference shifts.
  • .OCT: 294 of the 449 collision trees belonged to removed prims and are dropped. The other 155 belong to kept prims (weapons, items). They are copied with their sub-strip runs, and their prims' lColiId are repointed.
  • .BUF: the names of the removed geoms (864 strings) and the hideout rooms' exit arrays are zeroed.
  • .RMC, .RMI and .SGP are rebuilt. Of the hideout's rooms, only the AllLevels ones remain: the item viewer, the map legend, the scope and overlay rooms.

The .TEX keeps the hideout's textures, since kept prims (particles, items) refer to textures by id. The .ANM keeps the rat and canary animations.

Build order

build() in build_scene.py works in this order:

  1. Read the base archive and its loose .WAV/.WHD from the ISO (tools/port/disc.py). Parse .GMS, .BUF and .PRP, and pair the .PRP tree with the .GMS packed tree (build_tree).
  2. Simulate the base scene's run-time REFs (simulate_refs, below) and pair each .OCT block with its static container. The tool stops if their counts differ.
  3. Remove subtrees by path rules. Drop controllers by name (the level control's ScriptC), then the CloneGroup_* groups that no remaining ZAllocMany points at.
  4. Move 47's start: set Position and Matrix on the four herosetup groups.
  5. Add the texture (tex.add_texture) and the mesh (prm.add_mesh), then the ZROOM, ZSTDOBJ and ZENVIRONMENT records. Their names are appended to the .BUF, and their geom numbers start at the base scene's m_iHighestGeomNr. The .PRP objects come from prp.new_object.
  6. Clear every geometry path in the .PRP and the ZDefines that no longer resolves: a single reference becomes "", and a REFTAB entry is dropped. Apply the spec's ZDefines.
  7. Lay out the .GMS (layout_gms): tree words, group counters (one row per group-class geom plus the root), the base scene's type counts or more, an empty light table, no room environments, and our navigation block. gms.check must pass.
  8. Simulate the new REFs and map old REFs to new ones.
  9. Write the .OCT. It holds one block per static container in RecurGetNext order. Our room's block lists the mesh (GT_StdObjs) and the lights (GT_Lights). The root's GT_TreeGroups gains our room. The kept containers' trees are copied with remapped leaf ids, then come our collision tree and the kept collision trees.
  10. Blank the removed prims and scrub the .BUF.
  11. Build the .RMC and .RMI: the kept rooms' boxes, remapped, plus one axis-aligned box for our room. Build the .SGP with one RoomSpec per remaining ZROOM.
  12. Write the archive (fixed time stamps, so the output is the same from run to run), the .WAV/.WHD beside it and mod.json.

Run-time REFs

The .OCT, .RMC and .RMI name geoms by run-time REF, which is the base-geom slot + 1. They do not use the .GMS geom number. simulate_refs reproduces CreateGeoms:

  • ROOT is slot 0.
  • When a group's first child arrives, the group's counter-row sum of ZBaseGeoms is allocated in one run. The run is handed out per list type in type order: group, std obj, light, other, plus 8 × cAssumedGeomDrawList.
  • The list type comes from the class lineage, as in GetBaseGeomListType: ZSHAPE and ZSTDOBJ are std obj, except ZBOUND and ZSNDOBJ; ZGROUP is group; ZLIGHT is light.

On the hideout, the simulated REFs give exactly the ZROOMs that its .OCT root lists, and the .RMC boxes name, and every GT_StdObjs leaf is a std-obj geom. In the new scene the room is REF 2 and the mesh REF 34. Both values were confirmed in the port with obm.world.find_geom.

Static container order

CreateBoundTrees hands out .OCT blocks while it walks ZGROUP::RecurGetNext from the root. AttachGeom prepends, so each group's children are visited in reverse tree order. In the hideout, the first room in the file (Hitman_HideOut_medium) has the last block. static_containers walks the tree in that order.

level_pathfinder writes a PF4RunTime::ZData block with one graph and one component: the floor rectangle inset by nav_margin (40 units). The arrays are:

  • 4 split-tree nodes, testing x ≥ x0, −x ≥ −x1, z ≥ z0 and −z ≥ −z1. Each failed test leads to leaf −1, which means outside. The last passed test leads to leaf −2, which is component 0.
  • 1 height-tree node, whose ~side is plane 0, and 1 plane equation for the floor height.
  • 4 vertices and 4 corners, clockwise in (x, z) as on the disc, with neighbour −1 (wall).

A path inside one convex component is a straight line, so there are no nodes, links or exits. A temporary probe in the port gave these results: PositionInside is true inside the room and false outside it; MapLocation succeeds; and FindPathLength from (1600, 0, 1600) to (2400, 0, 2400) is 1131.4, which is √2 × 800.

The mod and how to load it

The output folder is the mod:

new_room/
  mod.json                            id openblood.new_room, category level, one levels entry
  raw/SCENES/NEWROOM/NEWROOM_.ZIP     the scene archive (Scenes/NewRoom/NewRoom_main.*, menu XML)
  raw/SCENES/NEWROOM/NEWROOM_.WAV     the effects bank beside it, from the base scene
  raw/SCENES/NEWROOM/NEWROOM_.WHD

The engine opens a scene by its long name: SCENES\NewRoom/NewRoom_main.zip. The port turns that into the 8.3 disc name SCENES\NEWROOM\NEWROOM_.ZIP (DiscFileName) and mounts the archive by reading its sectors. That read bypassed the mod file system, so the port needed one change. port/engine/system/_sdl/cdreadsdl.cpp now has a disc overlay: when the disc has no file at a path, an active mod's raw/<disc path> answers for it, with virtual sectors from 0x40000000 up. The disc keeps priority, so no existing file is replaced this way. Every member, the .PRP and the menu XML included, then loads through the mounted archive as it does for a disc scene. The .WAV/.WHD load through the same overlay. docs/modding/README.md describes the overlay.

The levels entry puts New Room in the launcher's Quick Play list. With base_scene NewRoom/NewRoom_main, it starts the scene through the M05 campaign slot (loadout and level number). With the mod installed in build/test-mods/new_room, run from the repository root:

build/port/cmake/openbloodmoney --user-dir build/scratch/user --version ps2 \
  --disc "Hitman - Blood Money (Europe).iso" --mods-dir build/test-mods \
  --only-mods --enable-mod openblood.new_room --mission new_room

An input script of one line, 600 1000000 lefty -1.0, walks 47 forward. He starts at (2000, 0, 2000) facing −Z, walks to z = 1440 and stops. That is 40 units from the wall at z = 1400.

A mission: two rooms, NPCs and targets

tools/port/scene/specs/two_rooms.json builds a small mission: a 12 × 10 m hall and a 10 × 10 m office joined by a 3 m doorway, two guards and a worker who walk waypoint routes (one guard's route loops through the doorway), and two targets. When both targets are dead the exit in the hall shows its Escape action; using it ends the mission with the stock debriefing (MISSION ACCOMPLISHED, rating, newspaper, save and continue).

python -I tools/port/scene/build_scene.py tools/port/scene/specs/two_rooms.json --out <mods folder>/two_rooms

The mod's levels entry has base_scene M01/TwoRooms_main, so the launcher lists Two Rooms under Quick Play and starts it in the A Vintage Year campaign slot (its loadout and level number). The archive is raw/SCENES/M01/TWOROOMS.ZIP, which the disc does not have, so the disc overlay serves it. The tool also writes level.json beside mod.json: every room, doorway, navigation rectangle, actor path, start and route, for probes and tests.

Where the actors come from: a mission base scene

Two ways were measured:

Hideout base, characters merged in Mission base, world stripped
Models, textures, animations move PRM prim chains (bones, LODs, cloth), TEX records, ANM collections and their variation buffers, and SND/WAV offsets from a mission archive into the hideout's already in the archive, unchanged; handles and offsets stay valid
Scripts the hideout module has alllevels\guard and civilian but no mission level control the mission's module (ScriptCModule) holds the level control script and every shared AI script
Level control ZHM3LevelControlHideout, no targets or exits the mission's ZHM3LevelControlMxx and its script, re-pointed by the spec
Work weeks: every member's cross-references the milestone 2 strip, plus clone and re-point

The second won. A Vintage Year (M01_main) is the base: it is small (8,352 geoms), has 21 alllevels\guard and 6 alllevels\civilian actors, and its level control is simple. ZHM3LevelControlM01 (C++) only plays music on kills and calls MissionCompleted on CutSequence_End; its script m01\m01_levelcontrol registers don and donSon as targets 1 and 2 (Silevelcontrol__Settargetnum), completes objective 1 or 2 when either dies, shows the exitMarkers list when both are dead, and on M01_ExitPlane completes objective 3 and starts cutsequenceTarget. That is the Controllers!EscapeCut ZVideoPlayer, which sends CutSequence_End back to the level control when the movie ends (at once with OPENBLOOD_NO_MOVIES). Every piece is data the spec can point at our objects. Other levels were less suitable: M08's level control dereferences its river-bank list in Init without a check, and M06's drives a parade float, club music and dance animations.

The tool keeps M01_main's non-world content as milestone 2 kept the hideout's. It removes the backdrop, M01_LOCATIONS.zip (the whole world, 4,998 geoms), cover points, every character, item and controller except the level control and EscapeCut, the security zones, the water box, the M01 audio, music zones and post-filter boxes and the M01 clone groups: 594 subtrees and 5,725 geoms, leaving 2,664. ScriptCModule stays M01, so the port attaches the M01 module as native code. The outfits (Clothbundles!* ZHM3HmAs), equipment, hero setup and map stay.

Actors

An actors entry clones a base-scene character group (template) before the removal rules run and places the copy under the spec's level_group (ROOT\Level):

Field Meaning
name the new group's name; the actor is ROOT\<level_group>\<name>\Ground, and @<name> names it elsewhere in the spec
template path of the base character group; its ZHM3Actor (Ground) brings the prim, mesh variant, animation collection, sound and material definitions and outfit (m_rHitmanAs)
children children of the template group to keep (default ["Ground"]; the target DonChileanSon also had a CheckInside box)
position, yaw the group's place and turn; Ground is reset to the group's origin
role for level.json and the reader; the game's role comes from the script's characterType
script {"imports": {...}} sets imports of the template's own ScriptC; {"name": ..., "imports": {...}} replaces it (prp.new_script)
properties ZHM3Actor properties to set (m_rHitmanAs, OverrideHitpoints, ...)
route {"type": LOOPING/PINGPONG/ONEWAY/RANDOM, "points": [[x, y, z(, yaw)], ...]}: one ZSTDOBJ per point (<name>_Wp_NN) and a ZLIST (<name>_Route) in the level group, and the actor's PathFollower pointed at the list (one is added if the template has none)

A clone gets new geom numbers; its records share the template's name strings in the .BUF. The two targets are M01's Don and his son with their scripts replaced by alllevels\civilian with characterType 3 (target), which Alllevels_Basefunc passes to Zhm3Actor__Setcharactertype. The guards keep alllevels\guard, and the worker keeps alllevels\civilian. Every actor start and waypoint must lie on the navigation; the tool checks this.

objects clones any other base object the same way (name, template, position, yaw, properties, and controllers with property values per controller). The spec clones three: Quarters (a ZGuardQuarterController box, see failure 4), Exit (M01's PlaneExit ZBoxPrimitive with its Escape ZAction, which sends M01_ExitPlane to the level control) and ExitList (its ZLIST, GeomList ["@Exit"]).

Mission

mission.level_control names the kept level-control object; script_imports sets its ScriptC imports (don @Don, donSon @DonSon, notifyTarget empty, exitMarkers @ExitList, cutsequenceTarget M01's EscapeCut), and controllers may set properties of its other controllers. Values starting with @ resolve to objects the spec made. What happened in the scripted run (build/newscene/evidence/m3/mission_run.log):

  1. A Lua probe kills Don, then DonSon (obm.world.explode at each). ZHM3LevelControl::CharacterKilled counts each as a target (m_stats.lTargetsKilled, obm.rating.live().targets_killed 1 then 2), the probe sees actor_killed, and the script completes objective 1 and 2: the OSD shows the tick-off mark.
  2. With both dead the script sends ActionShow to ExitList: the hall shows Escape (cross).
  3. 47 uses it. The script completes objective 3 and starts EscapeCut; its CutSequence_End reaches ZHM3LevelControlM01::Command, which calls MissionCompleted (the port logs mods: stock mission complete, mods get mission_outcome). MissionCompleted2 then loads M01_postmission (MISSION ACCOMPLISHED with 2 kills and 1 body found), M01_News and saveandcontinue.

A run with DefaultScene= crashes after step 3, and so does the stock M01/M01_Main started that way: in a single-scene run (ZLevelLinking::Init(0, "SingleSceneRun")) the scene MissionCompleted2 loads next has no .SUP, and DoLoadScene breaks on it. Which name it asks for was not traced. Start the level through the launcher instead; OPENBLOOD_LAUNCHER_PLAY=quick OPENBLOOD_LAUNCHER_MISSION=13 does that without clicking (13 is the first custom level after the 13 stock missions).

Rooms, doorways and portals

rooms is a list of room entries (milestone 2's single room still works). doorways joins two rooms: {"rooms": [a, b], "centre": c, "width": w, "height": h}. The rooms must touch along a wall (one's +x side on the other's -x, or the same in z); centre is the world coordinate along that wall. For each doorway the tool:

  • cuts the opening out of both rooms' walls (room_mesh splits a wall into the parts beside the door and a lintel above it); the two walls are separate zero-thickness meshes, one facing each room;
  • writes one ZROOM::ZExit (0x38 bytes) per room into the .BUF and sets the room's ExitsOffset and m_lNrExits. The corners are in room-local space, top edge first as on the disc, ordered so that (p2 − p1) × (p3 − p1) points into the room: ZOldViewBase::InitializeExit passes a portal only to a camera on that side. m_pNeighbor is the other room's geom number (ZROOM::RemapRefs turns it into a pointer), m_lNeighborExitIndex its slot in the other room, control EXIT_CONNECTED (2), type 0;
  • adds the exit to both rooms' sgp.RoomSpec, with world-space corners, so the sound graph has the portal.

Each room has its own mesh and collision tree, .OCT block (mesh and lights), RMC/RMI box and lights (_env_ambient, _env_character), and may name its own texture. In the game the office is drawn through the doorway from the hall (evidence/m3/01_portal_view_actors.png).

level_pathfinder builds one graph from axis-aligned rectangles: each room's floor inset by nav_margin, and one bridge per doorway that spans the wall between the two insets (nav_rects). Each rectangle is one component:

  • The split tree is a chain of four tests per rectangle. A failed test jumps to the next rectangle's chain (−1 after the last), and the last passed test is the leaf −2 − component.
  • Corners run clockwise in (x, z) as in milestone 2. Each edge is split where it meets a neighbour, and the corner that starts a shared segment names the component across it.
  • Each shared segment gets one ZNode at its middle and one ZSubNode on each side. m_Divider is the source component's corner index of the segment, m_SourceComponent is the source and m_Component is the one across. Within one graph, FindComponentPathAStar walks sub-nodes from component to component, and StraightenGates funnels the path through each shared edge.
  • No exit nodes, links or exit distances are needed with one graph.

StraightenGates narrows each gate by up to 40 units on one side and 90 on the other, so a doorway's bridge should be at least about 150 units wide: a 300-wide doorway with a 40 margin gives 220. The guard's route (-300, -300) → (1300, -300) → (1300, 300) → (-300, 300) crosses the doorway on every lap (evidence/m3/tracks_routes.csv: Hall → Office at T 7, 36 s; back at T 20, 49 s, at x ≈ 553..611 with z between −29 and 30). Every actor stays at y = 0 on the floor.

Spec format

Key Meaning
base archive, scene (member stem), loose_dir, loose (.WAV/.WHD)
scene path (scene name) and archive (8.3 disc path under raw/)
remove, keep path rules (path, prefix, name_prefix, class); a node a remove rule matches goes unless a keep rule matches it
drop_controllers {path, controllers} to drop
defines ZDefine values to set
start the hero setup groups, position, yaw
rooms name, mesh_name, centre, size (w, d, h), tile, cells, vertex_colour, coli_bits, geom_control, nav_margin, lights, optional texture
doorways rooms, centre, width, height
texture the default room texture
level_group name of the group that holds actors, waypoints and objects
objects, actors, mission above
mod files_dir and the mod.json manifest

Testing it

build/port/cmake/openbloodmoney --user-dir build/scratch/user --version ps2 \
  --disc "Hitman - Blood Money (Europe).iso" --mods-dir build/test-mods \
  --only-mods --enable-mod openblood.two_rooms --mission two_rooms

Install Two Rooms in build/test-mods/two_rooms first. The separate user directory keeps test profiles and saves together.

Mission logic, text and sound

tools/port/scene/specs/contract.json is the two-room mission with logic, text and sound of its own: three targets, our level-control script, our objectives, target names and briefing, a hum in the hall and an alarm when the last target dies.

python -I tools/port/scene/build_scene.py tools/port/scene/specs/contract.json --out <mods folder>/contract

The recipe names a Lua file in mission.script. When building a scene spec directly, use mission.lua to point to that file. A spec that supplies a compiled module in mission.script fails validation. The example in tools/port/scene/levels/contract/mission.lua registers the targets, exit and alarm. See Mission scripts.

Spec keys

Key Meaning
level_control The existing level-control object. Its ScriptC runs the shared base level control.
lua Path to the Lua file the builder copies into the level folder.
targets Ordered target actors and the text shown for each. The M01 briefing supports up to four pictures.
extra_objectives, exit_objective Required, optional or protection objectives after the target entries, followed by the exit. Set the Lua exit index when inserting extra objectives.
text, text_level Briefing paragraphs, location, hints and strings, with their LOC folder.
sounds Each entry has a name and WAV or synthesis parameters. Emitters play scene sounds. Lua can play other WAVs from the level’s sounds folder, optionally at a named marker.

The base level’s native scripts handle actors. The mod runtime loads the mission file when the level starts and unloads its hooks when the scene ends.

Text

mission.py edits the scene's .LOC under M01/, the name of the campaign slot the level runs in (ZLevelLinking::GetCurrentLevelName):

  • M01/MissionObjectives: every numbered folder and the hints are removed, then 1/ to n/ get Type T, WhoOrWhat, Objective, ObjectiveDetail, Age, Height, Weight, Hair, and n+1/ gets Type E. ZHM3BriefingControl::ObjectiveExists tests Type, and GetNumberOfTargetObjectives counts the Ts. LocationBrief, LocationDetail, LocationTime and Hints/HintN come from text.
  • M01/MissionBriefing/M01_MB_01D ... 0nD: the paragraphs. ZHM3DianaSpeech joins them for the briefing page; they have no sound, since the base level's ids would play Diana's M01 lines.

The briefing shows the objectives, target names and briefing text from the level.

Still M01's:

  • The target photos on the target pages (Don's face for target 1). They are textures of the menu; replacing them is a texture change in the scene's .TEX.
  • Buy Intel: M01's intel entries.
  • The pre-mission briefing scene M01_premission, the debriefing M01_postmission (its wine-cellar backdrop; the statistics are ours) and the newspaper M01_News. The quick start skips the briefing scene; MissionCompleted2 loads the other two by the slot's name. They are disc files mounted by sector, and the port's raw/ overlay only adds files the disc lacks, so replacing them needs a port change (an overlay that may replace a disc archive, or a level-table entry that names other scenes). Their text is in their own .LOC files under the same keys, so apply_text would serve them unchanged.
  • The escape movie (EscapeCut, skipped with OPENBLOOD_NO_MOVIES) and the music: ZHM3LevelControlM01::CompleteObjective starts M01 music for objectives 1 and 2.
  • The map and the M01/Map room names.

Sounds

For each sound mission.py writes the synthesised samples to sounds/<name>.wav in the mod (tools/port/scene/synth.py), reads them back with snd.read_pcm_wav, and appends them with snd.add_sound to the scene's .SND, .WHD and .WAV. contract.json makes two:

  • openblood_hum: 2 s at 22,050 Hz, 110 Hz and two harmonics with a slow swell, whole periods so it loops cleanly. Sound 0x3fd80, WHD record 0x18050, m_lFlags 3 (bit 0 loops), volume 100. The HallHum emitter plays it from the scene's start.
  • openblood_alarm: 1.6 s, 880 and 660 Hz alternating every 0.2 s. Sound 0x444d0, WHD record 0x18090, m_lFlags 2 (once). The level script plays it at ROOT\Hall\AlarmSpeaker, a marker mission.py puts in the hall, when the last target dies.

Testing mission outcomes

Start the contract in Quick Play with a separate user directory. Kill the three targets and use the exit to check the objective order, debriefing and newspaper. Restart and let 47 die to check the failure screen.

Making a level in Blender

tools/port/scene/gltf_level.py builds a level from a binary glTF (.glb) and a short spec. The model holds the rooms, doorways, geometry, materials and textures, lights, navigation, 47's start and the actors' places and routes. The spec holds the rest: the base scene, the character templates, the mission objects and the mod manifest.

python -I tools/port/scene/gltf_level.py tools/port/scene/specs/showcase.json --out <mods folder>/showcase

specs/showcase.json builds Gallery, a level written by tools/port/scene/make_showcase_glb.py into tools/port/scene/levels/showcase.glb (287 KB, all generated: geometry, PNG textures, lights, empties). It has a double-height hall with 13 steps up to a gallery on a panelled plinth behind an iron railing, an office through one doorway and a storeroom through another. The props are octagonal columns, crates, barrels, a table, chairs, shelves, a glazed screen and five hanging lamps. Two guards, a worker and M01's two targets walk routes in it; one guard's route goes up and down the stairs. The mission is milestone 3's (both targets, then the exit in the storeroom). The tool drives build_scene.Builder through a subclass (GltfBuilder), so the build order above applies. Its helpers are glb.py (a glTF reader and writer and a PNG codec, standard library only) and navmesh.py (navigation from meshes).

Export settings

File > Export > glTF 2.0:

  • Format glTF Binary (.glb). A .gltf works only with its buffers and images embedded as data URIs.
  • Include: Custom Properties (the tool reads them as node extras) and Punctual Lights.
  • Transform: +Y Up (the default).
  • Geometry: Apply Modifiers, UVs, Normals. Vertex colours are optional (COLOR_0 multiplies the baked light). Leave compression off: Draco meshes are not read.
  • Materials: Export, images as PNG. JPEG, WebP and KTX2 images are refused.
  • Armatures, skins and animations are ignored. Instanced meshes, parented objects and negative scales are handled (a mirroring transform flips the triangles back).

Axes and units

One Blender metre is 100 game units (centimetres). Blender X is game +X (east), Blender Y is game +Z (north on the in-game compass), Blender Z is game +Y (up). glTF stores Blender Y as −Z, so the tool maps glTF (x, y, z) to game (100x, 100y, −100z) (GLTF_Z_SIGN). That is a mirror, so the triangle winding is flipped to keep each face's front, and its normal, as modelled. The game camera facing Blender +Y shows Blender +X on the right. An axis test checked this with a red pillar front-right, a blue one front-left and an "F" texture on the far wall (build/newscene/m4-gltf/evidence/00_axis_test.png). UVs need no change: glTF's (0, 0) is the top-left of the image, as on the PS2.

An empty's facing is its local −Z in glTF, which is Blender's local +Y: an unrotated empty faces north, and rotating it about Blender Z turns it. The tool converts that to yaw_matrix degrees. Logged facings matched in the game: an empty turned 225° (compass bearing, south-west) gave f = (−0.71, −0.71).

Naming conventions

Objects are recognised by their node (Blender object) name, case-insensitively:

Name What it is Notes
room_<Name> a room volume, usually a box its bounds are the room: the ZROOM's place, its .RMC/.RMI box (what the engine tests to find the room 47 or the camera is in) and its sound-graph room. Not drawn.
portal_<A>_<B> a quad in the doorway between rooms A and B becomes one ZROOM::ZExit in each room and a sound-graph exit. Its extent along the doorway and in height gives the corners, ordered for each room as exit_corners does. Not drawn.
nav_<anything> walkable surfaces for the NPCs triangles at any height, may slope (stairs, ramps); see below. Not drawn.
col_<anything> collision only becomes a hidden sub-prim (PRIMDRAWMODE_HIDDEN) with collision bits. Use it for a slope over stairs, invisible walls and so on.
nocol_<anything> drawn, no collision the same as the custom property collide = false
start an empty: 47's start and facing required
actor_<Name> an empty: an NPC's start and facing custom properties below
route_<Name>_<n> empties: the NPC's waypoints in order of n the empty's facing is the waypoint's
object_<Name> an empty that places the spec's object <Name> the exit, the guard-quarters box, ...
view_<anything> (or any other empty) ignored, but the spec's start_from can start 47 there for test runs
a node with a KHR punctual light a light baked into vertex colours and used for the rooms' character lights
any other mesh drawn and collides

Custom properties (Blender: Object Properties > Custom Properties):

On Property Meaning
any mesh collide (bool) false: draw only
any mesh, col_ room put the triangles in that room instead of the one their place decides
room_ ambient [r, g, b] ambient light, 0 to 1 (default from the spec, [0.30, 0.30, 0.32])
room_ location the room's m_eLocationState
actor_ type a key of the spec's actor_types (template, role, script)
actor_ template, role override the type's
actor_ route PINGPONG (default), LOOPING, ONEWAY, RANDOM
actor_ run (bool) run instead of walk
actor_ import_<name> sets that import of the actor's script, as the spec's script.imports
a light range metres, when the light has no glTF range (Blender does not export one)
a material format texture format: p8 (default for opaque), p4, rgba32 (default for alpha)
a material max_size, mips, material texture size limit (default 256), mip levels (1), m_lMaterialDescription (1)

Patrol stop actions

A route_<actor>_<number> marker may carry a glTF extras property named stop_action. Use {"type":"arrive"}, {"type":"wait","seconds":3}, or {"type":"look","turns":2}. Waits accept 0.1–300 seconds and looks accept 1–12 turns. The marker's rotation sets the actor's facing for a wait or look. A marker without an action uses the normal passing distance. The writer emits a native use point for each action and keeps navigation detours as ordinary waypoints.

Geometry, materials and textures

Every triangle of the drawn and collision meshes goes to one room. That is the room whose volume holds its centroid. When two volumes touch there, the room in front of the face decides (the centroid moved 10 units along the normal). With no volume, the nearest room takes it. So one floor mesh may span several rooms, and a wall slab's two faces go to the rooms they face. Each room's triangles become one prim chain under one ZSTDOBJ (<Room>_Geometry): one sub-prim per material, split while a sub-prim would need more than 255 chunks (over 4,000 triangles), then the hidden collision sub-prims. The root sub-prim's bounds are widened to the whole chain. The room's .OCT bound trees and the root's tree-group entry use the room volume joined with the geometry bounds (the bounds key, build_scene.room_bounds).

Collision is the chain's sub-prims whose lColiBits is not 0: drawn meshes that collide and the col_ meshes get 0x62 (Background, Sight, Hero; failure 2), collide = false meshes 0. build_scene.strips_of_prim skips sub-prims with lColiBits 0 when it builds the collision tree.

Materials:

glTF In the game
baseColorTexture (PNG) a TEX record (tex.add_texture), resampled to powers of two up to max_size. One record per image and format, shared by materials.
no texture texture id 0: the vertex colour only
baseColorFactor multiplied into the vertex colours
alphaMode MASK, alphaCutoff draw mode PRIMDRAWMODE_TRANSPARENT (0x1) and lAlphaCutoff = cutoff × 128 (0.5 gives 0x40): the GS alpha test
alphaMode BLEND PRIMDRAWMODE_ALPHA_BLEND (0x200) and NO_ZWRITE (0x100)
emissiveFactor added to the baked light (lamp globes)
doubleSided ignored: every face is drawn from both sides, like the room shells

The showcase uses all three formats: seven opaque textures as p8 (marble tiles, plaster, planks, wallpaper, concrete, ceiling, crate), the brick as p4 (16 colours), and the iron railing (alpha test) and glazed screen (alpha blend) as rgba32.

Lighting

The world is unlit in the engine: static geometry carries its light in its vertex colours, as the disc's does. The tool bakes them. Each vertex gets the room's ambient light plus, for each light, its colour × brightness × max(0, n·l) × (1 − (d / range)²)². Brightness is the glTF intensity / light_scale (spec, default 50; a 1,000 W Blender point light exported with the default lighting mode comes out near 54). Range is the glTF range, the range property or 12 m. Spot lights cut off at their outer cone, and directional lights have no falloff. Then the material's emission is added, and the result is multiplied by the base colour and COLOR_0, at 0x80 = 1.0 (up to 2× overbright). There are no shadows. Light is per vertex, so subdivide large faces (the showcase uses cells of about 1 m). Each room also gets the two ZENVIRONMENT lights of milestone 2: _env_ambient from its ambient colour, and _env_character from the light that is brightest at the room's centre, turned toward it, which lights the characters.

navmesh.build turns the nav_ triangles into pathfinder graphs:

  1. Vertices within 1 unit are welded. Triangles steeper than 60° are dropped.
  2. Triangles on one plane are merged greedily into convex polygons (Hertel–Mehlhorn, longest shared edge first, up to 24 corners), and collinear corners are removed. Each polygon is a component with its own plane equation (height = A x + B z + C) and a one-leaf height tree. Flat floors at several heights and slopes are all just planes.
  3. Shared edges: each edge is cut where an edge of another polygon runs the other way along the same line (within 1 unit) with heights within 25 units at both ends of the overlap. T-junctions between separate nav objects therefore join. The corner that starts a shared piece names the polygon across it; other corners are walls (−1). The side of a stair flight against the floor does not join, because its heights differ.
  4. One ZNode per shared piece, at its middle and height, with one ZSubNode on each side (m_Divider = the corner index), as in milestone 3.
  5. The split tree is a chain of half-plane tests per polygon (eqn = the edge's inward normal, half a unit of slack); a failed test jumps to the next polygon, and the last passed one is the leaf −2 − component. Vertex normals are the inward bisectors.
  6. The graph's box spans the vertices' heights ±100 (GetGraphAndComponent tests it in 3D).

The builder snaps actors and waypoints to the surface below them and rejects points outside navigation. Stacked surfaces separated by at least 120 cm can belong to different graphs. Exit nodes, links and distance tables connect the graphs. A nav_door marker connects navigation through a door.

Model the nav surfaces where an NPC's centre may go: about 0.4 m in from walls and props, and keep doorways and stair flights at least 1.5 m wide after that inset (StraightenGates narrows gates by up to 40 and 90 units). Give stairs a slope through the step nosings, not the steps themselves, and use the same slope as a col_ mesh for 47 (the drawn steps are collide = false). The showcase's slope starts on the floor one run (0.3 m) in front of the first riser and meets the gallery at the last nosing.

Spec keys (glTF levels)

Key Meaning
gltf the .glb, relative to the spec
base_spec another spec to take base, remove, keep, drop_controllers, defines, level_group and the hero setup start.groups from (the showcase uses two_rooms.json)
scene, mod, mission, objects as for build_scene.py; objects are placed by object_<Name> empties
actor_types {type: {template, role, script, properties, children, route}}: what an actor_ empty's type names
actors optional per-name overrides of the model's actors
ambient, light_scale default room ambient ([0.30, 0.30, 0.32]) and the intensity that counts as brightness 1 (50)
texture_format, max_texture_size defaults for opaque textures (p8, 256)
geom_control the room geometry's geom control byte (0x200e2)
start_from start 47 at another empty (test runs)

The tool writes level.json as before, with the rooms' bounds, the portals' corners, the textures and their formats, and the navigation polygons.

Limits

  • Navigation supports up to 2,000 areas. A graph can have only one walkable height at each horizontal point. Separate graphs allow stacked floors.
  • Rooms are their volumes' axis-aligned bounds (.RMC/.RMI boxes). Portals are rectangles.
  • Light is baked per vertex, without shadows. Characters get one ambient and one directional light per room.
  • Budgets: about 4,000 triangles per sub-prim (the tool splits larger groups); the PRM handle table holds 40,960 entries, and the M01 base uses 20,977, leaving about 19,900 (the showcase's 4,000 triangles and 10 textures took 275). Texture ids run to 2,047 (the base uses 541). Textures are powers of two from 8 to 1,024, by default capped at 256. The level must lie inside the base scene's root tree frame (near M01's origin; the tool says so when not).
  • Characters, animations and sounds come from the base scene.

Limits and next steps

Builder troubleshooting records loader, collision and mission errors observed while building these examples.

  • Box rooms (rooms in a spec) are axis-aligned boxes on one floor height; doorways join rooms that share a wall. Modelled levels have stairs, slopes and other shapes (above) and can connect floors across graphs.
  • Characters come from the base scene's templates. A character from another mission needs its prims, textures, animation collection and sounds merged in.
  • Level logic is Lua (mission.lua, Mission scripting); the scene scripts themselves are the base mission's, run as native code.
  • These low-level examples reuse M01’s front-end assets. The recipe builder creates a custom briefing, pause map, newspaper and debriefing.