Repository navigation
Engine Overview
How the game is put together, as seen in the decompiled source tree: the libraries and what each is for, how the engine starts, what a frame does, and how the game layer sits on top. Everything here is read from matched code unless marked otherwise. Snapshot: main at commit a313ecb66. See Home for the reading guide.
Monolith Soft's code base is split into a reusable engine (the "monolib" family, shared with other Monolith games) and the game itself (BF2, the project code name that appears in the original source paths C:/Monolithsoft/BF2/prog/application/BF2/...). Each C++ namespace matches a folder:
| Layer | Namespace(s) | Where | What it is |
|---|---|---|---|
| Platform and tool library |
nn, nvn, nv
|
include/nn, include/nvn, include/nv.h
|
declarations of the Nintendo Switch OS/graphics interfaces the game calls (from the public nnheaders project) |
| Containers, math, memory |
mm, mm::mtl, mtl
|
src/libs/mcl, include/mm_*, include/mtl
|
FixedVector, FixedArray, FixedList, FixStr, Map, intrusive lists, bit flags, a Mersenne Twister, heaps and allocators; vector, box, sphere and cylinder math |
| Monolib engine |
ml and others |
src/libs/monolib_mm |
the work system, devices, files, windows and views, the scene and render system (dr, scn), the "cloud" system, the script VM (vm/yvm2), RNG and utilities |
| Graphics library | grlib |
src/libs/grlib |
a layer over the GPU API: pipelines, shaders, uniform blocks, samplers, display lists, vertex buffers, occlusion queries (files cglib_*) |
| Effects |
ptlib, effect
|
src/libs/eflib |
particle system: emitters, renderers, force fields, materials, noise |
| 2D layers | layer |
src/libs/layer |
the layout/UI renderer: layer objects, fonts, filters, animation |
| Animation |
anm, skd
|
src/libs/anmlib, src/libs/skdlib
|
skeletons, poses, blenders, mirror and retargeting, IK solvers; skd is a skeletal dynamics (secondary motion) library with a collision object and a solver |
| Collision | idcoli |
src/libs/idcoli |
ground and character collision: ground meshes and trees, moving ground objects, character, bone and phantom parameters, simple queries |
| Wind | wnd |
src/libs/wndlib |
wind simulation: world, areas, local and global wind, probes, an octree broad phase |
| Sound | ssd |
src/libs/ssd |
the sound system: audio file readers (AIFF, WAVE, SADF), banks, voices, groups, listener, effecter, streams |
| AI | ai |
src/libs/aiLib |
behaviour trees (selector, sequence, parallel, task, decorator nodes) and state machines (ai_state_fsm, ai_state_hfsm) |
| Scripting commands | skt |
src/libs/skt |
command manager and parameters |
| Framework | fw |
src/application/BF2/framework, include/fw
|
the game-independent application framework: managers for assets, models, animation, collision, effects, sound, script, BDAT and more (below) |
| Game | gf |
src/application/BF2/gf |
the game proper ("Gf" classes): data, objects, map, field, game rules, menus |
| Battle | btl |
src/application/BF2/battle |
battle system (see Battle-System) |
| Events | event |
src/application/BF2/event, plugin, rcha
|
the cutscene system (see Event-System) |
| Gimmicks | gmk |
src/application/BF2/gmk |
field objects that react to the player (see Field-Gimmicks) |
| UI | ui |
src/application/BF2/ui |
menu widget library (see Menus-and-UI) |
| Title / launch |
tl, apps
|
src/application/BF2/execute, apps
|
the title screen and the application launcher |
Folder names and namespaces do not always coincide: src/libs/monolib_mm holds the ml namespace (with grlib, cloud and others), and src/libs/mcl holds mm and mm::mtl. Role descriptions of the smaller libraries above are read from their file names and class lists, not from a deep reading of every function.
The figures per area are in progress/areas.json (the overall line is on Home); they count bytes of code in the executable that are matched. At the snapshot the biggest areas by code size are gf (4.3 MB of code, 78% matched), monolib_mm (1.7 MB, 48%), gmk (0.77 MB, 70%), event (0.73 MB, 73%), battle (0.57 MB, 23%) and framework (0.49 MB, 63%).
The game's build is not one object file per source file. The executable's function layout shows that some .cpp files were compiled together as one unit (a "unity" or "jumbo" build): functions of several files interleave or appear in the order of a single concatenated file. The repository reproduces this by #include-ing .cpp files into a host file: for example src/application/BF2/gf/data/gf_data.cpp includes gf_data_util.cpp, gf_data_item.cpp, gf_data_enemy.cpp, gf_data_blade.cpp, gf_data_driver.cpp and more in the order the game has them; gmk/gmk_manager.cpp includes the whole gimmick family (gmk_npc, gmk_enemy, gmk_tbox, gmk_event, ...); event/event.cpp includes the event system's data and parameter classes; gf/util/gf_item_util.cpp includes gf_equip_util.cpp, gf_shop_util.cpp and gf_recipe_orb_util.cpp. Comments next to the includes give the evidence (address ranges). It is a fact about how the original was compiled, not a design of the decompilation.
-
apps::FrameworkLauncher(src/application/BF2/apps/framework_launcher.cpp) is the root work object of the application.ml::WorkObjobjects form a tree and receivewkStandbyLogin,wkUpdate,wkTail,wkStandbyLogoutcalls.FrameworkLauncher::createWaitLoadResourceThreadandcreateAppletInitializeThreadstart two micro-threads (cooperative fibres ofml::MicroThread): one callsApplet::initializeResourceand waits untilfw::ResourceManager::isLoaded(); the other callsApplet::initialize, waits forApplet::isInitialized(), thenApplet::enter()andFramework::prepareEnter(). - The launcher's applet for the title is
tl::TitleApplet(src/application/BF2/execute/title/title_applet.cpp), a subclass offw::Applet. Itsupdatecallsgf::GfManager::update(info)and thenTitleMain::update(info); itspostUpdatecallsgf::GfManager::postUpdate(info); destruction callsTitleMain::destroyandgf::GfManager::destroy. In the matched code it is the only applet that drives the game manager, so the title screen is not a separate program: theTitleMainstate machine runs right after the game manager's update in the same applet. WhereGfManager::buildis called is not shown (TitleApplet::initialize,0x7100142c50, is not decompiled yet) [INFERENCE: probably there]. - The title application object is created by
tl::TitleApp::execute()with a title per language:Title,Title_english,Title_cn_simple,Title_cn_original(the strings are intitle_app.cpp; the English, simplified and traditional Chinese variants set a language-specific value on the object). -
fw::Framework::createManager(framework.cpp) creates the framework managers (next section).Framework::initializeManagerreturns true, and sets the state to "manager initialised" after initialising vibration data, onceManagerRegister::initialize()reports that every registered manager is initialised and BDAT slots 0 and 1 are enabled, the common effect pack is loaded and the sound manager has loaded its common and battle banks; it also updates the BDAT and resource managers on every call, so it is evidently polled until it succeeds [INFERENCE: the caller is not shown]. -
fw::Framework::createMemorySectioncreates four named memory sections at start:fw::SoundCommon(0x2600000bytes),fw::SoundPool(0x2800000),fw::SoundProc(0x4900000),fw::Movie(0x4400000).
Files in src/application/BF2/execute/title/. TitleMain runs states built on ai::State (the AI library's state machine): load, main screen, play game, play event, select event, select option, back to title and a debug "save continue" screen. Matched facts:
- On the main screen the game loads the default save slot (slot 22, see Save-Data) into a title buffer, checks its version word and, when the option record is invalid, writes a fresh one. It reads the story chapter from that save (
TitleMain::getChapterIdFromSaveData) and plays a title event chosen by chapter: a table of 12 entries, the chapter being clamped to 11 (TitleStateMainScreen::playTitleEvent), so the title scene changes as the story advances. - "Event theatre" is a title option that replays events: it builds a list of event ids and calls
GfManager::setupEventTheaterandstartEventTheater, which sets the exec state to "theatre". - Play game:
TitleStatePlayGamewaits for the title to request a state change; the actual start isGfManager::startGame(see Save-Data).
fw::Framework (src/application/BF2/framework/framework.cpp) owns one fw::Applet and a set of managers. Every manager derives from fw::ManagerObject, whose constructor registers it in fw::ManagerRegister (and the destructor removes it); ManagerRegister::initialize calls initialize() on each manager that is not yet initialised (setting an "initialised" flag when it returns true) and returns true when all are; finalize does the same in reverse order.
Framework::createManager creates, in this order: ManagerRegister, then LangUtil and RenderParam initialisation, AssetManager, CameraManager (only if bit 5 of the config flags is set), ModelManager, AnimationManager, DyanmicsManager (sic, the game's spelling), TransformManager, MessageManager, UpdatableObjectManager, ResourceManager, PadManager, BdatManager, ScriptManager, ColiManager (capacity 0x1000), NaviManager, LightManager, LayerSetManager, SoundManager, EffectManager, MovieManager, ParamManager, WindManager, SoundLayerManager, SensorManager. destroyManager deletes them in a different order. What each is for, from the files in framework/:
-
AssetManager,ResourceManager: asset and resource loading (asset_loader,resource_manager,localize_resource). -
ModelManager,AnimationManager,DyanmicsManager,TransformManager,LightManager: models, animation (control update, pose sampling, IK resolve jobs), secondary dynamics and wind forces, transforms, lights. -
ColiManager: collision objects and queries overidcoli(ColiCheck,ColiMoveObject,ColiCharactorProxy). -
NaviManager: navigation meshes (framework/navi,nvmsh_*). -
UpdatableObjectManager: all game objects that need an update call, filtered by layer. -
EffectManager: effect packs, casters, level-of-detail, clips. -
SoundManager,SoundLayerManager,MovieManager,MessageManager,PadManager,ScriptManager,SensorManager,ParamManager,BdatManager(BDAT-Data).
All of this is in Framework::update (matched, framework.cpp). The framework state must be between "manager initialised" and "finalizing" (isUpdating):
- Global managers first:
ResourceManager::update,ScriptManager::update,BdatManager::update; then the applet'supdate(only if the framework is in the "entered" state); thenColiManager::update,NaviManager::update,WindManager::update. -
Per layer, for each of the first 14 layers (
Framework::unknown001 = 14; up to 32 layers exist, each with its own speed and pause flag): if the layer is paused, onlyAnimationManager::applyPoseruns. Otherwise, in order:AnimationManager::updateControls,SensorManager::flushBeforeGame,UpdatableObjectManager::update(the game objects' own update),AnimationManager::samplePose,SensorManager::flushAfterAnimation,AnimationManager::solveIK,DyanmicsManager::updateColObjectsandupdateDynamics,AnimationManager::applyPoseandapplyAfterModifyPose,TransformManager::update,ModelManager::update,EffectManager::updateLayer,SoundLayerManager::update. So an object'supdateruns after animation controls advance and before the pose is sampled; IK, dynamics and the final transform follow. - A second pass over the layers runs
EffectManager::updateLayerPost(with a zero delta for paused layers). - Finally: an "object event 0" is broadcast to all layers (
UpdatableObjectManager::execEvent), thenEffectManager::update,CameraManager::update,MovieManager::update,MessageManager::update.
Other phases: Framework::beginFrame computes the update speed and per-layer speeds (a paused frame sets the delta to 0; the global speed unknown8c and per-layer speeds multiply the base delta 1 / frame rate) and updates the sound manager; preUpdate calls the applet's preUpdate; postUpdate calls the applet's postUpdate then ColiManager::postUpdate; tail calls the applet's tail (unless paused), UpdatableObjectManager::tail, the collision, navigation, layer-set and effect managers' tail. FrameworkLauncher::wkUpdate calls FrameworkLauncher::update() (not decompiled yet) and updates the launcher's micro-threads; wkTail calls Framework::tail and Scn::tail. [INFERENCE] FrameworkLauncher::update() is where beginFrame, preUpdate, update, postUpdate and endFrame are called; that is not shown.
Framework keeps up to 32 IPauseTrigger objects (constructed objects register themselves automatically); activate and deactivate call them on all. FrameworkLauncher::bkgHomeMenu(isOpen) is what the Switch HOME menu goes through: it pauses model double-buffering and effects (setDebugPause, EffectManager::setMasterPause) and deactivates the framework. Debug pause and single-step are supported (stepDebugPause).
gf::GfManager::initialize (src/application/BF2/gf/gf_manager.cpp) builds, in this order: GfEvent, game parameters, pad and sound-source bindings, GfPause, GfInfo, GfMemManager, GfDataManager (Save-Data, BDAT-Data), GfScriptManager, GfReqManager (a request/command queue), GfAssetManager, GfObjManager (game objects), GfSound, GfMapManager, GfGameManager, GfFieldManager, GfMenuManager, GfMovieManager, and finally btl::BattleManager. It waits (sleeping) until the menu manager is initialised.
Each frame GfManager::update(info) runs, in this order: GfInfo::apply, GfReqManager, GfAssetManager, GfObjManager, GfSound, GfMapManager, GfGameManager, GfFieldManager, btl::BattleManager::update (unless GfGameManager::isStopBattleSequence()), GfMenuManager::update, GfGameManager::updateParam. GfManager::postUpdate runs GfInfo::apply, then the map, field, battle, game, menu and object managers' postUpdate, and GfPause::update. At the end of update, the frame counter is incremented and the random number generator is advanced by a number of draws taken from the frame timer (see Blade-Creation, "Randomness").
gf::GfEvent is a broadcast bus: a manager derives from IGfEvent and registers (GfEvent::addEventCallback), then receives calls such as gevExecState, gevMapjump, gevBattleStart, gevBattleEnd, gevChangeScenarioFlag, gevReloadBdat, gevChangeWeather, gevLayerPause. Many cross-system interactions go through it rather than direct calls.
Exec modes. GfManager::setExec(state) stores a state and a set of flags taken from a table and notifies listeners (GfEvent::callExecState). The predicates show five states: debug (state 0, isExecModeDebug), the running game (state 1, set by startGame), advertising (state 2, set by execToAdvertize and TitleStateToTitle), theatre (state 3, isExecModeThater, set by startEventTheater) and tool (state 4, isExecModeTool); the flags answer isExecModeScenarioGame, isExecModeAdvertize and isExecKillPartyCreate. [INFERENCE] The mapping of state numbers to these names is read from the callers, not from names in the code. This is how the same code runs the real game, the title's event theatre and the demo loop.
ml::WorkCpu (src/libs/monolib_mm/source/work/work_cpu.cpp) manages the CPU threads and a job queue (allocJob, entryJobThread, wakeup, sync) and the render thread. The frame has these matched phases: beginFrame (resets the job counters, executes the pending display list, takes a time stamp), beginUpdate (wakes auto-executing groups), the update itself, endUpdate (marks the update done; when rendering is not threaded, syncs and calls swapBank), beginRender / thRender (the render thread runs WorkRootState::renderWork; in the "render after update" mode it spins until the update has finished or 0.1 s have passed), endRender (syncs the render and sub-CPU threads, waits until all job queues are empty) and endFrame (takes timings and, in threaded-render mode, calls swapBank). swapBank flips the even/odd bank flag (m_even) under a lock: engine state that both update and render use is double-buffered, and update writes one bank while render reads the other. WorkCpu::getFrameCount is the frame counter used by Framework::getFrameCount.
- Data: BDAT-Data, Save-Data
- Systems: Battle-System, Event-System, Field-Gimmicks, Drivers-Blades-Party, World-Progression, Menus-and-UI, Collision
- A worked example across data, menus and randomness: Blade-Creation