What the Build 42 engine actually does, written down while modding because almost none of it is published anywhere. Facts come from the game's own Lua and data files, from reading the shipped engine, or from what happened in game; class and method names are given so you can check them yourself. Nothing here is official, no game code is reproduced, and all of it will go stale.
400 notes in 16 sections. Since 24 September 2026: 186 added, 13 corrected, tagged New and Corrected.
What the corrections overturn (13)
- Which chunks a lot reaches is measured from its corner.
- Every level of every chunk on screen is drawn, below ground too, and a level with no light on it draws black.
- Per-pixel depth comes from two files, and
tileGeometry.txtis not one of them. - Corner walls name their own halves.
- A tree is two layers: a trunk sprite and one canopy.
- For a free-standing world sprite use an iso marker, and move it with
setPos. - The hook for "this object is going" is
OnObjectAboutToBeRemoved(obj). - Light bulbs burn out in 42.21.
- Vanilla's plumbing is live, and its water source is one level up.
- An MP client loads and runs the server Lua too; only a dedicated server leaves a tree out.
- No global mod data table can hold a secret, and a received one is stored by neither side.
setZombiesDontAttack(true)does nothing outside a debug launch.- An attachment name the BODY model does not declare draws the item at the character's origin.
Contents
- What changes in 42.22
- What changed in 42.21
- Maps and lots
- Basement lots
- Below ground: drawing, rooms, light
- Tiles and tilesets
- World objects from Lua
- Lua and Kahlua
- UI and rendering
- Multiplayer and authority
- Items, recipes, traits, skills
- Characters and zombies
- Animals
- Animation, models and art
- Foraging, fishing, farming, water
- Odds and ends
What changes in 42.22
Build 42.22 went stable on Steam on 9 November 2026 as 42.22.2 (Steam build 26486631). These notes come from comparing 42.21.0 with the 42.22 pre-release (Steam build 26409601): engine classes, Lua, scripts and tile definitions. The pre-release was then compared with 42.22.2: every Lua, script, tile and data file is the same, and the engine changed only its version string and its integrity report. The complete list of every class, method and field that changed is on its own page: the 42.22 engine diff.
The climb
- New
ClimbSheetRopeStateandClimbDownSheetRopeStateare gone. They are nowClimbStateandClimbDownState, andclimbSheetRope()andclimbDownSheetRope()are nowclimb()andclimbDown(). The patch notes do not list this. A class that is gone reads as nil in Lua, sost == ClimbSheetRopeState.instance()guarded by a nil check fails with no error, and the mod's climb code stops running without a word. To run on both builds, takeClimbState or ClimbSheetRopeStateand testplayer.climbbefore calling it. # - New A climb with no way off the top still never finishes.
finishClimbinghas no case for an undefined outcome, so a rope whose top has no window, frame or fence beyond it holds the climber at the top. New in 42.22, the backward key turns them round (ClimbSystem.isDirectionChanged), so they can go back down but not out. Any mod that steps a climber off such a top by testing the old state silently loses that step, which can strand players. # - New The rope's own wiring did not change. The
climbropeandclimbdownropeAnimSets and their actiongroups are byte-identical,canClimbSheetRope,canClimbDownSheetRopeandisTopOfSheetRopeHerehave the same bodies, the height step per frame is the same, and leaving the climb by clearing theClimbRopevariable still matches theto_idletransition. Conditioned animation nodes added to those two sets keep working. # - New Ladders are a climb of their own, keyed on the tile's
ladderN,ladderS,ladderEorladderWproperty. The new calls areIsoGridSquare.getLadder,getLadderUnder,IsoGameCharacter.getClimbLadder,getClimbLadderDown,isClimbingLadderandisClimbingDownLadder, run byISClimbLadderActionwith their ownclimbLadderandclimbLadderDownanimation sets.getClimbLadderneeds a solid floor under the foot.getClimbLadderDownlooks from the square beside the top, on the side the ladder faces, and refuses when the square above the ladder has a floor or another ladder. The top of the climb exits forward from the ladder's facing. # - New Don't leave a
climbSheetflag on a ladder tile. The interact key tries the ladder first (IsoPlayer.doContextClimb), butclimb()starts the rope whencanClimbSheetRopeis true, andClimbState.enterstill records the ladder, so a tile with both mixes the two climbs. Vanilla took the flags off its own three ladders that had both (industry_railroad_05_20,_21,_36). A patch file that gives ladder tiles the rope flag should stand down from 42.22. # - New The rope climb now has a sound, and it plays on anything without the ladder property.
ClimbState.enterandClimbDownState.enterplayClimbSheetRope, andexitstops it. A modded ladder that climbs through the rope states will sound like cloth unless the mod stops it:getEmitter():stopOrTriggerSoundByName("ClimbSheetRope"), once as each direction starts. # - New Vanilla ladders can no longer be picked up. Twelve ladder tiles (
carpentry_02_84to87,location_sewer_01_32,33,48,49, and the railroad and advertising ladders among them) lostIsMoveAble,MoveType,PickUpTool,PickUpLevel,PickUpWeightandPlaceTool, and gainedCanBreakandBlocksPlacement. Ladders already moved stay where they are. #
Types that changed under you
- New
getCore():getGameMode()returns aGameModeobject, not a string.getCore():getGameMode() == "Tutorial"is now false with no error.tostringstill gives the old name, and vanilla moved togetCore():isTutorial().setGameModetakes either type. TheCore.gameModeandCore.lastStandfields andCore.isLastStandare gone. # - New
PZArrayListis gone.getObjects(),getAllContainers,getObjectContainersand the rest now returnList;sizeandgetstill work.getElements,addUnique,containsReferenceandemptyListhave no replacement.TimSort,ComparableTimSortandSortunderzombie.entity.utilwent too. # - New
isHeavyItemanddropHeldItemsare gone fromIsoGameCharacter. In their place aredropHeavyItems,dropHeldItemsServer,dropPrimaryHandItem,dropSecondaryHandItem,dropHandItemForHandToHandandcanPerformHandToHandCombat, withWithPrimaryandWithSecondaryforms. A shove with a blocking item in hand now drops it. # - New A version test should read the first two numbers.
getCore():getVersion()reads42.22.2(42.22.1on the pre-release) plus a git revision and, when there is one, an integrity summary.getVersionNumber()gives42.22. #
New systems
- New Crowbar forcing is
ISForceOpen,ForceOpenState,IForceablePortalandIForceableDoor. All of them, plusForcingTypeandILockableDoor, are newly exposed to Lua. A door or thumpable refuses forcing (isNotValidForForcing) when it is already open, barricaded or force-locked, so a barricade stops a crowbar. The tool must be in the primary hand and carryItemTag.CROWBAR. Each attempt has a flat failure chance of 10%, or 5% withCharacterTrait.BURGLAR, then rolls the character's plus the object'sgetBaseForceOpenChance, with Strength level as the floor. # - New Sleep is refused at any bad smell. The bed and vehicle menus refuse sleep at
MoodleType.NOXIOUS_SMELLlevel 1 or more (ISWorldObjectContextMenuLogic,ISVehicleMenu). A mod that marks a building toxic now also stops sleep there. # - New One new event:
OnElectricityChanged. It has no arguments and fires fromIsoGenerator,AmbientSoundManagerandAmbientStreamManager. No event was removed. # - New Last Stand is Challenges.
lua/client/LastStandbecamelua/client/Challenge,Challenge1is gone, and the globalsgetAllSavedPlayers,deletePlayerSave,createStory,getLastStandPlayerFileNamesandgetLastStandPlayersDirectoryare gone. #
New animations, tiles, icons and sounds
- New Animations. 23 new clips in
anims_X/Bob. Sixteen areBob_Crowbar_*:DoorLeft,DoorRight,GarageandWindow, each withIn,Loop,FailandSuccess. Seven areBob_Ladder_*:ClimbUp,ClimbDown,Idle,GetOnTop,GetOnBottom,GetOffTopandGetOffBottom. 24 AnimSets and 56 actiongroups drive them. # - New Tile art.
Tiles2x.packgained 61 sprites:camping_0446,carpentry_02_on4,location_community_police_014,location_entertainment_theatre_014 andblends_grassoverlays_013. It lost 216, mostly test and leftover sheets, andTiles2x.floor.packlost 28 offloors_exterior_natural_01. No tile definition was added. # - New Icons. No new item icons:
UI.packandUI2.packhold the same sprite names as 42.21. There is one new UI file,ui/Ladder_Icon.png. # - New Lit items. 12 new lit textures for flashlights, a hand torch and lanterns, with 13
...Onmodel entries andStaticModelOnon 12 items. # - New Sounds. 558 new sound entries, mostly
EquipandUnEquipper weapon, plus ladder footsteps and the sheet rope climb.ZomboidSound.bankgrew from 647 MB to 735 MB. # - New No new items. Every new sprite and sound above belongs to something that already existed or to the new crowbar and ladder actions; no item name was added. #
Multiplayer
- New Hit handling was rewritten.
sendHitPlayerwent from three arguments to one andsendHitVehiclefrom four to two.PlayerHitCharacter,ZombieHit,AnimalHit,WeaponHitandDamageare gone, replaced byPlayerHitPacket,HitStatisticPacket,AnimalDamageandVehicleDamage. The patch notes describe damage as moving to the server. # - New The anti-cheat changed.
AntiCheatHitDamageandAntiCheatPlayerare gone. NewAntiCheatVehicleEnterflags entering a vehicle from more than 7 tiles.syncIsoObjectReceiveon doors, windows and thumpables now takes two arguments. #
Files and data
- New Vanilla's tile definitions moved to
media/tile_definitions/, and mods are not affected.LoadTileDefinitions,ZomboidFileSystem.loadModTileDefsandloadModPackFilesdid not change, so a mod's.tiles,.patch.tiles,tiledef=andpack=load as before. Only a tool that reads vanilla's files at the media root needs the new path. # - New The 1x texture packs are gone.
Tiles1x.pack,Overlays1x.pack,JumboTrees1x.packandTiles1x.floor.packwent, withCore.getOptionTexture2x,setOptionTexture2xand the options that used them. The 2x packs were rebuilt, so an atlas survey from 42.21 is stale. # - New Map data changed this time. 269
.lotheaderand 210.lotpackfiles differ in size, as do the map PNGs and sevenmap.infofiles, and the 156 files of the old challenge maps are gone. Any survey of the map cells needs redoing. # - New Sound banks moved up a folder.
media/sound/banks/Desktop/*.bankis nowmedia/sound/banks/*.bank. # - New Depth data changed in places.
tileDepthTextureAssignments.txt,tileGeometry.txtand tenDEPTH_*textures differ, andDEPTH_walls_interior_detailing_bathroom_01.pngis gone. A mod that borrows a vanilla depth cell should check the cell still has no borrow of its own, since a borrow is good for one hop. # - New Tile definitions. 113 of 32,284 are deleted (
crafted_0386,fixtures_windows_detailing_0220,vegetation_wall_015,carpentry_02_on2) and 20 changed. # - New Scripts. All 5,092 items keep their names, and 430 changed: 375 gained
EquipSound, 378 gainedUnequipSound, 35 changedTagsand 12 gainedStaticModelOn. A mod that re-declares a vanilla item by name should re-sync it. NineSaw*recipes becameSawIntoHalves,SawSheet,SawIngotIntoBlocksandSawBlockIntoChunks, andRefillLighterWithGasolineis new. # - New What did not change:
IsoFire.SpreadandOnNewFire, the vehicle level pick inBaseVehicle, every sandbox option name, and the mod tile and pack loaders. # - New A clean method scan does not clear a build. A removed class reads as nil, and a nil-guarded test on it never reaches a method call. Search your Lua for the removed class names as well as the method names. #
What changed in 42.21
Build 42.21.0 has been the live stable build since 28 September 2026. A mod's versionMin can stay at 42.20.0; nothing below forces a raise. These are the changes that touch modding, read from a diff of the two builds' engine classes, Lua, scripts and tile definitions. Details sit in the sections they belong to.
- New Map data did not change. No
.lotheader,.lotpack, texturepack or texture changed; onlyworldmap.xml(.bin)andstreets.xmldid. Any survey of the map cells or the atlases taken on 42.20 is still current. # - New
IsoGridSquare's boolean "north" lookups are gone.getWindow,getDoor,getWallHoppable,getHoppableThumpable,getThumpableWindow,getWindowFrame,hasBlockedDoorandhasBlockedWindowno longer take a boolean; they take aGridSquareEdgeor aGridSquareEdgeFacingDirection(both newly exposed), andisWallTo(square, int)takes aGetSquare. A call with the old argument throws from Java, past anypcall. # - New Some methods only look removed.
getOppositeSquare(),getSquare()andgetNorth()on doors, windows and thumpables moved into default methods ofGridSquareEdgeElementand still work from Lua (vanilla calls them). A diff of declared methods reports them as removed; it is wrong. # - New Removing a world object works differently in multiplayer.
sledgeDestroynow sends its packet only when the server optionAllowDestructionBySledgehammeris on, and the server checks the same option and does the removal itself.RemoveItemFromSquarePacket.processServeris gone, andtransmitRemoveItemFromSquarecalled on an MP CLIENT now only removes the client's own copy, which leaves a ghost no one else sees. On the server the one-argument form now removes every square of a multi-square object (IsoObjectUtils.isObjectMultiSquare,getAllMultiTileObjects); single player still removes one square, andsledgeDestroystill removes nothing in single player. # - New Zombies tear down sheet ropes, but only an object whose
sheetRopefield is set, which only vanilla's window tie (IsoWindow.addSheetRope) sets; a rope laid withIsoObject.newis untouched. The damage rebuilds the sprite name from the first two_parts plus the third part + 40 (crafted_01_8becomescrafted_01_48), so a rope on a sprite sheet of your own made through the vanilla tie becomes a name that does not exist. # - New Keybinds have a registry. Vanilla names its 82 bindings (78 in 42.20) through
KeybindId;KeybindId.X:getId()is the same string as before, andCore.getKey(String)andaddKeyBinding(String)are unchanged, so a mod'skeyBindingtable works as it did. Test a key against a vanilla binding withgetCore():isKey(KeybindId.INTERACT, key). # - New 29 more classes are exposed to Lua, among them
java.util.ArrayList,HashMap,HashSet,LinkedListandIterator,java.lang.Mathand the boxed number types; vanilla itself now callsArrayList:new(). # - New
IsoCell.getVehicles()is aHashSet. Walk it withiterator(); vanilla's own vehicle blood UI still callsget(i)on it. # - New The old renderer is no longer one keypress away. Through 42.20 the Home key toggled the old renderer; 42.21 makes it the unbound
ToggleOldRendererbinding. Any 42.20 observation of how something draws may have been made on the old renderer if Home was ever pressed. # - New Light bulbs burn out.
IsoLightSwitch.updatenow spends a bulb; details under World objects. # - New
ISDestroyStuffAction:getCornerWallSpriteis fixed. Through 42.20 it returned the wrong half of a corner and put the destroyed face back; 42.21 returnsCornerWestWallforDESTROY_NORTHandCornerNorthWallforDESTROY_WEST. # - New Script changes. 86 drink containers gained
base:cookableandbase:cookablemicrowave; the Metalworker's grants became welding recipes; and the Smither, Blacksmith, Cook, Gardener and Mason grants named recipes that did not exist, so through 42.20 they granted nothing; 42.21 replaces them with real names. A mod that re-declares a vanilla item by name freezes the item's other fields at copy time and must be re-synced after every update (a re-declared glazed clay jar lacks the newbase:cookableuntil it is). # - New Tile definition changes. The noise patch gave 229 damaged chainlink fences a
ThumpSound; roof snow now blocks rain and burns; church signs light to radius 4; the brazier became a moveable; 1,119 definitions were deleted, 1,078 of them slots with no art. Seven of the deleted ones with art are placed on the map (office desk pieceslocation_business_office_generic_01_2/3/4/9/12, in 111 cells) and are now propertyless. # - New What did not change apart from
ArrayListbecomingListin signatures: the tile-depth and tile-geometry loaders, mod tiledef loading,CustomPerks,OutfitManager.loaded,ModelManager.loadModAnimations,LightingJNI.updateChunk,NewMapBinaryFile.addToIsoChunk,IsoTrap.triggerExplosion, thecreateZombieglobal, andCore.getKey/addKeyBinding(String). # - New Vanilla bugs these notes describe that 42.21 did not fix: the operator-precedence slip in
isValidPerSquare,ISPickAxeGroundCoverItemwritingself.pickAxeand readingself.pickaxe, and thefetch.c == 0early return in the world context menu. The patch notes' "explosives now work in basements" could not be located as any change in the fire, trap or throwable classes; treat it as unverified. # - New After an update, diff before you rebuild. An index or survey of the previous build is the only copy of it; compare it with the new build first, then rebuild it. #
Maps and lots
map.info
- Seven keys, prefix-matched.
ChooseGameInfo.getMapDetailsreads the file withBufferedReader.readLine(), trims each line and prefix-matchestitle=,lots=,description=,fixed2x=,zoomX=/zoomY=/zoomS=,demoVideo=andonly_for_game_mode=. # only_for_game_mode=is real and rarely mentioned. It resolves throughRegistries.GAME_MODE; vanilla's March Ridge carriesonly_for_game_mode=Sandbox. #lots=is a list. It is repeatable. Every vanilla sub-map sayslots=Muldraugh, KY, which adds its directory to that map GROUP; it is not an override declaration. #description=concatenates. It is repeatable and the lines are joined with no newline inserted. #title=defaults to the folder name. Vanilla's sub-maps put a literal pointer string there (title=See media/lua/shared/Translate/EN/Rosewood, KY/title.txt) and take the real name from that file. #- Values are cut out with
String.replace. Every value is extracted withString.replace(key, ""), not a prefix strip, so a value that contains its own key text again is mangled. # - Line endings do not matter here. Both readers use
readLine(), which ends a line on\n,\ror\r\n, and then trim. Vanilla's copies are CRLF by convention, not requirement. #
IOException is caught around the parse loop, so a Float.parseFloat failure propagates out of getMapDetails and the map never appears. A missing key leaves the field at Java's 0.0f, and MapSpawnSelect.lua:727 explicitly guards against all three zoom values being 0. #Map registration
- A mod map is skipped unless
<mod>/common/media/maps/exists.MapGroups.createGroupsenumerates a mod's maps with aDirectoryStreamfiltered onmap.infoexisting, and the whole per-mod body is gated on that directory. Ship the map only under42/media/maps/and it is skipped without a word. Oncecommon/exists the version directory is scanned as well, so mount in exactly one place or the cells register twice. # - A free registration signal.
doMapZones(metazoneHandler.lua:82) warnscan't find map objects filefor every REGISTERED lot directory without anobjects.lua. Ship none and that warning proves your map registered. # - New On a server, the map list is the
Map=setting and nothing else.IsoMetaGrid.getLotDirectoriesusesGameServer.gameMapon a server andGameClient.gameMapon a client, split on;and followed through each map'slots=; only single player builds the list from the map group, which always includes an active mod's folder. Anything vanilla loads per lot directory (basements.lua,objects.lua, the lotheaders) is skipped for a mod folder a server'sMap=leaves out. The host settings screen adds a mod's folders toMap=only when the mod is added through its own Mods panel, andDefaultServerSettings:setDefaultsFromSingleplayerreturns at once, so nothing copies single player's mods and maps into new server settings. # - New A B42 server builds every chunk and sends it. A client generates nothing: a chunk the server has not saved is queued until generated (
PlayerDownloadServer), so what a client sees is the server's stamp. A fresh server save gets a new ResetID, on which every client deletes its cached copy of the world at connect. # - New Some town streets carry no
TownZone. Parts of Riverside's east and south have streets the map gives no town zone, so a "not in town" test on zones alone misses them. #
Cell size: both numbers are live
- A cell is 256 tiles, except where it is 300. A B42 cell is 256×256 tiles (Muldraugh's own
map.infodescription says so), butworldmap.xml's spatial index still uses 300-tile cells, andforest.pyramid.zipis on the 300 grid whilepyramid.zipis on 256. Both numbers are live in different files; never carry one into the other. The official map-authoring guide's "multiple of 300" is B41. #
Negative levels cannot be authored in TMX
- A
-1_layer prefix fails.MapLevel::levelForLayersplits the layer name on_and parses the prefix withtoUInt, so-1_Floorfails the conversion and is treated as having no level prefix. This holds in TileZed and in the maintained fork. Below-ground content reaches the world through the basement system instead, authored at level 0 and placed at a negative world level. #
.lotheader and .lotpack
- Header layout.
LOTH, version, tile-name count, the newline-separated palette, thenchunkW,chunkH,minLevel,maxLevel, the room table (each room carrying a name and a plain signed level), the building table, and a 1024-byte per-cell zombie-intensity tail. # - Pack layout.
LOTP, version, chunk count 1024 (32×32 chunks of 8×8), an int64 offset table, then the per-square streams. A square isint count;count == -1means the next int is a run of empty squares to skip, otherwise the next int is the room index andcount - 1palette indices follow.countincludes the room slot, which is the detail that makes the stream parse. # - The B41 forms carry no magic. A B41 lotheader opens with
int32 version = 0and the palette, a B41 lotpack straight into the chunk count; cells are 300 tiles of 900 chunks (30×30 of 10), and the art is 1x. #
x = (chunkIndex // 32) * 8 + (squareIndex % 64) // 8, y = (chunkIndex % 32) * 8 + (squareIndex % 64) % 8, level = minLevel + squareIndex // 64. A byte-identical round-trip cannot detect a transpose, because re-encoding a stream in its own order matches whatever order you read it in. Test against known world coordinates: pick a sprite you can locate on the real map and check it lands where it should. #(maxLevel - minLevel + 1) × 64 squares, including the trailing run of empties. Come up short and the reader runs on into the next chunk's bytes, putting every later square at the wrong index and the wrong Z, with no error, because nothing is counting. Vanilla is exact in all 70,656 of its chunks. #IsoLot.load seeks a chunk's recorded offset with no zero guard, so an offset of 0 reads the file magic as a square count and hits end-of-file, and that chunk renders as void. Write an all-skip run for every empty chunk. Once a save has touched a corrupt chunk it keeps it: a saved chunk overrides the map file for ever. #Overriding vanilla cells
- Squares are winner-takes-all. A cell shipped without vanilla's squares removes them from the world, observed in game as a hole through the surface that the player falls into. #
- Rooms load from both files. Carrying vanilla's room table forward re-registers every one of its rooms and logs
duplicate RoomDef.metaID, once per cell. A square stores the INDEX of its room in the header, so squares cannot be carried without the room table that gives those indices meaning. # - Building ids use the per-FILE index. A cell loaded twice numbers its buildings from 0 in each file, so vanilla's copy of an overridden cell duplicates the override's building ids; the live
IsoBuildingcache is keyed by that id, rooms of different buildings weld together and the roof cutaway stops matching the player's building, county-wide, while the mod is enabled. Two lotheaders per cell is not a supported configuration. To add content inside a vanilla cell, use basement lots; overriding whole cells is for maps that own their ground. #
The in-game map
- The game loads the binary, not the XML.
WorldMapDataAssetManagerchecks forworldmap.xml.binand loads it whenever it exists;WorldMapBinaryrejects "version 1 (cell size 300)". The Lua still checks forworldmap.xmlbefore the asset manager runs, so a stub XML must be present as a trigger though nothing reads it. # - The binary layout, little-endian throughout, is below. There is no offset table, so a cell has to be parsed to find where the next one starts.
streets.xmlandworldmap-annotations.luaare added with no per-directory close, so they are additive. #
"IGMB"
int32 version (2)
int32 cellSize (256)
int32 width, int32 height -- the world in cells
int32 stringCount
stringCount x ( int16 byteLen, byteLen bytes of utf-8 )
width*height cells, ROW MAJOR, each either
int32 -1 -- no features here
or
int32 cellX, int32 cellY, int32 featureCount
featureCount x feature:
int16 typeStringIndex
uint8 ringCount
ringCount x ( int16 pointCount, pointCount x (int16 x, int16 y) )
uint8 propertyCount
propertyCount x ( int16 keyIndex, int16 valueIndex )
qint8 but must be read UNSIGNED. The forest layer contains a polygon with 140 rings, which reads as −116 signed and sends a parser into the weeds. worldmap.xml.bin round-trips either way because nothing in it exceeds 127, exactly the accident that lets a wrong reader look proven. #- The image pyramid is a separate thing.
pyramid.zipis the ground image, not the vector data. Itspyramid.txtgivesbounds 0 0 19968 16128against the sameimageSize: 78×63 cells at 256, one pixel per world tile, no margin. Level 0 holds one 256 px tile per cell, named0/tile{cellX}x{cellY}.png, and levels 1–4 halve each time.worldmap.pngis the in-fiction tourist map at 2 tiles per pixel with a 250-tile margin (px = (tile + 250) / 2);spawnSelectImagePyramid.zipis a third image at another scale. # - The spawn-select screen is a real vector map on
self.javaObject:getAPIv3(), not a static image, so an overlay drawn on it must anchor its corners each frame throughmapAPI:worldToUIX/worldToUIY(vanilla's zone editor is the worked example). Spawn locations are separate:SpawnRegionMgr.loadSpawnRegionsFilereadsmedia/maps/<Map>/spawnregions.lua, falling through tospawnpoints.lua. #
The 300-grid override mask
- Owning two cells diagonally blanks four.
MapFiles.postLoadbuilds a per-directorybgHasCell300, marking a 300-cell covered when the 256-cells at its top-left and bottom-right are both present (formula below); the other two are never tested.WorldMapGeometrythen clips a 300×300 box out of every lower-priority cell's polygons for each covered 300-cell. For a contiguous region this is exact; for scattered cells it blanks map cells you do not own. It is driven by your.lotheaderfiles, not your map data, so the only fix is to supply map data for the spill as well. Not involved:WorldMapRendererconcatenates features from every data source for a cell and never consultsisLastDataInDirectory, andWorldMap.addImagesis purely additive. #
c256x = floor(c300x * 300 / 256)
c256y = floor(c300y * 300 / 256)
covered = hasCell(c256x, c256y) && hasCell(c256x + 1, c256y + 1)
Room loot and room names
- Room loot keys off
room.getName().Distributions.luaholds 462 room keys and they are TAB-indented; a pattern expecting four spaces finds 53 of them. # - A mod's own room names are a first-class surface. A file in
media/lua/server/Items/that doestable.insert(Distributions, myTable)is merged into the live distributions bymergeDistributions(), which takesDistributions[1]as vanilla and recursively merges every later table in. Entries areroomname = { containerkind = { procedural = true, procList = { ... } } }; prefix your room names. # - A room named after a vanilla room is stocked as that room. A sewer chamber called
toolstorefills with retail tool-shop stock. Keep container KIND names vanilla (crate,locker,counter,toolcabinet,metal_shelves): a kind the room entry misses falls through to that container'salldistribution. An inventedProceduralDistributionname is a silent nothing.crateandsmallboxare real kinds though no tile carries them. # - Loot respawn is zoned. Only buildings inside
TownZone,TrailerParkorFarmrespawn loot. # - Indoor zombie spawning is room-based (meta intensity × room area × building) and runs for any real room def, including a mod's rooms below ground. It fires from
IsoChunk.randomizeBuildingsEtcas the chunk loads, only while a player is within ONE level of the room;addSpawnedRoom(roomId)is public and marks a room spawned. #
Basement lots
A basement is a .pzby lot the engine stamps INTO a chunk vanilla owns, on that chunk's first generation, merging its rooms and one building into the meta grid. It is the one engine path that adds below-ground content to a cell without a second lotheader, and it is what the cutaway, the room system and the map all understand.
Registering lots
- Registration is plain Lua. A mod's own
media/maps/<Map>/basements.lua(the cell's lotheader directory must match) callsBasements.getAPIv1():addBasementDefinitions / addAccessDefinitions / addSpawnLocationswith plain tables of{ width, height, stairx, stairy, stairDir };loadMapBasementLuaFiles()walks EVERY lot directory onOnLoadMapZones, so a mod map directory is picked up automatically.metazoneHandler.luaaddsregisterBasementSpawnLocationfor zone-declared spots. # - Spawn locations. A spawn location with
choicesnames its layouts.addSpawnLocationstakesx,y, optionalz,stairDir,choicesandaccess, makes every spawn 1×1 and places the lot at the spawn point minus the lot's stair offset;canPlaceAtcomputesbasementZ = spawn.z - header.levels, so a spawn at z = 1 puts the lot's TOP level on the street.loadBasementDefinitionHeadersoverwrites a definition's width and height from the lot file, never its stair offsets. # - New A server that leaves the mod out of
Map=never runs itsbasements.lua. See Maps: a server's lot directories are itsMap=setting. A mod can load its registration itself onOnLoadMapZoneswhen its folder is missing fromgetLotDirectories(), guarded so it never runs twice;reloadLuaFile,fileExistsand the.pzbylookup all resolve through the mod-aware file system.Basements.beforeOnLoadMapZonesclears every per-map table just beforeOnLoadMapZones, so a registration made at file load is lost. # - New A registered lot joins the random-basement pool. A spawn location without
choices(every houseBasementzone, whichregisterBasementSpawnLocationregisters without any) considers EVERY definition registered for that map and picks among thosecanPlaceAtaccepts: the north flag, a lot that FITS inside the zone box (placed at zone + zone stair − lot stair) and the overlap test. To keep a lot out of the pool, move the lot's stair offset, its access stamp's and its spawn point by the same amount, larger than any zone (vanilla's stair offsets run 0..12 and its zones reach 20×23): placements are unchanged and no zone can contain the lot. # - New A spawn point must stay in a cell its map owns, and the lot's own cell is safest.
isCellFromThisMapdivides by 256 and asks whether the HIGHEST-priority map directory's lotheader for that cell belongs to the map (IsoMetaGrid.CreateStep1fills its header table withputAllfrom the last directory to the first). In a cell another map mod ships a lotheader for, every lot whose spawn lands there is refused silently, lot and access stamp both. # - New Fixed basements from different mods collide. Two mods that register fixed spawns under the same map overlap through the rule below, and whichever placement is computed second is dropped. #
Placement and the save
- The overlap rule, exact.
Basement.checkOverlapreturns false if the two placements' z ranges (placeZ .. placeZ + building.getMaxLevel()) miss, false if their building boxes miss, then walks the shared levels comparing room rects, and after that loop returns true unconditionally. So a box-and-z overlap with no room touching is still refused, and whichever placement is computed second is refused silently. A town-sized lot at z −1 would refuse every vanilla basement in the town; many small lots with pairwise-disjoint boxes, clear of every vanillaBasementzone, do not. # - New Placements are computed once per world and saved.
map_basements.binholds a magic, two ints, the placement list (x, y, z as ints; w, h as shorts; the lot name as UTF) and the building defs of the basements.Basements.beforeLoadMetaGridparses the definitions every load and then callsloadSavefile(); when the file loads, placements and building defs come from it and are never computed again. A saved layout stamps by lot NAME (SpawnBasementInChunk(chunk, name, x, y, z)), never by looking the name up among what is registered now. # - New What an update reaches. A changed
basements.lua(spawn points, conditions) reaches NEW worlds only and cannot break an old one. A changed.pzbyreaches chunks an old save has not generated yet, at the OLD placement, which is a seam.loadSavefilechecks nothing about which definitions are registered, so a basement mod added to an existing save never gets a placement. # - New Registration order is the random order.
calculateBasementPlacementswalks each map's spawn list in REGISTRATION order with one generator seeded from the world seed, andpickRandomdraws even from a one-item list, so every spawn that places consumes a roll. Modbasements.luafiles register inloadMapBasementLuaFiles(shared Lua, first) and the house zones indoMapZones(server Lua, after), so a mod's spawns shift every house zone's roll. Deletingmap_basements.binin an old save therefore redraws the random house basements, and in visited towns the saved chunks keep the old basement squares while the meta grid gets the new rooms. Registering from server Lua (afterdoMapZones) keeps the house rolls. # - New A mod cannot touch the saved layout.
getFileOutput,getFileInputandgetFileWriterall write under the Lua cache directory and refuse... An MP client computes its own layout (no network class carries the file) and agrees with its server only because both use the world seed and the same registration order; a server's sandbox settings reach the client in the connection handshake before the world loads, so a sandbox option can choose the order on both.GlobalModData.initandOnInitGlobalModData(isNewGame)run beforeOnLoadMapZonesinIsoWorld.init, so a world can record which order it was made in. # - Dead ends.
Basement.SpawnFrequencyis read by nothing; the Lua globalNewMapBinaryFile("TEST")targets a pre-format prototype and is useless. #
The lot and the stamp
- The stamp and the lotpack loader build a square the same way (
NewMapBinaryFile.addToIsoChunkagainstIsoCell.PlaceLot): both resolve tile names throughIsoSpriteManager.namedMap(a miss logsMissing tile definitionand skips) and callCellLoader.DoTileObjectCreationper tile in stream order. The stamp clears the square first under the attribute bits (0 clears everything; 1, 2, 4 keep floors, walls, other); the lotpack path clears only when the first tile is asolidfloor. The stamp skips every square the lot has no tiles on, and runsremoveFloorsAboveStairson the z0 column above every lot square. Rooms merge into the meta cell atroomDef.level - header.levels.SpawnBasementInChunkprints only underDebugType.Basement. # - Corrected Which chunks a lot reaches is measured from its corner.
Basements.onNewChunkLoaded(insideIsoChunk.LoadBrandNew, for every chunk with no save file) stamps a lot into a chunk whenchunkOverlaps(chunk, placement, w + 1, h + 1)holds, measured from the lot's CORNER. The shell one square past the rooms is therefore reached only when the rooms start at the corner: a lot whose rooms start one square in loses its far wall on the first column or row of a new chunk.Events.LoadChunkfires once per chunk at the end ofIsoChunk.doLoadGridsquarein single player, on an MP client and on a dedicated server, and is a place to lay what the stamp missed. # - Surface access lots (
media/basement_access/, 147 in vanilla) cut the floor under the entrance and lay the stair or rope head; a spawn location names one withaccess = "...". A square with NO floor at z0 is what makes a rope climbable there:canClimbDownSheetRopeon a floored square returnsgetZ() > 0. # - B42's random-basement route is a
Basementzone with StairX / StairY / StairDirection / Access and a seeded pick.duplicate RoomDef.metaIDonce per launch at a vanillaBasementzone is vanilla colliding with itself. # - The map's red basement pulse is debug-only (
Core.debug && renderer.getBoolean("Basements"), an option the player UI never sets), but the data it draws is Lua-readable from the first frame of a fresh save:getWorld():getMetaGrid():getBuildings(),BuildingDef.getMinLevel/getRooms,RoomDef.getName/getZ/getRects. Draw it with vanilla's own map idiom:mapAPI:worldToUIX(x, y)andself:drawPolygon(...)for a filled quad. # - Vanilla's own below-ground content. 72 cells carry negative levels (66 one deep, 3 at two, 1 at four, 2 at seventeen). The deepest is a research facility under Hog Wallow Forest whose levels −1 to −11 are two elevators and a hall and whose bottom holds the only
caveroom in the game. Its dug spaces use one vocabulary: the cobble wall quadwalls_logs_96/97/98/99on floor squares, the concrete quadwalls_garage_01_32..35on the non-floor side,boulders_*props, and heavyoverlay_grime_*. #
Below ground: drawing, rooms, light
FBORenderCell: performRenderTiles walks the per-player on-screen chunks and renderOneChunk loops from the chunk's min level to its max, calling renderOneLevel for each, gated only by lighting having run, the level being on screen (FBORenderLevels.calculateOnScreen, a screen-rectangle test) and the level having squares. Levels are baked into FBOs in PAIRS (calculateMinLevel: −2 and −1 share one, 0 and 1 the next). IsoCell.recalculateAnyGridStacks does clamp its lists to the player's own level below ground, but that is the OLD renderer's grid stack, which B42 keeps alive beside the new one. An earlier version of this page said only the player's level is drawn below ground; that was read from the old path and is wrong. #What hides what
- New A solid floor hides the level below unless it is
transparentFloor.IsoGridSquare.CalculateVisionBlockedblocks sight between levels at a square holdingsolidfloorwithouttransparentFloor(RecalcPropertiesclears the square's flag if any solid floor on it lacks it). AtransparentFloorsprite is still walked on and is drawn in the translucent-floor pass over the level below; vanilla's metal gratesindustry_01_37/38/39carry it, its sewer catwalk plates do not. A.patch.tilescan add the flag to a vanilla sprite, sincePropertyContainer.set(String, String)turns a flag name into itsIsoFlagTypebit. # - New A square no local player has seen draws black, and one write does not fix it.
LightingJNI.updateChunkpacksisSeen(player)into each square's vision bits for the native lighting pass and only revisits a chunk level whose light-check flag is set.setIsSeen(int, boolean)sets bit 0 of the square's lighting record, but that record is overwritten with the native result whenever the native side relights the square, andbSeen()refreshes first, so a single write is often gone before it is pushed. Re-mark the squares and flag the level for a relight (chunk:checkLightingLater_AllPlayers_OneLevel(int)) until they read seen.RoomDef.exploredis a different thing: the loot flag, read only by item pickers. # - The cutaway keeps two wall classes per chunk level (
FBORenderCutaways). A wall adjacent to a ROOM is cut by the room rule: only the wall squares whose floor one to three tiles behind is a seen square of the player's own room. A wall adjacent to NO room is an exterior wall cut by the fence rule: the whole run is cut whenever the player stands within 6 tiles north of a north-facing run or west of a west-facing run (the mouse pointer counts at 3), whether or not it hides anything. The test is per FACE, so a room's east wall, standing on the square outside it, still counts as adjacent. Unroomed corridors fence at every turn; the fix is real rooms, orsetRoomIDon the wall squares atLoadGridsquare(the chunk loader sets ids from RoomDefs and never saves them).NeverCutawayexists on four sign tiles and is not a lever. # - New The cutaway only cuts the camera's own level. Walls on a level below draw whole when looked down on (a vanilla stairwell too), and
shouldRenderBuildingSquarehides every square above the camera while the camera is below ground. Within a level the cut is matched by room id, so a borrowed room works. # - New A building whose nearest room rectangle is over 10 tiles away is drawn black.
FBORenderCell.checkBlackedOutBuildingsruns every frame over the buildings the cutaway has collapsed and blacks out any whoseBuildingDef.getClosestPoint(each room's rectangles) is more than 10 tiles from the player. A room id on a square does not put the square in the room's rectangles, so a room borrowed from far away goes black the moment the player steps onto it, torch and all. Add the square from Lua:room:getRoomDef():getRects():add(RoomRect.new(x, y, 1, 1))(RoomDef$RoomRectis exposed asRoomRect), and neverCalculateBoundson a far room: the building's bounds would span the map, and a 5,932-tile stretch froze the game for seconds at a time. Rectangles are not saved; put them back as squares load. The native lighting calls no Java and is handed only each square's building and room ids. # - No
IsoRegionexists below z0, so a dug space gets no room status from that system; the floor above is the ceiling. In a vanilla basement 97% of squares have a floor directly above and there are no ceiling tiles. # - New Undug rock is no square at all, so a dug space below the first level shows through it. Since every level is drawn, a tunnel at −3 under rock shows from a tunnel at −1. Vanilla's cave lays
ceilings_01_0on the level above wherever that level has no floor; do the same. A ceiling tile is a walkable plane seen from above, so treat aceilings_*floor as solid rock in any openness rule. # - The engine has no depth floor.
IsoChunk.minLevelandmaxLevelare plain ints,isValidLevelismin <= z <= max, andsetMinMaxLevelreallocates around whatever square is created; vanilla spans −17 to 29, and theIsoChunkLevelpool is a cache, not a cap. "Above ground" in vanilla Lua is writtengetZ() > getChunk():getMinLevel(). # - The engine's void filler is not ground, and nothing places it.
underground_01_0/1carrysolid,exteriorandcutWand nosolidfloor: a block that stops movement and is not a floor. No vanilla basement lot, no map cell and no engine class callsIsoGridSquare.addUndergroundBlock(String); the basement stamp is the one class besides the square that touches it, throughremoveUnderground(). The void round a basement lot is genuinely empty. Vanilla refuses to sledge a wall with nothing behind it:ISDestroyCursor:canDestroyopens withisBasementWallAdjacentToTheVoid. #
Indoors and outdoors
- New What makes a square outside.
isOutside()is theexteriorflag.RecalcPropertiesclears it when the square has a room id orhaveRoof, and sets it otherwise.setRoomID(id)with an id other than −1 clears it at once and resolves the room throughIsoMetaGrid.getRoomByID, so a square may take a room from another chunk.haveRoofis set only at chunk load (a rain-blocking tile above shelters every square below it, down to the min level) and has no Lua setter. So a roomless square under open ground is outside for ever. # - New What being outside costs a player below ground. It decides rain on the player (
BodyDamage.UpdateWetnessshelters onlyisInARoom()orhaveRoof), rain filling containers, floor items getting wet, rain waking a sleeper, snow drawn on a floor (no z test), puddles, fog rows, wind on objects, the inside/outside sound mix (ParameterInside), walking speed and dirt, animals spotting you, a helicopter seeing you (no depth test), and generator power on the square (refused on an exterior square unlessAllowExteriorGenerator, which every preset turns on). The falling-rain picture does not change below ground either way. # - New Runtime space can be made indoors with the engine's own room editor.
BuildingRoomsEditorexposes itself to Lua (the player-facing editor is switched off at its one entry). The sequence:BuildingRoomsEditor.Reset(),getInstance(),setCurrentBuilding(nil),createBuilding(),building:createRoom(z),room:setName(n),room:addRectangle(x, y, w, h), thenisValid()/getInvalidString()andapplyChanges(false).applyChangesremoves any user-defined building with the same meta id (taken from the first rect's NW corner, so growing a room north or west leaves an overlapping old one), recalculates ids, tells the lighting, and walks every loaded chunk, which is heavy: batch it. Nothing ever SAVES these rooms (PlayerRoomsFile.save()has no caller), every machine must register its own (the meta grid is not synced), and on a dedicated server, whose room update walks only local players' chunks, set each square by hand (setRoomID,setRoom(def:getIsoRoom()),RecalcProperties()). # - New A room id from map row 32 south cannot cross into Lua exactly.
RoomID.makeIDpacks((cellY << 16 | cellX) << 32) | index, and Kahlua hands a Java long to Lua as a double. From cell row 32 (y 8192 and on) the id is 2^53 or more, where a double holds only even integers, so a room with an odd index comes back as its even neighbour's id. The engine keeps ONEIsoRoomper id (getRoomByIDcaches it), so a room OBJECT read off a square never passes through a number and compares with==; move rooms by object, never by id. # - New A room has no temperature. The air a character feels is the climate temperature; a square in a room with grid power reads 22 °C; below ground the outside value is damped; heat sources only raise it. There is no temperature field on a room, building or square and no Lua setter, and the climate's modded tier is one value per machine. #
Light below ground
- A point light announces itself; an ambient does not. A lattice of lamps reads as lights arriving and leaving as the player walks, whatever their colour, spacing or radius. To lift a whole unlit space, drive the engine's ambient through the climate modded tier (under World objects). #
- New Below ground the whole view is multiplied by the interior global light.
RenderSettings$PlayerRenderSettings.updateRenderSettingslerps the scene's colour modifiers towardClimateManager.getGlobalLight().getInterior()when the playerisInARoom(), and the weather shader multiplies the world by them, lamps and torches included, soCOLOR_GLOBAL_LIGHT's modded tier is a whole-view dimmer as well as a tint.FLOAT_DESATURATIONis the one murk a room can have:ImprovedFog.startRenderreturns at once when the player is in a room. # - New A map-placed lamp tile is a real light switch.
CellLoader.DoTileObjectCreation, the path both a lotpack and a basement stamp take, makes anIsoLightSwitchof any sprite whose type is a light switch. A sprite carryinglightRgets its own light and starts on; one without is a room light following the room. It is lit whilehasElectricityAround(): mains when its square or a neighbour is a building square, otherwise a generator in reach. So a lamp in a roomed basement runs on the grid until the shutoff and on a generator after, and the player can switch it, unscrew its bulb and pick it up with no code. #
Things that fall through
- New A vehicle is filed on the level its physics height rounds to wherever a floor lies below.
BaseVehiclesets the level from the physics height plus 0.05 and keeps it when that square or the one below has a floor; itsrenderreturns for any vehicle that is not the camera character's when its square is unseen. A light trailer dipping a hair under the road is filed on level −1 wherever a basement lies below, and draws black or not at all. # - New A corpse or a ragdoll lands on the level its height rounds down to. A body takes the character's current square, set through
IsoCell.getGridSquare(double, double, double), which floors z, so a ragdoll resting a hair under a floor's plane is filed on the level below whenever a square exists there, drawn at street height and lootable from below. A living character ragdolling the same way is dropped a level when the fall ends.removeCorpse(body, true)/addCorpse(body, true)move a body with nothing sent (falsesends the packet). # - New Ragdolls stand on
solidfloorand on solid blocks. Chunk physics (IsoChunk.calcPhysics) gives a floor only to a square whose properties carrysolidfloor, and a solid block to any square carryingsolid,solidtransorblocksight, sosolidtranswater has an invisible block over it a ragdoll can land on.IsoDeadBodyhas no falling logic of its own. # - New A burning zombie lights the square it dies on.
IsoDeadBody's constructor starts a fire on the body's square when the zombie was burning, so one that falls down a hole and dies lights a fire there. #
Tiles and tilesets
Shipping a tileset
- Two files and two
mod.infolines.media/texturepacks/<name>.packdeclared aspack=<name>, andmedia/<name>.tilesdeclared astiledef=<name> <N>.Nmust be 100–8189 and unique across every enabled mod, orloadModTileDefslogs a collision and skips the tiledef entirely. File names are lowercased before lookup; sprite names match case-sensitively. A pack or tiledef themod.infodoes not declare is never loaded, and the symptom is missing art with no message. # - Inside the
.tilesbinary, a sheet's number is its INDEX WITHIN THE FILE, 1..512, not the file's tiledef id. Anything else throwsinvalid tileset number N, must be from 1 to 512fromIsoWorld.LoadTileDefinitions, and the throw unwinds out ofIsoWorld.initfrom both the tiledef pass and the property-string pass, so every mod tiledef later in the load order never loads either, with nothing naming it. The limits are 512 tilesets per file and 512 tiles per tileset. A round trip of the file cannot catch this; it reproduces whatever number it was given. # - New A sprite's saved id is arithmetic on the tiledef number.
IsoObject.savewritessprite.idas a big-endian int:(tileset − 1) × 1024 + ifor file 1, and1048576 + (file − 2) × 262144 + (tileset − 1) × 512 + iotherwise,filebeing thetiledef=number. That is why 8189 is the top of the range (8190 overflows an int), and why a saved chunk filemap/<cx>/<cy>.bin(cx, cy = tile ÷ 8) can be scanned for a sheet's ids with no chunk decoder. # - A
.patch.tilesfile ADDS properties to sprites already defined.IsoWorld.LoadTileDefinitionsreads the patch flag from the file name, looks each<sheet>_<index>up and adds to it; a sprite that does not exist is skipped. Declare it astiledef=<name>.patch <id>; it loads after vanilla's seven, and vanilla's owntiledefinitions_noiseworks.patch.tilesis the precedent. Any parser of the tiledefs must MERGE a patch per tile: the noiseworks patch re-lists nearly every floor with onlyFootstepMaterial, and a replacing parser reports 588 floors with nosolidfloor. # - The
.txtform of a tile definition is a TileZed export artifact. The game never reads it. # - A sprite can exist as art and have no definition (all 64 sprites of
overlay_graffiti_wall_02, for one); the engine logsSEVERE: Missing tile definitionand the object cannot be described. A script-declared sprite must be defined; only a runtime-created one may be path-loaded (see World objects). # - A pack sprite is trimmed to its ink and carries an offset into its own 128×256 canvas; draw it at that offset or everything floats. Vanilla's
Tiles2x.packandTiles2x.floor.packboth name their pagesTiles2x0, ..., so key pages by pack AND name. Vanilla atlas pages are at or under 1024×1024 and often not powers of two. # - Canvas size decides the scale fixer (
IsoSprite.performRenderFrame): a 64×128 original at tile scale 2 is force-doubled LINEARLY and comes out blurred; a 128×256 original draws 1:1. Pre-double 1x art with nearest neighbour. A pack whose recorded canvas fields disagree with its images is doubled twice and renders huge. # - New Measure a sprite at alpha above 128. Vanilla drop shadows are real ink at alpha 1..32, so a bounding box at alpha > 0 measures the shadow; a pallet measured that way reads 124 px wide and 3 px off centre, at alpha > 128 its real 118. Find a flat surface's centre line from its widest ink row. #
Depth
- Corrected Per-pixel depth comes from two files, and
tileGeometry.txtis not one of them. The renderer readscommon/media/depthmaps/DEPTH_<sheet>.png(one 128×256 cell per slot; blue/255 is the depth, alpha 0 means no depth) andcommon/media/tileDepthTextureAssignments.txt(myTile = otherTile,borrows another tile's cell). A sprite with neither falls back toDEPTH_whole_tile.png, the square's cube, so it draws OVER anyone standing on its own square.tileGeometry.txt's boxes, cylinders and polygons are the debug depth editor's source data:TileDepthTexture.recalculateDepthis the only rasteriser and nothing in the jar calls it. Vanilla's geometry tiles work because their result is baked into vanilla's own depth maps. An earlier version of this page said the primitives were rasterised at load; they are not. # - New
tileGeometry.txtstill matters: it is loaded for itspropertiesblocks and it gates the depth maps.TileGeometryManagerappliesItemHeight,Surface,CurtainOffset,OpaquePixelsOnly,TranslucentandUseObjectDepthTexturefrom it, andTileDepthTextureManager.initloads a mod'sdepthmaps/folder ONLY whencommon/media/tileGeometry.txtexists. The assignments file needs no such gate. All of these load fromcommon/media/only, never the version directory. # - New A depth map is always read as 8 columns.
TileDepthTextures.createTilesetpasses 8 whatever the sheet's own width, so<sheet>_<i>is cell (i mod 8, i div 8) and the map must be 1024 wide. # - New Two depth scales. A cell baked from geometry is exactly
floor(255 × (1 − (fx + fy) / 4 − h / 2)): 255 at the square's back floor corner, 127.5 at its front, 63.75 a storey up the middle. Vanilla's hand-made wall presets fit246 − 63 × (fx + fy) − 127 × h, about 8 nearer. Art moved along the floor by dy canvas rows moves 63/32 of a value per row; a sideways move changes nothing. A baked cell for borrowed art is the donor's cell MOVED WITH THE INK, gaps filled from the nearest defined pixel. # - New A depth borrow is good for one hop.
TileDepthTextureAssignmentManager.initSpritesreads the donor NAME's own cell by index and skips the line when that cell is empty; it never follows the donor's own borrow. Several vanilla ore and furniture cells are borrows themselves, so a line naming one silently does nothing: resolve the donor along vanilla's chain to the first name with a real cell. # - Depth reaches registered sprites only.
initSpriteswalks the named sprite map and skips any sprite with no tileset name, which only tiledef loading sets; there is no Lua depth setter, so a runtime-created sprite is always at the cube. # - Never give art another sprite's cell when the two share a square. Panel and curtain with pixel-identical depth clip on the same plane, and panel pixels past the donor's painted depth sample nothing. A byte-identical copy may borrow safely (vanilla's own
constructedobjects_01_30 = constructedobjects_01_28); a repaint that grows past the donor's ink needs its own cell. Walls take the presetspreset_depthmaps_01_4/5/6/7(W, N, NW, SE), as vanilla assigns them towalls_logs_96..99; floors need nothing, and vanilla gives every floor and every shore blend overlaypreset_depthmaps_01_0. # - New A ladder's depth is its wall's plane. Vanilla's ladder cells are the wall plane; art moved along a wall goes half as far down as across. A depth box meant to be in front of a body must clear the body (about 0.2 of a tile), not its centre line. A wall-face object streamed before its wall is covered by the wall; stream it after. #
Floors and the floor pass
- The floor pass takes only
solidfloororRenderLayer = Floorsprites; everything else is an object at whole-tile depth.RenderLayer = Floorputs a non-floor mod sprite (a shore edge, a hole cover) on the floor pass, as vanilla's 252 railroad tiles do. Floor status comes fromsolidfloorand nothing else:IsoWorldsets the flag only from that property,RecalcPropertiesaggregates it, andgetHeightAboveFloorwalks down to the firstTreatAsSolidFloor()square (that flag, stairs or a slope) or the chunk's min level. # - New
diamondFlooris how roads blend their corners.FBORenderCell.renderFloordraws a floor-layer sprite with the diamond shaper (the four corner lights blended, seams fixed) when it carriesdiamondFloororwater, and the de-diamond shaper otherwise; every vanilla road and street tile carries it. A TRIMMED sprite given the flag is stretched over the whole diamond, so it suits only art that fills the floor diamond. # - A floor diamond sits at the bottom of its canvas. Diamonds tessellate edge to edge and never overlap, so a diamond pushed DOWN is clipped and the surface notches. Build any face that fills a cut from the tile's own measured edge: vanilla's water diamond rasterises one row low on its north edge and one row high on its west. #
- Water is a floor sprite (
blends_natural_02_0..15,FloorMaterial = Water) carryingwaterandsolidtrans;FootstepMaterial = Waterdoes not exist, and inventing it makes a channel silent. Awater-flagged floor is handed to the water shader whenever the square's water geometry is valid, and the shader draws nothing four levels down; a deep pool needs static copies WITHOUT the flag, opaque past the diamond edge. # - Ground blends are declared and one-sided. A blend tile carries
FloorMaterial(the material blended in) andFloorAttachmentN/W/E/S. Measured over five shipped cells, the letter points AT the blended material (97.7% of 3,107 boundary placements), the overlay sits on the RECEIVING square (99.1%), and blending is a hierarchy: grass feathers onto gravel, dirt and road, water onto dirt, never the reverse. Sixteen materials ship complete families;Gravelandfloors_exterior_street_01_0have none. Shores lay the ground at object index 0 and the edge at 1. #
The property vocabulary: ask the definitions what a thing is
DoorSoundseparates openables. Fourteen families:GarageDoor(84 sprites),MetalGate(48),MetalPoleGate/ Double / Small,WoodGate/ Small,WoodLogGate,FarmGate,PrisonMetalDoor(4),MetalDoor,WoodDoor,WoodShackDoor,SlidingGlassDoor. There is nogarageorgateproperty anywhere. #- The engine groups garage and double doors itself. Garage doors carry
GarageDoor = 1..6(1–3 the closed run, 4–6 its open twin);IsoDoor.getGarageDoorIndex(obj)(−1 for a non-piece),getGarageDoorFirst/Prev/Next,toggleGarageDooranddestroyGarageDoorare static and Lua-reachable, and vanilla'sbuildUtil.getGarageDoorObjectsjust walks Prev/Next.getDoubleDoorIndex/getDoubleDoorObject(obj, i)do the same for four-piece double doors. # - New A double gate moves its middle leaves when it opens. A double gate is FOUR squares. Opening moves each sprite by
DoubleDoorNorthSpriteOffset {5, 3, 4, 4}(West{4, 4, 5, 3}) and REBUILDS leaves 2 and 3 as new objects on other squares, so the four open pieces of a north gate stand at (0,0) (0,1) (3,1) (3,0), and anything attached to a moved leaf is lost. Every vanilla gate hinges at its square's north-west corner. # - New A car knocks a tile over through two properties.
BaseVehicle.breakingObjectscallsIsoObject.Collisionon the authority for any object under the car carryingHitByCar; at the damage threshold it swaps to the tile'sDamagedSprite, gated byMinimumCarSpeedDmg(150 when absent), and a server sends the change. Vanilla's stop signs and mailboxes are the pair; a prop on your own sheet gets a synced knock-over with no code. # HoppableN/HoppableWis a barrier you VAULT. A railing is hoppable by definition. A square owns only its north and west faces, so a barrier is vaultable from the north and west only; vaulting needs a square on the far side to exist. The vanilla minimum is a see-through wall (HoppableN+WallNTrans+wall+IsLow); 142 hoppable tiles pair the face withcollideN/Winstead. #- New A hoppable face is climbed by walking into it, and
solidtransdoes not stop it. Twelve vanilla tiles combine a hoppable face withsolidtrans(the beds you vault over). "Hoppable, but not by accident" cannot be built; a rim you must not fall over issolidtranswith no hoppable face. # wallis a classification, not the collision flag. Plain walls carryWallN/WallW, door framesDoorWallN/W, windowsWindowN/W, and all three also carrywall. A bare door frame with noIsoDoorin it is passable; a zombie-broken door is one of the commonest states in the game.forceFadefades a piece when it would hide what is behind it. #WallSEis the corner post closing the diagonal where a north run and a west run pass. Vanilla places it where the tile west carries a north wall and the tile north a west wall, and the post square carries no WALL of its own but usually a floor (450 of 633 posts over seven cells). #- Corrected Corner walls name their own halves. 237 of the game's 240
WallNWsprites carryCornerNorthWallandCornerWestWallnaming their two single-face halves, readable on the object withhasProperty/getProperty, so cutting one face of a corner needs no per-theme table. Vanilla'sgetCornerWallSpritereturned the wrong half through 42.20 and is fixed in 42.21: the surviving half of a cut west face is the north one. # - Stairs are six sprites.
constructedobjects_01_88/89/90(west) and_96/97/98(north). A run is three tiles on ONE level and the player arrives on the level above, on the square past the top piece (hasFloorAtTopOfStairs). Any sprite becomes a real staircase withobj:setType(IsoObjectType.stairsBN)on the OBJECT, never the shared sprite; it is not saved. # - Ramps.
ramps_01inB42ChunkCaching2x.packcarriesSlopedSurfaceDirectionandSlopedSurfaceHeightMin/Maxin percent (5% a tile, so a level is twenty tiles), walked smoothly bygetSlopedSurfaceHeight.floors_exterior_street_01_32/33/34are only the ART of a street ramp. Whether a MOD tiledef's sloped-surface properties are honoured is untested. # - Moveables.
IsMoveAblealone is the pickup gate;MoveTypedefaults to"Object"and matters only forWallObject,WallOverlay,FloorRugandWindowObject.GroupNameis PREPENDED to the displayed name. What a pickup becomes is the tile'sCustomItem; with none, a single-sprite tile yieldsMoveables.<spriteName>, which no recipe can name. An item'sWorldObjectSpritedecides only what it LAYS; a round trip needs both claims. WithCustomItemthe pickup weighs the item'sWeight, notPickUpWeight÷ 10.Icon = defaultis the convention on 337 of about 350 vanilla moveables. # - Containers.
container = <kind>andContainerCapacityon a tile are read by the CHUNK LOADER, not byIsoObject.new; an object placed from Lua needssetContainer(ItemContainer.new()). A multi-tile container puts the property on ONE of its halves. A player's log stack is a container: vanilla'scamping_01_24..31and_48..59carrycontainer = logs. # - Multi-tile objects.
SpriteGridPosis relative to the min-x / min-y square; E/W-facing objects run along x, N/S along y (settled by the coffin, the one object drawn in all four facings). EntitySpriteConfigfaces lay out down-right at (+64, +32) per cell. # - New Ore nodes are known by four substrings.
IsoObject.isOre()is aCustomNamecontainingironOre,copperOre,FlintBoulderorLimestoneBoulder; vanilla's "Remove Mineral Deposit" is offered on those only, andISPickAxeGroundCoverItempays one, two or three ore for a Small, Medium or Large node by name, plus Masonry XP. That action never wears its tool (it writesself.pickAxeand readsself.pickaxe). Theboulderssheet is never ore:_0..7are solid singles with no name,_8..15walkable stones,_16..35multi-square groups. # - New Paint: furniture by tint, walls by sprite swap.
ISPaintAction:complete(server-side in MP) looks upPainting[type][paint .. north]and swaps the sprite; with no sprite there it takesOtherPainting[type][paint]and sets the object's custom colour, multiplied into the light and saved.canPaintaccepts any object whose sprite carriesIsPaintableand aPaintingTypekeyed in either table, both plain globals. Vanilla's crates and tables use the tint, so dark wood paints dark. # - Other flags.
BlockRain(1,838 tiles, all roofs);waterPiped(see Water);AmbientSoundonindustry_01_4/5hums with no code;waterAmount = waterMaxAmount = 999999makes the well and pump sprites infinite water;IsoType = IsoFireplaceon four of the ninecrafted_01metal drums makes them fireplaces, so aCustomNameis not a classification. A tile withIsMoveAbleandIsStackablemay be built on an occupied square. #
Trees, bushes and overlays
- Corrected A tree is two layers: a trunk sprite and one canopy. Every vanilla tree sheet holds six seasonal frames of each size (0 bare, 1 bare with snow, 2 blossom, 3 green, 4 autumn, 5 thinning), sizes 1–4 on
e_<x>_1atframe × 4 + (size − 1), 5–6 one_<x>JUMBO_1atframe × 2 + (size − 5), 7 and 8 on the XL and XXL sheets. Only frames 0 and 1 carry thetreeproperty, whichIsoTree.initTree()reads for size, logs and health (defaulting to size 4), and only they hold a trunk: frames 2–5 are the canopy alone, with a shadow where the trunk goes. Vanilla keeps frame 0 (1 in snow) as the sprite and ATTACHES the season's frame (attachedAnimSprite);IsoTree.renderhands the tree renderer only the trunk texture and the first attached sprite, so a second attached layer is never drawn. An earlier version of this page said tosetSpritethe season; that draws a floating canopy. # - The erosion system owns the tree sheets.
NatureTreesmatches any object whose sprite starts with one of the elevene_*names, reads the trailing index as the growth stage and drives stage and season from then on;NatureBushclaimsf_bushes_1_andvegetation_foliage,WallVinesclaimsf_wallvines_1_.ErosionObj.setStageObjectclears the object's attached sprites. Three evergreens ship frames 0 and 1 only. The small sheets are defined intiledefinitions_erosion.tiles; jumbo art is inJumboTrees2x.packandJumboTreesBigs2x.pack, where an XL or XXL sheet holds TWO trees and the jumbo trunk is frames 0–3 with the leaves as overlays 4–11. # - New Nothing rides on a tree, but a raised object can sit in one. Every object is drawn at its offset plus
renderYOffset× tile scale, which is saved with the object, so an object raised withsetRenderYOffsetcan sit up in a tree's crown on the tree's square or a neighbour. # f_bushes_1is a layer sheet: twigs, snowy twins, a green leaf layer, an autumn layer and berry and flower layers landing pixel-perfect on the same frames; green to tan is a pure hue rotation.f_wallvines_1sorts itself into west, north and corner pieces throughCornerNorthWall/WestWall. #- Overlay sheets mix plain-wall pieces with pieces drawn for an opening, and only the art says which: a plain-wall piece paints the full face width (x 2..65 in a west sprite's canvas, 60..123 in a north one). Only the "full" floor grime sprites tile alone (
overlay_grime_floor_011, 9, 32, 33, 40, 41, 44, 82–85); wall grime is per face throughattachedW/N. # - A multi-tile wall decal runs in opposite screen directions on the two faces. A north face walks +x (down-right), a west face +y (down-left). Each tile of a graffiti tag is a whole syllable, so a reversed run reads as three unrelated fragments; count from the far end on a west face. #
The map tools' sheets
- The editor derives slots from the PNG. A TMX references sheets by RELATIVE path; the editor derives a sheet's slot count as
(w ÷ 128) × (h ÷ 256)and ignores the size field inconfig/Tilesets.txt, which it regenerates on scan. TheTiles/1xvsTiles/2xfolder name declares the scale to PRESENT at: the game's own sheets are 2x art and belong under1x, where2xquarters every tile. # - Every extracted sheet set is wrong somewhere: flattened to 8 columns where the game declares 16, or short on rows so high indices do not exist. Rebuild sheets from the game atlas; matching columns is necessary and not sufficient. A hand-written TMX must escape its attributes: three sheet names contain a bare
&. # - The Steam build of TileZed's Lua console crashes on a bare
print;setTile(x, y, nil)and any write outside the map crash it too (the erase call isclearTile(x, y)). #
World objects from Lua
Creating geometry at runtime
- A mod can create grid squares at runtime, below ground included. The primitive is vanilla's own (
ISBuildRampCursor:addRampObject):IsoGridSquare.new(getCell(), nil, x, y, z)thengetCell():ConnectNewSquare(square, false), or the one callgetCell():getOrCreateGridSquare(x, y, z); thenIsoObject.new(getCell(), square, getSprite(name))andsquare:AddTileObject(obj). Vanilla-sprite objects PERSIST, so every build path must be idempotent. Creating a square that exists returns the existing one andAddTileObjectnever validates: count existing floored squares before writing, because a basement may already be there. Follow every runtime geometry change withsquare:RecalcAllWithNeighbours(true), as vanilla does, or lighting and collision never refresh. # - New
getOrCreateGridSquareanswers even for a chunk that is not loaded, and that square is lost. AskgetChunkForGridSquare(x, y, z)first.IsoGridSquare.addFloor(name)removes the old floor, grass overlays, bushes and tainted water, and keeps a tree. # - A mod's own PNG can be a world sprite by full media-relative path WITH extension:
IsoObject.new(square, "media/textures/MyThing.png"), the form vanilla's forageworldSpritestable uses. The bare name, the name with.png, atextures/-relative path and anItem_prefix all resolve to a textureless sprite. Limits:IsoSpriteManager.AddSprite(String)assigns no id, so the object comes back spriteless after a save; the sprite has an EMPTY property container; and a path-loaded texture is linear-filtered with a one-pixel fringe. Anything a script names or the world persists needs a tiledef. # - An attached sprite's offset lives on the sprite, so caching one sprite per texture makes every carrier move together. Make a fresh wrapper per carrier:
IsoSprite.CreateSprite(IsoSpriteManager.instance)thenLoadSingleTexture(path); the texture is still shared by name. # - Test that a sprite name resolves with
getSprite(name):getTextureForCurrentFrame(IsoDirections.N). The method TAKES A DIRECTION; called bare it throws Java-side, past anypcall. Always include a known-good and a known-bad control in a sprite test. # - Corpses, zombies, players and animals are not in
square:getObjects(). They are moving objects; usesquare:getDeadBodys()orgetStaticMovingObjects(). Aninstanceoftest forIsoDeadBodyinside agetObjects()loop silently never matches. #
Free-standing sprites and markers
- Corrected For a free-standing world sprite use an iso marker, and move it with
setPos.getIsoMarkers():addIsoMarker(textureName, square, r, g, b, a)is engine-managed and occluded correctly (vanilla's forage icons run on it). It is tile-snapped and drawn only when its level equals the player's, in the translucent pass. Move it withsetPos(int, int, int):setSquareis a bare field store and the draw position is written only bysetPos, so a marker moved withsetSquarestays where it was made. An earlier version of this page listedsetSquareas the way to move one. # - Never use one
IsoObjectper moving particle.AddTileObjectre-bakes the chunk-level FBO, flushes every player's line-of-sight cache and dirties pathfinding. # - New
RenderOpaqueObjectsInWorldis the only world-pass Lua hook. The five per-square draw events (OnPostCharactersSquareDraw,OnPostTilesSquareDraw,OnPostWallSquareDraw,OnPostFloorSquareDraw,OnPostTileDraw) are registered and fired by no class in 42.21, andOnPostFloorLayerDrawnever fires on the FBO renderer.IsoSprite.renderTextureWithDepthhas no vanilla Lua call site, and calling it from that event leaves render state disturbed so that no roof or wall cutaway works anywhere; the state lives inIndieGL, which Lua cannot reach.Render3DItem(item, square, x, y, z, rotation)is the one established Lua draw inside the event (the fishing bobber uses it). # square:setHasFlies(bool)toggles the engine's own depth-correct corpse-fly flipbook. #
Telling clients about an object
- New
transmitAddObjectToSquaresends nothing for an object already on the square. Its body returns when the square already holds the object, then adds it, then (on a server) callstransmitCompleteItemToClients. So the common pairAddTileObject(o)followed bytransmitAddObjectToSquare(o)adds the object on the server and never sends it. Usesquare:transmitAddObjectToSquare(o, index)ALONE, orAddTileObjecttheno:transmitCompleteItemToClients(). A client that receives an object for a square it lacks creates the square and its neighbours, so runtime squares reach clients with their first object; a square the server creates with no object never does. Removals are unaffected. # transmitCompleteItemToClients()CREATES a new object on every client; it never updates one. The packet inserts a fresh object at the server's index with no lookup, so calling it on an object clients already hold gives every client a copy; because sprite and mod-data updates are index-addressed, only the newest copy changes from then on while the stale ones draw on top. Vanilla calls it only on objects it has just constructed. For an EXISTING object: sprite =setSpriteFromName+transmitUpdatedSpriteToClients(), data =transmitModData(), state =sendObjectChange(IsoObjectChange.STATE), a floor item's fluid =worldItem:sync(). A buildable'sOnCreatemust not transmit: the build action sends the object once right after it returns. #ObjectModDataPacket.processServerapplies a client's table to the server object before relaying, so an MP client must nevertransmitModDataa server-owned world object. #GameServer.sendObjectModDatadrops the packet while the server fast-forwards (every player asleep). Sprite updates have no such guard andEveryHoursstill fires, so an object that publishes its state only through mod data can wake clients to a fresh sprite over stale data. Give it a re-sync the player triggers. #- Corrected The hook for "this object is going" is
OnObjectAboutToBeRemoved(obj). It fires fromIsoGridSquare.RemoveTileObjectfor every removal (sledgehammer, fire, explosion, felling, another mod). The object is still on the square, and the engine throws if a handler removes it; record the square and act next tick, and make the handler idempotent and authority-gated.OnDestroyIsoThumpablefires only fromIsoThumpable.destroy(), which the sledgehammer never calls. In 42.21 the multiplayer path changed (see What changed): a client can no longer remove a world object for everyone, andsledgeDestroystill removes nothing in single player while apcallround it returns true. # OnWeaponHitTreefires only on a free melee swing. The right-click chop action callstree:WeaponHitfrom Lua and triggers nothing;IsoTree.toppleTreeremoves the tree through the removal path above, and callsdropWood()itself. A per-stroke effect has no event on the action path. #ItemPickerJava.getItemContainer(room, kind, proceduralName, bool)throws on a nil third argument (pass""), and its last argument must be nil, notfalse. Write your built-ness marker BEFORE anything that calls into Java, or a throw leaves the room built and unmarked and the next build stacks a second copy. #
Light, climate, power, fire
getCell():addLamppost(x, y, z, r, g, b, radius)constructs and returns a light source;removeLampposttakes the source or an (x, y, z) triple; the source is mutable in place (setRadius,setR/G/B,setActive). A lamppost is not saved and not synced, a pure client render concern. It accepts an out-of-bounds coordinate and returns a live source, so a coordinate bug is invisible. #- New A light's colour reaches the lighting doubled and capped, its radius capped at 20.
IsoLightSource.setR/G/Bis a bare field write;LightingJNI.checkLightssendsclamp(2r),clamp(2g),clamp(2b)when they change, and a new light goes in withmin(radius, 20). So a channel at 0.5 or more is already full, and a repaint dims visibly only below half. # - New A colour change is never relit on its own. The lighting thread recomputes lamp light only while a global relight is pending; the Lua global
invalidateLighting()asks for one.addLamppost,removeLamppost,AddTileObjectandIsoLightSwitch.setActiveask by themselves; a mod that only changes a light's colour must call it (vanilla's TV flicker does). # - New A lamp's lit tile follows its switch, not its light. A tile with
HasLightOnSpritegets an_on_overlay drawn at full brightness while the square is seen, the switch is activated and there is power; the light itself is turned off only when there is no bulb or no power. A client may clearIsoLightSwitch.setActivated(false)(a plain field write) to hide the lit tile while the light burns. # - Corrected Light bulbs burn out in 42.21.
IsoLightSwitch.updatecounts burn minutes while the switch is on with a bulb and power, unlessLightBulbLifespanis 0 or less; once a game hour it rolls a chance that is zero for about the first week lit and rises after, and a burn-out switches the lamp off, removes the bulb and playsLightbulbBurnedOut. A map lamp counts as burning since the game began. Through 42.20 nothing read the option. A bulb taken out withremoveLightBulbcomes back as a fresh item that copies only its colour. # - Climate has a modded tier a mod is meant to drive.
getClimateManager():getClimateFloat(ClimateManager.FLOAT_AMBIENT)(andFLOAT_FOG_INTENSITY,FLOAT_TEMPERATURE,FLOAT_DESATURATION...) andgetClimateColor(COLOR_GLOBAL_LIGHT)carry override, admin and MODDED tiers (setEnableModded,setModdedValue,setModdedInterpolate).setModdedValueREPLACES the world's value, so a lift must bemax(getInternalValue(), target)re-applied on a tick.interpolateis a BLEND WEIGHT, not a glide. Clear with per-objectsetEnableModded(false), never the manager'sresetModded(), which clears every mod's tier. Climate is one state per machine. # - A working generator can be made from Lua.
IsoGenerator.new(nil, cell, square), thensetConnected(true),setCondition,setFuel,setActivated,setSurroundingElectricity(). A buildable'sOnCreatemay return{ replaceObject = true, object = X }to swap the built thumpable for any Java object. A generator reaches three levels and two chunks (both private constants); world power levels run −32..31, so one on the street powers down to −3.square:haveElectricity()is the one Lua test for power and covers the grid before the shutoff and a generator after;IsoGenerator.isPoweringSquaretakes six ints and has no vanilla Lua call site. # - The generator and toxic air.
setActivated(b)on a non-exterior square with a building callsbuilding.setToxic(b): set on start, cleared on any stop, re-asserted once a game hour while running. An idle generator touches nothing, andremove()never clears it, so picking up a running generator leaves its building toxic. The flag is per BUILDING, with no radius, and a server sends a packet on every call. # - Fire and safehouses.
IsoFireManager.StartFire(cell, square, true, 100, 500)is vanilla's server call; a safehouse check isSafeHouse.isSafeHouse(square, username, true). # - Small helpers.
IsoTree.dropWood()pays a felled tree's logs and rolls acorns, pinecones and holly berries;setbFalling(true)+setFallTime(0)is a drop with no injury;getGameTime():getWorldAgeHours()is the clock for anything that should age. #
Doors, vehicles, plumbing
- New A locked door opens from the inside unless its tile says
forceLocked.IsoDoor.ToggleDoorActualunlocks a locked door for a player standing in the door's room or the room beyond. No vanilla tile carriesforceLocked; some map packs do. A door's key id is its own when set, else its building's (checkKeyId). # - New A parked car is on no square's object list.
square:isFree(false)answers yes under one;square:getVehicleContainer()is the engine's own "which car covers this square".addVehicleDebug(type, dir, nil, square)builds the car and places it only if it clears the cars near it; it returns the car either way, placed only whengetSquare()is non-nil. # - Corrected Vanilla's plumbing is live, and its water source is one level up. No Lua adds the "Plumb" option; the JAVA does:
ISWorldObjectContextMenuLogicsetscanBeWaterPipedfor a moved fixture in a room with a source in reach, or an unmovedwaterPipedsprite not yet using one, and adds the option (greyed without a pipe wrench).waterPipedis a TILE flag (56 vanilla fixtures). The action callssetUsesExternalWaterSource(true);hasWater,getFluidAmountanduseFluidthen draw on the mains until the water shutoff.FindExternalWaterSourcewalks the object's footprint and checks the square ABOVE and the 3×3 round it for a non-floor thumpable holding fluid (in practice a rain barrel on the floor above), never one beside the sink. An earlier version of this page said nothing turns the feature on and that the source must sit on the footprint; both were wrong. #
Ready-made frameworks
- The GlobalObject framework (
SGlobalObjectSystem/CGlobalObjectSystem; campfires, farming, traps and rain barrels run on it) gives a world object with server-simulated state: one object per square enforced in Java, persistence of whitelisted Lua fields togos_<name>.bin, a connect-time client mirror,sendCommandboth ways, and chunk reconciliation. Limits: one object per square per system, sync to ALL clients with no proximity filter, andregisterSystemreturns an existing system of the same name, so prefix yours. # - Entity components are declarative.
component Resources { group slots { ... } }on a buildable gives engine-synced item slots;component FluidContainera fluid tank drainable through vanilla's transfer UI;UiConfig { uiEnabled = true }plusLuaWindowClass = MyWindowin the xuiSkin opens your window from the world menu with per-player registry and networked mutual exclusion (entity:setUsingPlayer). AnxuiSkinblock must bemodule Baseor the engine ignores it at boot; the entity block may live in your own module. The build-menu icon isIconin the xuiSkin style (141 of 149 vanilla values areBuild_*); without one the menu draws a "?". # - An entity
SpriteConfigsprite belongs to exactly one entity type. A second entity naming a sprite vanilla's own entity claims throwsSprite 'X' is duplicateand world load dies. Ship a byte-identical copy under your own sheet name. # - Wall-mounted buildables mount through their
faceletters.NandWon the square's own faces,SandEon the north wall of y+1 and the west wall of x+1. Refusals belong inOnIsValid, neverOnCreate.isValidPerSquare's floor block is unreachable for any tile with a sprite (an operator-precedence slip), so a floor may be built over nothing;floor.OnIsValidchecks only the four neighbours at the SAME level, andfloor.OnCreatecallssquare:EnsureSurroundNotNull(), which CREATES the eight neighbouring squares. An entity'sOnCreate/OnIsValidresolve throughLuaManager.getFunctionObject(String)at call time, so your own dotted function name is legal. #
Lua and Kahlua
The dialect and its limits
- Lua 5.1 on Kahlua. No
goto(and a table field namedgotoparses here and fails a newer Lua), no integer division, no bitwise operators.nextis not a global (vanilla uses it once); run thepairs()loop instead. Rangedmath.random(a, b)throws a Java exception; zero-argument works. UseZombRand(n)(0..n−1),ZombRand(a, b)(a..b−1, soZombRand(1, 1)is not a roll) andZombRandFloat.table.newarrayandtable.wipeare Kahlua extensions;unpackis a global. # - New The game compiles with Lua 5.1's limits, and a newer Lua does not check them. Kahlua's compiler is a fork of the 5.1 one, so a file Lua 5.4 accepts can still fail to load: an
ifover a block too long to jump ("control structure too long nearend"; the jump field is 18 bits signed, about 131,000 instructions), more than 60 upvalues, more than 200 locals, more constants than one function holds, and all 5.2+ syntax. Compile with a real Lua 5.1 before shipping, and put a big generated data block inside a function you call, never inside anif. # - 200 local slots per FUNCTION, counting every
localdeclared anywhere in it (block scope never frees one), about four per numericfor, and the parameters. Breaching it is a compile error that kills the WHOLE FILE silently: every event hook and menu entry in it vanishes. Split big functions and pass one state table. # - Two adjacent string literals (
"a " "b") are a 5.1 syntax error that kills the file the same way. A call to a missing method (self:gone()) is not a syntax error; it fails at runtime on the frame that reaches it. # - New The game's
%truncates toward zero. Kahlua computesa - (int)(a / b) * b(a zero divisor gives NaN), where real Lua floors. So-90 % 360is −90 in game and 270 in Lua, and(0 - 1) % 4is −1, so anyt[(a % n) + 1]with a negativeaindexes nothing. Wrap witha - math.floor(a / n) * n, and keep operands small: the(int)cast clamps a quotient past 2^31. # - New A mod's Lua folder runs in file-name order. A file that uses another file's table must
requireit: a file that sorts ahead of the one defining what it calls finds nil at load. Guard anything the required file hooks (Events.X.Add) to install once, because the directory walk may run that file a second time. #
Java from Lua
- Kahlua's
pcalldoes not catch Java exceptions. A wrong arity or argument type on an engine call throws fromMultiLuaJavaInvokerand unwinds past thepcall; validate arguments before the call. # - New Indexing nil throws past
pcalltoo. Indexing a Java null, or a Lua nil inside apcall'd closure (pcall(function() return sq:getRoom() end)withsqnil), throws a RuntimeException fromKahluaThread.tablegetthat thepcallnever sees; the trace climbs to the event dispatcher once per call. Nil-test a value BEFORE the closure.IsoPlayer.getPlayers()is a fixed list whose empty splitscreen slots are Java nulls; walkgetNumActivePlayers()withgetSpecificPlayer(i), and nil-test every Java list element. A method chain through a null (sq:getFloor():getSprite():getName()) is the same crash; one call per step. # - A missing method on an exposed class reads as nil; on an unexposed class it throws. That is why
x.getInventory and x:getInventory()guards. A fresh zombie'sGenericDefaultStateis not exposed, sostate.getNamethrows;tostring(obj)is the one call every Java object answers, and its class name names it. # local ok, v = obj and pcall(f)is not a guard. An expression is adjusted to one value, sovis always nil. Two statements, or guard first andpcallsecond; the same holds for anything on the right of a multiple assignment. #- What Kahlua reaches. Public methods and public STATIC fields only, never a public instance field (
RoomDef.level,IsoChunk.wx/wyandgetWorld().helicopterare invisible). A class in the jar says nothing about whether Lua can reach it; a vanilla Lua call site does.InventoryItemFactoryis not a global (useinstanceItem("Base.X"));StateMachineis not exposed. Through__classmetatables[JavaClass.class].__indexa mod can rewrite a Java method for every instance game-wide: real, powerful, last resort. # - New B42's
PropertyContainerhashas(String)andget(String), notIsandVal. Those are the B41 names, soprops.Isis nil, and code written as "no method, so not a match" answers false for every sprite. # - Ask an engine object for the method it has.
item:getContainer()is the container the item is IN; a bag's contents areInventoryContainer:getInventory()orgetItemContainer(), which a plainInventoryItemlacks, so gate every descent oninstanceof(it, "InventoryContainer"). #
Events
- Vanilla registers its events in
LuaEventManager.OnPlayerConnectis not one; server-side player events areOnCreatePlayerandOnPlayerDeath, andOnPlayerUpdatenever fires in a server process (a server sweeps withEveryOneMinuteorOnTickovergetOnlinePlayers()).triggerEvent("Name", ...)fires any registered event by hand.OnThrowableExplode(trap, square)fires first intriggerExplosion, on the authority.LevelPerk(player, perk, level)fires on level-up. # - New Some event names in circulation do not exist.
OnServerTickis registered by nothing, so a guardedEvents.OnServerTicknever runs.OnRefreshInventoryWindowdoes not exist either; the real event isOnRefreshInventoryWindowContainers(page, state), fired four times per refresh byISInventoryPage. Check a name against the registry (identifiers inLuaEventManagerplus everyAddEventandtriggerEventname in vanilla Lua) before relying on it. # - New The
Eventstable is replaceable from Lua, and a reload swaps handlers by file and function. EachEvents.<name>is a plain table whoseAddandRemoveare Java functions; the game triggers from the event's own callback list, so replacingAdd/Removechanges only what Lua calls.Addappends with no duplicate check and ignores anything that is not a Lua closure. During a file reloadAdddoes nothing; instead every new closure replaces the callbacks whose prototype has the same file and function name, so a reloaded file's handlers take over their old slots.getFilenameOfClosureandgetFirstLineOfClosureread a closure's origin;getTimestampMsis the finest clock (whole milliseconds). # - New
OnFillContainer's third argument is not always a container. When a bag is rolled into a container the event fires with the bag'sItemContainerand again, where the bag type has a loot table, with that table's definition, which Lua cannot use. Gate oninstanceof(container, "ItemContainer"). # Events.X.Add(fn)is a dot call. A stub with aselfparameter swallows the handler silently. #
Wrapping vanilla
- Assigning a vanilla method more than once discards every other mod's wrapper of it. The community idiom wraps at file load, so a later mod wraps YOUR wrapper, and any re-assignment from an event handler throws theirs away. Install ONCE behind a flag; if the behaviour must survive a reload, install a stable dispatcher that forwards to a mutable field. Forward varargs, and
pcallyour own body on a per-frame path. # - Never gate a mod file's whole body on a vanilla class existing at load: mod Lua can run before vanilla's, and the file bails with zero errors. The same holds for
:deriveat file scope: make the table at file scope and hang the parent on it atOnGameStart(setmetatable(MyClass, Parent); Parent.__index = Parent), plus at once on a reload. # - New
ISBuildingObjectis SERVER Lua, so a client file can never derive from it at load. Vanilla keeps it inmedia/lua/server/BuildingObjects/, and server Lua loads after every client file (an MP client loads it too, after its own client Lua); every vanilla cursor that derives from it is server Lua itself. A client cursor must be parented late, as above. # - Class-table wrapping of vanilla timed actions is not dependable. With a tracer on six fluid actions, no wrapper ever ran. Watch items and state instead, or write a networked action of your own; never trust a wrap without a tracer print. #
- The
WeaponSwingHOOK is a trap.Event.triggercalls every hook protected and returns true whenever ANY hook is registered, so registering one reverts every swing of every player.WeaponHitCharacteris the same kind of hook.SwipeStatePlayer.enterfiresOnWeaponSwingand on the next line clears the action queue, so anything queued in the handler is wiped; count hits fromOnWeaponSwingHitPoint, which fires at the hit frame with or without a target, and for a bare-handed shove too. # - Hand yourself every object of a sprite as it loads with
MapObjects.OnLoadWithSprite / OnNewWithSprite(sprite, fn, priority), rather than sweeping the world. #
Keybinds and options
- Append to the global
keyBindingtable. An action is{ value = "ID", key = default }, a section header{ value = "[Inner]" }with no key.MainOptions.loadKeys()is the only caller ofgetCore():addKeyBinding(), so register onOnGameBoot. Display names areUI_optionscreen_binding_<value>, brackets stripped for a header. Read back withgetCore():getKey(id). # - Default every binding to 0. Vanilla claims most letters and the function row; a mod that grabs G, L and U silently takes Toggle Safety, the Skill Panel and Vehicle Mechanics away, and a shipped default never goes through the duplicate-key dialog.
getKeyreturns 0 for an unbound action, so always testb ~= 0.addKeyBindingis a map keyed by name; a second registration path is dead code that resets bindings on a reload. # - New
PZAPI.ModOptionsis the client options page.PZAPI.ModOptions:create(id, name), then:addTickBox(id, name, value, tooltip)or:addKeyBind(id, name, key, tooltip), each withgetValue()/setValue(). Values are read fromModOptions.inionly when the options screen is built at the main menu, so create the page before then (at file load when the table exists, else atOnGameBoot);:save()rewrites the file. It is the right home for display-only settings that would otherwise burn sandbox options. # - New Per-machine files live in
Zomboid/Lua/.getFileWriter(name, true, false)andgetFileReader(name, false)read and write there, vanilla's own home for UI layout; the right place for a HUD position, never player mod data. #
UI and rendering
Panels and overlays
- A full-screen
ISUIElementinUIManagerbreaks every vanilla "mouse over UI or world?" test. Drag-to-ground item dropping, the build cursor and the moveable cursor all call the JAVA element'sisPointOver, which for a top-level element is visible + bounds + nothing else covering the point. It never calls a LuaisPointOveroverride, andsetConsumeMouseEvents(false)only gates event consumption. An overlay that only draws keeps its Java element ZERO-SIZED and tracks its viewport in Lua fields; a top-level element'srenderhas no size gate and draws are not clipped to bounds. # - Never draw into
ISInventoryPanefromrender(). The page opens a stencil, the pane draws its rows inprerender, and the pane'srender()ends by clearing the stencil level without resetting the pixels, after which every draw inside the pane is rejected. Draw from aprerenderwrap, viadrawItemDetails, orrepaintStencilRectthe area first. # - New
ISPanel:close()andISCollapsableWindow:close()only hide. They callsetVisible(false)and nothing else: noonClose(), noremoveFromUIManager(). A panel tracked in a registry that callsself:close()becomes unopenable (the next open finds the entry and brings an invisible panel to the top). Overrideclose()to do the real teardown, and have the opener checkgetIsVisible(). # - Draw-call argument order differs.
drawRect/drawRectBordertake(x, y, w, h, a, r, g, b);drawTexttakes(str, x, y, r, g, b, a, font);drawTextureScaled(tex, x, y, w, h, a, r, g, b)tints, which is how one white PNG becomes every colour.self.javaObject:DrawTexturePercentage(tex, ratio, x, y, w, h)exists.setConsumeMouseEventsmust be called onjavaObject, whichaddToUIManagercreates. # getTexttakes at most four substitutions. A fifth throws, and fromrender()that repeats every frame until the error box cannot be closed. A translation value uses%1..%4; a Lua fallback goes throughstring.formatand uses%s, so a%1in a fallback prints the placeholder on exactly the day a key is missing. A literal%in a translation value must be%%. #- Native 9-patch textures.
NinePatchTexture.getSharedTexture(path)+tex:render(x, y, w, h, r, g, b, a), in Android's.9.pngformat.getSharedTexturereturns nil on the FIRST call for a path (it loads and caches, then falls through), so call it at install and again at draw; a path that fails once is poisoned until texture packs reload. # - New A modal dialog widens to its longest line.
ISModalDialog.CalcSizesplits the text on newlines and sizes the window to the longest line, so a long one-line message opens wider than asked, and a dialog centred from the asked width runs off screen. Wrap the text and centre the real size.ISModalDialog:new(x, y, w, h, text, yesno, target, onclick, player, param1, param2)places the dialog under the mouse when x or y is 0;onclick(target, button, param1, param2)readsbutton.internal("YES","NO","OK"). # - New Text over a head.
Events.OnPreUIDrawfires before any window with blending on and depth off;isoToScreenX/Y(playerIndex, x, y, z)give the screen point (vanilla's fishing gauge uses z + 0.6 for overhead),getTextManager():DrawStringCentre(font, x, y, text, r, g, b, a)draws it, andIsoObject.getAlpha(playerIndex)is the engine's fade of a body the player cannot see. #
The world view
- The world render is depth-buffered. Static geometry bakes into per-chunk FBOs with depth, every sprite carries a depth from its world coordinates, and iso overlap is a depth question.
RenderOpaqueObjectsInWorldfires once per player per frame inside the world pass. # - Per-square fog of war is readable.
square:isCanSee(pn),isCouldSee,isSeenandgetDarkMulti(pn); zombies hide by exactly that plus a per-object alpha fade. Walls withouttransparent, closed doors and curtains, barricades,solid/blocksightsquares and trees of size 3 or more block sight; windows and hoppable fences never do.square:getRoomID() ~= -1is the cheapest interior test. # - New A right-click's
worldobjectslist puts the picked tree LAST.ISObjectClickHandler.doRClickbuilds it as the engine's picked object, then the picker's door, window, window frame, thumpable and hoppable, thenPickTree. A tree is drawn tall, so a click on it usually lands on a square north-west of its trunk; never take the first object's square as the one meant. Walk the whole list for your object, as vanilla's farming menu does. # - New The interact key reaches Lua only when vanilla has nothing to do with it.
IsoPlayer.doContextcollects vanilla's contextual actions (door, window, fence, rope, curtain, bed, animal...) in front of the player and runs the best; only when there is none does it fireEvents.OnContextKey(player, heldMs)(and always while sitting). A mod listening there never steals the key. Use a once-per-press guard reset inOnKeyStartPressedwithgetCore():isKey(KeybindId.INTERACT, key). A mod cannot add a contextual action; the names are chosen in Java. # - The farming hover popup is an
ISToolTipfollowing the mouse. Lease one fromISWorldObjectContextMenu.addToolTip(), setfollowMouse = true, put rich text in.description(<LINE>,<RGB:r,g,b>) and an icon withsetTexture(). It exists only because a cursor mode is active, so a mod without one shows and hides it every frame itself. # - The HUD clock (
UIManager.getClock()) is one Java element gated on a WORNAlarmClockClothing; its faces are inmedia/ui/ClockAssets/and drawable from Lua. The time-speed controls live under it, so a second readout goes beside it, never below. # - Map symbols.
MapSymbolDefinitions.getInstance():addTexture(id, path, tab)(the B41 four-argument form is gone and throws); the store ismapAPI:getSymbolsAPIv2(); per-symbol MP sharing exists; annotation colour is raw floats. Freehand drawing is symbol spam. The colour buttons are one table duplicated inISWorldMapSymbols,ISTextBoxMapandISMapSymbolDialog; a new hue is a new item plus a row in all three, or edited annotations silently repaint to the default. #
Multiplayer and authority
Who runs what
- Corrected An MP client loads and runs the server Lua too; only a dedicated server leaves a tree out.
GameLoadingState.entercallsLuaManager.LoadDirBase("server")with no client check, after shared and client, so every server Lua file (vanilla's and every mod's) runs on a joining client; 33 of vanilla's 294 server files open with anisClient()return for exactly that reason. A dedicated server loads shared and server and never client. So a client calling a server-tree function finds it defined but reading the client's own empty state, while a server file calling client-only code still breaks on a dedicated server. An earlier version of this page said a server-tree function is nil on every MP client; it is not. # - The server simulates a player's body and stats; an MP client is a display.
BodyDamage.UpdateandBodyPart.DamageUpdatereturn at once on an MP client even for the local player, and the server pushes snapshots: per-part health every 500 ms, full stats every 1000, the whole body every 2000. A client-side stat or body write is reverted on that cadence. Apply effects on the server; immediate pushes are the server-only globalssyncBodyPart(bodyPart, bitmask)andsyncPlayerStats(player, bitmask). Whole-body pain is derived from per-part pain every frame, so writeBodyPart:setAdditionalPain. A hosting player is an MP CLIENT of its own server process. # - New Traits, XP and skill levels follow the server every second. On the 1000 ms tick the server sends each player
XP.save(traits first, then XP and levels), and the client's load REPLACES its own. So a trait, XP or level changed on the server reaches its player within a second with no code, and one changed only on a client is undone unless the client sends it up (SyncXp(player), client-only). The immediate push is the server-onlysendSyncPlayerFields(player, mask): 1 known recipes (additive), 2 traits (replace), 4 books read (additive), 8 the body's main fields, 16 is-reading, 32 fitness. # - New A trait added at runtime is only a flag.
CharacterTraits.add/removeis a map write: no packet, noXPBoosts, no granted recipes (those apply at creation only). The engine askshasTraitwhen it matters, which is why a runtime trait still works. A trait's creation package is readable:CharacterTraitDefinition.getCharacterTraitDefinition(t):getXpBoosts(). #
What reaches a client
- A client may not create or destroy items.
sendAddItemToContainerdoes nothing on a client whilesendRemoveItemFromContainerdoes not, so the usual add + remove + both sends deletes the original on the server and leaves the replacement on one screen. The client reports item ids; the server re-derives the decision and performs the swap. # - New What each server item call sends.
ItemContainer.AddItemsends nothing; pair it withsendAddItemToContainer(container, item), which carries the whole item, fluid included.sendItemStats(item)updates condition, uses and fluid on an item the client already holds (it does nothing if the client lacks it), never the name or mod data, and applies fluid withcopyFluidsFrom, which an input-locked container refuses.syncItemFields(player, item)carries condition, uses, weight, name and the WHOLE item mod data, which the client wipes and refills.ItemContainer.RemoveneedssendRemoveItemFromContainer.syncItemFields()on an item inside a bag crashes other clients' packet parsers; sync top-level items. # - New A B42 drainable's fill is
getCurrentUsesFloat(). It is uses × use delta;setUsedDelta(f)storesround(f / useDelta)uses.getUsedDelta()exists onClothingonly and no inventory class hasgetDelta(), so a reader that leads with either reads every drainable as empty with no error. # - New What reaches a client, layer by layer. Global mod data:
ModData.transmitand the answer toModData.requestarrive asOnReceiveGlobalModData(name, table)and the engine STORES NOTHING; a client handler must callModData.add(name, table), and a client should request on joining, because a server sends only on change. Item mod data:sendItemStatsdoes not carry it;syncItemModData(player, item)(server-only) sends it to nearby players, never for a floor item. Square mod data travels only with the chunk. XP:addXp(player, perk, n)sends from a server and does nothing on an MP client. A zombie's added looks: an ordinary zombie's item visuals are never sent; a client builds a zombie from its outfit id. # - Corrected No global mod data table can hold a secret, and a received one is stored by neither side.
GlobalModData.receiveRequestreturns ANY named table to any client with no allowlist, and a transmitted table goes whole to every client. Since a received table is only handed toOnReceiveGlobalModData, a client's transmit no longer overwrites the server's rows; keep one writer anyway. An earlier version of this page said a client's transmit pushes its stale copy over everyone's. # - A player's mod data is one wholesale-replaced table with two writers. A server
transmitModData()on a player is sent (to the players near it, the owner included) and the receiver wipes the whole table before reloading, while the owning client's send replaces the server's. Two writers erase each other's keys; pick one per table. # - New A zombie's mod data and animation variables never reach a client; its network id does. No packet carries an
IsoZombie's mod data, and the engine syncs only 14 fixed zombie flags, nothing set withsetVariable. On a servercreateZombiegives the zombie a unique id, andgetOnlineID()reads the same number on every machine, so send id-to-record from the server and look zombies up by id (ids are reused, so rebuild the map from each push). # ObjectModDataPacket.processServerapplies a client's world-object table before relaying, so MP clients must nevertransmitModDataa server-owned object. #
Commands and actions
sendClientCommandwithout the player argument is attributed to player 0 of the connection. Send the player form only. EveryOnClientCommandlistener sees every module's commands, vanilla's included. In single playersendServerCommanddoes not loop back toOnServerCommand; run the same handler table in process. A handler is reachable with any arguments, so a coordinate needs a proximity gate and a grant must depend on the world change having happened. #- A Lua timed action that defines
complete()is networked and server-authoritative for free. The client'sstart()ships it to the server, which re-instantiates it by callingType:new(...)with deserialised arguments, runscomplete()in server context and force-stops the client's action if it returns false. The codec reads the PARAMETER NAMES ofnewand ships the same-namedself.fields, so store constructor parameters under identical names. It carries items (by id), objects, squares, characters, vehicles, recipes and tables. Insidecomplete()item adds and removes are legal;perform()stays cosmetic. On an MP client the action waits for the server, so itsperformruns AFTER the server'scomplete; single player runsperformthencompleteon one object. # - New A client-side teleport is a kick by default.
teleportTo(x, y, z)is purely local, andAntiCheatSpeedmeasures speed from position samples, flags over 20 tiles a second, and defaults to kick. The server's own teleport (GameServer.sendTeleport, which whitelists the jump) is not exposed to Lua, and theteleportPlayersglobal only sends players who are out of range. So no mod can move an ordinary player far on a server. #
Mods, saves and servers
mod.info. A server'sMods=line matches the declaredid=case-sensitively, and a mismatch fails silently: the item downloads and nothing appears. Server modlists use backslash-prefixed ids (\ModID).incompatible=is honoured;loadModAfter=andloadModBefore=are real fields.versionMax=and acommon/tree merging under the version directory let one item serve two builds; B42 reads only the version directory'smod.info. Arequire=added to a live mod pushes the dependency into every subscriber's save. #- New A character holding a trait from a removed mod cannot load.
CharacterTraits.loadturns each saved name into a registry lookup that returns null for a trait nobody registered, and the next step calls a method on that null. A saved skill or profession from a removed mod loads harmlessly, and an object whose sprite is gone loads spriteless. Any mod that adds traits needs a way to strip them before it is removed. # - New A server that ever ran a mod with a buildable entity must keep the mod. The world dictionary records every entity a mod declares the first time it loads in a world (built or not) and never marks a removed one unloaded. An MP client checks the list (
parseLoadListClient) and throwsMissing dictionary script on clientfor every entry the server sends as loaded, so the world does not load; no server option relaxes it and the dictionary is not exposed to Lua. A removed ITEM, by contrast, is logged and drops out of inventories. # - New What an update may change under an existing save. Item, recipe and script changes apply at once. A changed basement registration reaches new worlds only (see Basement lots). A removed entity or trait is permanent damage as above, so add, never remove. #
- Test single player first, then multiplayer. The worst live bugs seen while writing these notes were client-authoritative item edits that worked perfectly in single player. #
Items, recipes, traits, skills
Item scripts
- B42 has no
Type =field; it isItemType = base:<kind>. Fifteen values:normal,clothing,food,literature,weapon,moveable,container,drainable,radio,alarmclockclothing,map,weaponpart,key,alarmclock,animal. An item with a missing or unknown kind returns null fromgetItemType()and the debug item viewer throws on it for every mod at once.DisplayNameandObsoleteare B41 fields B42 discards. Field names are a vocabulary:needToBeLearn(forNeedToBeLearn) andToolTip(forTooltip) are ignored without a word, and a perk name that is not a perk (CarpentryforWoodwork,MetalworkingforBlacksmith) is a gate that silently does not exist. # - Comments in script
.txtfiles are unsafe. An apostrophe inside a comment is read as a string delimiter, the parser resumes mid-sentence, the entity is dropped andScriptManager.LoadthrowsScript load errors: the game does not start. Vanilla ships zero comments in any entity script. # fluid = Name:Nin a FluidContainer component is a FRACTION of capacity, not litres (addInitialFluidmultiplies by the percentage). Vanilla writes1.0in 148 of 149 declarations, so the wrong reading agrees with every vanilla item. Write1.0for full,0.0for empty.setCapacityfloors capacity at 0.05. #- A bare
ReplaceOnDeplete/ReplaceOnUsename resolves to the item's OWN module, and a miss creates nothing; writeBase.-prefixed names.ReplaceOnDepleteis implemented only for drainables and does fire from recipe consumption.item:isSealed()is the authoritative sealed check. # - Vanilla never swaps item types on drain. A beer bottle opens by
flags[Unseal]on amode:keepinput, drinks to empty and stays the same item, namedEmpty %1byFluid_HoldingNone. # - New A missing mesh or texture in a
modelblock fails silently. The item renders as nothing, or keeps what it had. Resolve both against your mod's media roots, then the game's, before shipping. #
Icons and models
IconFluidMask = Namedrawsmedia/textures/Item_Name.pngtinted with the fluid's colour and clipped from the bottom toamount / capacity, on every icon path. The clip is floored at 0.15 and an EMPTY container's colour is white, so keep the mask's bottom 15% transparent. It drains only for a real FluidContainer. #IconColorMasktints a second mask with the item's ownColorRed/Green/Blue(0–255), but not on abase:moveable, whose icon path never fills the mask. An icon a script names is registered asItem_<icon>; one named only in Lua may not be. A mod icon is a loose PNG atmedia/textures/<Icon>.png. Vanilla icons carry binary alpha and a one-pixel dark outline. #- An item's inventory picture is overridable per instance through the mod-data key
customInventoryIcon(a bareItem_-prefixed name): persisted, carried in the add-item packets, and falling back silently to the normal icon. Vanilla uses it for gas-mask filters and SCBA tanks. # - New A food's rotten, cooked and burnt pictures are found by name.
Item.DoParamand theFoodconstructor tryItem_<Icon>Rotten, then...Spoiled, then..._Rotten, andCooked/_Cooked,Overdone/Burnt/_Burntthe same way; there is noIconRottenfield. # - World models tint from the item's colour, with no clothing gate: one greyscale texture serves every colour of a ONE-colour object (vanilla's tinted rubber duck) and cannot serve a body-plus-accessory object.
StaticModel(in hand) andWorldStaticModel(on the ground) are different fields; an item with only the second plays every action empty-handed. A timed action shows its item only if it callssetOverrideHandModels(primary, secondary)instart(). # - Carried light.
canEmitLight()is a light strength above 0 (and uses left for a drainable);isEmittingLight()adds "not activatable, or activated".getActiveLightItemswalks the two hands and every ATTACHED item, at most four, and the path is typedIsoPlayer: worn clothing never emits light, and a zombie cannot carry one. # - Attachments are four bare strings across four files: a garment's
AttachmentsProvided, the hotbar definition'stype, the item'sAttachmentTypeand theAttachedLocationsid, each join failing silently.ISHotbarbuilds slots from ALL worn items, so a hat can offer a slot as a belt does;AttachedLocationsis plain appendable shared Lua;getAttachedItem("Holster Left")reads a clip by location id. #
Inventory
- New Which lookups reach into bags. Top level only:
contains(item),getItemWithID(int),getItemsFromType(String),FindAndReturn. Recursive:getItemsFromType(String, true),contains(item, true),containsRecursive(item),getFirstTypeRecurse,FindAndReturnRecurse,getCountTypeRecurse(String).getAllTypeRecursetakes a list to fill and has no one-argument form.Remove(item)on a container that does not hold the item silently does nothing, so remove fromitem:getContainer(). The recurring bug is a menu that lists recursively over an action that validates or removes at the top level. # - A container item's
WeightReductionapplies only while it is worn or held.getInventoryWeight()asks an unequipped item for actual + contents with no reduction, which is why every vanilla packed item is a plain item with a fixed weight. An item CAN carry its own weight, name and mod data per instance (setActualWeight+setCustomWeight(true),setName+setCustomName(true)), and all three persist and cross the wire; the inventory pane stacks by display name. # - A container can refuse items engine-side through a Lua function named as a dotted string (
AcceptItemFunctionon the script, orcontainer:setAcceptItemFunction(String)), called asfn(container, item)and compared against true, so an error refuses everything. OnlyhasRoomForandisItemAllowedconsult it, notAddItem. # - A dropped item's FluidContainer lives on the world object. Read
item:getFluidContainer() or item:getWorldItem():getFluidContainer(). # - New A tool with a head has two condition tracks. Vanilla's pickaxe declares both
ConditionMaxandHeadCondition(withHeadConditionLowerChanceMultiplier, tagbase:hastoolhead); wear that only callssetConditionleaves the head perfect for ever. Ask the engine withgetHeadConditionLowerChance()and wear it withreduceHeadCondition(). # - New There is no loose sand, dirt or gravel item. Only the drainable bags (
Dirtbag,Sandbag,Gravelbag,Claybag, a quarter per scoop from anEmptySandbag).base:holddirtis also on the dead-animal bags and wheat sacks, so match a sack by type. #
Food
- New Vanilla food poison survives cooking and crafting.
FoodcarriessetPoisonPower,setPoisonDetectionLevelandcopyPoisonFrom(Food); evolved recipes and crafted outputs carry it from an ingredient, and the item stats packet sends it to clients.PoisonDetectionLevelis the skill-gated tell foraging uses ("Poisonous" in the inventory).Food.isTainted()/setTainted()is the UNBOILED-WATER flag, not a general word for spoiled meat. # - New Drinking from a world water source is
ISTakeWaterActionwith no item. It is a networked action whosecomplete()is where the water is drunk, on the authority; with an item it fills the container instead. Tainted water's effect is the TaintedWater fluid's own poison block. # - New Nothing in vanilla ever lowers
CharacterStat.SICKNESS. It is read and never written outside the debug panel; vanilla's corpse sickness isFOOD_SICKNESS, which decays. A mod that raisesSICKNESSowns lowering it, and should lower only its own share. #
Recipes
- Every vanilla
craftRecipeis inmodule Base. A recipe in a mod's own module never marks its product as a craft product. A bare fluid name resolves across modules (-fluid 5.0 [Slip], like vanilla's[Water]). Every ITEM reference must be module-qualified, even inside its own module: an unqualified name isitem not foundand a world-load failure. # - A
mode:mixturefluid draw requires everyitemline ABOVE it to have amount 1, or the world fails to load; put the bulk ingredient below the draw. A plain named draw has no such rule. # - A craftRecipe re-declared with an existing name does NOT override. Both load and the recipe shows doubled requirements; same-name replacement is an ITEM behaviour. A vanilla recipe's input list cannot be widened from a script. An unknown ITEM in an input list is dropped silently; an unknown FLUID in an input throws; an invalid OUTPUT throws. Cross-mod compatibility is an alternative in an INPUT list, never a cross-mod output or fluid draw. #
- A Normal-mode input that owns a FluidContainer is never consumed without
ItemCount; an empty fluid item that should be used up needsmode:destroy. AnitemMapperPAIRS inputs to outputs;flags[InheritCooked; InheritFoodAge; InheritFreezingTime]carry food state; count-prefixed names give per-type counts in one recipe. # - A recipe's hooks resolve through the Lua namespace. Five of them (
OnTest,OnStart,OnUpdate,OnCreate,OnFailed), each resolved withLuaManager.getFunctionObject(string)at call time, soMyMod.onXis the same mechanism asRecipeCodeOnCreate.x. The script'soutputsblock is not the whole story: 146 recipes carry anOnCreatethat hands out items the script never names. # - New A recipe hook receives
(craftRecipeData, character). The created items arecraftRecipeData:getAllCreatedItems()orgetFirstCreatedItem(), the inputsgetAllConsumedItems(). A hook written for an(items, result, player)shape gets the crafter as its "result" and nil as its "player", and fails silently. # - The packing precedent. 32 vanilla recipes in category
Packing, 63 pack/open pairs; output weight is ×1.20 of the inputs for generic packing, ×2.50 for nails and screws, ×3.00 for a log stack.RecipeCodeOnCreate.addToPackwithRecipeCodeOnTest.canAddToPackis the incremental add. Paint is a drainable atUseDelta = 0.1, so a recipe count is DOSES; no vanilla recipe consumes paint. # EvolvedRecipebelongs to the ingredient (Soup:3;Stew:3on the item). Vanilla's whole fish carries none; the fillet does, andCutFishtakestags[base:uncutfish], so cookability is a tag question. #- What vanilla ships and never wires.
fluid Acid(no item or recipe uses it);Base.LargeMeteorite(one legendary forage entry, no consumer); thebase:ironore/ironsource/hasmetaltags (no recipe input; the live smelting hook is thebase:smeltableiron*family); several unused vanilla icons (a garter snake, a froglet, a rotten squirrel, a digital watch). Check for an unused vanilla icon before painting one. #
Traits, professions, skills
- Traits and professions are declarative.
CharacterTrait.register("ns:name")/CharacterProfession.registerinmedia/registries.lua, thencharacter_trait_definition/character_profession_definitionblocks; the creation screen picks them up with no UI code. Detect them withCharacterTrait.get(ResourceLocation.of(id))thenplayer:hasTrait(t), anddesc:getCharacterProfession():getName();getTraits(),HasTrait(string),ProfessionFactoryanddesc:getProfession()do not exist in B42, and B41-shaped helpers silently return false. # - A profession must grant traits whose
IsProfessionTrait = true, or the player can remove one at creation and keep the points. All 12 vanilla profession-granted traits are free at cost 0.MutuallyExclusiveTraitsis one-directional; the two-way fix from Lua is the public staticCharacterTraitDefinition.setMutualExclusive(a, b), called with a contains-check first. A trait's icon ismedia/ui/Traits/trait_<name>.png, lowercased with the namespace stripped. A profession'sCostis points ADDED to the pool. # - New A profession's cost has no setter. The creation screen copies it into Lua when a profession is selected, so a mod changes a price there. The profession list is built at the MAIN MENU, before any sandbox is chosen; re-apply anything sandbox-driven when the screen is shown. #
- A mod adds a real skill with one text file,
media/perks.txt(VERSION = 1,thenperk Id { parent = Crafting, translation = Key, passive = false, xp1 = 50 ... xp10 = 6000 }).CustomPerksreads it from every enabled mod,Perks.<Id>becomes a global, XP is saved by id so it survives reload, and the skills panel shows it with no UI code. Grant a custom skill's starting levels from Lua (a scriptXPBoostsresolves perk names at script load, a race against perks.txt), and register its skill books in vanilla'sSkillBooktable, which is reset at load. # - New A custom skill needs a
MultiplierConfig.<Perk>sandbox option.XP.AddXPmultiplies by the global multiplier whileMultiplierConfig.GlobalToggleis on (every vanilla preset), else looks upMultiplierConfig.<perk>with no null check; vanilla declares its per-skill options by hand, so a custom skill has none and every grant throws on a world with the global multiplier off. Declareoption MultiplierConfig.<Perk> { type = double, min = 0.0, max = 1000.0, default = 1.0, ... }. # - Tool and level hooks.
Events.LevelPerk(player, perk, level)fires on level-up;addXpNoMultiplier(player, perk, n)skips the multiplier lookup. # - New Reading.
ISReadABookis a networked action.IsoGameCharacter.ReadLiteratureapplies the stress change, learns everyLearnedRecipesstring not already known (learnRecipe(String)takes any string) and uses up an item taggedbase:consumeonread. A known-recipe string is therefore a free per-character flag: saved, synced, read withisRecipeKnown(String), and it draws the read tick (all of an item's learned recipes known). Vanilla's own read-to-gain-a-trait path is dead in B42. #
Characters and zombies
The player
- New The human body simulation belongs to
IsoPlayerby construction. The character constructor buildsBodyDamage,MoodlesandXPonly for anIsoPlayerthat is not an animal (an animal gets aBodyDamagealone; a zombie gets none), andBodyDamage.Updateopens by returning for a zombie or an animal. Hunger, thirst, fatigue and the rest are computed by non-public methods. So an NPC on a zombie body can borrow the game's RULES (the rates and thresholds), never its simulation;getBodyDamageRemote()builds a body record for any character, but nothing updates it. # - New A new character's start.
SpawnRegionMgr.getSpawnRegionsfiresEvents.OnSpawnRegionsLoadedwith every region before returning them, on the machine that picks (single player or the server); the pick readspoints[profession:getName()], falling back topoints.unemployed, and a server picks withRand.Next(1, len), never the last of two or more. Vanilla files ALIAS one list under many keys, so assign a new list rather than inserting into one.OnNewGame(player, square)fires once per new character in single player and on the server, after the spawn square, traits and granted recipes and before the player is saved and sent, so items, traits and mod data set there ride the first snapshot.OnCreatePlayernever fires on a server and fires on every load. # - New In single player a new character is called "Bob" while
OnNewGameruns. The player constructor sets the name;IngameState.enterrenames it from forename and surname afterOnNewGame. Anything filed under the username atOnNewGameis lost; key it by the splitscreen slot in single player and the account on a server. # - New Setting the start square. In single player,
CharacterCreationProfession.initWorld(onOnInitWorld) picks the square and callsgetWorld():setLuaPosX/Y/Z; a mod moves the start by setting those in its ownOnInitWorldhandler added atOnGameBoot, so it runs after vanilla's. # - New Single player clears the starting building by itself.
IsoWorld.initcallsZombiePopulationManager.playerSpawnedAtin single player only, refusing zombies inside that building's box for ten real seconds, whatever the settings say.RoomDef.explored, set at the same time, is the loot flag only. # - New Climbing odds are one public number.
getClimbingFailChanceInt()is a score built from Fitness, Strength and Nimble (two each), less tiredness, drunkenness, carried load, pain and weight, adjusted by gloves and traits, then square-rooted; a tall fence fails 1 time in that score, and the sandboxEasyClimbingskips the roll. # - New A landing recorded outside the falling state is never cleared.
updateFallingsettles a character and, after a fast enough drop, records a landing that onlyPlayerFallingState.exitclears (clearFallDamage()). A record left standing keepsbLandLightMasktrue, which only the hand-mask landing nodes read while a held bag's walking pose demands it false: the body walks normally and the held arm lifts and drops on a loop.getImpactIsoSpeed(),getCurrentStateName(),isbFalling()andclearFallDamage()are public; clear a record still standing a moment after the character is back on its feet outside the falling state. #
Ropes and ladders
- The engine climbs ropes and never ladders. The sheet-rope tiles carry real climb properties (tops
climbSheetTopW/N/E/S, bodiesclimbSheetW/N/E/S) and the climb predicates read those square PROPERTIES, so a Lua-laid rope is climbable. Vanilla'sladderN/W/E/Stiles do nothing. The engine parks a climber at a fixed point per rope direction (setIdealDirection), so a rope's ink must sit on that column and one climb clip serves all four facings. # - New A climb's ending is decided once, when it starts.
ClimbSheetRopeState.calculateClimbwalks up to the first rope top and stores an outcome from the square beyond it: no floor there is Blocked (the engine climbs the character back down), a window or window frame opens and climbs through, a hoppable thumpable or wall hoppable is a Fence (the low-fence vault), anything else is Undefined, which does NOTHING: the climber rises a hair and is set back every frame, the climb clip playing on the spot. That square is asked with no null check, so make it exist.climbOverFence(dir),climbDownSheetRope()andsetClimbRopeTime(float)are public, so a mod can finish a climb itself. # - New An invisible railing turns a rope top into a vault.
getWallHoppableTois any object withHoppableN/Won the edge, so an inkless tile carryingHoppableN+collideNmakes the top a vault; vaulting that railing from the ledge onto a rope top ends in the climb-down state, which IS the way down. A rope climb never falls whilesetClimbRopeTime(0)is applied each update (the fall roll waits on that timer). # - Rope climb rates.
ClimbSheetRopeState.executeaddsspeed / 10 × GameTime.getMultiplier()per frame (the multiplier sums to 48 a second), andgetClimbRopeSpeedis one of eleven values from a clamped stat (0.096 to 0.672 levels a second). Every ladder sprite in the game has a 32 px rung pitch, so a storey is exactly six rungs. #
Zombies
- A live zombie is drawn from its outfit VISUALS, never its worn items.
IsoZombie.getItemVisualscopies the outfit's visual list unlessisUsingWornItems(), false for a walking zombie; at the kill the corpse's clothing and pockets are rebuilt from the visuals and anything put on or into a live zombie is discarded. Dress a live zombie withItemVisual.new(),setItemType,pickUninitializedValues(getClothingItem()),zombie:getItemVisuals():add(iv),resetModel(); death loot isaddItemToSpawnAtDeath(item). # - The model manager dresses a zombie itself the first time it builds the model.
ModelManager.AddandResetrundressInRandomOutfit(outfit, blood, dirt, holes and an attached weapon) when the zombie's flag is up, thendressInPersistentOutfitIDwhen the persistent id is uninitialised, andcreateZombiereturns exactly that state. Shut both gates BEFORE dressing:setDressInRandomOutfit(false)andsetPersistentOutfitID(0, true); set the skin name AFTER (the skin falls back to a zombie texture whenever the name is empty). # - New A zombie's mod data does not survive the player walking away; its persistent outfit id does.
ZombiePopulationManager.virtualizeZombiekeeps a body's position, facing,getPersistentOutfitID(), state flags and path target, nothing else, and a returning player gets a NEW zombie built from those numbers (OnZombieCreatefires again). Keep per-zombie history in world mod data keyed by the outfit id, on the authority. # - New What a zombie wears changes what it sees and hears.
IsoZombiesight and hearing are fields set only from the sandbox, but vision is divided bygetWornItemsVisionModifier()(then clamped to 10..20 tiles) and hearing multiplied bygetWornItemsHearingMultiplier(), both computed from the zombie's ITEM VISUALS'VisionModifierandHearingModifier. Vanilla's hoods and helmets already blind and deafen their wearers. They are recomputed only inOnClothingUpdated, so callupdateWornItemsVisionModifier()andupdateWornItemsHearingModifier()after changing a zombie's visuals. Never callDoZombieStatsto change one zombie: it re-rolls its cognition, memory and speed. # - New A woken zombie sits against a wall on its own level, outside any building. One in three zombies made real from the population asks
getSquareForSittingZombie, which scans the 6×6 round it at the zombie's own z for a free, floored, roomless square with a wall and a clear line; an occupied square is not free, so a group woken together sits side by side along one wall. # - New A dead zombie fills its own pockets and bags. The corpse's container is
inventorymaleorinventoryfemale, and the item picker rolls the body'sOutfit_<name>table and fills every bag in the corpse from that bag's own distribution, so an NPC on a zombie body gets a wallet, keys and pocket clutter at death for free. # - Wounds from Lua.
BodyPart.setScratched(scratched, forceNoInfection)andsetCut(...), with the second argument suppressing infection;bodyPart:AddDamage;BodyPartType.FromString("Hand_L").Base.BareHandsis a real item, so an empty hand may be nil OR that item. #
NPCs on a zombie body
- Every B42 NPC mod uses the same shape.
createZombie(x, y, z, nil, 0, IsoDirections.S)oraddZombiesInOutfit(...), AI suppressed every update (setUseless(true),setNoTeeth(true), lunge and attack states forced back to idle), movement through the engine's pathfinder (getPathFindBehavior2():pathToLocationF(x, y, z)+setVariable("bPathfind", true)and the pathfind state), one-shot clips throughsetBumpType("Name")matched by a node in thebumpedstate, and MP ownership asked of the engine (isRemoteZombie()on a client,getOwnerPlayer()on the server). A REMOTE zombie runs throughwalktoward-network,lunge-networkandattack-network, so nodes added towalktowardalone show the NPC walking like a zombie on every client but the owner. # - Corrected
setZombiesDontAttack(true)does nothing outside a debug launch. For anything that is not a player it is stored only with a capability that is true only in a-debugsingle-player game; otherwise it writes false. An earlier version of this page listed it among the working suppressions. Clear any zombie targeting the body instead:AttackStatecasts its target toIsoPlayer, so a zombie attacking an NPC body throws. # - New
uselessdoes not stop a walk. It is read by the sound response, spotting, idle wandering and the walk-toward state, never by the pathfind state, so a body can stay useless for good and still walk when put in the pathfind state (setMoving(false)afterpathToLocationF). # - New What a zombie body costs the player.
IsoPlayer.updateLOScounts every visible zombie within 7 tiles, NPC bodies included: panic rises with the count, the game speed is reset to 1 within 4 tiles, a jump scare plays under 3, and sleeping and search mode check the count.Stats.setNumVisibleZombiesis the only setter. AndIsoZombie.updateInternalmakes the body shootable and solid again every update, whileSayreturns at once for a zombie. #
Clothing
- A mod's
clothing.xmlmerges.OutfitManager.loaded()parses each mod's file, replacing a known outfit name and appending a new one. Outfits address garments by GUID; a GUID naming nothing is dropped silently. Vanilla ships 239 male outfits against 170 female and its work outfits are male-only. Hats control hair throughhairStyles.xmlcategories. Clothing textures alpha-blend, including on static attachments. # - A static head attachment is
m_Static = true+m_AttachBone = Bip01_Headwith the mesh in head-bone local space (+X up, +Z forward). The attach frame is the bone's inverse-bind matrix in the body mesh's own SkinWeights block; composing the skeleton's frame chain gives a frame about 9.6° pitched and 5 cm off. # - Breathing gear.
isProtectedFromToxic(drain)walks the worn items once: an SCBA switched on with a tank and air left returns true without draining; a mask with a filter spends0.01 ×the filter's use delta. The tank is spent bycheckSCBADrainwhenever it is worn and switched on, fresh air or foul. Neither is removed at empty.hasTank()/hasFilter()read item mod data; a fitted filter is written onto the garment's own use delta. #
Animals
Defining an animal
- A mod animal is a vanilla animal's state machine wearing new skin. A type is a Lua table
AnimalDefinitions.animals[type]in any shared file, naming abodyModel(mesh = Skinned/X,shader = animalEffect,animationsMesh = Name), per-breed textures and ananimset.AnimationSet.Loadresolvesmedia/AnimSets/<name>mod-aware, butActionGroup.loadreadsactiongroups/<name>from the GAME directory only, so a new animset name loads its clips and gets NO state machine, and the animal freezes.animsetmust be one of vanilla's 22 animal groups (buck chick cockerel cow cowcalf deerdead doe ewe fawn hen lamb mouse pig piglet rabbit rabkitten raccoon ram rat turkey turkeypoult); a mod may only add NODES to an existing state, scoped by a variable it sets, at a condition priority above vanilla's 0.AdvancedAnimator.load()folds every mod'sAnimSetsandactiongroupsfolders into the animation checksum a client must match. # - Three ways to give it a body. A new mesh skinned to the vanilla skeleton by bone name plays vanilla's clips for free; an own rig with its clips EMBEDDED in a glb, named to match the animset's clip names and declared
animationsMesh X { meshFile = Skinned/X, keepMeshAnimations = true }; or the mouse shape, the same skeleton with its own animation directory. A skeleton cannot carry a longer-legged animal's ground contact; give such an animal its own rig. # - New A missing definition breaks the server every frame. The
IsoAnimalconstructor looks the type up inAnimalDefinitionsand, when it is missing, logs one debug line and returns early: Lua gets an animal and no error. Added to the world, itsupdate()reads the missing definition and throws every frame, and a server stops answering. The definition map is built lazily once and never refilled. Askanimal:getAdef()beforeaddToWorld. # - Spawning.
IsoAnimal.new(cell, x, y, z, type, breed)+setWild+addToWorld()(vanilla's trap release). An animal is world state and persists, so cap, despawn and sweep. A carcass isIsoAnimal.newnever added plusIsoDeadBody.new(animal, true, true). A held animal is already dropped by any item swap. # - New Take an animal away with both calls.
IsoMovingObject.removeFromWorldtakes it out of the cell's lists and never off its square; vanilla always follows it withremoveFromSquare(). Left on the square, the chunk unload finds it again and removes it a second time. # - One brain for every species.
BaseAnimalBehavioris one Java class; species differ by about a hundred definition keys plus Lua on a tick. Rats and mice are real vanilla animals with breeds. # - New A swap to a twin type is how a mod changes what an animal is.
IsoAnimal.newof the new type,getData():setSizeForced(old:getData():getSize()),addToWorld(), and the old oneremoveFromWorld()+removeFromSquare(); the type's definition fields are read once at load and cannot be changed per animal. #
In the world
- New An animal on an unloading chunk goes into the wild-animal pool.
IsoChunk.removeFromWorldhands every animal on the chunk to the native pool, the SAME object with its mod data, and the pool puts it back on its own terms (exactly where it was the first time; anywhere in the chunk once it has a virtual id or migration group). The loaded area is 13 chunks across, about 48 tiles round a player, so a mod that removes its animals "when no player is near" must do it inside that, and anything counting animals out from the loaded cell loses pooled ones. # - New A pathless animal is moved by its clip. Root motion is applied only with no path (or in the walk-toward states), and the world-collision passes are skipped when
collidableis false (setCollidable(boolean)), so stop, hold and face an animal, turn its collision off, and a clip with root motion carries it straight over water the pathfinder will not cross. # - New Removing a mod that adds an animal type wipes the animals saved round one of its animals. Every free animal is saved in the population's per-cell files, not the chunk saves.
IsoAnimal.loaddereferences the type's definition unchecked, the cell loader catches nothing, and on the throw the cell is treated as never saved and refilled with fresh wild animals; the next save makes it permanent. In single playerOnSavefires BEFORE the cell and the population are saved, so a mod that takes its animals out of the world there keeps them out of every save; a dedicated or hosted server saves through a queued path that fires no Lua event, so there a sandbox switch is the only way. # - New An animal never draws a held or attached item, and is one mesh.
ModelManager.DoCharacterModelPartsreturns early for anIsoAnimal, before equipped items AND before clothing, hair and beard. A prop "in the mouth" is drawn by Lua:animal:getAttachmentWorldPos("name")gives the world point of an attachment the animal's model declares, andRender3DItemdraws an item there. # - New Wild stress never goes down.
IsoAnimal.updateStressreturns at once for a wild animal, so its stress only climbs, and above 50 the idle sound comes from the stressed slot.changeStress(f)is public. #
Taming, acceptance, homes
- New Any animal standing in a player's animal zone is tamed unless its definition says
canBeDomesticated = false.IsoAnimal.checkZoneruns every 2000 ticks and callssetWild(false)whenever a designation zone is under the animal; vanilla's pickup and live trap catch do the same. OnlycanBeDomesticated = falserefuses all three (vanilla sets it on the deer).setWild(true)is never refused. # - New Two kinds of animal zone. The player's designated zone (
DesignationZoneAnimal, 2..40 tiles a side; touching zones join; fences are never checked) is a soft pen: an animal with a zone that is not hungry or thirsty picks its wander square inside it. The map's wild Animal zones are polylines migration groups walk, leaving tracks, dung and broken twigs. # - New Acceptance is per player and matters only to a tame animal. Petting, hand-feeding, a lure and being held raise it. A wild animal, or one with
alwaysFleeHumans, always flees; a tame one flees a moving player by a chance built from stress and acceptance, and never at acceptance 40+ with stress under 70. # - New Hutches are appendable.
HutchDefinitions.hutchs[name]is plain Lua; a buildable whoseOnCreatereturns{ replaceObject = true, object = IsoHutch.new(square, north, sprite, def, nil) }makes one, and an animal uses one when its definition lists the type. #
Genes, breeds, products
- New Genes are settable from Lua and a corpse keeps the animal's mod data.
animal:getFullGenomeList()lists the genes (names lowercased); set a copy withallele:setCurrentValue(v). Size reads the gene live, so setting both copies beforeaddToWorldand thengetData():setSize(getData():getMaxSize())grows an adult to its gene. Butchering scales by the corpse's recorded size and meat ratio. Of vanilla's hidden genetic traits only seven are read by anything; the rest are listed and inert. # - New A colour variant is cheapest as a breed. The breed is chosen at
IsoAnimal.new, synced and saved by the engine, and every per-breed table (textures, icons, parts, sounds,IGUI_Breed_<name>) follows it. # - New A breed's icons are looked up in the texture PACKS only. The animal in hand and the corpse call a plain
Texture.getSharedTexture(name)on the breed'sinvIcon*, which tries packs and then poisons the name, never falling back to a loosemedia/texturesPNG the way a script item'sIcondoes. Ship a mod animal's icons in a.packof the mod's own. The rotten picture is the dead name plusRotten(vanilla's ownItem_Squirrel_Rottenis reached by nothing). # - New Butchering off the ground multiplies counts by 2.8 for an animal that cannot hang on a hook. The count is rolled from
minNbandmaxNb× size × F, where F is 2.8 for an animal with no hook entry and 0.6 only for a hookable one on the ground, and food is further scaled by the meat ratio; that is why vanilla's raccoon gives 13–20 pieces. AnoSkeletonanimal's bones and skull come only from a corpse left to rot. # - New Sounds. A breed sound's interval is rolled in REAL seconds after each play, whatever the game speed.
forceFleeFromChrplays the stressed call every time it is asked (vanilla's ownfleeFromChrgates it on a timer and the animal having stopped), so Lua that re-forces a flee on a timer shrieks on that timer. # - New Per-type touches. The pet animation is chosen per animal type (
AnimSets/player/petanimal/pet<type>.xml, else a default with a bull's reach). The Animal Info picture's view half-size is25 − zoom, with zoom set from the avatar definition × the animal's size every frame, so a large size gives a sliver or a mirrored, negative view. #
Animation, models and art
Clips and the animator
- A
.xclip is readable and rewritable text: the rest hierarchy, a 617-vertex skinned proxy body with weights, and per-bone R/S/T tracks at 4800 ticks a second. A key composes to the column-form local matrixT @ R(conj q) @ S, the quaternion CONJUGATED; skinning isworld_bone @ SkinWeights offset @ vertex; aFrameTransformMatrixis sixteen floats row-major. A bone's local translation is in its PARENT's frame, andBip01's parent carries a 90° rotation about X. On a skinned body the SkinWeights offsets differ from the inverse rest worlds by up to 0.93, so deforming bypose @ inv(rest)tears the mesh. Rewrite the AnimationSet of a vanilla clip and write rotations only, so the skeleton cannot stretch. # - New A skinned model may have at most 60 bones. The animation track fills a fixed 60-slot per-bone array, so a rig with more throws an index error from
AnimationTrack.Updateevery frame for every character wearing it. An animal is anIsoPlayersubclass, so its animation faults read asIsoPlayer.postupdatein a trace. # - A mod adds a player animation by adding a conditioned node to a state that exists.
AnimationSet.Loadmerges a mod'smedia/AnimSets/player/<state>/<name>.xml;ModelManager.loadModAnimationsloads a mod's clips frommedia/anims_X/<animationDirectory>/(the player's isBob, with no prefix). Vanilla's nodes are mostly unconditioned at priority 0, so a node with a condition on a variable the mod sets wins. A mod cannot add a state. Whether a clip LOADED cannot be asked from Lua; the tell is a frozen pose. # - The
bumpedstate is a universal one-shot player.setBumpType("Name"), a node matchingBumpType == "Name"and an end event settingBumpAnimFinished; attacks, gestures and reloads on an NPC body all go through it. # - New Root motion is on unless a node switches it off. An empty
m_DeferredBoneNamemeansTranslation_Data, so a clip's travel still moves the body;<m_useDeferredMovement>false</m_useDeferredMovement>plays a walk on the spot.m_SpeedScalemay name a variable instead of a number, so a clip's cadence can follow the body's real speed; withm_SpeedScale0 andm_TrackTimeToVariablea node holds a clip at a time a Lua variable chooses. # - An animal is moved by its clip's
Translation_Datatravel, so a clip baked in place runs on the spot. Vanilla's rat walk moves that bone 0.18 over 0.533 s toward the head; glb bodies carry theirs along +Z (glTF faces +Z where a DirectX.xfaces −Z). # - New Vanilla ships an unused floor crowbar clip.
Bob_IdleLeverOpenLow(4.33 s: kneel, lever at the floor, stand) is played by no vanilla node; its Mid and High twins are the crowbar barricade removal. # - Clip speed does not follow the rope climb.
animFrameIncreasereaches only the legacy 2D sprite classes, so a 3D clip does not speed up with the climb; syncing feet to rungs means one node per speed. Vanilla's climb states are one node each, a one-second rope shimmy with no root motion, and there is no ladder clip in the game. #
Models and attachments
- The model-to-world scale.
Model.vectorToWorldCoordsnegates x, rotates by the rendered angle, swaps y and z, then scales x and y by 1.5 and z by 0.6123723, so one level is 1.63299 rig units, a storey draws 192 px at tile scale 2, and the Bob rig's head at 0.85 units is a 100 px character. # - New An attached item is drawn at
Bone × BodyAttach × ItemAttach × Mesh.transformToParentapplies the parent bone, the body's attachment named by the slot, then the item model's attachment of the same name, NOT inverted (the invert flag is a static nothing writes), then the mesh's root and the modelscale. An attachment istranslation(offset).rotateXYZ(x, y, z).scale(s), and JOML'srotateXYZisT × Rx × Ry × Rz, so Z turns the point first (Blender's Euler 'XYZ' is the opposite product). To place an item where a fit put it relative to a bone,ItemAttach = inverse(BodyAttach) × Fit. A held item usesBip01_Prop1, whose body attachment is identity. A DROPPED item inverts the model'sworldattachment, its ground frame in mesh space. # - Corrected An attachment name the BODY model does not declare draws the item at the character's origin. An attachment point is declared twice: on the body model (
knife_headis the only head point vanilla declares) and on the item's model block. A name the body lacks resolves to no transform and the item is drawn on the ground between the feet, while its light still works. An earlier version of this page said it renders nothing. A mod cannot add a point to the vanilla body; hang from a vanilla point and carry the difference on the item's own attachment. # - New The game's
.fbxmeshes do not agree on units. One declares yards with a 1/36 node scale, others inches or feet, each with its own pre-rotation, and each item'sscalewas tuned to its own file. A re-export writes new settings and the size comes out wrong by an amount nothing offline can measure; edit only the geometry of vanilla's file and write every other element back unchanged. # - The tile-art camera is orthographic at rotation X 60, Y 0, Z 45; about 26.57° is the screen slope of a tile edge, not a camera value, and true isometric (54.736°) never lines up. With one unit to a tile, ortho scale √2 against a 128 px-wide render fills a tile exactly; render at 4× and downscale; use the Standard view transform. The game's 12 fish meshes and 20 skins are paired by
models_fish.txt's<Species>_Groundblocks. #
Foraging, fishing, farming, water
Foraging
- The most mod-friendly subsystem in the game.
lua/shared/Foraging/forageDefinitions.luadocuments every field. Registration is public and additive (forageSystem.addForageDef(name, def)). Custom CATEGORY and SKILL defs must be STAGED intoforageSystem.categoryDefinitions/forageSkillDefinitions, neveraddCatDef/addSkillDef:forageSystem.initclears the live tables and rebuilds them from the staging tables, so a category registered live is wiped before the game uses it. # - New There is one live def per item type.
populateItemDefswalks the staged definitions and keys the live defs bydef.type; a second def for a type replaces the first whole, and which wins is hash order. Every reader goes by type, so a type has ONE zones table, month list, skill and category list for every zone. To add a vanilla item to your own zone, add your zone's rolls to the def that already names the type (atpreAddItemDefs), or decorate the LIVE def atonAddForageDefs; never stage a second def. # - New Every def gets one roll in every zone it does not name.
addItemDeffills a missing zone from itscontainsBiomes, and the default zone's empty list is truthy, so the fill-in is one roll: every vanilla item is in every zone, a mod zone included, and the rarest find in a category becomes as likely as the commonest there. Take unwanted types back out of the loot table aftergenerateLootTable, or set the fill-in yourself before it. # zones = {Zone = n}is the NUMBER OF ROLLS, not a weight.pickRandomItemTypepicks a category by the category's zone rolls, then an item by the item's, each ×validMonths[month] or 0and the weather and time.ForestGoodsis hidden with weight 0 everywhere, so a def whose only category is ForestGoods never spawns; a def below itsskillis excluded, so compare weights against the eligible vanilla set per skill band. Months are 1-based. #- New A find's search picture is
altWorldTextureon its item def. A list of lists of texture names (tile names ormedia/textures/...png); one inner list is picked each time an icon is built and drawn with its bottom centre on the marker square's centre at its own pixel size, so a picture of something lying on the square must end at that centre or be anchored a square further south-east. AspawnFuncruns when the icon's item list is BUILT on a single-player client and at pickup on a server, so it is no place for a side effect. # - The zone lookup ignores the player's level.
getForageZoneAt(x, y)asks for level 0, so a zone is found by x, y alone; registration needs no map file (getWorld():getMetaGrid():registerZone(name, type, x, y, z, w, h)). Forage icons are stamped at LEVEL 0 and seen only on the searcher's own level, so a below-ground zone must place its own icons. A mod zone must give EVERY category a roll count, zero included, or the first search throws inprocessEntries. #
Fishing
- The fishing tables are plain Lua.
Fishing.RiverZonesandNoFishZonesare rectangle tables read by trivialisRiver(x, y)lookups; appendable, but identical on server and every client only if derived from shared data.Fishing.lureis the bait table, and what it hands over is the CATEGORY per item.Fishing.fishesstoressetMaxWeightin KILOGRAMS and the actual weight in POUNDS.isWaterCoordsandisNearShoreread level 0;Fishing.onCreateFishis a plain Lua function 23 item blocks name, and returns at once on a client.RecipeCodeOnTest.cutFishcompares a zero-based month against 3 and 4: April and May. #
Troughs, rain, plants, traps
IsoFeedingTrough.checkWaterFromRain()fills nothing from rain. Its whole body drops an empty fluid container, and nothing in the game rain-fills a trough. The rain pattern is the rain barrel's: a GlobalObject system onEveryTenMinutesthat returns unlessRainManager.isRaining()and adds a fixed amount perisOutside()object. The trough does give water as a first-class value (getWater,addWater(FluidType, float)), a real FluidContainer,getMasterTrough()for multi-tile troughs and an appendable def table (FeedingTroughDef), and map troughs are retrofitted into real objects at chunk load. #- A method whose name states a behaviour is a hypothesis until its body is read. The trough and the plumbing were both assumed from their names first. #
- Vanilla's plant decay.
SFarmingSystem:EveryTenMinutesdrains one water point everyhourForWaterhours (default 5; 12 / 8 / 5 / 3 / 2 byPlantResilience); 49 of 64 crops declarewaterNeeded = 70, struggling belowwaterNeeded / 1.10and dying below/ 1.30; a pour adds 10. # - Traps.
TrapAnimalsis a plain appendable table;removeAnimalItemruns food arithmetic on every caught item with no guard, so a catchable item must bebase:food+CantEat = truewith aHungerChangethat makes the size multiplier exactly 1.0. The size roll isZombRand(minSize, maxSize), min..max−1. #
Odds and ends
Text, sound, vehicles
- Translations are JSON per category.
UI.json,Sandbox.json,ItemName.json,Tooltip.json,Recipes.json,Fluids.json,ContextMenu.json,IG_UI.jsonand so on, no BOM; a key is only found in the file its category names, so aContextMenu_*key inUI.jsonshows the raw key with no error.ItemName.jsonkeys are bareModule.Item,Recipes.jsonkeys bare recipe names. Vanilla's strings (UI_optionscreen_None, species, professions) are translated in all 29 locales; check before inventing a key. A machine translation goes wrong on SHORT LABELS first, and a count cannot agree with a placeholder in a language with cases; use the colon form (Ill: %1). # - Sound. Clips are
file =, notevent =. Positional long audio isgetWorld():getFreeEmitter(x, y, z)+playSoundImpl(sound, sourceObject)(a nil source crashes), and FMOD culls beyonddistanceMax, soisPlaying()false is indistinguishable from the track ending. Continuous attraction is periodicaddSound(...)at the source.testHelicopter()andendHelicopter()drive the vanilla flyover;getGameTime():setHelicopterDay()reschedules it. The welding animation and its sound are both namedBlowTorch; keep the sound handle so it can be stopped. # - New A file sound clip is at full volume out to 10 tiles unless it declares
distanceMin.GameSoundClipdefaults bothdistanceMinanddistanceMaxto 10 and a file clip uses FMOD's default inverse curve: full volume inside the minimum, then min ÷ distance, never reaching silence. The script grammar takesdistanceMinthough no vanilla script writes it; vanilla's own voices are bank events with their falloff designed elsewhere. # - Vehicles.
VehicleZoneDistributionis a shared Lua global; append.zone.vehicles["Base.X"] = { index = -1, spawnChance = N }, weights RELATIVE per zone, with per-zonespawnRate,baseVehicleQualityandchanceToPartDamage. Part animations are non-static model blocks withboneWeightinto the family FBX, driven byBaseVehicle.playPartAnim. # - New A car's key in the ignition is the Keys loot setting, not the zone key chance. The zone chance decides whether a key exists;
addKeyToWorldputs it in the ignition only on a roll against the loot setting and with an unlocked door, else the glove box, the ground, a nearby zombie or a container. Zone settings are copied into Java lazily, so Lua edits after first use are invisible to the engine. # - Teleporting. Client
setX/Y/Z+setLastX/Y/Z+faceLocation(there is nosetLx); after a teleportgetCurrentSquare()is nil until the chunk streams; teleport on the NEXT TICK, never inside a timed action'sperform();UIManager.FadeOut(playerNum, seconds)/FadeInin the two-argument form. A coordinate is not a place to stand: gate every teleport onIsoGridSquare.hasFloor(). On a server see Multiplayer: a long client teleport is a kick. #
Test worlds and debugging
- New A mod can launch a test world from the main screen two ways. The debug SCENARIOS panel (shown with
-debug) lists the globaldebugScenarios; a click runs the entry'ssetSandbox, sets the map, creates the world, then callsonStartfromOnNewGameandonLoadGSfromLoadGridsquare, with no character creation.DebugScenario.ForceLaunchplusforceLaunch = trueon an entry boots straight into it. Solo > Challenges takesaddChallenge(T)from anOnChallengeQueryhandler;T.gameMode,T.world(a map of its own is allowed), a spawn andT.OnInitWorld,T.AddPlayer,T.RemovePlayerandT.Render, all of which must exist; it works without-debug. Vanilla ships a cut challenge map,challengemaps/Studio, that nothing registers. # - The whole debug UI is plain Lua in
media/lua/client/DebugUIs/, one folder per feature, and the dev scenarios are Lua too. If a debug option breaks the client at launch,debug-options.initin the Zomboid folder holds the toggles. # - New The erosion system is reachable.
ErosionMain.getInstance()exposesgetConfig(),getSeasons()andgetEtick(); it drives vanilla's outdoor overgrowth on its own schedule with no per-square control. #
Publishing
- New The game's uploader replaces the Steam page with
workshop.txton every upload. It joins everydescription=line with a newline, trims each, and sends that plus a footer of ids; a one-line summary there is why pages "reset on updates". Keep the whole page inworkshop.txt. A description is measured after the browser's newline normalisation (CRLF), so a page near the 8,000 cap is longer than its file. # - New Workshop images.
preview.pngmust exist, open as PNG, be square at 256 or 512 and weigh at most 1,024,000 bytes. Steam stores an animated PNG whole but shows only its first frame; an animated GIF stays animated, and can only be set outside the game's uploader (a SteamCMDworkshop_build_itemnaming just the preview). A mod poster in the game's mod list is always drawn as a still. Steam's description[img]renders whitelisted hosts only. # - New Item pages are server-rendered if you ask for HTML. Steam content-negotiates: a request without
Accept: text/htmlgets a client-rendered shell with no description in it. An image host does the opposite: ask for HTML and it sends a page instead of the picture. The update history at/sharedfiles/filedetails/changelog/<id>is the authoritative record of what shipped. #
The map tools and measuring
- The map tools. TileZed, WorldEd and BuildingEd ship on Steam (2x config, 128×256 cells); a maintained fork adds native 256-cell projects, a working Lua console and expanded tilesets. The official authoring pipeline is a painted BASE image, a VEG image and a 10×-smaller greyscale zombie spawn map, one pixel per tile, exact RGB keys, converted with BMP to TMX and compiled with Generate Lots; images must be a multiple of 256. #
- Measuring. A checker that has never failed is an untested checker: negative-test every validator against a file you know is broken. A round-trip proves the codec, not the interpretation. A test that buries its subject where nothing is expected to change cannot prove the code reached it. A suspiciously round total (every option dead, every walk wrong) is nearly always the checker. A fix recorded in one tool does not protect the tool written beside it; when two tools decode one format, test them against each other. #
Where this came from. The IGMB layout and the toUInt level-prefix behaviour were read from the map tools' own published source (ingamemapwriterbinary.cpp and MapLevel::levelForLayer in the TileZed and WorldEd repositories). Cell sizes, the pyramid registration, the vanilla map.info examples, the chunk counts, the tile property censuses, the basement lot census and the animation numbers were measured from the game's own data files. Engine behaviour is described from reading the shipped code and from what happened in game while building mods on it; no game code is reproduced here, method and class names are given so a reader can look for themselves, and nothing on this page is official. Checked against Build 42.21.0, with the 42.22 pre-release compared on 5 November 2026 and 42.22.2, the stable build, on 9 November 2026; notes tagged New or Corrected changed since 24 September 2026. It will go stale. Corrections are welcome at the address below.
