Architecture
This page draws the engine’s moving parts and how they work together, at the level of functions and files. The diagrams follow the code at the v2.8.1 tag; How Each Part Works goes deeper into each part.
The engine object
Everything hangs from one object. src/monogatari.ts defines a class, Monogatari, with only static members, and src/browser.ts puts the class itself on the page as window.monogatari (and the whole module as window.Monogatari, so Monogatari.default is the same object). There are no instances: the class is the engine, and there is one per page.
The class holds:
- the registries:
_actions(classes, in matching order),_components(classes),_translations,_listeners(thedata-actionhandlers); - the game’s declarations:
_script,_characters,_assets,_settings,_preferences,_configuration; - the stores:
_state(what is on screen now, saved),_history(what was shown before, for reverting, saved),_storage(the game’s variables, saved),_globals(runtime flags, never saved); - the media players, the caches, and
Storage, the ArtemisSpacethat saves to the browser.
Most methods delegate to a module in src/engine/ and pass the class as the first argument: Monogatari.proceed() is proceed(this.asEngine(), …) from src/engine/lifecycle.ts. The modules type the engine as VisualNovelEngine, the interface in src/lib/types/Monogatari.ts.
Booting
dist/index.html loads engine/debug/debug.js, then engine/core/monogatari.js, then the game’s js/options.js, js/storage.js and js/script.js, which call monogatari.settings(), monogatari.storage(), monogatari.script() and the like, and last js/main.js, which calls monogatari.init('#monogatari') once the page is ready. Loading the bundle already registered every built-in: src/index.ts assigned _translations, _components and _actions when it ran.
The events willInit, willSetup, didSetup, willBind, didBind and didInit fire on the <visual-novel> element around those steps. With MultiLanguage and LanguageSelectionScreen both on, a first run shows the language selection screen before displayInitialScreen().
Two details shape everything after:
- Components are defined after the saved preferences are read, inside
setup(). Until then the<visual-novel>markup inindex.htmlis plain unknown elements. - Registering after
setup()behaves differently.registerComponent()defines the element at once andunregisterComponent()shows theengine:component:unregister_after_setuperror;registerAction()still works, but the action’ssetup(),bind()andinit()never run.
From a statement to an action
A script is an object of labels, each an array of statements. A statement is a string ('show scene beach with fadeIn'), an object ({ 'Choice': { … } }) or a function. state.label and state.step say which statement the game is on; monogatari.label() returns the current label’s array.
prepareAction() in src/engine/lifecycle.ts does the matching. It walks actions(), which is _actions without the experimental ones (unless the ExperimentalFeatures setting is on), so the order of _actions in src/index.ts decides ties, and Dialog, which takes any string, is last. A game’s registerAction() puts its action first.
run() wraps the three steps: it calls every action’s static beforeRun(), fires willRunAction, and after didApply() fires didRunAction and calls every afterRun(). A failure in willApply() or apply() stops the chain. Before calling next(), run() checks that label and step are still the ones it started with: if something else moved the game while the statement ran (a click during an asynchronous willApply(), as the comment in the code says), it doesn’t advance a second time.
An action records what it did in two stores, by convention, in didApply():
stateholds what is on screen now:state('images')lists theshow imagestatements whose images are visible. Saves keep it, and a load rebuilds the screen from it.historyholds what is needed to go back:history('image')lists theshow imagestatements in the order they ran. A rollback reads it to know what to undo or restore.
Nothing enforces the convention; every action implements it, and stage 4 of the learning path shows what breaks without it.
What a click does
The right arrow and the space bar call the same proceed() (bound in bind() with Mousetrap). Auto-play and skip call it from timers in src/engine/ui.ts with autoPlay: true or skip: true, so an action’s shouldProceed() can treat them differently. Any rejection in the chain stops the click; the listener logs the reason with debug.log(), visible at debug level 4 and above.
Clicks on buttons don’t move the game. bind() handles every click on a [data-action] element: it stops the event from propagating and calls runListener() with the element’s data-action value, which runs the listeners registered under that name (registerListener('save', …) and so on). The game screen’s listener sits on the same element, so stopping propagation doesn’t keep the click from it: it checks the clicked element itself, and ignores a click on or inside a data-action, data-delete or data-choice element.
Rollback, one revert at a time
v2 has no snapshots. Going back undoes statements one by one, in reverse, by calling each action’s revert().
So a rollback from a line of dialog reverts the statements before it until it reaches one whose didRevert() returns advance: false, usually the previous line of dialog, which shows itself again. Show::Image returns advance: true, so going back past an image removes it and keeps going.
What each revert() restores is up to the action. ShowImage.revert() removes the image and didRevert() drops it from history('image') and state('images'). Jump.revert() puts label and step back from history('jump'). A { 'Function': { 'Apply', 'Revert' } } statement runs its Revert. Nothing restores storage() on its own: a variable changed by a plain function statement stays changed, and revert() refuses to go back over a plain function at all.
If willRevert() or revert() throws (a Jump with no history, for instance), revert() runs the current statement again and the game stays where it was.
Saving and loading
saveTo() and loadFromSlot() are in src/engine/persistence.ts. A save is only written while global('playing') is true. The slot’s key is the SaveLabel or AutoSaveLabel setting, an underscore and the slot’s number, or the time in milliseconds when no number is given. image is the third word of state.background or state.scene, shown on the slot when there’s no screenshot.
On a load, each action rebuilds its part of the screen in its static onLoad(), usually by running the statements in its state again with didApply({ updateHistory: false, updateState: false }) so they aren’t recorded twice. Scene loads first (loadingOrder = -2), ShowCharacterLayer last (1). The load screen then runs the statement at the saved step again, which is what puts the dialog back.
Where the data goes depends on the Storage setting: setupStorage() picks Artemis’s LocalStorage, SessionStorage, IndexedDB or RemoteStorage adapter, or FileSystemStorage (src/lib/FileSystemStorage.ts) for desktop builds. The space is named after the game’s Name setting and versioned with its Version, which is what monogatari.upgrade() hooks into.
Components and the page
The page’s structure is in dist/index.html, not generated: a <visual-novel> element holds the screens (<main-screen>, <game-screen>, <load-screen>…), and <game-screen> holds <dialog-log>, <text-box> and <quick-menu>. Each is a custom element defined from a class in src/components/, rendered into the light DOM by Pandora.
- Screens extend
ScreenComponent: they getdata-screenfrom their tag and toggle theactiveclass from theiropenstate.showScreen('load')closes every screen and opens one. - Elements an action creates (
choice-container,message-modal,text-input,timer-display,centered-dialog,character-sprite,canvas-container) are made withdocument.createElement()in the action, given props withsetProps(), and appended to the game screen. They aren’t inindex.html. The engine itself createsalert-modal(src/engine/ui.ts), andtype-writerwraps each character it types, except spaces, in atype-character. - Components take part in the game’s flow through the same static methods as actions:
shouldProceed(),willProceed(),shouldRollback(),willRollback(),onStart(),onLoad(),onReset(). By default the static method asks every instance on the page.
monogatari.configuration() holds data some components render from: the main menu’s and quick menu’s buttons ('main-menu', 'quick-menu') and the credits. A game changes a menu by changing its configuration, which fires configurationElementUpdate::<name> and redraws the menu on screen.
The build
build.ts turns src/ and debug/ into four outputs, all committed: the browser bundle and stylesheet in dist/engine/core/, the debug module in dist/engine/debug/, the ES module in lib/, and the declarations in dist/types/. Building and Packaging covers each.