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 (the data-action handlers);
  • 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 Artemis Space that 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.

flowchart TD init["init('#monogatari')"] --> registry["_setupRegistry(): Pandora's error, mount and unmount hooks"] registry --> storage["setupStorage(): a Space for the Storage setting's adapter"] storage --> setup["setup()"] setup --> prefs["Storage.get('Settings'): saved preferences, or the first run"] prefs --> define["Registry.register() every component: the custom elements upgrade"] define --> sw["register service-worker.js when served"] sw --> listeners["built-in listeners: start, open-screen, skip, auto-play…"] listeners --> setups["every component's and action's setup()"] setups --> bind["bind(): the data-action click handler, keyboard shortcuts,<br/>aspect ratio, every bind()"] bind --> localize["localize(): fill every data-string element"] localize --> inits["state({ label }), every init(), the autosave timer"] inits --> first["displayInitialScreen(): preload, then the splash label or the main screen"]

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 in index.html is plain unknown elements.
  • Registering after setup() behaves differently. registerComponent() defines the element at once and unregisterComponent() shows the engine:component:unregister_after_setup error; registerAction() still works, but the action’s setup(), bind() and init() 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.

flowchart TD statement["label()[step]"] --> kind{"What is it?"} kind -- "a function" --> fn["run it with the engine as this;<br/>advance unless it returned false"] kind -- "a string" --> replaceVars["replaceVariables(): _(key) translations and {{variables}}"] replaceVars --> split["split on spaces"] split --> matchString["the first action whose matchString(words) is true"] kind -- "an object" --> matchObject["the first action whose matchObject(statement) is true"] matchString --> instance["new Action(words or object)<br/>_setStatement(), _setCycle('Application'), setExtras()"] matchObject --> instance instance --> willApply["willApply()"] --> apply["apply()"] --> didApply["didApply()"] didApply --> advance{"{ advance }"} advance -- "true" --> next["next(): step + 1, run the next statement"] advance -- "false" --> wait["wait for the player"]

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():

  • state holds what is on screen now: state('images') lists the show image statements whose images are visible. Saves keep it, and a load rebuilds the screen from it.
  • history holds what is needed to go back: history('image') lists the show image statements 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

sequenceDiagram participant Player participant GameScreen as game-screen listener participant Engine as lifecycle.ts participant Actions as every action and component participant Action as the next statement's action Player->>GameScreen: click on the game screen GameScreen->>Engine: proceed({ userInitiated: true }) Engine->>Engine: shouldProceed(): no modal, not distraction-free,<br/>not block or _engine_block Engine->>Actions: static shouldProceed() on each Note over Actions: Dialog rejects while text is typing,<br/>and finishes the line instead Engine->>Engine: global('_engine_block', true) Engine->>Actions: willProceed() on each Engine->>Engine: next(): state({ step: step + 1 }) Engine->>Action: run(): willApply(), apply(), didApply() alt the statement throws Engine->>Engine: run() shows the error and remembers the position else Action-->>Engine: { advance: false } end Engine->>Engine: global('_engine_block', false)

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().

sequenceDiagram participant Player participant Engine as lifecycle.ts participant Actions as every action and component participant Action as the previous statement's action Player->>Engine: rollback() (Back button or left arrow) Engine->>Engine: AllowRollback on? at step 0, a jump to come back through? Engine->>Actions: shouldRollback() on each, then willRollback() Engine->>Engine: global('_engine_block', true), previous() Engine->>Engine: revert(): label()[step - 1]<br/>(at step 0, the statement that jumped here) alt a statement that failed when it ran Engine->>Engine: step over it: step - 1, revert() the one before else a plain function Engine->>Engine: refuse: step - 1, then proceed() runs the current statement again else an action Engine->>Action: prepareAction(cycle 'Revert'), willRevert(), revert(), didRevert() Action-->>Engine: { advance, step } Engine->>Engine: step true: state({ step: step - 1 }) Engine->>Engine: advance true: revert() the statement before it too end Engine->>Engine: global('_engine_block', false)

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

flowchart TD subgraph save ["Saving"] button["Save button or slot (save-screen, slot-container)"] --> saveTo["saveTo('SaveLabel', id, name)"] autosave["AutoSave timer"] --> saveToAuto["saveTo('AutoSaveLabel', id)"] saveTo --> object["{ history, state, storage }"] saveToAuto --> object object --> slot["Storage.set('Save_<id>', { name, date, image, game, screenshot? })"] end subgraph load ["Loading"] click["a slot on the load screen"] --> loadFromSlot["loadFromSlot('Save_<id>')"] loadFromSlot --> reset["resetGame(): every reset() and onReset(),<br/>history emptied, storage back to its structure"] reset --> read["Storage.get(): a v1.4.1 save is converted,<br/>a v2 save goes through src/migrations/"] read --> restore["state(), history(), storage()"] restore --> clamp["step past the label's end? move it back"] clamp --> onLoad["onLoad(): actions by loadingOrder, then components"] onLoad --> show["show the game screen, didLoadGame"] show --> rerun["run label()[step] again"] end

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 get data-screen from their tag and toggle the active class from their open state. 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 with document.createElement() in the action, given props with setProps(), and appended to the game screen. They aren’t in index.html. The engine itself creates alert-modal (src/engine/ui.ts), and type-writer wraps each character it types, except spaces, in a type-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.