Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cataclysm: Bright Nights Docs

Welcome to the comprehensive reference for gameplay, modding, and development. Here you can…

Changelog Guidelines

PR title follows Convensional Commits for easier changelog generation. The format is one of:

<Type>: <PR subject>
<Type>(<Scope>, <Scope>, ...): <PR subject>

For Example, a PR title can be:

feat: add new mutation
feat(port): port mutation description from DDA

The PR title should be easy to understand for players at a glance. It’s recommended to use imperative and descriptive title (<verb> <noun>) like:

- feat: rebalancing some rifles
+ feat: nerf jam chance of m16 and m4

before: it’s hard to know whether they are buffed or nerfed, and which rifles are changed unless reading the full PR description. after: it’s easy to understand what exactly is changed from the title itself.

Type

The type is the first word in the PR title. They specify the type of change being made. When in doubt, use feat for new features, and fix for bugfixes. Here are some frequently used categories:

feat: Features

New features, additions, or balance changes.

fix: Bugfixes

Anything that fixes a bug or makes the game more stable.

refactor: Infrastructure

Make development easier without changing its behavior. For example:

  • C++ refactorings and overhaul
  • Json reorganizations
  • docs/, .github/ and repository changes
  • other development tools

build: Build

Improve build process:

  • more robust
  • easier to use
  • faster compile time

Others

  • docs: Documentation changes
  • style: Code style changes (whitespace, formatting, etc), usu. fixing JSON formatting.
  • perf: Performance Improvements
  • test: Adding missing tests or correcting existing tests
  • ci: Changes to CI process
  • chore: Other changes that don’t fit into any of the above categories
  • revert: Reverts a previous commit

Scopes

  1. Use them inside parentheses after the category to further narrow the scope of your PR.
  2. There are no limits to number of scopes.
  3. They are optional, but recommended.
  4. these are only guidelines, not rules. choose the best one for your PR freely!

<None>: General Features

For example,

Changes related to player:

  • player can do something new (e.g: mutations, skills)
  • something new can happen to the player (e.g: new disease)

New contents like:

  • new monsters
  • new map areas
  • new items
  • new vehicles
  • new doohickeys

Example PR title:

feat: strength training activity
feat: mutation system overhaul
feat: semi-plausible smokeless gunpowder recipe
feat(port): game store

lua: Changes to Lua API

Changes to the Lua API, such as:

Example PR title:

feat(lua): add dialogue bindings

UI: Interfaces

UI/UX changes like:

  • adding mouse support
  • adding/adjusting menus
  • change shortcuts
  • streamlining workflows
  • quality of life improvements

Example PR title:

feat(UI): More info about items dropped with bags
feat(UI): overhaul encumbrance UI

i18n: Internationalization

Improve translation and other languages support.

fix(UI,i18n): recipe names not translated unless learned

mods or mods/<MOD_ID>: Mods

  • changes contained within a mod
  • extends what is capable within a mod

Example PR title:

feat(mods/Magical_Nights): add missing owlbear pelts recipe
fix(mods): No Hope doesn't make the world freezing

balance: Balance Changes

Changes to game balance.

Example PR title:

feat(balance): Give moose pelts instead of hides

port: Ports someone else’s contribution

For example, from DDA or other forks.

Example PR title:

feat(port): game shop

Contributing

Want to help?

Help is appreciated, especially with:

  • Reporting bugs. Including ones inherited from DDA.
  • Identifying problems that aren’t bugs. Misleading descriptions, values that are clearly off compared to similar cases, grammar mistakes, UI wonkiness that has an obvious solution.
  • Making useless things useful or putting them on a blacklist. Adding deconstruction recipes for things that should have them but don’t, replacing completely redundant items with their generic versions (say, “tiny marked bottle” with just “tiny bottle”) in spawn lists.
  • Tileset work. I’m occasionally adding new objects, like the new electric grid elements, and they could use new tiles.
  • Balance analysis. Those should be rather in depth or “obviously correct”. Obviously correct would be things like: “weapon x has strictly better stats than y, but y requires rarer components and has otherwise identical requirements”.
  • Identifying performance bottlenecks with a profiler.
  • Code quality help.

How-to

Contributing to Cataclysm: Bright Nights is easy:

  1. Fork the repository here on GitHub.
  2. Make your changes.
  3. Send us a pull request.

Note

License

Cataclysm: Bright Nights is released under the Creative Commons Attribution ShareAlike 3.0 license. The code and content of the game is free to use, modify, and redistribute for any purpose whatsoever. See http://creativecommons.org/licenses/by-sa/3.0/ for details. This means any contribution you make to the project will also be covered by the same license, and this license is irrevocable.

Guidelines

There are a couple of guidelines we suggest sticking to:

  • Add this repository as an upstream remote.
  • Keep your main branch clean. This means you can easily pull changes made to this repository into yours.
  • Create a new branch for each new feature or set of related bug fixes.
  • Never merge from your local branches into your main branch. Only update that by pulling from upstream/main.

Code Style

C++

C++ style is enforced by the repository formatter helpers. Run just fmt before committing; see CODE_STYLE for details.

JSON

JSON files are formatted using custom formatter available in tools/format. Visit JSON Style Guide for details.

Markdown

Markdown files such as doc/ are formatted using deno’s built-in formatter. Run deno fmt anywhere to format markdown files. On VSCode, you can set following configuration to auto-format markdown files on save:

// .vscode/settings.json
{
  "[markdown]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "denoland.vscode-deno"
  }
}

Lua

Lua files are formatted using dprint’s built-in formatter. Run deno task dprint fmt anywhere to format Lua files. For details, see Lua Style Guide.

Translations

The translation of Cataclysm: BN is done using Transifex. Look at the translation project for an up-to-date list of supported languages.

For more information:

Documentation

Doxygen Comments

Extensive documentation of classes and class members will make the code more readable to new contributors. New doxygen comments for existing classes are a welcomed contribution.

Use the following template for commenting classes:

/**
 * Brief description
 *
 * Lengthy description with many words. (optional)
 */
class foo {

}

Use the following template for commenting functions:

/**
 * Brief description
 *
 * Lengthy description with many words. (optional)
 * @param param1 Description of param1 (optional)
 * @return Description of return (optional)
 */
int foo(int param1);

Use the following template for commenting member variables:

/** Brief description **/
int foo;

Guidelines for adding documentation

  • Doxygen comments should describe behavior towards the outside, not implementation, but since many classes in Cataclysm are intertwined, it’s often necessary to describe implementation.
  • Describe things that aren’t obvious to newcomers just from the name.
  • Don’t describe redundantly: /** Map **/; map* map; is not a helpful comment.
  • When documenting X, describe how X interacts with other components, not just what X itself does.

Building the documentation for viewing it locally

  • Install doxygen
  • doxygen doxygen_doc/doxygen_conf.txt
  • firefox doxygen_doc/html/index.html (replace firefox with your browser of choice)

Example Workflow

Setup your environment

(This only needs to be done once.)

  1. Fork this repository here on GitHub.

  2. Clone your fork locally.

$ git clone https://github.com/YOUR_USERNAME/Cataclysm-BN.git
# Clones your fork of the repository into the current directory in terminal
  1. Set commit message template.
$ git config --local commit.template .gitmessage
  1. Add this repository as a remote.
$ cd Cataclysm-BN
# Changes the active directory in the prompt to the newly cloned "Cataclysm-BN" directory
$ git remote add -f upstream https://github.com/cataclysmbn/Cataclysm-BN.git
# Assigns the original repository to a remote called "upstream"

For further details about commit message guidelines please visit:

Update your main branch

  1. Make sure your main branch is tracking upstream’s main not origin’s main by typing:
$ git branch --set-upstream-to upstream/main main
# makes your branch 'main' to track upstream's main.

To check whether your main is correctly pointing to upstream, type git remote -v and you should see something like

$ git remote -v

origin  [email protected]:YOUR_USERNAME/Cataclysm-BN.git (fetch)
origin  [email protected]:YOUR_USERNAME/Cataclysm-BN.git (push)
upstream        https://github.com/cataclysmbn/Cataclysm-BN.git (fetch)
upstream        https://github.com/cataclysmbn/Cataclysm-BN.git (push)

and when you type git branch -vv you should see [upstream/main] next to main branch like:

$ git branch -vv

# ...
* main   ed11439ee61 [upstream/main] feat: add more vending machines to marina (#7001)
# ...
  1. Make sure you are on your main branch.
$ git switch main
  1. Pull the changes from the upstream/main branch.
$ git pull --ff-only upstream main
# gets changes from "main" branch on the "upstream" remote

Note If this gives you an error, it means you have committed directly to your local main branch. Click here for instructions on how to fix this issue.

Make your changes

  1. Update your main branch, if you haven’t already.

  2. For each new feature or bug fix, create a new branch.

$ git switch --create new_feature
# Creates a new branch called "new_feature" and makes it the active branch
  1. Once you’ve committed some changes locally, you need to push them to your fork here on GitHub.
$ git push origin new_feature
# origin was automatically set to point to your fork when you cloned it
  1. Once you’re finished working on your branch, and have committed and pushed all your changes, submit a pull request from your new_feature branch to this repository’s main branch.

Note any new commits to the new_feature branch on GitHub will automatically be included in the pull request, so make sure to only commit related changes to the same branch.

Pull Request Notes

If you file a PR but you’re still working on it, please mark it as draft. This can help speed up our review process by allowing us to only review the things that are ready for it, and will prevent anything that isn’t completely ready from being merged in.

It is not required to solve or reference an open issue to file a PR, however, if you do so, you need to explain the problem your PR is solving in full detail.

AI-assisted pull requests

Caution

PR summary must be written by a human. PRs with AI-generated summary will be closed without warning. This is because

  1. those summaries are almost always of low quality, and hard to read for reviewers
  2. it usually indicates that the PR author vibe-coded the PR and doesn’t understand what the PR does.

If AI coding assistants contributed to a PR, the PR description must disclose the use of AI.

Each commit that was written, generated, or substantively revised with AI assistance must include an Assisted-by: trailer in the Linux kernel format described in AI Coding Assistants and Submitting patches.

Example:

Assisted-by: Claude:claude-3-opus coccinelle sparse

Closing issues using keywords

One more thing: when marking your PR as closing, fixing, or resolving issues, please include this somewhere in the description:

- {keyword} #{issue}

for example: - fixed #12345

keyword

{keyword} must be one of the following:

  • close, closes, closed
  • fix, fixes, fixed
  • resolve, resolves, resolved

issue

and {issue} is the number of the issue you’re closing after PR gets merged.

This would automatically close the issue when the PR is pulled in, and allows merges to work slightly faster.

closing multiple issues at once

- {keyword} #{issue}, {keyword} #{issue}

See https://help.github.com/articles/closing-issues-using-keywords for more.

Tooling support

Various tools are available to help you keep your contributions conforming to the appropriate style. See DEVELOPER_TOOLING for more details.

Advanced Techniques

These guidelines aren’t essential, but they can make keeping things in order much easier.

Using remote tracking branches

Remote tracking branches allow you to easily stay in touch with this repository’s main branch, as they automatically know which remote branch to get changes from.

$ git branch -vv
* main        xxxx [origin/main] ....
  new_feature xxxx ....

Here you can see we have two branches; main which is tracking origin/main, and new_feature which isn’t tracking any branch. In practice, what this means is that git won’t know where to get changes from.

$ git checkout new_feature
Switched to branch 'new_feature'
$ git pull
There is no tracking information for the current branch.
Please specify which branch you want to merge with.

In order to easily pull changes from upstream/main into the new_feature branch, we can tell git which branch it should track. (You can even do this for your local main branch.)

$ git branch -u upstream/main new_feature
Branch new_feature set up to track remote branch main from upstream.
$ git pull
Updating xxxx..xxxx
....

You can also set the tracking information at the same time as creating the branch.

$ git branch new_feature_2 --track upstream/main
Branch new_feature_2 set up to track remote branch main from upstream.

Note: Although this makes it easier to pull from upstream/main, it doesn’t change anything with regards to pushing. git push fails because you don’t have permission to push to upstream/main.

$ git push
error: The requested URL returned error: 403 while accessing https://github.com/cataclysmbn/Cataclysm-BN.git
fatal: HTTP request failed
$ git push origin
....
To https://github.com/YOUR_USERNAME/Cataclysm-BN.git
xxxx..xxxx  new_feature -> new_feature

Unit tests

There is a suite of tests built into the source tree at tests/. You should run the test suite after ANY change to the game source. CMake builds the test executable under the selected build preset’s tests/ directory. With no arguments it will run the entire test suite. With --help it will print a number of invocation options you can use to adjust its operation.

$ cmake --preset linux-slim
... configuration details ...
$ cmake --build --preset linux-slim --target cata_test-tiles
... compilation details ...
$ ./out/build/linux-slim/tests/cata_test-tiles
Starting the actual test at Fri Nov  9 04:37:03 2018
===============================================================================
All tests passed (1324684 assertions in 94 test cases)
Ended test at Fri Nov  9 04:37:45 2018
The test took 41.772 seconds

I recommend habitually invoking CMake build and test commands for your selected preset.

In-game testing, test environment and the debug menu

Whether you are implementing a new feature or whether you are fixing a bug, it is always a good practice to test your changes in-game. It can be a hard task to create the exact conditions by playing a normal game to be able to test your changes, which is why there is a debug menu. There is no default key to bring up the menu so you will need to assign one first.

Bring up the keybindings menu (press Escape then 1), scroll down almost to the bottom and press + to add a new key binding. Press the letter that corresponds to the Debug menu item, then press the key you want to use to bring up the debug menu. To test your changes, create a new world with a new character. Once you are in that world, press the key you just assigned for the debug menu and you should see something like this:

┌─────────────────────────────────────────────────────┐
│ Debug Functions - Manipulate the fabric of reality! │
├─────────────────────────────────────────────────────┤
│ i Info                                              │
│ Q Quit to main menu                                 │
│ s Spawning...                                       │
│ p Player...                                         │
│ t Teleport...                                       │
│ m Map...                                            │
└─────────────────────────────────────────────────────┘

With these commands, you should be able to recreate the proper conditions to test your changes. The BN wiki may have useful informations regarding debug menu.

Frequently Asked Questions

Why does git pull --ff-only result in an error?

If git pull --ff-only shows an error, it means that you’ve committed directly to your local main branch. To fix this, we create a new branch with these commits, find the point at which we diverged from upstream/main, and then reset main to that point.

$ git pull --ff-only upstream main
From https://github.com/cataclysmbn/Cataclysm-BN
 * branch            main     -> FETCH_HEAD
fatal: Not possible to fast-forward, aborting.
$ git branch new_branch main          # mark the current commit with a tmp branch
$ git merge-base main upstream/main
cc31d0... # the last commit before we committed directly to main
$ git reset --hard cc31d0....
HEAD is now at cc31d0... ...

Now that main has been cleaned up, we can easily pull from upstream/main, and then continue working on new_branch.

$ git pull --ff-only upstream main
# gets changes from the "upstream" remote for the matching branch, in this case "main"
$ git checkout new_branch

For more frequently asked questions, see the developer FAQ.

Updating documentation

To update the documentation site, you need to:

Browser

  1. Click the Suggest an edit pencil icon at the top right of the page.

  1. You will be redirected to the github page of the documentation site. You can edit and preview your changes here.

Note

.md in CONTRIBUTING.md stands for markdown files.

  1. Click the Commit changes... button on the top right corner to commit your changes. Make sure to
  • Write a short and descriptive Commit message
  • Check the Create a new branch for this commit and start a pull request checkbox.

  1. You will be redirected to the Comparing changes page. Click the Create pull request button to create a pull request.

  1. Click the Create pull request button to open a PR. It’s okay to leave the PR body empty for small changes.

Local development

Note

This section assumes you have some knowledge of git. You can learn it as you go.

To run the documentation site locally, install mdBook.

Setup dev server

(Cataclysm-BN) $ just docs

Open http://localhost:3000. The page reloads when you save a file.

Add a page

Add each new page to docs/en/SUMMARY.md. The sidebar shows only the pages listed there.

Automated page generation

Lua and CLI docs are generated automatically from the source code. To generate them, go to project root and run:

(Cataclysm-BN) $ deno task docs:gen

This regenerates docs/en/mod/lua/reference/lua.md and lua_annotations.lua (used for Lua IDE autocompletion).

License

  • By contributing to markdown files (including, but not limited to .md files), you agree to license your contributions under CC-BY-SA 3.0, the same license as the game.

  • By contributing to source code of documentation page (including, but not limited to .js and .toml files), you agree to license your contributions under AGPL 3.0.

Vehicle Tiles Display

Overview

This document describes the implementation plan for adding tile-based rendering to the vehicle interaction screen (veh_interact), making it easier to visualize vehicles during construction and modification.

Goal

Add graphical tile rendering to the vehicle construction screen as an alternative to ASCII display, improving usability especially for players unfamiliar with the ASCII representations.

Current Architecture

Vehicle Interaction Screen (src/vehicle/veh_interact.cpp)

The current display_veh() function (line 2284) uses ASCII rendering:

void veh_interact::display_veh()
{
    werase( w_disp );
    const point h_size = point( getmaxx( w_disp ), getmaxy( w_disp ) ) / 2;

    // Iterate over structural parts
    std::vector<int> structural_parts = veh->all_standalone_parts();
    for( auto &structural_part : structural_parts ) {
        const int p = structural_part;
        int sym = veh->part_sym( p );      // ASCII symbol
        nc_color col = veh->part_color( p ); // ncurses color

        const point q = ( veh->part( p ).mount + dd ).rotate( 3 );
        mvwputch( w_disp, h_size + q, col, special_symbol( sym ) );
    }
}

Key members in veh_interact:

  • catacurses::window w_disp - The vehicle display window
  • point dd - Current cursor offset (negative of cursor position)
  • int cpart - Currently selected part index
  • vehicle *veh - The vehicle being modified

Tile Rendering System

Core class: cata_tiles (src/cata_tiles.cpp)

Vehicle part rendering (draw_vpart() at line 3612):

bool cata_tiles::draw_vpart( const tripoint &p, lit_level ll, int &height_3d,
                             const bool ( &invisible )[5], int z_drop )
{
    const vpart_id &vp_id = veh.part_id_string( veh_part, z_drop > 0, part_mod );
    const int subtile = part_mod == 1 ? open_ : part_mod == 2 ? broken : 0;
    const int rotation = std::round( to_degrees( veh.face.dir() ) );
    const std::string vpname = "vp_" + vp_id.str();

    const tile_search_params tile = {vpname, C_VEHICLE_PART, empty_string, subtile, rotation};
    return draw_from_id_string( tile, p, bgCol, fgCol, ll, true, z_drop, false, height_3d );
}

Key parameters:

  • Tile ID: "vp_" + vpart_id.str() (e.g., "vp_frame", "vp_engine_v8")
  • Category: C_VEHICLE_PART
  • Subtile: 0 (normal), open_ (open door), broken (damaged)
  • Rotation: Degrees from veh.face.dir()

Template: Character Preview (src/character_preview.cpp)

This file demonstrates how to render tiles in a UI screen outside the main map:

class char_preview_adapter : public cata_tiles
{
public:
    static char_preview_adapter *convert( cata_tiles *ct ) {
        return static_cast<char_preview_adapter *>( ct );
    }

    void display_avatar_preview_with_overlays( const avatar &ch, const point &p, bool with_clothing ) {
        const tile_search_params tile { ent_name, C_NONE, "", corner, rotation };
        draw_from_id_string(
            tile, tripoint( p, 0 ), std::nullopt, std::nullopt,
            lit_level::BRIGHT, false, 0, true, height_3d );
        //                              ^ as_independent_entity = true
    }
};

Key patterns:

  1. Adapter class: Static cast to access protected draw_from_id_string
  2. Zoom control: tilecontext->set_draw_scale( zoom )
  3. Pixel positioning: Convert terminal units to pixels via termx_to_pixel_value()
  4. Independent rendering: as_independent_entity = true allows rendering outside map bounds

Implementation Plan

1.1 Create Vehicle Preview Adapter Class

File: src/vehicle/vehicle_preview.h / src/vehicle/vehicle_preview.cpp

#if defined(TILES)

class veh_preview_adapter : public cata_tiles
{
public:
    static veh_preview_adapter *convert( cata_tiles *ct ) {
        return static_cast<veh_preview_adapter *>( ct );
    }

    // Draw a single vehicle part at pixel position
    void draw_vpart_at_pixel( const vpart_id &id, const point &pixel_pos,
                               int part_mod, units::angle rotation, bool highlight );

    // Draw entire vehicle centered in a window
    void draw_vehicle_preview( const vehicle &veh, const catacurses::window &win,
                                point cursor_offset, int highlight_part );
};

struct vehicle_preview_window {
    catacurses::window w_preview;

    void prepare( int nlines, int ncols );
    void display( const vehicle &veh, point cursor_offset, int highlight_part ) const;
    void zoom_in();
    void zoom_out();
    void clear() const;

private:
    int zoom = 64;  // Default zoom level
    static constexpr int MIN_ZOOM = 16;
    static constexpr int MAX_ZOOM = 128;

    point calc_center_pixel() const;
};

#endif // TILES

1.2 Add Graphics Option

File: src/options.cpp

Add new option in add_options_graphics():

#if defined(TILES)
    add( "VEHICLE_EDIT_TILES", graphics, translate_marker( "Graphical vehicle display" ),
         translate_marker( "If true, the vehicle interaction screen will display vehicle parts using graphical tiles instead of ASCII symbols." ),
         true, COPT_CURSES_HIDE );
#endif

This option:

  • Only appears when compiled with TILES support
  • Hidden in curses-only builds (COPT_CURSES_HIDE)
  • Defaults to true (use tiles when available)

1.3 Modify veh_interact Class

File: src/vehicle/veh_interact.h

Add members:

#if defined(TILES)
    std::unique_ptr<vehicle_preview_window> tile_preview;
#endif

Add methods:

#if defined(TILES)
    void display_veh_tiles();  // New tile-based rendering
#endif

1.4 Implement display_veh_tiles()

File: src/vehicle/veh_interact.cpp

#if defined(TILES)
void veh_interact::display_veh_tiles()
{
    if( !tile_preview ) {
        tile_preview = std::make_unique<vehicle_preview_window>();
        tile_preview->prepare( getmaxy( w_disp ), getmaxx( w_disp ) );
    }

    tile_preview->display( *veh, dd, cpart );
}
#endif

void veh_interact::display_veh()
{
#if defined(TILES)
    if( is_draw_tiles_mode() && get_option<bool>( "VEHICLE_EDIT_TILES" ) ) {
        display_veh_tiles();
        return;
    }
#endif
    // ... existing ASCII implementation ...
}

1.5 Rendering Logic

In vehicle_preview_window::display():

void vehicle_preview_window::display( const vehicle &veh, point cursor_offset,
                                       int highlight_part ) const
{
    werase( w_preview );

    // Get window dimensions in pixels
    const int win_w_px = getmaxx( w_preview ) * termx_to_pixel_value();
    const int win_h_px = getmaxy( w_preview ) * termy_to_pixel_value();
    const point center_px = { win_w_px / 2, win_h_px / 2 };

    // Get tile dimensions at current zoom
    const int tile_w = tilecontext->get_tile_width();
    const int tile_h = tilecontext->get_tile_height();

    auto *adapter = veh_preview_adapter::convert( &*tilecontext );

    // Draw all vehicle parts
    for( int p : veh.all_standalone_parts() ) {
        const vehicle_part &part = veh.part( p );
        const point mount = part.mount;

        // Calculate position relative to cursor
        // Note: rotate(3) is used in ASCII mode for display orientation
        const point rel = ( mount + cursor_offset ).rotate( 3 );

        // Convert to pixel position (centered in window)
        const point pixel_pos = center_px + point( rel.x * tile_w, rel.y * tile_h );

        // Get part rendering info
        char part_mod = 0;
        const vpart_id &vp_id = veh.part_id_string( p, false, part_mod );
        const units::angle rotation = veh.face.dir();
        const bool is_highlighted = ( p == highlight_part );

        adapter->draw_vpart_at_pixel( vp_id, pixel_pos, part_mod, rotation, is_highlighted );
    }

    // Draw crosshair at center (current cursor position)
    draw_cursor_crosshair( center_px );

    wnoutrefresh( w_preview );
}

File Changes Summary

New Files

  • src/vehicle/vehicle_preview.h - Tile preview adapter class
  • src/vehicle/vehicle_preview.cpp - Tile preview implementation

Modified Files

  • src/vehicle/veh_interact.h - Add tile preview member
  • src/vehicle/veh_interact.cpp - Integrate tile display
  • src/options.cpp - Add VEHICLE_EDIT_TILES option
  • CMakeLists.txt - Add new source files

Options

  • VEHICLE_EDIT_TILES (Graphics) - Toggle graphical vehicle display (default: true)

Technical Considerations

Conditional Compilation

All tile-related code must be wrapped in #if defined(TILES):

#if defined(TILES)
#include "cata_tiles.h"
#include "sdltiles.h"
// ... tile code ...
#endif

Coordinate Systems

The vehicle screen uses multiple coordinate systems:

  1. Mount coordinates: Vehicle-local (origin at vehicle center)
  2. Screen coordinates: Terminal units (cols/rows)
  3. Pixel coordinates: SDL pixels (for tile rendering)

Conversion:

// Mount -> Screen (with cursor offset and rotation)
point screen = ( mount + cursor_offset ).rotate( 3 ) + window_center;

// Screen -> Pixel
point pixel = screen * point( termx_to_pixel_value(), termy_to_pixel_value() );

Performance

  • Cache tile lookups where possible
  • Only redraw on changes (use dirty flags)
  • Limit zoom levels to prevent excessive texture scaling

Fallback Behavior

  • If tiles fail to load, fall back to ASCII automatically
  • Curses-only build must still compile and work

Testing Checklist

  • Tiles render correctly for all vehicle parts
  • Zoom in/out works smoothly
  • Cursor position is clearly visible
  • Part highlighting works (selected part stands out)
  • VEHICLE_EDIT_TILES option appears in Graphics settings (tiles build only)
  • Disabling option falls back to ASCII display
  • Curses-only build still compiles (no TILES defined)
  • Performance is acceptable for large vehicles (50+ parts)
  • Open doors show correct “open” tile variant
  • Broken parts show correct “broken” tile variant
  • Vehicle rotation is displayed correctly

Compatibility with screen readers

There are people who use screen readers to play Cataclysm Bright Nights. In order for screen readers to announce the most important information in a UI, the terminal cursor has to be placed at the correct location. This information may be text such as selected item names in a list, etc, and the cursor has to be placed exactly at the beginning of the text for screen readers to announce it.

The recommended way to place the cursor is to use ui_adaptor. This ensures the desired cursor position is preserved when subsequent output code changes the cursor position. You can call ui_adaptor::set_cursor and similar methods at any position in a redrawing callback, and the last cursor position of the topmost UI set via the call will be used as the final cursor position. You can also call ui_adaptor::disable_cursor to prevent a UI’s cursor from being used as the final cursor position.

best practices

List of conventions used in the project, plus just plain good practices. Not rules per se, most of the codebase doesn’t meet those standards.

Naming

Good names:

  • Are not abbreviated if it could make meaning less obvious - count, not cnt
  • Are obvious from context - direction::left is clear, int rotate requires reading the documentation
  • Obey same conventions as nearby names - max_stored_kcal and stored_kcal, not max_stored_calories but stored_kcal or caloried_stored

snake_case is preferred for consistency with most of the project’s code.

Classes

  • Don’t add methods where a regular function in a namespace would work - crafting::consume_tools(tool_list,Character &), not Character.consume_tools(tool_list)
  • Don’t add both getters and setters if all they do is read/write a field - those are just disguised fields
    • Getters without (public) setters are OK
  • Use private where possible, public when not, protected only when there’s a clear reason for it

Types

  • Avoid pointers, instead use references, std::optional or even a function overload where possible
  • Avoid using std::pair and std::tuple in headers, instead create a named struct
  • Avoid using int or std::string where an enum class would work

File organization

Try to avoid including headers from other headers. This negatively impacts compilation times (both clean and partial builds), especially when the header in question is already big and widely used (such as character.h, avatar.h, map.h, game.h, item.h, npc.h, etc.), and frequently pollutes source files with definitions they have no need to know.

Some tips here:

  • Compiler doesn’t always need to know the whole definition of a class, a declaration may be enough. Say, if in character.h the vehicle class is only ever used for a function argument of type vehicle & - references are always of the same size regardless of what type they refer to, so compiler only needs to know there exists a type named vehicle, not its internal details. Adding class vehicle; declaration in character.h is enough in this case.
  • It’s possible to use pointer-to-implementation idiom for class members to remove the need for the definition, see src/pimpl.h for implementation and explanation. There are many usage examples in the codebase (mainly game.h), but the overall idea is to replace class member with a pointer, and only require definition when accessing the member through pointer. This incurs a tiny performance overhead, but it’s unnoticeable in most cases.
  • If you’re adding some functionality to a frequently included header, and that functionality is supposed to be used only in a few source files, consider creating a separate header instead. This way, your code won’t make it into dozens or hundreds of compilation units which don’t ever use it, and the compiler wouldn’t spend time to build it all these dozens or hundreds of unneeded times.
  • Including system and std headers is OK, most of them are precompiled anyway.
  • Including common “utility” headers (optional.h, calendar.h, coordinates.h, etc.) is OK, those are already extensively used in many headers and source files, so not including them makes too little impact to warrant the inconvenience.

C++ Code Style Guide

All C++ code in the project is styled. Run just fmt before pushing, or just fmt-cpp for C++-only changes. The helper uses astyle only for top-level src/*.cpp and src/*.h; most other C++ files use clang-format. Formatter-sensitive fixtures such as tools/clang-tidy-plugin/test/ are left unchanged.

Where astyle is still used, use version 3.1. Version 3.0.1 will disagree in only a few places, while Version 3.6.6 will disagree in nearly every file.

Blocks of code can be passed through astyle to ensure that their formatting is correct:

astyle --style=1tbs --attach-inlines --indent=spaces=4 --align-pointer=name --max-code-length=100 --break-after-logical --indent-classes --indent-switches --indent-preproc-define --indent-col1-comments --min-conditional-indent=0 --pad-oper --add-braces --convet-tabs --unpad-paren --pad-paren-in --keep-one-line-blocks

These options are mirrored in .astylerc, doc/CODE_STYLE.txt and msvc-full-features/AStyleExtension-Cataclysm-BN.cfg

For example, from vi, set marks a and b around the block, then:

:'a,'b ! astyle --style=1tbs --attach-inlines --indent=spaces=4 --align-pointer=name --max-code-length=100 --break-after-logical --indent-classes --indent-switches --indent-preproc-define --indent-col1-comments --min-conditional-indent=0 --pad-oper --add-braces --convet-tabs --unpad-paren --pad-paren-in --keep-one-line-blocks

See DEVELOPER_TOOLING.md for other environments.

Code Example

Here’s an example that illustrates the most common points of style:

auto foo( int arg1, int *arg2 ) -> int
{
    if( arg1 < 5 ) {
        switch( *arg2 ) {
            case 0:
                return arg1 + 5;
                break;
            case 1:
                return arg1 + 7;
                break;
            default:
                return 0;
                break;
        }
    } else if( arg1 > 17 ) {
        int i = 0;
        while( i < arg1 ) {
            printf( _( "Really long message that's pointless except for the number %d and for its "
                       "length as it's illustrative of how to break strings properly.\n" ), i );
        }
    }
    return 0;
}

Code Guidelines

These are less generic guidelines and more pain points we’ve stumbled across over time.

Prefer Immutable Values

  • Prefer immutable values and declare variables with const. Less moving parts mean more predictable code flow.

Use int or int64_t

  • Prefer int.
    • long in particular is problematic since it is not a larger type than int on some platforms we support.
    • Using integral value larger than 32 bits should be avoided. Use int64_t if it’s really necessary.
  • uint is also a problem, it has poor behavior when overflowing and should be avoided for general purpose programming.
    • If you need binary data, unsigned int or unsigned char are fine, but you should probably use a std::bitset instead.
  • float is to be avoided, but has valid uses.

Use Auto Keyword

Use auto keyword where it makes sense to do so, for example:

Trailing Return Types

  • Prefer trailing return types in function declarations. Long return types obscure function name and makes reading class methods a painful experience.
    class Bar;
    auto foo( int a ) -> int
    {
        const Bar &bar = some_function();
    
        return is_bar_ok( bar ) ? 42 : 404;
    }
    

Decltype Style Generic Functions

  • Use for decltype style generic functions
    template<typename A, typename B>
    - decltype(std::declval<A&>() * std::declval<B&>()) multiply(A a, B b)
    + auto multiply( A a, B b ) -> decltype( a * b )
    {
        return a*b;
    }
    

Aliasing for Long Iterator Declarations

  • Aliasing for long iterator declarations
      std::map<int, std::map<std::string, some_long_typename>> some_map;
    
    - std::map<int, std::map<std::string, some_long_typename>>::iterator iter = some_map.begin();
    + auto iter = some_map.begin();
    

Lambda Declarations

  • Required for Lambda declarations
    auto two_times = []( int a ) { return a * 2; };
    

Editor Type Hinting

  • Doesn’t otherwise sacrifice readability for expedience. Options for inlay type hinting are available in popular code editor such as vscode.

Avoid using namespace

  • Avoid using namespace for standard namespaces, because it pollutes the global namespace.

Avoid Member Methods

  • Avoid adding new member methods to classes unless required.
    // this function does not access non-public data members or member methods in the class, and thus can be made a free function
    - std::string Character::profession_description() const
    - {
    -     return prof->description( male );
    - }
    + auto profession_description( const Character &c ) -> std::string
    + {
    +     return c.prof->description( c.male );
    + }
    

Design document

See Game Balance and Lore for more detailed discussion coresponding to particular elements of the CDDA design document. This document covers the core philosphy of CBN.

One of the primary priorities of Cataclysm Bright Nights is fun.

Gameplay is more important than realism.

Realism isn’t inherently wrong. But it often comes at the expense of the new player experience. So the fundamentals of Game Design are a priority for Cataclysm Bright Nights.

Depth is preferable to complexity. But complexity is valuable as long as it isn’t overwhelming. See porting principles 3 and 5. Complexity generally becomes overwhelming when there are too many things to track at the same time to be able to tell what is important. So then you have to put in more work than you want to, to understand and filter the information down to what matters.

Generally a cap should be set for how many things are displayed or being dealt with simultaneously.

Complexity can be managed:

  • By having the most important info visible at a glance.
  • Making the most important menus more apparent and accessible.

General rules

There are six principles applied for content in general:

  1. Things that are useless should be either made useful or removed.

  2. Weird/wonky mechanics should be either reworked or removed. If there is value in retaining them, they should be clearly communicated to the player through UI.

  3. Each mechanic/item/monster/etc. should fill its own niche or have its own purpose, e.g. there shouldn’t be many different effects that penalize the character in the same way, or a dozen of guns that differ only in name and +1 to damage value. If such variety is desired, it should be relegated to mods.

3.1 Clutter benefits nobody. If these additions are just more bloat, mainline mod it. Examples are guns, books, food, drugs, morale items, furniture variants, clothes. Opt-out is preferred for additional bloat, and Opt-in for things that change game theme. e.g. Magical Nights, Aftershock, CRIT. When in doubt, ask.

  1. The gameplay should be less about pressing buttons and spending time in submenus and more about interacting with the surrounding world and progressing (achieving results).

  2. Different play styles should be balanced against each other, with their own upsides and downsides, so that you can actually choose a different play style and have it not suck just because “realistically, firearms are better than everything else”, but actually be playable and have a different feel to it.

  3. Rewards should be proportional to amount of effort spent on achieving them (e.g. weapon with harder craft recipe, or one that requires rarer components, or rarer ammo, should deal more damage).

Reasoning

  1. useless things only serve to clutter interfaces and item lists. increasing complexity for little value. Often strategically removing things can add more value than an addition.
  2. weirdness is a sign that things are unintuitive. Somethings benefit from not being obvious. But things that are too far from people’s expectations break the suspension of disbelief and require people to remember more disconnected elements.
  3. More items means more interactions, more depth, but finding what you want or understanding what items are good when we have 30 AK pattern rifles and 30 AR-15 platforms. Distributions are also cluttered badly from increased variants. This is bad for gameplay. A more believable world has 10,000 firearm variants, a more playable world has 10. If in doubt, Add your new items as a mod package.
  4. Sorting through complexity in menus isn’t fun. menus are only fun when there are meaningful choices or tradeoffs being made there. (I.E. what to equip, what to carry, what to loot first, etc.)
  5. and 6. are kind of common sense applications of prioritizing gameplay.

Removals and re-adding

Removal of content is a contentious problem in the community. To clarify official stance:

  • Content should not be kept inside the mainline on the basis of “it can be made good”. If it isn’t good now, it isn’t good. Shift it to a mainline mod, or improve/obsolete it.
  • Content should not be re-added to mainline on the basis of “it was present before”. Re-added content should be treated the same way new content is.
  • Content should not be “spared” from shifting/obsoletion by giving it forced updates that still don’t make it good enough. It should be treated like new content is.
  • This doesn’t cover arguments regarding content being thematic, liked etc., content can still be given extra “points” based on those. We want a level of flavor to the world.

In short, if it doesn’t feel like a good “default” experience, improve or shift to a mod.

Depth

Depth occurs primarily from interactions between mechanics and different elements of the game. For example, a common scenario is:

enemies spot you close, what do you do? The general options are: run away quickly.(Where to?) move to a good spot and fight them. kite them at location.

But the exact details change the preferable answer. those factors bring depth into that decision and interesting gameplay. As well as playing into resource management elements that are classic fun elements of roguelikes.

Some factors here are: damage you deal vs. enemy resilience and numbers (How long to kill? Can I kill?) How much cost do you take from a fight? How far/fast can I run vs. them (Speed + stamina) terrain nearby.(terrain speed slowdowns. damage terrain, chokepoints, etc.) other clusters of enemies. How much benefit is there to a fight? (zombie drops + nearby loot locations that are now safe)

Bloat

Bloat happens because we all want to add things that we personally like. But we can’t add everything.

The rule on bloat is to save it for opt-out/opt-in mods, or third party mods.

Bloat is when there is no meaningful reason to have something in the game, A gun is a gun. Clothes are clothes. We don’t want 30 variations of the same T-Shirt but colored differently inside the base game. Now you can’t find what you want.

There is a difference between bloat, and flavor. Flavor is adding a missing cooking recipe. We’ve historically not represented much European/African/Asian cooking. Some recipes exist, Such as lutefisk and haggis, but a lot of recipes are generic or common American fare.

Bloat is adding rechambered versions of firearms, example being Vektor variants. Another example would be adding 30 variations of the bible, or 30 novels. Put it in an expanded literature mod, or a religion mod in the case of religious books. We don’t need 20 types of beer, it just makes it harder to parse the comestibles menu. Put it in a (craft) brewery mod. We don’t need clothes whose only distinction is a different player sprite. Put it in a clothing/fashion mod.

Game Objects

Many of the things that physically exist within the game world are game objects(GO). Currently this only covers items, but creatures and vehicles are coming soon and then probably furniture at some point. GOs have a small common interface with methods like name and position that you can find in game_object.h. GOs use private constructors, this means your variables must always be references or pointers. Trying to assign a variable without a layer of indirection like that will cause a compile error. Likewise trying to copy one object over another will cause a similar error.

item& it_ref = ...; // Good
item* it_pointer; // Good

item it = ...; // Compile error
it_ref = other; // Compile error
*it_pointer = other; // Compile error

New GOs can be created via ::spawn static methods that return a detached_ptr to the newly created game object. A detached_ptr represents an object that does not currently exist in the game world. There can only be one detached_ptr to an object at a time (those who know std::unique_ptr will be familiar with this behavior). Functions that add an object to the world will require that you std::move in a detached_ptr. In general detached_ptrs must be std::move’d when they’re passed into a function. Note that you should never use any variable after it has been moved. Likewise functions that remove an object from the world will return a detached_ptr. This ensures that you can’t add the same thing to the world twice.

Functions that don’t add things to the world just accept normal pointers. You can turn a detached_ptr into a normal pointer by doing this. Note that you can use this to keep a valid pointer to something even after you std::move it, but you must do this before the std::move happens.

&*detached

And you can go the other way using this. Though note that it removes the object from the game world in the process and will cause errors if called on an object that isn’t in the game world.

detached_ptr<item> as_detached = normal_ptr->detach();

Trying to access an invalid detached_ptr (for instance one that has been std::move’d from) will cause a debugmsg and give you the null version of that object.

Safe References

Game objects support safe references. safe_reference<item> will refuse access to an object that has been destroyed or is outside of the reality bubble without losing track of it, and they can be saved and loaded. You must check them as a boolean (e.g. if( ref )) to see if they’re valid. Trying to access them when they’re not will cause debugmsgs and give you a null object instead. They have a small interface that lets you check if they’re destroyed or unloaded etc. If they were destroyed or unloaded this turn, they have a method that will allow you to access the object in a const fashion, for instance to display an error message.

If you’re moving objects around you need to use detached_ptrs, but otherwise when choosing which reference to use the most important thing to consider is how long you want to hold onto it. If you’re just using something temporarily, for instance most arguments and variables, you should use a normal reference or pointer. If you need to store it for longer you should use a safe reference and this means it can be easily stored in the save file. In the rare case that you do want to save it across turns but don’t want to store it in the save file, which means caches, there’s also a fast cache_reference<item>, which does last across turns but can’t be saved.

Game objects can sometimes be split into pieces or merged together. Item stacks are the main example of this but there are others like vehicles being split or dissoluted devourers merging. When a stack of items is split, the stack that stays in place is the one that safe references will follow. When they are merged safe references to either half of the merge will now point to the merge result.

Points, tripoints, and coordinate systems

This document describes the coordinate system in CBN, as well as covers the patterns contributors should use when touching coordinate-related code during the ongoing tripoint → typed coordinate migration. The goal is to eliminate raw tripoint/point from game-logic code, consolidate the legacy conversion functions, and make coordinate intent explicit at compile time.

Axes

The game is three-dimensional, with the axes oriented as follows:

  • The x-axis goes from left to right across the display (in non-isometric views).
  • The y-axis goes from top to bottom of the display.
  • The z-axis is vertical, with negative z pointing underground and positive z pointing to the sky.

Coordinate systems

CBN uses a variety of coordinate systems for different purposes. These differ by scale and origin.

The most precise coordinates are map square (ms) coordinates. These refer to the tiles you see normally when playing the game.

Three origins for map square coordinates are common:

  • Absolute coordinates, sometimes called global, which are a global system for the whole game, relative to a fixed origin.
  • Bubble coordinates, which are relative to the corner of the current “reality bubble”, or map roughly centered on the avatar. In local map square coordinates, x and y values will both fall in the range [0, MAPSIZE_X).
  • Vehicle coordinates, which are relative to the pivot point of the current vehicle, and rotate with it. This origin is special because it requires that you use the mount_to_* and *_to_mount functions for them to work correctly, as all other coordinate spaces do not require you to account for rotation like vehicles do.

There is a vehicle scale (veh), however this is only used for the mount functions and is currently the same as map square coordinates. It only serves to make it harder to make mistakes with vehicle coordinates.

The next scale is submap (sm) coordinates. One submap is 12x12 (SEEXxSEEY) map squares. Submaps are the scale at which chunks of the map are loaded or saved as they enter or leave the reality bubble.

Next comes overmap terrain (omt) coordinates. One overmap terrain is 2x2 submaps. Overmap terrains correspond to a single tile on the map view in-game, and are the scale of chunk of mapgen.

Then there’s memory map region (mmr) coordinates. These are currently only used in saving/loading submaps and you are unlikely to encounter them.

segment (seg) coordinates are used in a similar fashion to memory map regions, just a larger scale.

Largest are overmap (om) coordinates. One overmap is 180x180 (OMAPXxOMAPY) overmap terrains. Large-scale mapgen (e.g. city layout) happens one overmap at a time.

As well as absolute, bubble and vehicle coordinates, sometimes we need to use coordinates relative so some larger scale. For example, when performing mapgen for a single overmap, we want to work with coordinates within that overmap. This will be an overmap terrain-scale point relative to the corner of its containing overmap, and so typically take x and y values in the range [0,180).

Vertical coordinates

Although x and y coordinates work at all these various scales, z coordinates are consistent across all contexts. They lie in the range [-OVERMAP_DEPTH,OVERMAP_HEIGHT].

Vehicle coordinates

Each vehicle has its own origin point, which will be at a particular part of the vehicle (e.g. it might be at the driver’s seat). The origin can move if the vehicle is damaged and all the vehicle parts at that location are destroyed.

Vehicles use two systems of coordinates relative to their origin:

  • vehicle / mount coordinates provide a location for vehicle parts that does not change as the vehicle moves. It is the map square of that part, relative to the vehicle origin, when the vehicle is facing due east.

  • map square is the map square, relative to the origin, but accounting for the vehicle’s current facing.

Vehicle facing is implemented via a combination of rotations (by quarter turns) and shearing to interpolate between quarter turns. The logic to convert between vehicle mount and map square coordinates is complicated and handled by the vehicle::abs_to_mount() and vehicle::mount_to_bubble() families of functions.

Currently, vehicle mount coordinates do not have a z-level component, but vehicle map square coordinates do. The z coordinate is relative to the vehicle origin. This is likely to change, as we migrate to typed tripoints.

Point types

To work with these coordinate systems we have a variety of types. These are defined in coordinates.h. For example, we have point_abs_ms for absolute map-square coordinates. The three parts of the type name are dimension _ origin _ scale.

  • dimension is either point for two-dimensional or tripoint for three-dimensional.
  • origin specifies what the value is relative to, and can be:
    • rel means relative to some arbitrary point. This is the result of subtracting two points with a common origin. It would be used for example to represent the offset between the avatar and a monster they are shooting at.
    • abs means global absolute coordinates.
    • bub means relative to the corner of the reality bubble.
    • mnt means relative (and rotated to) the reference point of a vehicle.
    • sm means relative to a corner of a submap.
    • omt means relative to a corner of an overmap terrain.
    • om means relative to a corner of an overmap.
  • scale means the scale as discussed above.
    • ms for map square.
    • veh for vehicle mount coordinates (only relevant for the mnt origin).
    • sm for submap.
    • omt for overmap terrain.
    • seg for segment.
    • om for overmap.

Raw point types

As well as these types with origin and scale encoded into the type, there are simple raw point types called just point and tripoint. These can be used when no particular game scale is intended.

At time of writing we are still in the process of transitioning the codebase away from using these raw point types everywhere, so you are likely to see legacy code using them in places where the more type-safe points are more appropriate. Code should prefer to use the types which include their coordinate system where feasible.

The rule of thumb: If a tripoint or point represents a position in the world (or derivative reference frame) then it should be typed.

Converting between point types

Changing scale

To change the scale of a point without changing its origin, use project_to. For example:

point_abs_ms pos_ms = get_avatar()->abs_pos().xy();
point_abs_omt pos_omt = project_to<coords::omt>( pos_ms );
assert( pos_omt == get_avatar()->abs_omt_pos().xy() );

The same function project_to can be used for scaling up or down. When converting to a coarser coordinate system precision is of course lost. If you care about the remainder then you must instead use project_remain.

project_remain allows you to convert to a coarser coordinate system and also capture the remainder relative to that coarser point. It returns a helper struct intended to be used with std::tie to capture the two parts of the result. For example, suppose you want to know which overmap the avatar is in, and which overmap terrain they are in within that overmap.

point_abs_omt abs_pos = get_avatar()->abs_omt_pos().xy();
point_abs_om overmap;
point_om_omt omt_within_overmap;
std::tie( overmap, omt_within_overmap ) = project_remain<coords::om>( abs_pos );

That makes sense for two-dimensional point types, but how does it handle tripoint? Recall that the z-coordinates do not scale along with the horizontal dimensions, so z values are unchanged by project_to and project_remain. However, for project_remain we don’t want to duplicate the z-coordinate in both parts of the result, so you must choose exactly one to be a tripoint. In the example above, z-coodinates do not have much meaning at the overmap scale, so you probably want the z-coordinate in omt_within_overmap. That can be done as follows:

tripoint_abs_omt abs_pos = get_avatar()->abs_omt_pos();
point_abs_om overmap;
tripoint_om_omt omt_within_overmap;
std::tie( overmap, omt_within_overmap ) = project_remain<coords::om>( abs_pos );

The last available operation for rescaling points is project_combine. This performs the opposite operation from project_remain. Given two points where the origin of the second matches the scale of the first, you can combine them into a single value. As you might expect from the above discussion, one of these two can be a tripoint, but not both.

tripoint_abs_omt abs_pos = get_avatar()->abs_omt_pos();
point_abs_om overmap;
tripoint_om_omt omt_within_overmap;
std::tie( overmap, omt_within_overmap ) = project_remain<coords::om>( abs_pos );
tripoint_abs_omt abs_pos_again = project_combine( overmap, omt_within_overmap );
assert( abs_pos == abs_pos_again );

Changing origin

project_remain and project_combine facilitate some changes of origin, but only those origins specifically related to rescaling. To convert to or from bubble or vehicle coordinates requires a specific map or vehicle object.

Bubble Conversions - Use abs_to_bub / bub_to_abs

Never compute bubble coordinates by hand. Use the map’s conversion functions:

// Bad - manual arithmetic, easy to get wrong
tripoint local = p - tripoint( abs_sub.x() * SEEX, abs_sub.y() * SEEY, 0 );

// Good
tripoint_bub_ms bub = here.abs_to_bub( abs_ms_pos );
tripoint_abs_ms abs = here.bub_to_abs( bub_ms_pos );

Free-function overloads (no get_map(). needed at call sites) exist for all common typed variants:

abs_to_bub( tripoint_abs_ms )  →  tripoint_bub_ms
bub_to_abs( tripoint_bub_ms )  →  tripoint_abs_ms
abs_to_bub( tripoint_abs_sm )  →  tripoint_bub_sm
bub_to_abs( tripoint_bub_sm )  →  tripoint_abs_sm
// …and their 2D point_ variants

Avoid using these in performance critical locations, since the functions themselves have to fetch the map object. This is most pertinent to lighting, shadows, and other cache calculations. These make up most of the valid uses for bubble space, so think before you use them. Prefer keeping a local variable for the map before large iterations if possible.

Bubble-space z is always the absolute z-level.

“Bubble space” means coordinates measured from the top-left corner of the reality bubble, exactly as tripoint_sm_ms means “map squares from the top-left of this submap.” The x and y components are bubble-relative, but z is absolute because the bubble never shifts vertically (vertical_shift only updates abs_sub.z(); it does not reorganize the grid). Therefore:

bub.z() == abs.z()    // always true

This is enforced by abs_to_bub and bub_to_abs, which transform XY only. Do not add or subtract abs_sub.z() from z manually - it is always a no-op and will introduce bugs.

Point operations

We provide standard arithmetic operations as overloaded operators, but limit them to prevent bugs. For example, most point types cannot be multiplied by a constant, but ones with the rel origin can (it makes sense to say “half as far in the same direction”).

Similarly, you can’t generally add two points together, but you can when one of them has the rel origin, or if one of them is a raw point type.

For computing distances a variety of functions are available, depending on your requirements: square_dist, trig_dist, rl_dist, manhattan_dist. Other related utility functions include direction_from and line_to.

To iterate over nearby points of the same type you can use closest_points_first.

Deprecated → preferred reference

DeprecatedPreferred
here.bub_to_abs( tripoint )here.bub_to_abs( tripoint_bub_ms( p ) )
here.abs_to_bub( tripoint )here.abs_to_bub( tripoint_abs_ms( p ) )
ms_to_sm_copy( p )project_to<coords::sm>( p )
sm_to_ms_copy( p )project_to<coords::ms>( p )
sm_to_omt_copy + sm_to_omt_remainproject_remain<coords::omt>( p )
omt_to_ms_copy( omt ) + offsetproject_combine( omt, offset )

Available Template Helpers

All of the following are implemented and available for use:

HelperLocationPurpose
project_to<S>(p)coordinates.hScale conversion, preserves origin
project_remain<S>(p)coordinates.hQuotient + remainder decomposition
project_combine(coarse, fine)coordinates.hRecombine quotient + remainder
abs_to_bub(p) / bub_to_abs(p)map/map.h (free functions)Bubble ↔ absolute
p.reinterpret_as<T>()coordinates.hExplicit type-pun during migration scaffolding only
IsCoordPoint<T> conceptcoordinates.hConstrains templates to typed coordinates
rl_dist(a, b) typed overloadline.hAccepts any same-type coord_point pair
ch.bub_pos() / ch.abs_pos()creature.hTyped creature position accessors

reinterpret_as<T>() is a migration scaffold: it makes unsafe origin-punning explicit and grep-able. A call site that still uses it is not fully migrated.

Absolute vs Bubble Space

Prefer absolute space for game logic when the conversion is straightforward. Bubble space is appropriate for:

  • Rendering and display code
  • Functions that are inherently tied to the reality bubble e.g. map::shift
  • Code where converting is non-trivial and the change is out of scope

Legacy code leaned on the reality bubble as a convenient local frame. When you encounter such code and the fix is a simple swap, make it. If it requires broader surgery, move on.

User Interface

Cataclysm: Bright Nights uses ncurses, or in the case of the tiles build, an ncurses port, for user interface. Window management is achieved by ui_adaptor, which requires a resizing callback and a redrawing callback for each UI to handle resizing and redrawing. Details on how to use ui_adaptor can be found within ui_manager.h.

Some good examples of the usage of ui_adaptor can be found within the following files:

  • query_popup and static_popup in popup.h/cpp
  • Messages::dialog in messages.cpp

Failed to create glyph error

There were similar issues reported in BN and DDA for MSYS Windows builds and some Mac builds. https://github.com/CleverRaven/Cataclysm-DDA/issues/50115

It’s something in newer versions of SDL2/freetype not agreeing with with our default font, and apparently vcpkg updated both of them 20 and 9 days ago respectively (https://github.com/microsoft/vcpkg/pull/19509, https://github.com/microsoft/vcpkg/pull/19284). I’m using month old vcpkg, and there’s no glyph issue, so that looks to me like the root of the problem.

Unfortunately, vcpkg being Microsoft’s official C++ library manager does not allow you to install libraries of some specific version. Thus, you have two options:

  1. Grab an older version of vcpkg, from before the updates. I’ve installed from this one, it should work: https://github.com/microsoft/vcpkg/tree/6bc4362fb49e53f1fff7f51e4e27e1946755ecc6

  2. Open config/fonts.json and remove Terminus.ttf entries. I don’t remember why we’re not using unifont by default, but if you’re not planning on working on i18n/fonts code, it shouldn’t affect you beyond visually.

Formatting & Linting

This guide explains how to format and lint code in Cataclysm: Bright Nights.

Quick Reference

ScopeToolCommand
Staged filesall formattersjust fmt
All filesall formattersjust fmt --all
C++ (.cpp/.h)astyle/clang-formatjust fmt-cpp
JSONjson_formatterjust fmt-json
Markdown/TSdeno fmtjust fmt-docs
Luadprintjust fmt-lua

Automated Formatting

Pull requests are automatically formatted by autofix.ci. If your code has style violations, a commit will be pushed to fix them.

Tip

To avoid merge conflicts after autofix commits, either:

  1. Run git pull to merge the autofix commit, then continue working
  2. Format locally before pushing, then git push --force if needed

C++ Formatting

Top-level src/*.cpp and src/*.h files use astyle. Most other C++ files use clang-format. Formatter-sensitive fixtures such as tools/clang-tidy-plugin/test/ are left unchanged.

# Install formatters (Ubuntu/Debian)
sudo apt install astyle clang-format

# Install formatters (Fedora)
sudo dnf install astyle clang-tools-extra

# Install formatters (macOS)
brew install astyle clang-format

Using the helper

just fmt-cpp
# or, for all staged file types
just fmt

If you already have a CMake build tree with bash available, cmake --build <build-dir> --target format calls the same C++ helper. The style configurations are in .astylerc and .clang-format at the repository root.

JSON Formatting

JSON files are formatted with json_formatter, a custom tool built from the project source.

Using the script

just fmt-json
# or
build-scripts/format-json.sh

The script builds json_formatter in out/build/json-format and formats JSON files. It does not require a configured game build or a CMake preset. Override the helper build directory with CATA_JSON_FORMAT_BUILD_DIR if needed.

Note

The data/names/ directory is excluded from formatting because name files have special formatting requirements.

JSON Syntax Validation

Before formatting, you can validate JSON syntax:

build-scripts/lint-json.sh

This runs Python’s json.tool on all JSON files to catch syntax errors.

Markdown & TypeScript Formatting

Markdown and TypeScript files are formatted with Deno.

# Install Deno
curl -fsSL https://deno.land/install.sh | sh

# Format Markdown and TypeScript
deno fmt

Lua Formatting

Lua files are formatted with dprint via Deno.

# Format Lua files
deno task dprint fmt

Dialogue Validation

NPC dialogue files have additional validation:

tools/dialogue_validator.py data/json/npcs/* data/json/npcs/*/* data/json/npcs/*/*/*

Pre-commit Workflow

Install the optional pre-commit hook with prek:

prek install
# or
just hooks-setup

When you commit, the hook runs just fmt: Deno and dprint run normally, while C++ and JSON formatters run only on staged created/updated files. Formatted staged files are re-added so the commit includes the formatted result.

To run the same formatting manually against staged files:

just fmt

Before committing without the hook, run these checks:

# Format staged files
just fmt

# Format all formattable files
just fmt --all

CI Integration

The CI pipeline runs these checks automatically:

  1. JSON syntax validation - build-scripts/lint-json.sh
  2. JSON formatting - build-scripts/format-json.sh
  3. Dialogue validation - tools/dialogue_validator.py

If any check fails, the build will fail. Use the commands above to fix issues locally before pushing.

Editor Integration

VS Code

Use the repository helper for C++ and the Deno extension for Markdown/TypeScript:

  • C++: run just fmt-cpp
  • Deno: Deno

Visual Studio

Install the formatters once from PowerShell. LLVM provides clang-format and clang-tidy.

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
irm get.scoop.sh | iex
scoop install llvm astyle
clang-format --version
clang-tidy --version
astyle --version

If Scoop is already installed, run only scoop install llvm astyle. If any version command is not found, close and reopen PowerShell and Visual Studio so they reload PATH.

After installing the tools:

  1. Open the repository folder in Visual Studio as a CMake project.
  2. Configure CMake. If Visual Studio already configured the project before installing the formatters, reconfigure the CMake cache.
  3. Open View > Other Windows > CMake Targets View.
  4. Build the format target before committing.

Visual Studio’s normal Format Document command does not run repository style. Run just fmt-cpp in a terminal; the CMake format target is a wrapper for environments with bash available.

Vim/Neovim

Use the helper instead of calling astyle or clang-format directly:

autocmd BufWritePre *.cpp,*.h !just fmt-cpp %
autocmd BufWritePre *.md,*.ts !deno fmt %

Troubleshooting

“json_formatter not found”

Run the JSON formatter script. It configures and builds the formatter helper automatically:

build-scripts/format-json.sh

C++ formatter not found

Make sure astyle and clang-format are installed and in your PATH:

# Check if formatters are available
which astyle
which clang-format

# Install if missing (Ubuntu/Debian)
sudo apt install astyle clang-format

Then rerun:

build-scripts/format-cpp.sh

C++ formatters produce different results

Use the repository helper from the repository root so each file goes through the right formatter:

just fmt-cpp

Items Cookbook

Here are some common tasks that you might want to do with items. For more on item(game objects), check here.

Processing nested items

Top-level map and vehicle active item caches track the outer item that is placed in the world. If a nested item needs per-turn or periodic processing, its parent containers must also report that they need processing so the outer item stays in the cache.

Use the normal item and item_contents mutation APIs when changing active state, processing-related flags, or contents. These paths invalidate the cached processing-item list up the parent chain and resync the placed top-level item with the map or vehicle active cache when needed. Avoid changing item_tags, item_contents storage, or active state directly unless the caller also invalidates the processing cache upward.

Processing cadence is inherited from the fastest processing child. A food container with an active tool inside it must keep the active tool’s one-turn cadence even though food-only containers can use a slower rot cadence. If a mutation can change item::processing_speed(), re-adding the outer item to the active cache moves an existing reference to the correct speed queue instead of leaving stale entries behind.

When processing contents recursively, take a mutation-safe snapshot of contents.processing_items() before detaching or processing children. Preserve parent container context such as sealed or preserving containers while processing nested food so rot behavior remains unchanged.

Moving items from one tripoint to another

auto move_item( map &here, const tripoint &src, const tripoint &dest ) -> void
{
    map_stack items_src = here.i_at( src );
    map_stack items_dest = here.i_at( dest );

    items_src.move_all_to( &items_dest );
}

C++20 Range Compatibility

To enable std::ranges algorithms, iterators must satisfy std::default_initializable, std::copyable (assignable), and provide postfix increment.

Guidelines

  • Enable Copy Assignment: Replace const Container& members with const Container*. References delete the assignment operator; pointers do not.
  • Enable Default Construction: Provide iterator() = default and initialize member pointers to nullptr.
  • Define Concepts: Add using iterator_concept = std::forward_iterator_tag;.
  • Enforce Trailing Return Types: Convert signatures to auto fn() -> Type.
  • Implement Postfix Increment: Required by standard concepts (it++).
  • Modernize Comparisons: Implement operator==. Remove operator!= (synthesized automatically). Implement operator<=> only for Random Access iterators.
  • Utilize View Interface: Inherit from std::ranges::view_interface to automatically generate empty(), front(), back(), and data().

Refactoring Diff

- template<typename Tripoint>
- class tripoint_range
+ template<typename Tripoint>
+ class tripoint_range : public std::ranges::view_interface<tripoint_range<Tripoint>>
  {
-         const tripoint_range &range;
+         const tripoint_range *range = nullptr;

      public:
+         using iterator_concept = std::forward_iterator_tag;

-         point_generator( const Tripoint &_p, const tripoint_range &_range )
-             : p( _p ), range( _range ) {
-         }
+         point_generator() = default;
+         point_generator( const Tripoint &_p, const tripoint_range *_range )
+             : p( _p ), range( _range ) {}

-         point_generator &operator++() {
+         auto operator++() -> point_generator& {
              // ... logic ...
              return *this;
          }

+         auto operator++(int) -> point_generator { auto tmp = *this; ++(*this); return tmp; }

-         const Tripoint &operator*() const {
-             return p;
-         }
+         auto operator*() const -> reference { return p; }

-         bool operator!=( const point_generator &other ) const {
-             const Tripoint &pt = other.p;
-             return traits::z( p ) != traits::z( pt ) || p.xy() != pt.xy();
-         }
-
-         bool operator==( const point_generator &other ) const {
-             return !( *this != other );
-         }
+         // C++20 synthesizes != from ==.
+         // If Tripoint supports ==, use default. Otherwise implement manual ==.
+         auto operator==( const point_generator &rhs ) const -> bool { return p == rhs.p; }
  };

Verification

Add static assertions to ensure compliance.

static_assert( std::forward_iterator<tripoint_range<Tripoint>::iterator> );
static_assert( std::ranges::forward_range<tripoint_range<Tripoint>> );

Recording terminal captures

To show a bug or a fix in a PR, record the curses build with asciinema. Then turn the recording into a GIF with just term-capture. PR #11041 has a before and an after capture.

Requirements

  • the curses build: cmake --preset linux-curses and cmake --build --preset linux-curses --target cataclysm-bn (see CMake)
  • asciinema to record
  • agg to render the recording
  • uv to run just term-capture

Record

  1. Make the terminal small, for example 120 columns and 40 rows. The file is smaller with a small terminal.

  2. Make a directory outside the repository for the saves, the settings and the recordings:

    mkdir -p ~/bn-capture
    
  3. From the repository root, start the game in asciinema:

    asciinema rec -c "out/build/linux-curses/src/cataclysm-bn --userdir $HOME/bn-capture/ --configdir $HOME/bn-capture/config/" ~/bn-capture/before.cast
    

    With --userdir and --configdir, the game uses new saves and settings and does not change your own.

  4. Use the debug menu to set up the scene, then do the steps that show the bug.

  5. Quit the game from its menu.

  6. Record ~/bn-capture/after.cast the same way with the fixed build.

Make the GIF

Run the just term-capture commands from the repository root.

just term-capture render ~/bn-capture/before.cast ~/bn-capture/before.gif

The GIF plays at 2x speed. Pauses longer than 1 s become 0.5 s.

Drag the GIF into the PR description or a comment. The GIF must be 10 MB or smaller.

Add captions

To cut the game start and show a caption for each step:

  1. Save each frame of the GIF as a PNG file:

    just term-capture frames ~/bn-capture/before.gif ~/bn-capture/before-frames/
    
  2. Open the PNG files in an image viewer. Find the first frame of each step and the last frame to keep. The frame number is the PNG file name.

  3. Write the steps to ~/bn-capture/scenes.json. color is optional and can be red or green.

    [
      { "start": 40, "caption": "enable UPS charging" },
      { "start": 67, "caption": "next turn: invalid ammo error", "color": "red" }
    ]
    
  4. Make the captioned GIF. Give the number of the last frame to keep with --last:

    just term-capture encode ~/bn-capture/before.gif ~/bn-capture/before-captioned.gif --scenes ~/bn-capture/scenes.json --last 80
    

    The GIF starts at the first step and ends at the --last frame. The last frame of each step stays on screen for 2 s, and the last frame of the GIF stays for 6 s.

Testing Cataclysm

When you make Cataclysm from source, an executable tests/cata_test is built from test cases found in the tests/ directory. These tests are written in the Catch2 framework.

Run tests/cata_test --help to see the available command-line options, and/or consult the Catch2 tutorial for a more thorough introduction.

Playtesting pull requests

Use just playtest [--os OS] <PR URL> to download and launch an existing PR build without compiling locally. The tooling guide covers prerequisites, supported platforms, artifact selection, and save locations.

Showing a fix in a pull request

To show a bug or a fix in the curses build as a GIF, see Recording terminal captures.

Guidelines

When creating tests, ensure that all objects used (directly or indirectly) are fully reset before testing. Several tests have been rendered flaky by properties of randomly generated objects or interactions between tests via global objects (often the player object). As a general guideline, test cases should be standalone (one test should not rely on the output of another).

When generating objects with json definitions, use REQUIRE statements to assert the properties of the objects that the test needs. This protects the test from shifting json definitions by making it apparent what about the object changed to cause the test to break.

Writing test cases

You can choose several ways to organize and express your tests, but the basic unit is a TEST_CASE. Each test .cpp file should define at least one test case, with a name, and optional (but strongly encouraged) list of tags:

TEST_CASE( "sweet junk food", "[food][junk][sweet]" )
{
    // ...
}

Within the TEST_CASE, the Catch2 framework allows a number of different macros for logically grouping related parts of the test together. One approach that encourages a high level of readability is the BDD (behavior-driven-development) style using GIVEN, WHEN, and THEN sections. Here’s an outline of what a test might look like using those:

    TEST_CASE( "sweet junk food", "[food][junk][sweet]" )
    {
        GIVEN( "character has a sweet tooth" ) {

            WHEN( "they eat some junk food" ) {

                THEN( "they get a morale bonus from its sweetness" ) {
                }
            }
        }
    }

Thinking in these terms may help you understand the logical progression from setting up the test and initializing the test data (usually expressed by the GIVEN part), performing some operation that generates a result you want to test (often contained in the WHEN part), and verifying this result meets your expectations (the THEN part, naturally).

Filling in the above with actual test code might look like this:

    TEST_CASE( "sweet junk food", "[food][junk][sweet]" )
    {
        avatar dummy;
        dummy.clear_morale();

        GIVEN( "character has a sweet tooth" ) {
            dummy.toggle_trait( trait_PROJUNK );

            WHEN( "they eat some junk food" ) {
                item necco( "neccowafers" );
                dummy.eat( necco );

                THEN( "they get a morale bonus from its sweetness" ) {
                    CHECK( dummy.has_morale( MORALE_SWEETTOOTH ) >= 5 );
                }
            }
        }
    }

Let’s look at each part in turn to see what’s going on. First, we declare an avatar, representing the character or player. This test is going to check the player’s morale, so we clear it to ensure a clean slate:

avatar dummy;
dummy.clear_morale();

Inside the GIVEN, we want some code that implements what the GIVEN is saying - that the character has a sweet tooth. In the game’s code, this is represented with the PROJUNK trait, so we can set that using toggle_trait:

GIVEN( "character has a sweet tooth" ) {
    dummy.toggle_trait( trait_PROJUNK );

Now, notice we are nested inside the GIVEN - for the rest of the scope of that GIVEN, the dummy will have this trait. For this simple test it will only affect a couple more lines, but when your tests become larger and more complex (which they will), you will need to be aware of these nested scopes and how you can use them to avoid cross-pollution between your tests.

Anyway, now that our dummy has a sweet tooth, we want them to eat something sweet, so we can spawn the neccowafers item and tell them to eat some:

WHEN( "they eat some junk food" ) {
    dummy.eat( item( "neccowafers" ) );

The function(s) you invoke at this point are often the focus of your testing; the goal is to exercise some pathway through those function(s) in such a way that your code will be reached, and thus covered by the test. The eat function is used as an example here, but that is quite a high-level, complex function itself, with many behaviors and sub-behaviors. Since this test case is only interested in the morale effect, a better test would invoke a lower-level function that eat invokes, such as modify_morale.

Our dummy has eaten the neccowafers, but did it do anything? Because they have a sweet tooth, they should get a specific morale bonus known as MORALE_SWEETTOOTH, and it should be at least 5 in magnitude:

THEN( "they get a morale bonus from its sweetness" ) {
    CHECK( dummy.has_morale( MORALE_SWEETTOOTH ) >= 5 );
}

This CHECK macro takes a boolean expression, failing the test if the expression is false. Likewise, you can use CHECK_FALSE, which will fail if the expression is true.

Requiring or Checking

While the CHECK and CHECK_FALSE macros make assertions about the truth or falsity of expressions, they still allow the test to continue, even when they fail. This lets you do several CHECKs, and be informed if one or more of them do not meet your expectations.

Another kind of assertion is the REQUIRE (and its counterpart REQUIRE_FALSE). Unlike the CHECK assertions, REQUIRE will not continue if it fails - this assertion is considered essential for the test to continue.

A REQUIRE is useful when you wish to double-check your assumptions after making some change to the system state. For example, here are a couple of REQUIREs added to the sweet-tooth test, to ensure our dummy really has the desired trait, and that the neccowafers really are junk food:

    GIVEN( "character has a sweet tooth" ) {
        dummy.toggle_trait( trait_PROJUNK );
        REQUIRE( dummy.has_trait( trait_PROJUNK ) );

        WHEN( "they eat some junk food" ) {
            item necco( "neccowafers" );
            REQUIRE( necco.has_flag( "ALLERGEN_JUNK" ) );

            dummy.eat( necco );

            THEN( "they get a morale bonus from its sweetness" ) {
                CHECK( dummy.has_morale( MORALE_SWEETTOOTH ) >= 5 );
            }
        }
    }

We use REQUIRE here, because there is no reason to continue the test if these fail. If our assumptions are wrong, nothing that follows is valid. Clearly, if toggle_trait failed to give the character the PROJUNK trait, or if the neccowafers turn out not to be made of sugar after all, then our test of the morale bonus is meaningless.

You can think of REQUIRE as being a prerequisite for the test, while CHECK is looking at the results of the test.

Profiling with tracy

Tracy is a realtime profiler which you can use to analyze performance bottleneck. It consists of two parts: client and profiler. The client integrated in BN sends profiling data to the profiler. As the client is opt-in, you need to build BN with tracy client in order to start profiling.

Install Tracy Profiler

Caution

Both the game and profiler have to be built with same version of tracy to work properly. Due to numerous issues, The windows version uses v0.10 wheras the linux version uses 6d1deb5640ed11da01995fb1791115cfebe54dbf.

Linux

$ git clone https://github.com/wolfpld/tracy
$ cd tracy
$ git checkout 6d1deb5640ed11da01995fb1791115cfebe54dbf # the commit used by BN tracy client
  1. Clone https://github.com/wolfpld/tracy.
# for ubuntu (X11)
$ sudo apt install cmake clang git libcapstone-dev xorg-dev dbus libgtk-3-dev

# for ubuntu (wayland)
$ sudo apt install libglfw-dev libgtk-3-dev libfreetype6-dev libtbb-dev debuginfod libwayland-dev dbus libxkbcommon-dev libglvnd-dev meson cmake git wayland-protocols

# for arch, copied from https://github.com/wolfpld/tracy/blob/master/.github/workflows/linux.yml#L16C12-L16C163
$ pacman -Syu --noconfirm && pacman -S --noconfirm --needed freetype2 tbb debuginfod wayland dbus libxkbcommon libglvnd meson cmake git wayland-protocols
  1. Install dependencies.
$ cmake -B profiler/build -S profiler # if you're using wayland
  1. Set up cmake. By default tracy uses wayland, if you want to use X11, you need to add LEGACY=1 flag.

Note

for X11

$ cmake -DLEGACY=ON -B profiler/build -S profiler # if you're using X11

tracy uses wayland by default, if you want to use X11, you need to add LEGACY=1 flag.

Note

fileselector fixes

$ cmake -DGTK_FILESELECTOR=ON -B profiler/build -S profiler

Due to issues with default fileselector (xdg-portal), tracy may fail to open or save trace history. As an workaround, add GTK_FILESELECTOR=ON in compile flags to use gtk fileselector.

$ cmake --build profiler/build --config Release --parallel $(nproc)
  1. Build the binary. It will be available on ./profiler/build/tracy-profiler.

Tip

Adding desktop entry

[Desktop Entry]
Version=1.0
Type=Application
Name=Tracy Profiler
GenericName=Code profiler
GenericName[pl]=Profiler kodu
GenericName[ko]=코드 프로파일러
Comment=Examine code to see where it is slow
Comment[pl]=Znajdowanie wolno wykonującego się kodu
Comment[ko]=코드 분석해서 느린 곳 찾기
Exec=<THE_PATH_WHERE_YOU_INSTALLED_TRACY>/profiler/build/tracy-profiler %f
Icon=<THE_PATH_WHERE_YOU_INSTALLED_TRACY>/icon/icon.ico
Terminal=false
Categories=Development;Profiling;
MimeType=application/tracy;
X-Desktop-File-Install-Version=0.26

To make the profiler available in app runner, create $HOME/.local/share/applications/tracy.desktop file with the following content. Make sure to replace <THE_PATH_WHERE_YOU_INSTALLED_TRACY> with the path where you installed tracy!

Windows

Download pre-compiled executable from https://github.com/wolfpld/tracy/releases.

Build BN with Tracy Client

Build on cmake with -D USE_TRACY=ON flag. For example,

$ cmake -B out/build/tracy -DUSE_TRACY=ON ...other flags...

See CMake options for more information.

Mark zone to profile

Mark ZoneScoped in the function you’d like to profile. It will be displayed in the tracy GUI. For example,

bool game::do_turn()
{
    ZoneScoped;

    /** Other code... */
}

There are also more complex profiling macros available. Check following links for more:

Use Tracy Profiler

  1. Start BN (built with USE_TRACY=ON), and run the tracy profiler.

  1. Click connect button to connect to the game.

  1. Profiling data will be displayed in the GUI.

Working with both BN and DDA

Sometimes you may need to port some changes from DDA. It could be done via adding remote and cherry-picking.

tl;dr version

git remote add dda https://github.com/CleverRaven/Cataclysm-DDA
git fetch dda
git checkout -b ddamaster dda/master
git checkout ddamaster && git pull

Explained version

Setting up

Assuming you have a directory with BN named Cataclysm-BN, open a terminal there.

Add the remote tracking branch for DDA. Let’s name the branch dda (doesn’t need to be dda):

git remote add dda https://github.com/CleverRaven/Cataclysm-DDA

To download the contents of the new branch, it has to be fetched:

git fetch dda

This downloads all the content from the remote tracking branch. It shouldn’t take very long, because it doesn’t download the things common to both repos. Once fetched, you can merge, pull, checkout etc. the branches on the remote, but you have to prepend them with dda/, for example dda/master. It’s useful to have a local branch pointing to the remote tracking one:

git checkout -b ddamaster dda/master

This creates an ddamaster branch, which is basically DDA’s master branch. You can take other name instead of ddamaster.

Updating

The simplest way is:

git checkout ddamaster 
git pull

This shouldn’t result in any conflicts. If it did, you probably committed changes to the main branch. In this case you may want to back them up:

git checkout -b temp-branch-name

And reset the main branch to the remote:

git branch -f ddamaster dda/master

Contributing

# Switch to BN branch
git checkout main
# Update local content
git pull
# Create new branch for your changes
git checkout -b chainsaw-toothbrush-rebalance
# [do stuff with files]
...
# Commit the changes
git commit -a
# Upload your changes to your fork of Cataclysm (assuming its branch is named origin)
git push -u origin chainsaw-toothbrush-rebalance
# Go to BN's github and make a pull request

Porting

Porting is done with git cherry-pick. First, you need to find the hash of the merge commit, or the first and the last of the commits from the range you want to port. On github, those are on the right side of commit descriptions in a PR. You can use the full hash or the shortened version. In the examples, fafafaf is the merge commit, while a0a0a0a and b1b1b1b are the first and last commit from a range (order is important). Then, from a branch you are porting to, cherry-pick the merge commit or the range of commits:

# Merge commit
git cherry-pick fafafaf
# Commit range
git cherry-pick a0a0a0a..b1b1b1b

Resolve the conflicts (there will be many for non-trivial PRs and you’ll have to resolve most of them manually):

git mergetool

The above may require setting up a merge conflict resolving tool (TODO: describe how to do that). Then commit and push, as usual.

CMake builds on Atomic Distros

This article goes over building BN on distros that are immutable, and thus where containerization is the desired solution rather than layering the dependencies onto your base install.

Example: Fedora Atomic-based (Bazzite)

Caution

As of writing this, Bazzite’s default container image is fedora-toolbox:38, which may result in having to edit the dependencies installation script. On distros that grab a more modern version of Fedora as their image (or by manually grabbing one yourself), you can be more certain in just using the standard Fedora script

Caution

when using distrobox, using exported compiler (e.g ~/.local/bin/clang) won’t work as it cannot access /usr. instead, use absolute path for compilers like /usr/bin/clang.

Setting up the container

Bazzite, being based on the Atomic versions of Fedora Linux, has the containerization tool known as Toolbx pre-installed. As such, it is the method we will be using for this example.

To start, create a toolbox with:

$ toolbox create

This will likely prompt you to download an image to base the container on. If this asks about downloading “fedora-toolbox:38” (or any other number) or asks about downloading Fedora Workstation, then you’re on the right track! Answer ’y’es, and wait for the container to be built. This can take some time, depending on your hardware, but is fortunately a step you should only need to take once.

After creating your toolbox, navigate to your Cataclysm-BN folder with a src folder. (I.e. your local copy of the github repo or your downloaded source code). There, you can enter into your toolbox with a simple command:

$ toolbox enter

You’ll need to run this command every time you intend on building in order to enter into your container.

Once you’re in your toolbox, you can install your dependencies with a Fedora-based distro installation script. For Bazzite, that script looks like:

$ sudo dnf install git cmake clang ninja-build mold ccache \
  SDL2-devel SDL2_image-devel SDL2_ttf-devel SDL2_mixer-devel \
  freetype glibc bzip2 zlib-ng libvorbis ncurses gettext flac-devel \
  sqlite-devel zlib-devel

After this, your container is set up for all your building needs in the future! Now, onto the steps of actually building.

Building

If you aren’t already in your container, in the Cataclysm-BN folder, then navigate to the folder and enter into the container. From there, you may run the cmake script to generate its files (don’t worry about creating the build folder yourself, cmake will automatically generate it if it’s not present already) For Bazzite, this looks like:

cmake \
  -B build \
  -G Ninja \
  -DCATA_CCACHE=ON \
  -DCMAKE_C_COMPILER=clang \
  -DCMAKE_CXX_COMPILER=clang++ \
  -DCMAKE_INSTALL_PREFIX=$HOME/.local/share \
  -DJSON_FORMAT=ON \
  -DCMAKE_BUILD_TYPE=RelWithDebInfo \
  -DCURSES=OFF \
  -DTILES=ON \
  -DSOUND=ON \
  -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
  -DCATA_CLANG_TIDY_PLUGIN=OFF \
  -DLUA=ON \
  -DBACKTRACE=ON \
  -DLINKER=mold \
  -DUSE_XDG_DIR=ON \
  -DUSE_HOME_DIR=OFF \
  -DUSE_PREFIX_DATA_DIR=OFF \
  -DUSE_TRACY=ON \
  -DTRACY_VERSION=master \
  -DTRACY_ON_DEMAND=ON \
  -DTRACY_ONLY_IPV4=ON

Assuming all goes well, you should now have your CMake files generated! Now, all you need to do is run the Ninja command to actually build.

$ ninja -C build -j $(nproc) -k 0 cataclysm-bn-tiles

$(nproc) just grabs the number of “threads” your CPU has, but you can specify a lower number if you’d prefer to use less threads for compiling (albeit at the cost of performance).

CMake

Prerequisites

You’ll need to have these libraries and their development headers installed in order to build CataclysmBN:

  • General
    • cmake >= 3.2.4
    • clang >= 22
    • gcc-libs or equivalent C++ runtime libraries
    • glibc
    • zlib
    • bzip2
    • sqlite3
    • SDL >= 3.0.0 *
    • SDL_shadercross >= 3.0.0 *
  • Curses
    • ncurses
  • Tiles
    • SDL_image >= 3.0.0 (with PNG and JPEG support) *
    • SDL_mixer >= 3.0.0 (with Ogg Vorbis support) *
    • SDL_ttf >= 3.0.0 *
    • freetype
  • Sound
    • vorbis
    • libbz2
    • libz

Note

Dependancies marked with * will be built automatically if missing.

In order to compile localization files, you’ll also need gettext package.

Build Environment

You can obtain the source code tarball for the latest version from git.

git clone --filter=blob:none https://github.com/cataclysmbn/Cataclysm-BN.git
cd Cataclysm-BN

Tip

filter=blob:none creates a blobless clone, which makes the initial clone much faster by downloading files on-demand.

UNIX Environment

Obtain packages specified above with your system package manager.

  • For Ubuntu-based distros (26.04 onwards):
sudo apt install git cmake ninja-build mold clang-22 llvm-22 ccache \
libsdl3-dev libsdl3-image-dev libsdl3-ttf-dev \
libfreetype-dev bzip2 zlib1g-dev libvorbis-dev libncurses-dev \
gettext libflac++-dev libsqlite3-dev zlib1g-dev
  • For Fedora-based distros:
sudo dnf install git cmake ninja-build mold clang llvm ccache \
SDL3-devel SDL3_image-devel SDL3_ttf-devel \
freetype glibc bzip2 zlib-ng libvorbis ncurses gettext flac-devel \
sqlite-devel zlib-devel

Note

Neither Ubuntu or Fedora ship SDL3_mixer or shadercross These libraries will be build automatically when compiling

  • For Arch based distros:
sudo pacman -S sdl3 sdl3_image sdl3_ttf sdl3_mixer zip sqlite

Verifying Compiler Version

You need Clang 22 or newer to build CataclysmBN. You can check your compiler version with:

$ clang++ --version
clang version 22.1.6 (Fedora 22.1.6-1.fc44)
Target: x86_64-redhat-linux-gnu
Thread model: posix
InstalledDir: /usr/bin

Tip

when installed clang-{version} but clang is not found

Use update-alternatives to set the default Clang version:

sudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-22 100
sudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-22 100

If Ubuntu only installs versioned LLVM binutils such as llvm-ar-22 and llvm-ranlib-22, register those names too:

sudo update-alternatives --install /usr/bin/llvm-ar llvm-ar /usr/bin/llvm-ar-22 100
sudo update-alternatives --install /usr/bin/llvm-ranlib llvm-ranlib /usr/bin/llvm-ranlib-22 100

macOS Environment

Install dependencies via Homebrew:

brew install cmake ninja ccache sdl3 sdl3_image sdl3_ttf sdl3_mixer \
  freetype gettext sqlite pkg-config ncurses flac

Note

Apple Clang shipped with Xcode 16+ supports the C++23 features required by CataclysmBN. You do not need to install a separate compiler.

Windows Subsystem for Linux (WSL)

Follow the same instructions for UNIX environment; it just works (TM)

If you plan on using tiles, make sure you have the latest WSL 2 that supports GUI and have installed matching drivers.

Windows Environment (MSYS2)

  1. Follow steps from here: https://msys2.github.io/
  2. Install CataclysmBN build deps:
pacman -S mingw-w64-x86_64-toolchain msys/git \
   	  mingw-w64-x86_64-cmake \
   	  mingw-w64-x86_64-SDL2_{image,mixer,ttf} \
   	  ncurses-devel \
      gettext \
      base-devel

This should get your environment set up to build console and tiles version of windows.

Note

If you’re trying to test with Jetbrains CLion, point to the cmake version in the msys32/mingw32 path instead of using the built in. This will let cmake detect the installed packages.

CMake Build

CMake has separate configuration and build steps. Configuration is done using CMake itself, and the actual build is done using build-system agnostic cmake --build ..

There are two ways to build CataclysmBN with CMake: inside the source tree or outside of it. Out-of-source builds have the advantage that you can have multiple builds with different options from one source directory.

Caution

Inside the source tree build is NOT supported.

There’s multiple predefined build presets available, which simplifies build process to just two commands.

For Linux:

cmake --preset linux-slim
cmake --build --preset linux-slim --target cataclysm-bn-tiles

For macOS:

cmake --preset osx-arm-slim
cmake --build --preset osx-arm-slim

This will place the executable into out/build/linux-slim/ or out/build/osx-arm-slim/ respectively.

Tip

To build with clang-tidy plugin and tracy profiler support, try linux-full.

Note

You can build multiple targets at once with:

cmake --build --preset linux-slim --target cataclysm-bn-tiles cata_test-tiles

Or limit maximum number of threads with --parallel option:

cmake --build --preset linux-slim --target cataclysm-bn-tiles --parallel 4

Build without Presets

To build CataclysmBN out of source:

mkdir -p out/build/custom
cmake -B out/build/custom -DCMAKE_BUILD_TYPE=Release
cmake --build out/build/custom

The above example creates a build directory under out/build/, but that’s not required - you can just as easily create it in a completely different location.

To install CataclysmBN after building (as root using su or sudo if necessary):

cmake --install out/build/custom

Creating Distribution Packages

Tip

Check build presets for a list of distribution presets.

Use a build preset to create a portable distribution package:

# Configure for tiles distribution
cmake --preset dist-tiles

# Build the game and tools
cmake --build --preset dist-tiles

# Create distribution package
cmake --install build --prefix cataclysmbn-linux-tiles

This creates a self-contained directory with the following structure:

cataclysmbn-linux-tiles/
├── cataclysm-bn-tiles     # Game executable
├── cataclysm-launcher     # Launcher script
├── json_formatter         # JSON formatting tool
├── data/                  # Game data files
├── gfx/                   # Tilesets
├── lang/                  # Translations
├── doc/                   # Documentation
├── README.md
├── LICENSE.txt
└── VERSION.txt

To create a tarball for distribution:

tar -czvf cataclysmbn-linux-tiles.tar.gz cataclysmbn-linux-tiles

Tip

The cataclysm-launcher script sets up the correct working directory and library paths. Use it to run the game from any location.

Portable vs System Install

OptionUSE_PREFIX_DATA_DIR=OFFUSE_PREFIX_DATA_DIR=ON
Data location./data//usr/share/cataclysm-bn/
Config location./config/~/.config/cataclysm-bn/
Best forPortable/release buildsSystem packages (deb/rpm)

Tip

Check build options for information on how to configure builds

Build for Visual Studio / MSBuild

Caution

This guide is quite old and requires manual dependency management.

For modern alternative, see CMake Visual Studio build with vcpkg

CMake can generate .sln and .vcxproj files used either by Visual Studio itself or by MSBuild command line compiler (if you don’t want a full fledged IDE) and have more “native” binaries than what MSYS/Cygwin can provide.

At the moment only a limited combination of options is supported (tiles only, no localizations, no backtrace).

Get the tools:

Get the required libraries:

  • SDL2 (you need the “(Visual C++ 32/64-bit)” version. Same below)
  • SDL2_ttf
  • SDL2_image
  • SDL2_mixer (optional, for sound support)
  • Unsupported (and unused in the following instructions) optional libs:
    • ncurses - ???

Unpack the archives with the libraries.

Open windows command line (or powershell), set the environment variables to point to the libs above as follows (adjusting the paths as appropriate):

set SDL2DIR=C:\path\to\SDL2-devel-2.0.9-VC
set SDL2TTFDIR=C:\path\to\SDL2_ttf-devel-2.0.15-VC
set SDL2IMAGEDIR=C:\path\to\SDL2_image-devel-2.0.4-VC
set SDL2MIXERDIR=C:\path\to\SDL2_mixer-devel-2.0.4-VC

(for powershell the syntax is $env:SDL2DIR="C:\path\to\SDL2-devel-2.0.9-VC").

Run the CMake configuration step

cd <path to cbn sources>
cmake -B out/build/msbuild -DTILES=ON -DLANGUAGES=none -DBACKTRACE=OFF -DSOUND=ON

Build!

cmake --build out/build/msbuild --config Release --parallel 2

The --parallel 2 flag controls build parallelism - you can omit it if you wish. The --config Release flag selects the optimized Visual Studio configuration. If you omit it, the Debug configuration would be built instead.

The resulting files will be put into a Release directory inside your source Cataclysm-BN folder. To make them run you’d need to first move them to the source Cataclysm-BN directory itself (so that the binary has access to the game data), and second put the required .dlls into the same folder - you can find those inside the directories for dev libraries under lib/x86/ or lib/x64/ (you likely need the x86 ones even if you’re on 64-bit machine).

The copying of dlls is a one-time task, but you’d need to move the binary out of Release/ each time it’s built. To automate it a bit, you can configure cmake and set the desired binaries destination directory with -DCMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE= option (and similar for CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG).

Run the game. Should work.

Build Options

To change build options, you may either pass the options on the command line:

cmake -DOPTION_NAME1=option_value1 [-DOPTION_NAME2=option_value2 [...]]

Or use either the ccmake or cmake-gui front-ends, which display all options and their cached values on a console and graphical UI, respectively.

cmake --preset linux-slim
ccmake out/build/linux-slim
cmake --preset linux-slim
cmake-gui -S . -B out/build/linux-slim

CMake specific options

  • CMAKE_BUILD_TYPE=<build type>

Selects a specific build configuration when compiling. release produces the default, optimized (-Os) build for regular use. debug produces a slower and larger unoptimized (-O0) build with full debug symbols, which is often needed for obtaining detailed backtraces when reporting bugs.

NOTE: By default, CMake will produce debug builds unless a different configuration option is passed in the command line.

  • CMAKE_INSTALL_PREFIX=<full path>

Installation prefix for binaries, resources, and documentation files.

CataclysmBN specific options

OptionDefaultEffect
CURSESON (OFF with TILES)Build curses version.
TILESOFFBuild graphical tileset version.
SOUNDONBuild audio support.
LANGUAGES" "Build specificed language support.
TESTSONBuild test units.
USE_HOME_DIRON (OFF on WIN32)Use $HOME directory for save and config files.
USE_XDG_DIROFFUse XDG directories for save and config files.
USE_PREFIX_DATA_DIROFFUse UNIX system directories for game data in release build.
JSON_FORMATOFFBuild JSON formatter.
CATA_CCACHEONTry to find and build with ccache.
BUILD_SDL3OFFForce Build SDL3 instead of using system libraries.
BUILD_SHADERCROSSONBuild SDL_shadercross from source when shadercross is not on PATH.
SHADER_TARGETSspirv;msl (dxil;spirv;msl on WIN32)Shaders to build.
DYNAMIC_LINKINGONUse dynamic linking. Or use static to remove MinGW dependency instead.
LINKER" "Custom Linker to use
BACKTRACEONSupport for printing stack backtraces on crash.
LIBBACKTRACEOFFPrint backtrace with libbacktrace.
USE_TRACYOFFUse tracy profiler. See Profiling with tracy for more information.
GIT_BINARY" "Git binary name or path.

Build Presets

Check the cmake docs for more information

Preset NameDescription
linux-cursesLinux Slim Build (Curses)
linux-slimLinux Slim Build (Tiles, Sounds)
linux-fullLinux Full Build (Tiles, Sounds, Clang-Tidy, Tracy)
linux-cross-aarch64
linux-slim-cross-aarch64
linux-full-cross-aarch64
dist-tilesLinux Distribution (Tiles, Sounds, Languages)
dist-cursesLinux Distribution (Curses, Languages)
osx-curses-distmacOS Distribution (Curses, Languages)
osx-tiles-distmacOS Distribution (Tiles, Sounds, Languages)
osx-arm-slimmacOS ARM Slim Build (Tiles, Sounds)
osx-arm-distmacOS ARM Distribution (Tiles, Sounds, Languages)
lintLint and Format Only
ciCI Build (Tiles, Curses, Sound)

Note

The macOS distribution presets build a DMG with the dmgdist target. dmgbuild must be available on PATH. If you do not have dmgdist and biplist installed already, you can install them using pip

python3 -m pip install dmgbuild biplist

Use osx-curses-dist and osx-tiles-dist to build one app for Apple Silicon and Intel. These presets need universal SDL3 frameworks and ncurses. Homebrew packages have only one architecture. Install the universal libraries first, then give the ncurses path to CMake:

build-scripts/macos-universal-libs.sh ~/Library/Frameworks ~/ncurses-universal
cmake --preset osx-curses-dist -DCMAKE_PREFIX_PATH="$HOME/ncurses-universal"

Building with Translations Locally

Starting in 2026, translation files (.po files) are no longer kept in the repository. CI pulls them from Transifex, stores them in workflow artifacts, and uses them to build release packages.

For local builds, use one of the following:

Option 1: Build Without Translations (Fastest)

If you are not working on translations, disable them:

cmake --preset linux-full -DLANGUAGES=none
cmake --build --preset linux-full

Option 2: Pull Translations from Transifex

If you need to test translations locally and have Transifex access:

  1. Install the Transifex CLI:
curl -sL https://github.com/transifex/cli/releases/download/v1.6.17/tx-linux-amd64.tar.gz | sudo tar zxvf - -C /usr/bin tx
  1. Pull the translation files:
tx pull --force --all
  1. Build with translations enabled:
cmake --preset linux-full -DLANGUAGES=all
cmake --build --preset linux-full

Option 3: Download the translations Workflow Artifact

If you do not have Transifex access, use the artifact produced by the translation workflow:

  1. Open a recent successful workflow run in Actions
  2. Download the translations artifact
  3. Extract lang/po and src/lang_stats.inc into your local checkout
  4. Build normally with -DLANGUAGES=all

Note

Most code changes do not need translations. Use -DLANGUAGES=none unless you are testing localized output.

Note

Release archives only include compiled lang/mo files for packaged builds. They do not contain the lang/po sources required to rebuild translations locally.

Cygwin

Cygwin Makefile builds have been removed.

Use the CMake MSYS2 instructions, WSL instructions, or the Visual Studio vcpkg guide for Windows builds.

MSYS2

MSYS2 Makefile builds have been removed.

Use the CMake MSYS2 instructions or the Visual Studio vcpkg guide for Windows builds.

Building with Visual Studio 2022 and CMake

This guide covers building Cataclysm: Bright Nights on Windows using Visual Studio 2022’s native CMake integration. After the one-time setup, everything — configuration, building, debugging — is done directly inside Visual Studio with no external tools required.

Legacy build: The .sln-based build in msvc-full-features/ still works and is untouched by this system. Both can coexist in the same checkout.

How it works

The project ships two CMake configuration files:

FileUsed by
CMakeSettings.jsonVisual Studio IDE
CMakePresets.jsoncmake CLI, CI, Linux

VS reads CMakeSettings.json directly when you open the folder. No manual cmake configure step is required before opening VS.

VS setting: In Tools → Options → CMake, set “When a CMakeSettings.json or CMakePresets.json file is detected” to “Use CMakeSettings.json (Legacy)” or “Never use CMake Presets”. This ensures VS uses CMakeSettings.json and ignores CMakePresets.json.

Tip

If you prefer a prompt-driven workflow launched from Visual Studio, see Visual Studio External Tool Automation (Windows + WSL).

Prerequisites

ToolMinimum versionWhere to get it
Visual Studio 202217.6visualstudio.microsoft.com
VS workload: Desktop development with C++—VS Installer
cmake3.24Included with the VS workload above
ninjaanyIncluded with the VS workload above
vcpkganyIncluded with VS 2022 17.6+ (see below)
gitanygit-scm.com

vcpkg

Visual Studio 2022 17.6 and later includes vcpkg. If you accepted the recommended install options, it is already present. CMake will find it automatically through the VCPKG_INSTALLATION_ROOT environment variable that the VS Developer environment sets.

If you installed a standalone vcpkg separately, set VCPKG_ROOT to its path and CMake will use that instead.


Daily workflow in Visual Studio

1. Open the folder

Open Visual Studio 2022, then File → Open → Folder… and select the project’s root directory (the one containing CMakeLists.txt).

Do not open a .sln file from the msvc-full-features/ directory — that is the legacy build system. Both are separate; do not mix them.

2. Select a configuration

In the Standard toolbar, open the Configuration drop-down and choose:

ConfigurationUse when
DebugDebugging, all symbols, no optimisation
RelWithDebInfoNormal development — optimised but debuggable
ReleasePerformance testing, distribution
TestsBuilding and running the test suite
TracyPerformance profiling with the Tracy profiler

RelWithDebInfo is the best default for day-to-day development. It is optimised (so the game runs at normal speed) but retains enough debug information for breakpoints and stack traces to work reliably.

The Tests configuration is a RelWithDebInfo build with the test suite enabled. The other configurations have tests disabled to keep build times shorter.

The Tracy configuration is a Release build with Tracy profiler instrumentation compiled in. See Tracy profiling.

3. Build

Build → Build All (or Ctrl+Shift+B).

The first build downloads and compiles vcpkg dependencies, which takes a while. Subsequent builds are incremental.

4. Run and debug

Set the startup item in the toolbar to the executable you want:

ConfigurationStartup item
Debug / RelWithDebInfo / Release / Tracycataclysm-bn-tiles.exe
Testscata_test-tiles.exe

Then press F5.

The working directory is set to the project root via launch.vs.json, so the game will find its data files without any additional setup.


Customising your build

To override cmake variables for your local build, open CMakeSettings.json and add entries to the variables array of the configuration you use. The file is tracked by git, so for personal overrides either edit a local branch or copy the configuration with a new name.

Useful variables

VariableDefaultEffect
TESTSOFF (ON in Tests config)Build the test suite
JSON_FORMATONBuild the JSON formatter tool
LOCALIZEONBuild translation support
SOUNDONBuild audio support

Tracy profiling

Tracy is a real-time frame profiler. Select the Tracy configuration in the VS toolbar and build normally. Tracy uses TRACY_ON_DEMAND mode — the profiler connects and starts recording only when the Tracy viewer attaches, so the game is usable without the viewer running.

Tracy is also available through the terminal workflow using the windows-tiles-sounds-x64-msvc-tracy cmake preset — see Terminal workflow.


Terminal workflow

setup.ps1 validates prerequisites and configures the cmake preset used for terminal builds. Run it once from a plain PowerShell window:

.\setup.ps1

The script checks all prerequisites, downloads the gettext binaries needed for building translations, and runs cmake --preset windows-tiles-sounds-x64-msvc.

After that, the standard cmake commands work from a VS 2022 Developer Command Prompt or Developer PowerShell:

# Configure (one time, or after CMakeLists.txt changes)
cmake --preset windows-tiles-sounds-x64-msvc

# Build
cmake --build --preset windows-msvc-relwithdebinfo

# Run the game (from the project root directory)
.\out\build\windows-tiles-sounds-x64-msvc\src\RelWithDebInfo\cataclysm-bn-tiles.exe

# Run tests
.\out\build\windows-tiles-sounds-x64-msvc\tests\RelWithDebInfo\cata_test-tiles.exe

# Build translations only
cmake --build --preset windows-msvc-relwithdebinfo --target translations_compile

# Install (copies game + data to a self-contained directory)
cmake --install out\build\windows-tiles-sounds-x64-msvc --config RelWithDebInfo

Note: cmake --build from a plain terminal (not a VS Developer terminal) relies on the baked VS environment in CMakeUserPresets.json. If that file is missing, run setup.ps1 to regenerate it, or use a VS Developer Command Prompt instead.


Troubleshooting

CMake configure fails immediately

Most common cause: vcpkg is not found.

Check that VCPKG_ROOT is set (or that VS’s bundled vcpkg is available). Open a VS Developer Command Prompt and run:

echo %VCPKG_ROOT%
echo %VCPKG_INSTALLATION_ROOT%

At least one should point to a directory containing vcpkg.exe. If neither is set, run setup.ps1 — it locates the VS-bundled vcpkg automatically.

VS shows an x64-Debug configuration or the ncurses error appears

VS is not using CMakeSettings.json. Go to Tools → Options → CMake → General and set the preset integration to “Use CMakeSettings.json (Legacy)” or “Never use CMake Presets”. Then do a full reset (see below).

Configure succeeds but build fails with missing headers/libs

The VS environment (INCLUDE, LIB, PATH) may not have been captured correctly. Try:

  1. Delete CMakeUserPresets.json from the project root.
  2. Delete the relevant out\build\ subdirectory entirely.
  3. Run setup.ps1 again to regenerate both.

Game launches but immediately crashes / can’t find data

launch.vs.json at the project root sets the working directory to the project root for F5 launches. If the file is missing or VS is not reading it, the game may not find ./data/.

If you are launching the .exe directly from File Explorer or a terminal, make sure to run it from the project root directory:

# Correct — run from the project root
.\out\build\win-rel-deb\src\cataclysm-bn-tiles.exe

# Wrong — game can't find ./data/
cd out\build\win-rel-deb\src
.\cataclysm-bn-tiles.exe

“VsDevCmd.bat not found” error during configure

VsDevCmd.bat is inside your VS installation. If this error appears, VS may be installed in a non-standard location. Set the DevEnvDir environment variable to the path of your VS Common7\IDE directory before running cmake:

$env:DevEnvDir = "D:\VisualStudio\Common7\IDE\"
cmake --preset windows-tiles-sounds-x64-msvc

Builds are very slow

ccache is detected and used automatically if it is installed and on PATH. Install it from ccache.dev to dramatically speed up incremental builds after git clean or branch switches.

How to fully reset the build environment

If things are broken and you want a clean slate:

# Delete VS's cached project state (stale configurations, IntelliSense DB)
Remove-Item -Recurse -Force .vs

# Delete all build output directories
Remove-Item -Recurse -Force out\build

# Delete the generated user presets (will be regenerated on next configure)
Remove-Item -Force CMakeUserPresets.json

# Re-run setup for terminal builds (VS will reconfigure itself on next open)
.\setup.ps1

CMakeUserPresets.json shows “already exists” on reconfigure

This is intentional. The file is only generated on first configure to avoid overwriting your customisations. If you want to reset it to the default generated content, delete it and run setup.ps1.

Visual Studio External Tool Automation (Windows + WSL)

This page documents the Visual Studio External Tool workflow used to run Cataclysm: BN CMake build automation from a cmd/PowerShell interface.

Overview

  • The workflow is launched from Visual Studio’s External Tools menu.
  • The same flow drives Windows (MSVC) builds and WSL-based Linux builds.
  • All selections are made through menus — no manual shell commands are needed.
  • Full debugger support: Windows auto-attaches the VS debugger; Linux uses VS SSH attach.

Add the external tool in Visual Studio

Open Tools -> External Tools… and add an entry. The Arguments field is the same regardless of which interface mode you choose:

FieldValue
TitleBN Build
Commandcmd.exe
Arguments/c "$(SolutionDir)cmake-build.bat"
Initial directory$(SolutionDir)

The Use Output Window checkbox controls which interface mode the tool uses:

Use Output WindowInterface
UncheckedOpens a separate cmd window; numbered text menus appear inline
CheckedRuns inside the VS Output window; WinForms GUI list-pickers appear instead

The GUI pickers (checked) keep everything inside VS but require clicking through floating windows. The text menus (unchecked) open a separate console window where you type a number to select. Both modes complete all the same steps — the choice is purely a preference.

For a dedicated debug shortcut (e.g. “BN Debug”), add a second entry with the same settings but append -Action debug to the Arguments field:

/c "$(SolutionDir)cmake-build.bat" -Platform win -Preset 1 -BuildType 2 -Action debug

Interface modes

Text menus (“Use Output Window” unchecked): numbered prompts appear inline in the cmd window. Enter the number for your selection.

WinForms GUI pickers (“Use Output Window” checked): floating list-box windows appear for each selection. Click an item and press OK, or double-click to confirm.

Linux/WSL note: GUI pickers apply only to the initial platform selection when building for Linux. After that, the script re-launches itself in an elevated administrator console (required for WSL operations), and all subsequent menus in that window use text prompts.

Workflow

On each run the script prompts for:

  1. Platform — Windows (MSVC) or Linux (WSL)
  2. Configure preset — read from CMakePresets.json (and CMakeUserPresets.json if present)
  3. Build type — Debug / RelWithDebInfo / Release (Windows only; Linux type is set in the preset)
  4. Target — derived from the preset’s TILES/TESTS cache variables, or enter a custom name
  5. Action — Build, Run, Rebuild, Delete, or Debug

After a successful build the script offers to Run or Debug immediately without returning to the main menu.

A “Repeat last” option is shown at the end of each session to re-run the same configuration without re-answering every prompt.

Elevation

Windows builds run entirely at standard (unelevated) integrity. Do not run cmake-build.bat or Visual Studio as administrator — this is required for the debugger auto-attach to work (see below).

Linux/WSL builds require administrator privileges for WSL filesystem and network operations. The script detects when it is not elevated and automatically spawns an elevated PowerShell window, passing all selected options through so no re-selection is needed.

Debugging

Windows

Selecting the Debug action:

  1. Launches the game executable at standard integrity with Start-Process.
  2. Connects to the running Visual Studio instance via COM automation (the DTE object from the Running Object Table).
  3. Calls Debugger.Attach() on the game process — VS attaches its native debugger automatically.

The script polls for up to 5 seconds for VS to register the process, then reports success or prints fallback instructions.

Requirements:

  • Visual Studio must be open and running at standard (non-elevated) integrity. If VS was launched as administrator the COM ROT is partitioned by integrity level and auto-attach will fail with a “no running VS instance found” message. Restart VS without elevation.
  • cmake-build.bat must also run without elevation (the launcher does not elevate for Windows builds).

If auto-attach fails, the script prints the process PID. Attach manually via Debug → Attach to Process (Ctrl+Alt+P) and find the process by name or PID.

Linux (SSH attach)

Debugging a Linux WSL build uses Visual Studio’s SSH remote-attach feature. The script configures everything automatically on each debug run:

  1. Installs openssh-server in WSL if not already present.
  2. Enables PasswordAuthentication yes in /etc/ssh/sshd_config.
  3. Runs ssh-keygen -A to generate any missing host keys.
  4. Starts (or restarts) the SSH service.
  5. Sets /proc/sys/kernel/yama/ptrace_scope to 0 — required so that GDB (used by VS) can attach to a process that is not a direct child of the debugger.
  6. Resolves the current WSL IP address (WSL2 assigns a new IP on each start).
  7. Removes any stale netsh port proxy and creates a fresh one: Windows localhost:2222 → WSL <ip>:22
  8. Verifies that localhost:2222 is reachable.
  9. Writes a small launch script to /tmp/ inside WSL and opens it in a new WSL window so the game has a real TTY and WSLg display environment (DISPLAY/WAYLAND_DISPLAY).
  10. Prints step-by-step attach instructions.

To attach in Visual Studio after the game window opens:

  1. Open Debug → Attach to Process (Ctrl+Alt+P).
  2. Set Connection type to SSH.
  3. Set Connection target to localhost:2222.
  4. Press Enter or click the connect button; enter your WSL username and password when prompted.
  5. Find the game process (e.g. cataclysm-bn-tiles) in the process list.
  6. Click Attach.

Visual Studio saves the SSH connection after the first use. On subsequent debug runs you only need to open “Attach to Process”, select the saved localhost:2222 connection, and attach.

The port proxy uses 127.0.0.1 (loopback only), so no inbound Windows Firewall rules are required.

ptrace_scope=0 is set transiently (resets on WSL restart). It is not written to a persistent sysctl file, unlike the TSan vm.mmap_rnd_bits fix.

Non-interactive shortcuts

All prompts can be bypassed by passing parameters directly to cmake-build.bat. This is useful for additional External Tool entries that go straight to a specific action.

rem Windows MSVC build (preset 1, RelWithDebInfo)
cmake-build.bat -Platform win -Preset 1 -BuildType 2 -Action build

rem Windows debug (launch game and auto-attach VS debugger)
cmake-build.bat -Platform win -Preset 1 -BuildType 1 -Action debug

rem Linux WSL build (preset by name)
cmake-build.bat -Platform linux -Preset linux-slim -Target cataclysm-bn-tiles -Action build

rem Linux run with test filter
cmake-build.bat -Platform linux -Preset 2 -Action run -RunArgs "[map]"

Parameter reference:

ParameterValuesNotes
-Platformwin / linux
-Presetpreset name or 1-based indexIndexes match the order in CMakePresets.json
-BuildType1=Debug 2=RelWithDebInfo 3=ReleaseWindows only
-Targetcmake target nameDerived from preset if omitted
-Actionbuild run rebuild delete debug
-RunArgsstring forwarded to the binarye.g. [map] for test filtering
-ExtraFlagsextra cmake configure flagse.g. -DFOO=ON

Visual Studio + vcpkg

This guide contains steps required to allow compilation of Cataclysm-BN on Windows using Visual Studio and vcpkg.

Steps from current guide were tested on Windows 10 and 11 (64 bit), Visual Studio 2019 and 2022 (64 bit), but should as well work with slight modifications for other versions of Windows and Visual Studio.

Prerequisites:

  • Computer with modern Windows operating system installed (Windows 10 or 11), Windows 7 and 8.1 are not guaranteed to work;
  • NTFS partition with ~15 Gb free space (~10 Gb for Visual Studio, ~1 Gb for vcpkg installation, ~3 Gb for repository and ~1 Gb for build cache);
  • Git for Windows (installer can be downloaded from Git homepage);
  • Visual Studio 2019 or 2022
    • Note: If you are using Visual Studio 2022, you must install the Visual Studio 2019 compilers to work around a vcpkg bug. In the Visual Studio Installer, select the ‘Individual components’ tab and search for / select the component that looks like ‘MSVC v142 - VS 2019 C++ x64/x86 Build Tools’. See https://github.com/microsoft/vcpkg/issues/22287.
  • Latest version of vcpkg (see instructions on vcpkg homepage).
  • If you plan on contributing your changes to Bright Nights, you’ll also have to install a code formatter, see Code style section for more info.

Note: Windows XP is unsupported!

Installation and configuration:

  1. Install Visual Studio (installer can be downloaded from Visual Studio homepage).
  • Select the “Desktop development with C++” and “Game development with C++” workloads.
  1. Install Git for Windows (installer can be downloaded from Git homepage).

  2. Install and configure latest vcpkg:

WARNING: It is important that, wherever you decide to clone this repo, the path does not include whitespace. That is, C:/dev/vcpkg is acceptable, but C:/dev test/vcpkg is not.

git clone https://github.com/Microsoft/vcpkg.git
cd vcpkg
bootstrap-vcpkg.bat -disableMetrics
vcpkg integrate install

Cloning and compilation:

  1. Clone Cataclysm-BN repository with following command line:

Note: This will download the entire CBN repository; 3+ GB of data. If you’re just testing you should probably add --depth=1.

git clone https://github.com/cataclysmbn/Cataclysm-BN.git
cd Cataclysm-BN
  1. Open the provided solution (msvc-full-features\Cataclysm-vcpkg-static.sln) in Visual Studio, select configuration (Release is advised if you just want to compile, Debug is if you’re planning on editing code) and platform (x64 or x86) and build it. All necessary dependencies will be built and cached for future use by vcpkg automatically.

  2. Open the Build > Configuration Manager menu and adjust Active solution configuration and Active solution platform to match your intended target.

This will configure Visual Studio to compile the release version, with support for Sound, Tiles, and Localization (note, however, that language files themselves are not automatically compiled; this will be done later).

  1. Start the build process by selecting either Build > Build Solution or Build > Build > Cataclysm-vcpkg-static. The process may take a long period of time, so you’d better prepare a cup of coffee and some books in front of your computer :) The first build of each architecture will also download and install dependencies through vcpkg, which can take an especially long time.

  2. If you want to launch the game directly from Visual Studio, make sure you have specified correct working directory as explained below. Otherwise, you’ll only be able to launch the game from the file explorer.

  3. If you need localization support, execute the bash script lang/compile_mo.sh inside Git Bash GUI just like on a UNIX-like system. This will compile the language files that were not automatically compiled in step 2 above.

Running from Visual Studio and debugging

  1. Ensure that the Cataclysm game binary project (Cataclysm-vcpkg-static) is the selected startup project (right click on it in Solution Explorer -> Set as Startup Project)

  2. Configure the working directory in the project properties to $(ProjectDir).. (right click on it in Solution Explorer -> Properties -> select All Configurations and All Platforms at the top -> Debugging -> Working Directory)

  3. Press the debug button (green right-facing triangle near the top, or use the appropriate shortcut, e.g. F5)

If you discover that after pressing the debug button in Visual Studio, Cataclysm just exits after launch with return code 1, that is because of the wrong working directory.

Debug vs Release builds

Debug builds run significantly slower than Release builds, but provide additional safety checks.

If you just want to build the executable and play the game, Release is advised.

If you plan on editing the code, Debug is advised.

If you have enough experience with C++ to know:

  • under-the-hood differences between Debug and Release
  • how Release optimizations may affect the debugger
  • how to avoid undefined behavior in code

Then you might want to use Release build all the time to speed up dev process, and disable optimizations on a file-by-file basis by adding

#pragma optimize("", off)

line at the top of the file.

Running unit tests

Ensure that the Cataclysm test binary project (Cataclysm-test-vcpkg-static) is the selected startup project, configure the working directory in the project properties to $(ProjectDir).., and then press the debug button (or use the appropriate shortcut, e.g. F5). This will run all of the unit tests. Additional command line arguments may be configured in the project’s command line arguments setting, or if you are using a compatible unit test runner (e.g. Resharper) you can run or debug individual tests from the unit test sessions.

Code style

Run just fmt-cpp before committing C++ changes. The CMake format target is also available from Visual Studio when bash is on PATH.

As of October 2022, the code style check is run automatically on each PR on GitHub, so if you forgot to style your changes you’ll see the corresponding check failing.

Make a distribution

There is a batch script in msvc-full-features folder distribute.bat. It will create a sub folder distribution and copy all required files(eg. data/, Cataclysm.exe and dlls) into that folder. Then you can zip it and share the archive on the Internet.

CLI Options

Note

This page is auto-generated from scripts/gen_cli_docs.ts and should not be edited directly.

The game executable can not only run your favorite roguelike, but also provides a number of command line options to help modders and developers.


Info

--help

print this message and exit.

--version

print the version and exit.

--paths

print the paths used by the game and exit.

Command line parameters

--seed <string of letters and or numbers>

Sets the random number generator’s seed value.

--jsonverify

Checks the BN json files.

--check-mods [mods…]

Checks the json files belonging to default or specified BN mods.

--check-all-mods

Checks the json files belonging to all non-obsolete BN mods.

--dump-stats <what> [mode = TSV] [opts…]

Dumps item stats.

--world <name>

Load world.

--basepath <path>

Base path for all game data subdirectories.

--dont-debugmsg

If set, no debug messages will be printed.

--lua-doc <output path>

Generate Lua docs to given path and exit.

--lua-types <output path>

Generate Lua types to given path and exit.

--gpu-backend <driver>

Override the SDL_GPU backend driver for diagnostics (vulkan / direct3d12 / metal / software)..

--datadir <directory name>

Sub directory from which game data is loaded.

--autopickupfile <filename>

Name of the autopickup options file within the configdir.

--motdfile <filename>

Name of the message of the day file within the motd directory.

Map sharing

--shared

Activates the map-sharing mode.

--username <name>

Instructs map-sharing code to use this name for your character..

--addadmin <username>

Instructs map-sharing code to use this name for your character and give you access to the cheat functions..

--adddebugger <username>

Informs map-sharing code that you’re running inside a debugger.

--competitive

Instructs map-sharing code to disable access to the in-game cheat functions.

--worldmenu

Enables the world menu in the map-sharing code.

User directories

--userdir <path>

Base path for user-overrides to files from the ./data directory and named below.

--savedir <directory name>

Subdirectory for game saves.

--configdir <directory name>

Subdirectory for game configuration.

--memorialdir <directory name>

Subdirectory for memorials.

--optionfile <filename>

Name of the options file within the configdir.

Frequently Asked Questions

Adding stuff

Adding a monster

  1. Edit data/json/monsters.json or create a new json file and insert the definition of your new monster there (probably copy an existing entry).
  2. Make sure the id value is unique among all other monster types.
  3. Your monster type is now valid, but won’t be spawned. If you want it to be spawned among similar monsters, edit monstergroups.json. Find the appropriate array, and insert the identifier for your monster (e.g, mon_zombie). cost_multiplier, makes it more expensive to spawn. The higher the cost, the more ‘slots’ it takes up, and freq is how frequent they spawn. See mongroupdef.cpp
  4. If you want your monster to drop items, edit monster_drops.json. Make a new array for your monster type with all the map item groups it may carry, and a chance value for each.
  5. Your monster may have a special attack, a monattack::function reference. Edit monattack.h and include the function in the class definition; edit monstergenerator.cpp and add the translation, then edit monattack.cpp and define your function. Functions may be shared among different monster types. Be aware that the function should contain a statement that the monster uses to decide whether or not to use the attack, and if they do, should reset the monster’s attack timer.
  6. Just like attacks, some monsters may have a special function called when they die. This works the same as attacks, but the relevant files are mondeath.h and mondeath.cpp.
  7. If you add flags, document them in json_flags.md, and mtype.h. Please. Or we will replace your blood with acid in the night.

Adding structures to the map

Most “regular” buildings are spawned in cities (large clusters of buildings which are located rather close to each other).

In file omdata.h in the enum oter_id structure define names (code identifiers) for your building.

If you want your building to be displayed at overmap in different orientations, you should add 4 identifiers for each orientation (south, east, west and north correspondingly).

In the same file in structure const oter_t oterlist[num_ter_types] we should define how these buildings will be displayed, how much they obscure vision and which extras set they have. For example:

{"mil. surplus", '^', c_white, 5, build_extras, false, false},
{"mil. surplus", '>', c_white, 5, build_extras, false, false},
{"mil. surplus", 'v', c_white, 5, build_extras, false, false},
{"mil. surplus", '<', c_white, 5, build_extras, false, false}

Comments at the beginning of this structure are rather useful. In the file mapgen.cpp find the subroutine called draw_map(...); where you should find a huge variant operator (“switch”). This is where you should put your code defining the new building by adding new case-statement.

It should be mentioned that most buildings are built on the square SEEX*2 x SEEY*2 tiles.

If you want your building to be spawned not only in city limits you should refer to structures in file omdata.h (starting from the line #define OMSPEC_FREQ 7).

These structures are also commented in source code. Add new identifier in enum omspec_id structure before NUM_OMSPECS and then add a record in const overmap_special overmap_specials[NUM_OMSPECS] array. For example:

{ot_toxic_dump,   0,  5, 15, -1, mcat_null, 0, 0, 0, 0, &omspec_place::wilderness,0}

The comments given in source code to structure struct overmap_special explain the meaning of these constants in the example above.

Adding a bionic

  1. Edit data/json/bionics.json and add your bionic near similar types. See JSON_INFO.md for a more in-depth review of the individual fields.
  2. If you want the bionic to be available in the game world as an item, add it to item_groups.json, and add a bionic item to data/json/items/bionics.json.
  3. Manually code in effects into the appropriate files, for activated bionics edit the player::activate_bionic function in bionics.cpp.
  4. For bionic ranged weapons add the bionic weapon counterparts to ranged.json, give them the BIONIC_WEAPON flags.
  5. For bionic close combat weapons add the bionic weapon to data/json/items/melee.json give them NON_STUCK, NO_UNWIELD at least.

How armor protection is calculated

  1. When the player is hit at a specific body part, armor coverage determines whether the armor is hit, or an uncovered part of the player is hit (roll 1d100 against coverage).
  2. If the above roll fails (ie roll value is above coverage), then the armor does not absorb any damage from the blow, neither does it become damaged.
  3. If the above roll succeeds, the armor is hit, possibly absorbing some damage and possibly getting damaged in the process.
  4. The above steps are repeated for each layer of armor on the body part.
  5. Armor protects against bash and cut damage. These are determined by multiplying the armor thickness by the material bash/cut resistance factor respectively, given in materials.json.
  6. If the armor is made from 2 materials types, then it takes a weighted average of the primary material (66%) and secondary material (33%).
  7. Materials resistance factors are given relative to PAPER as a material (this probably needs some fine-tuning for balance).

Adding an iuse function.

  1. Add the new item use code to iuse.cpp and iuse.h.
  2. Add the new json_flag to your item. And link it to the iuse function in item_factory.cpp.
  3. Document the new flag in json_flags.md.

Acid resistance

This determines how items react to acid fields. Item acid resistances are a weighted average of the materials acid resistance (see item::acid_resist):

  • An item acid resistance of zero means it will get corroded every turn;
  • An item acid resistance above zero means it has a chance of getting corroded every turn;
  • An item acid resistance above 9 means completely acidproof.

Acid resistance values are in materials.json, and defined as such:

  • 0 - zero resistance to acid (metals)
  • 1 - partly resistant to acid
  • 2 - very resistant to acid
  • 3 - complete acid resistance

FAQ

Q: How do I prevent an item from showing up in NPC inventory?

A: Add the TRADER_AVOID flag to it.

Q: What the heck is up with the map objects?

A: The pertinent map objects are submap, mapbuffer, map, and overmap. The submap contains the actual map data, in SEEXxSEEY chunks. Vehicles and spawns are stored in vectors because they are relatively sparse. Submaps live in the single global mapbuffer, MAPBUFFER. Map encapsulates the area around the player that is currently active. It contains an array of MAPSIZE * MAPSIZE submap pointers called grid. This is a 2D array, but is mapped to a 1D array for (questionable) indexing purposes. When the player moves from one submap to another, map::shift() is called. It moves the pointers in grid to keep the player centered. The leading edge of grid is populated by map::load(). If the submap has been visited before, it’s loaded from MAPBUFFER. Otherwise a 2x2 chunk of submaps is generated based on the corresponding overmap square type. An overmap encapsulates the large-scale structure of a map (such as location and layout of cities, forests, rivers, roads, etc…). There are an arbitrary number of overmaps. Additional overmaps are generated as the player enters new areas.

Q: What is the relation of NPCs/Monsters vs maps. How are they stored, where are they stored? Are they stored?

A: All npcs are now stored in the overmap. Active npcs only contain the currently active npcs. There is a difference between npc active npc coordinates, and overmap coordinates. So these will need to be changed when saving the npcs. Or else the npcs will be saved at the wrong location. And yes they are stored.

Tileset Web Tool (Experimental)

Use this page to compose/decompose a small tileset directly in your browser.

For normal tileset work, use scripts/tileset.ts instead:

deno run -A scripts/tileset.ts --pack gfx/Retrodays
deno run -A scripts/tileset.ts --unpack gfx/ChestHole16Tileset

See Tilesets for the full workflow. The TypeScript tool was added in PR #8151.

Input directory

Tileset root folder means the folder in your working copy that contains tileset.txt, for example gfx/Retrodays/ or gfx/ChestHole16Tileset/.

For compose, select a folder that contains:

  • tileset.txt
  • tile_info.json
  • one or more pngs_* directories with sprite PNGs and tile_entry JSON files

Name each sprite folder pngs_<sheet name without .png>_<sprite width>x<sprite height>. For the key "normal.png" with 32x32 sprites, the folder is pngs_normal_32x32:

MyTileset/              <- select this folder
├── tileset.txt
├── tile_info.json      <- [ { "width": 32, "height": 32 }, { "normal.png": {} } ]
└── pngs_normal_32x32/
    └── images0/
        ├── t_grass.png
        └── t_grass.json

If the folder you pick has tile_info.json and a pngs_* folder, Compose is selected. If not and it has tile_config.json, Decompose is selected.

For decompose, select a folder that contains:

  • tileset.txt
  • tile_config.json
  • the tilesheet PNG files referenced by tile_config.json

The browser does not upload files. It reads the selected local folder and downloads a ZIP with the result.

Limits

  • Intended for quick validation and tutorial usage.
  • Supports one regular tilesheet per tileset.
  • Preserves pixel data for sprite extraction/composition.



Developer Tooling

Playtesting pull requests

From the repository root, download and launch a PR’s tiles build without compiling locally:

gh auth login
just playtest 10443
just playtest https://github.com/cataclysmbn/Cataclysm-BN/pull/10443
just playtest --os linux https://github.com/cataclysmbn/Cataclysm-BN/pull/10443
just playtest "Exact PR title"
just playtest branch-name

The first argument accepts a PR number, URL, branch, or exact title. Titles must match exactly one PR; quote titles containing spaces. The optional --os is linux, windows, macos, or android, and defaults to the host OS. Desktop builds must run on their matching OS. Linux builds require x86_64; macOS selects Intel or ARM according to the host architecture.

Install just, Deno, and the GitHub CLI. The repository’s justfile also requires Bash, including on Windows. Linux extraction requires GNU tar; macOS uses the built-in hdiutil, ditto, and open tools. The downloaded game still needs its platform’s runtime libraries.

For Android, connect an ARM64 device with USB debugging enabled and ensure adb devices shows one authorized target, then run just playtest --os android https://github.com/cataclysmbn/Cataclysm-BN/pull/10443. This installs or updates the experimental app with adb install -r and launches it. An existing app signed with a different key cannot be updated this way.

Warning

Only playtest PRs you trust: their artifacts execute code on your computer or Android device.

The command selects the newest unexpired artifact matching the PR’s current head SHA. If none exists, check the PR’s matrix workflow: the build may be pending, skipped, failed, or expired. Older commits are not used as a fallback.

Desktop downloads are cached under /tmp/cataclysm-bn/artifacts/PR-<number>-<SHA>/<os>/build-<artifact-id>/. On Windows, the root is %TEMP%\cataclysm-bn\artifacts (the repository directory is used if TEMP is unset). Repeated launches reuse the same artifact directory and preserve its saves and configuration; a new SHA or artifact ID gets a separate directory. Temporary-directory cleanup can remove these files, so copy any saves you want to keep elsewhere. Android saves remain on the device.

Code style (C++)

C++ formatting uses Artistic Style only for top-level src/*.cpp and src/*.h. Most other C++ files use clang-format. Formatter-sensitive fixtures such as tools/clang-tidy-plugin/test/ are left unchanged. Use the repository helpers so each file goes through the right formatter.

Invoking C++ formatting

just fmt
# or, for C++ only
just fmt-cpp

Invoking C++ formatting through CMake

If you have configured a CMake build tree with bash available, this target calls the same C++ helper:

cmake --build <build-dir> --target format

Invoking formatting via pre-commit hook

Install the optional hook with:

just hooks-setup

Astyle extensions for Visual Studio

Use these only for top-level src/*.cpp and src/*.h; use just fmt-cpp for repository style. There are astyle extensions in the Visual Studio Marketplace, but none of them have been confirmed (yet) to correctly work for our purposes on VS2019 or VS2022.

Visual Studio 2022

Head over to https://github.com/olanti-p/BN_Astyle and follow instructions in the README.md. You may compile and install the extension from source, or take advantage of the pre-built version in releases section.

Visual Studio 2019

Extensions’s source code lives over at https://github.com/lukamicoder/astyle-extension. To install and compile it:

  1. Add the Visual Studio extension development workload through Visual Studio installer to your VS2019
  2. Download and extract the source code, or clone the repository (a simple git clone --depth 1 https://github.com/lukamicoder/astyle-extension.git should do).
  3. From the root folder, open astyle-extension/AStyleExtension2017.sln
  4. Select Release build configuration (most likely VS will select Debug configuration by default)
  5. Build the solution
  6. If the build succeeded, you’ll see the compiled extension in AStyleExtension\bin\Release. Double click it to install.
  7. Configure the extension according to Configuration instructions (Visual Studio 2019 or older) section.

Visual Studio 2017 or earlier

You may follow the steps for VS2019 to compile from source, but there are pre-built versions available on Visual Studio Marketplace, you should be able to install the extension through VS’s extension manager and then configure it the same way.

Configuration instructions (Visual Studio 2019 or older):

  1. Go to Tools - Options - AStyle Formatter - General.

  2. Import https://github.com/cataclysmbn/Cataclysm-BN/blob/main/msvc-full-features/AStyleExtension-Cataclysm-BN.cfg on Export/Import tab using Import button:

  1. After import is successful you can see imported rules on C/C++ tab:

  1. Close Options menu, open file to be astyled and use Format Document (Astyle) or Format Selection (Astyle) commands from Edit - Advanced menu.

Note: You can also configure keybindings for aforementioned commands in Tools - Options - Environment - Keybindings menu:

JSON style

See the JSON style guide.

ctags

In addition to the usual means of creating a tags file via e.g. ctags, we provide tools/json_tools/cddatags.py to augment a tags file with locations of definitions taken from CDDA JSON data. cddatags.py is designed to safely update a tags file containing source code tags, so if you want both types of tag in your tags file then you can run ctags -R . && tools/json_tools/cddatags.py.

clang-tidy

Cataclysm has a clang-tidy configuration file and if you have clang-tidy available you can run it to perform static analysis of the codebase. We test with clang-tidy from LLVM 22 with CI, so for the most consistent results, you might want to use that version.

To run it, you have a few options.

  • clang-tidy ships with a wrapper script run-clang-tidy.py.

  • Use CMake’s built-in support by adding -DCMAKE_CXX_CLANG_TIDY=clang-tidy or similar, pointing it to your chosen clang-tidy version.

  • To run clang-tidy directly try something like

grep '"file": "' build/compile_commands.json | \
    sed "s+.*$PWD/++;s+\"$++" | \
    egrep '.' | \
    xargs -P 9 -n 1 clang-tidy -quiet

To focus on a subset of files add their names into the egrep regex in the middle of the command-line.

Custom clang-tidy plugin

We have written our own clang-tidy checks in a custom plugin. refer to clang-tidy.yml for the exact steps to build the plugin on ubuntu 24.04.

Build plugin on Ubuntu 24.04

Follow exact steps in cmake guide with following changes:

Also install these additional dependencies:

sudo apt-get install \
  clang-22 libclang-22-dev llvm-22 llvm-22-dev clang-tidy-22

add CATA_CLANG_TIDY_PLUGIN=ON to cmake flags when configuring the build.

Build plugin on Fedora 40

Follow exact steps in atomic cmake guide with following changes:

Also install these additional dependencies:

sudo dnf install clang-devel llvm-devel clang-tools-extra-devel

add CATA_CLANG_TIDY_PLUGIN=ON to cmake flags when configuring the build.

Using the plugin

To run the plugin on a single file, run following command on project root:

$ ./build-scripts/clang-tidy-wrapper.sh -fix src/event/achievement.cpp

To run the plugin on multiple files, use GNU parallel:

$ parallel ./build-scripts/clang-tidy-wrapper.sh -fix ::: src/*.cpp

include-what-you-use

include-what-you-use (IWYU) is a project intended to optimise includes. It will calculate the required headers and add and remove includes as appropriate.

Running on this codebase revealed some issues. You will need a version of IWYU where the following PR has been merged (which has not yet happened at time of writing, but with luck might make it into the clang-10 release of IWYU):

  • https://github.com/include-what-you-use/include-what-you-use/pull/775

Once you have IWYU built, build the codebase using cmake, with CMAKE_EXPORT_COMPILE_COMMANDS=ON on to create a compilation database (Look for compile_commands.json in the build dir to see whether that worked).

Then run:

iwyu_tool.py -p $CMAKE_BUILD_DIR/compile_commands.json -- -Xiwyu --mapping_file=$PWD/tools/iwyu/cata.imp | fix_includes.py --nosafe_headers --reorder

IWYU will sometimes add C-style library headers which clang-tidy doesn’t like, so you might need to run clang-tidy (as described above) and then re-run IWYU a second time.

There are mapping files in tools/iwyu intended to help IWYU pick the right headers. Mostly they should be fairly obvious, but the SDL mappings might warrant further explanation. We want to force most SDL includes to go via sdl_wrappers.h, because that handles the platform-dependence issues (the include paths are different on Windows). There are a couple of exceptions (SDL_version.h and SDL_mixer.h). The former is because main.cpp can’t include all SDL headers, because they #define WinMain. All the mappings in sdl.imp are designed to make this happen.

We have to use IWYU pragmas in some situations. Some of the reasons are:

  • IWYU has a concept of associated headers, where each cpp file can have some number of such headers. The cpp file is expected to define the things declared in those headers. In Cata, the mapping between headers and cpp files is not nearly so simple, so there are files with multiple associated headers, and files with none. Headers that are not the associated header of any cpp file will not get their includes updated, which could lead to broken builds, so ideally all headers would be associated to some cpp file. You can use the following command to get a list of headers which are not currently associated to any cpp file (requires GNU sed):
diff <(ls src/*.h | sed 's!.*/!!') <(for i in src/*.cpp; do echo $i; sed -n '/^#include/{p; :loop n; p; /^$/q; b loop}' $i; done | grep 'e "' | grep -o '"[^"]*"' | sort -u | tr -d '"')
  • Due to a clang bug, uses in template arguments to explicit instantiations are not counted, which leads to some need for IWYU pragma: keep.

  • Due to these missing features of IWYU, it does not count uses in template arguments to return types, which leads to other requirements for IWYU pragma: keep.

  • IWYU seems to have particular trouble with types used in maps. Have not looked into this in detail, but again worked around it with pragmas.

First Day Guide

Tip

Should you be confused with keybindings at any time, use ? to check your keybindings in game, or use the main menu to display the keybindings menu.

Creating your first character

Points

The points system you choose doesn’t make much of a difference, and in truth the points given to the various options are fairly loose. Most people stick with the default multiple pools, except for when/if they switch into freeform to make truly wacky characters (or to give themselves that little extra boost, like throwing on the Spiritual trait when they’ve already used their trait points up)

This guide will be made using the default points balance on ‘Multiple pools’

Scenario

Scenarios provide the list of available starting map locations, amongst other effects and special attributes to the world. As such, while they are recommended to play around with for experienced users looking for a new challenge or a new way to play the game, it’s recommended to stick with the basic ‘Evacuee’ scenario for your first playthrough (unless you have prior experience with a Cataclysm fork, such as DDA)

Profession

Professions primarily affect what items you start with, but can also grant you starting traits, skills, addictions, bionics, or even spells if you’re running Magical Nights in the future. There’s a wide variety of choices, and mods love to add onto them. In general, this is where a large amount of the flavor in your playthrough comes from, alongside the Scenario.

The default profession of ‘Survivor’ is well balanced and what we will primarily be assuming that you are using in the guide; however, unlike scenarios, it is safer to play around with professions a little even on your first playthrough. We wouldn’t recommend going with something like Defective Cyborg or Tweaker, but Lumberjack or Backpacker are also safe and simple options if you want just a bit of flare (though they will change the tools immediately available to you).

Stats

Strength raises your base HP, increases your carry weight, and contributes majorly to bash damage. Strength also allows you to use higher-power bows effectively, and can sometimes help out in a pinch when working on small vehicles where you’d otherwise need a tool to lift them up.

Dexterity affects your accuracy, and can be good in almost any playthrough.

Intelligence lowers your reading times (i.e. you can read books faster), messes with skill rust if you enabled it (don’t for a first playthrough, and no-body generally runs it in BN in general), and gives a straight up crafting bonus (so that you can craft quicker). It also affects your ability to fail crafts (with a low enough intelligence you can fail boiling water at low skill levels), directly acts as a threshold for many advanced books where you get an additional malus to reading if you do not meet the requirement, and with magic mods it also affects your mana capacity

Perception allows you to aim your guns and other ranged weapons better, gives you better night vision, and also is used for spotting traps before they blow you up. In general, primarily upped on ranged weapon playthroughs.

Stats, compared to skills, are a pain to increase later, especially with the default settings. The primary method is mutating, which is inherently unpredictable (although it aims for a positive net points value by default.) As such, many would put them as being more important than skills. With the Stats through Kills or Stats through Skills mods, however, stats become a lot easier to get.

For a beginner character, it’s not recommended to lower any of these beyond their starting value of 8. A fairly basic stat spread would be 10 Strength, 9 Dexterity, 10 Intelligence, and 9 Perception. Strength is prioritized due to how widely applicable it is, and Intelligence is similarly prioritized due to how useful books can be (and the fact that no-one likes failing crafts).

Traits

Perhaps the most choice-paralysis-inducing menu of the character creation screen, traits can really make-or-break a playthrough. On the left we have the ‘good’ traits, in the middle we have the ‘bad’ traits, and on the right we see ‘neutral’ traits (usually just hair, skin, and eye color in vanilla) alongside certain profession-related traits. Due to the sheer depth that traits can provide, here we’re just going to cover a recommended set for a new player.

Positive traits: Fleet footed (movement bonuses are always nice, lets you kite easier), Infection immune (As of writing, this trait is 1 point. It is an incredible trait, and likely should be higher. In general, a new player is likely to have a very tough time with any infections.), and Pain Recovery (Pain is annoying, and a new player will be going through enough as it is.) Negative traits: Addicitive Personality (practically free), High Thirst (water should not be a concern in game at the moment, just a mild annoyance), Sleepy (despite the points it gives, is pretty free and not much of a concern) Then combine with whatever cosmetic traits you want on the right side (especially recommended is some hair, because as the preview will show you in the top-right, you do NOT have any by default!)

Skills

In general, most of the time you will get crafting skills just by playing normally, most of the ‘interaction’ skills aren’t that useful to have early on, and social skills are practically a dump for most people. Melee and ranged skills are where it’s at for those initial points, though a few shine out and a few aren’t too useful early on (without professions or good game knowledge already). Additionally, one interaction skill in particular heavily shines through.

Recommended skills: Bashing Weapons (the most common weapon type early on, and also somewhat considered the best out of the three in general), Dodging (Because early on you’ll likely be low-enough encumbrance to take advantage of it, and it’s nice to avoid damage entirely), Melee (generalist skill for all melee attacks, useful for martial arts, least useful out of these recommended skills), and the odd one out: First Aid. Unlike the other interaction skills, it is highly useful early on due to how much medical care you’ll likely need after bumbling into some zombies, and it’s also a PAIN to level up unless you have a book, especially early on.

Author’s choice: Dodging and First Aid

Description

Nothing that you can change on this screen matters for gameplay, just go with what seems cool to you / fits your roleplay (Technically Gender has an effect on gameplay, but only if you want to min-max so much that you’d choose Female for the slight bit of extra armor since most professions’ only gender difference is which set of underwear you get.)

Spawning in: The First Day

Welcome to the Evac Shelter, your first base for at least the next few days. Look around a little, maybe use x to look around outside of your immediate screen’s worth of viewing or to look at exactly what each given tile is. Then, proceed on to the first day’s activities.

The First Day: Getting the Tools

Tear down curtains from one of the windows by examining them and choosing the tear option, then wield the heavy stick that drops and use it to smash down the door leading up to the roof (you’ll know which door by the fact that it is locked and informs you as much when trying to walk into it). If your character is failing to damage the door several times, their stamina might fall a decent amount. If your character’s stamina is low, it can be a good idea to manually press | to “Wait a while”, and in particular to wait until you catch your breath. Once you do break down the door, go up there and look around a little, but don’t destroy the solar panel. Then, go back down into the evac shelter and bash up some of the lockers to get metal supplies: In particular, you want to get at least 10 scrap metal and a pipe (The pipe can be particularly troublesome sometimes, so don’t be afraid to bash down the lockers!). Once you’ve gotten the metal supplies, go outside and grab (you can either use grab to grab the items, or you can examine the tile they’re on) a couple rocks off the ground (or bash small boulders if you can’t find any rocks convenient). If you started as a profession that doesn’t start with a knife, you can also use rocks to make a stone knife. Use the Butcher menu while standing on the same tile as the long string from your curtain earlier to process it into small strings, then use the rocks and some wood to make a primitive/stone hammer. Then, use the metal supplies from the lockers to make a screwdriver and makeshift crowbar. Congratulations, you now have your basic set of tools!

The First Day: Gathering Supplies

Now, you can either deconstructing some of the nearby wooden benches to get some extra wood supplies and train your construction skill, or you can get right to going upstairs and deconstructing the standing tank on the roof to get some more metal stuff and in particular some 60L tanks for liquid storage. In order to deconstruct furniture, you have to go into the construction menu, which is bound to * by default, and select the ‘Deconstruct Furniture’ item from the list (pressing / or f to search can make finding it a lot easier). Once you’ve gone up and deconstructed the steel tanks, drag the tanks back downstairs (you can drag items under your feet using \), and then choose to wield one of the tanks and then go outside. Look for the nearest tile of water, and examine it to collect water into the tank. Now, tote it back to the evac shelter with a mind for keeping your eye on your stamina. If it drops too low, then just use | to rest until you catch your breath. You now have a good supply of water back at your base! (You may have to wander a bit to find the water tile, but even a single random spot of it will do)

Before doing any of the following, it is generally advisable to check whether you should craft a makeshift sling to increase your carriable volume. In the case of the default start, it usually is!

From here, you can:

  • Get right to making a brazier, setting up a firewood source nearby that you put some planks on, and get to making some of the unclean water into clean water
  • Go out and forage first to get some food before the brazier rather than after
  • Or, if you’re really brave, go out and try to raid the very edge of a nearby town (or a cabin or farm house if you can find one)

For the purposes of this guide, we will be doing the second option. Foraging in BN is very simple, you just have to find the right plant tiles. It is also very easy to feed yourself on foraging early on, so long as you have enough forest tiles to roam through. In particular, we will be looking out for three things:

  • underbrush
  • fruit (or nut) trees
  • berry bushes

Underbrush is the most variable by far, with what you get from it being a random chance based partly on your survival skill (as well as the season, of course). Some of the things you can get aren’t even food, including shards of glass, cups, and newspapers! Some of the things that are food won’t be useful to us right now, namely things that can’t be cooked into good food without a higher cooking level (such as wild roots). What we are looking for, primarily, is things like bird and reptile eggs or wild vegetables. These are good sources of food that are easy to cook for an early-game survivor.

Fruit and nut trees, as well as berry bushes, largely fall into the same category of usefulness. Fruits and berries are highly seasonal, and as such a decent chunk of the bushes and trees you find right now will not be harvestable in the current season. For Spring, here are some of the ones that are harvestable: Cherries, Blueberries, Strawberries, Grape leaves (but not grapes themselves)

If you’re having terrible luck finding anything from the underbrush and aren’t seeing fruit trees or berry bushes, then here are some additional foragables:

  • dandelions
  • fiddleheads (Not particularly recommended, they tend to be very low caloric value)
  • pine nuts (pine trees, require further processing) Burdocks are also foragable, but the majority of their recipes are locked behind books as of writing. Sad.

The First Day: Cooking

Once you have an inventory or two of foragables collected back at your base, it is time to make a brazier and set up cooking! A brazier can be crafted at Fabrication 1 from a single sheet metal with a hammer, and it allows you to cook safely with fire. Once you’ve crafted it, you must activate the item to deploy it. We recommend putting it close to your ingredients pile and your water tank. Once you’ve deployed your brazier, it’s time to mark down a firewood source for it in the construction menu. This is a helpful marker for where the game should draw valid fuel from when lighting or maintaining a fire in the brazier. We recommend you put a few planks on the marker from your bench deconstruction earlier, but you can also go pick a wide variety of trees for some long sticks to use.

Once you have the brazier deployed and the firewood source marked, you can examine the brazier to start a fire! When you have a fire going, you can also examine it to put out the fire. You now have most of the requirements to cook food, so now you just need to get a pot or pan of some kind to cook with. A makeshift pot is just another sheet metal and 20 minutes away in the crafting menu, which will allow you to cook!

The first thing to “cook” will actually be a batch of clean water. It’s what you want to drink, and it will also get you the first cooking level that you’ll need to cook some of your foragables from earlier. You can make batches of a recipe by hovering over it and hitting b. For now, let’s make 20x clean water. Once you’ve finished making the clean water (and put it away), you should have gained a cooking level and thus be able to try out some more advanced cooking recipes! Your eggs and your veggies will serve you well here, for making items such as scrambled eggs, wild vegetable omelettes, and normal cooked wild vegetables. Your fruits, for the moment, will be best put to use in making cooked fruit (although they, unlike most of your other foragables, can also be eaten raw just fine!) You’ll want to pay attention to your ingredients and see which ones are going to spoil the fastest. For example, if you foraged some dandelions then you best find a way to cook them quickly, because they spoil in about one day! Most fruit spoils in two days, so that can be another concern.

The End of the First Day

Once you’ve cooked up some tasty food, it’s probably about time you invested in making a makeshift bed. Once night falls, it will be much more annoying to get the light to be able to see what you’re doing, and thus it’s a good idea to build a bed now rather than later. A makeshift bed requires Fabrication 2 and some materials that it is easy to get around your evac shelter. Disassembling benches won’t get you beyond Fabrication 1 on its own, so you need to do something that requires Fabrication 1, either in crafting or in construction. Crafting tends to be a bit easier to find things to do in early on, so we’ll look there. While you can choose among a lot of things, we suggest crafting a few wooden needles for the moment since they’re cheap and effective. Once you do have Fabrication 2, you should gather the materials and make yourself a makeshift bed. Once you’ve made your bed, you can place down a sheet or unfold an emergency blanket on it to help you get comfy later!

Now that you have a bed, food, and the basic tools, you can take a look at your clock and the map and see what you want to do. The two main options are either crafting or exploring, with a particular favorite of a lot of people being to do some basic tailoring to end off their first day (which the wooden needle from earlier can help with!). Exploring can be a fun option, as can looting a house on the edge of a nearby town if there is one. Given that where I happened to spawn in where writing this had no town in immediate view, but did have wasps nearby, I elected to do some tailoring.

Tailoring in your evac shelter is fairly straightforward. You either salvage some of the sheets from the curtains in the Butchery menu, or you diassemble them (either from Butchery or from the dedicated diassembly menu on (). Salvaging them is quicker but gives less rags and doesn’t give any thread directly. You can also get thread by turning long strings into short strings and then short strings into thread. Some recipes will also let you use short strings directly! Once you have some rags and some thread, it’s time to consider your options for 0 Tailoring. One of the most popular options is to make a turban, a long patchwork scarf, a pouch, and a bandana to be turned into a blindfold. The turban and scarf help keep your head warm in early spring, the pouch is a useful crafting component much later, and a blindfold can help if you ever need to sleep while it’s still light outside but can’t or don’t want to actually remove the light from the room. From there, the next items on the list would be some more warmth-management items: arm warmers, stockings, light gloves, and tights. Tailoring 2 is where options really start to open up, and you can likely end up crafting some of the progression to Tailoring 3 simply by crafting items fitting for roleplaying.

Once your character is tired and night is starting to fall (about 8 or 9PM), it’s time to go to sleep. Walk over to your bed, Wear your emergency blanket or sheet to cuddle it, and then press $ to sleep. Usually, I like to set an alarm for 9 hours unless I have a particular reason to want to wake up earlier than that or to leave it up to my character. This will conclude your first day in the Cataclysm.

Game file and save corruption

Game files and save corruption falls into following categories:

  1. Caused by your system
  2. Caused by your launcher
  3. Caused by the game
  4. Caused by improper upgrade procedure
  5. Caused by character death

Corruption caused by your system

Common symptoms

  • Nonsensical error messages when trying to load a save (e.g. “expected comma”, or “expected array”)
  • Problematic files, when opened with a decent text editor (Notepad++ for you Windows users), are partially filled with zero bytes or some other gibberish

Common causes and ways to avoid

  1. Insufficient disk space (buy a bigger disk)
  2. Faulty disk (buy a new disk)
  3. Saving on a USB stick / external hard drive and pulling it out without “Safe Removal” (don’t do this)
  4. Blackout (buy a UPS for your computer)
  5. Power loss due to hardware failure (call for a PC repair crew)
  6. Power loss due to user actions (don’t pull the power plug of your PC, don’t shut down laptop by long-pressing power button)
  7. Blue screen or a similar unrecoverable OS error (again, call PC repair crew)

Fixing corruption

There’s nothing we can do about it, but you can try your OS file backup functionality (or game launcher backup functionality, if its backups didn’t get corrupted as well).

Corruption caused by your launcher

Common symptoms

  1. All (or some) saves are suddenly gone
  2. All (or some) of your personal tweaks in [game root]/data/ are suddenly undone
  3. All (or some) of your mods/soundpacks are suddenly gone
  4. All (or some) settings are reset to defaults

Common causes and ways to avoid

  1. The launcher is buggy. Bug the author(s)/maintainer(s) to fix it, or find a different launcher - maybe one that tries to avoid touching user data.
  2. Your mods/soundpacks/personal tweaks were inside [game root]/data/ folder. That folder is for base game stuff only, so don’t get surprised if it gets overwritten/erased/corrupted after an update. Specifically to avoid this situation the game allows placing these files into so-called “user” folders - on Windows, that would be folders named [game root]/mods/ and [game root]/sound/. All personal tweaks should go into a dedicated mod placed into same [game root]/mods/ folder, and when that’s not possible due to limitations of modding system - kept in some backup form, preferably away from [game root]/ to avoid launcher treating it as junk.
  3. The launcher may have some quirks. For example, one of the recent updates of a popular launcher had a big warning on it that some people decided to ignore. Advice here is similar, bug the author(s)/maintainer(s) to solve these (add migration?) or just be more attentive.

Fixing corruption

Not much we can do about this either. Try bugging launcher people for a fix or your OS for the backups.

Corruption caused by the game

Common symptoms

  1. Whenever you load a save, something weird but non-game-breaking happens (you die, or lose 10kg, or your NPC companion teleports around)
  2. Whenever you load a save, the game screams at your about lost item locations

Common causes and ways to avoid

These are game bugs and should be fixed, not avoided. We can’t fix what we don’t know about, so bugs need to be reported - either on GitHub via creating a Bug Report (you only need a working email address to make a GitHub account, it’s not that hard) or by joining our Discord server and complaining in #development channel - you’ll most likely get a faster response there. If you know how to fix it (or want to take a stab at it) - help is always appreciated.

Fixing corruption

Saves in these cases can usually be fixed, though exact method varies on a case-by-case basis.

If the game is showing red-on-black messages that say something about ACT_XXX lost target item or item_location lost target during save/load cycle, try making a backup of the save, then opening your character’s save file (usually [game root]/save/[World Name]/#[gibberish].sav) with any decent text editor (Notepad++ for Windows is ok), finding all occurrences of sequences starting with ACT_ (e.g. ACT_DROP, or ACT_WASH) and replacing them with ACT_NULL.

Corruption caused by improper upgrade procedure

Common symptoms

  1. After a manual update the game is showing weird errors noone you ask knows about, or experiences, even if you’re not using any mods.
  2. The errors go away after a clean reinstall of the game.

Common causes and ways to avoid

You’re most likely updating the game by downloading a fresh version and unpacking it over the existing installation. This is not supported and has never been supported. It is generally a bad idea to update programs in such way, unless they explicitly state they can handle this and it’s allowed. BN can’t handle this. The mods you downloaded and upgraded in same way also most likely can’t handle this.

Fixing corruption

Just do a clean reinstall, or use a launcher.

Corruption caused by character death

Common symptoms

Your character dies - it’s a tragedy, and you wish you could turn back time to the good old days. And then you realize you can do exactly that by pressing Alt+F4. But when loading the save next time, you see your corpse nearby with all items duplicated and your vehicle is nowhere to be seen.

Common causes and ways to avoid

You tried to cheat death, but failed, and ultimately was forgotten among the billions lost in the cataclysm.

Fixing corruption

You’ll have to live with the reminder of your mistakes. Try backing up the save next time. Technically it’s a bug, but it’s also an easy way out, so noone actually cares about fixing it.

New player guide

Tip

Should you be confused with keybindings at any time, use ? to check your keybindings in game, or use the main menu to display the keybindings menu.

Your first character

Runs can end abruptly. Starting as a default survivor in the evac shelter will allow you to learn the game in a fairly stress-free environment. It has solar and a battery so little effort is needed to install an oven or fridge. You can utilize the woods for your food and water, and train up your skills before you go into town. A wooden spear or some form of ranged attack are fairly safe ways of taking out starter zombies. You can be entirely self sufficient via the woods but you are on a race to keep up with monster evolution. The guns in an average gun store will suffice if you can survive and get into one. When you run into somewhere you can’t access, a pickaxe or jackhammer can destroy concrete and metal walls and doors, and a hacksaw can cut the bars off windows. Managing stamina is important in combat. You run out, you will probably die, especially as a new player.

fabrication

You can work your way through fabrication to smithing medieval equipment, as a melee character it will be important. Finding a library in town will let you find the necessary books to read your way to this skill level but you’ll need the book no matter what for recipes. When zombies are little threat either via firearm or melee combat, you will want to look into training other skills, finding a working vehicle, and preparing to loot places of greater danger and reward.

finding CBM’s or mutagens

CBM’s will require an autodoc (unless the manual installation mod is active), and to successfully install you need high first aid, computers, and electronics. Manual installation requires mechanics instead of computers. Some zombies will have CBM’s on them, and dissection with a scalpel and high first aid will yield these. Without saying too much of the mutation system, you will want to loot labs to pursue this route. Turrets are extremely dangerous and can end a run quickly, but that is not all you will find. Unless you have a science ID, you’ll be hacking or using brute force to get in.

Auto actions

Auto actions allows you to minimize keystrokes.

Auto pickup

you can set casings and shotgun hulls to auto pickup. It’s important to utilize auto pickup properly such as weight and volume limits and alongside safe mode to avoid picking up in combat.

Auto pulping

Auto pulping lets you do pulping in combat without pressing smash (s) after every kill.

Auto forage

Auto forage is great for living off the lands but remember to disable it when traveling, and

Auto mining

Auto mining will let you repetitively move into terrain to mine it. Auto mining is dangerous, you may accidentally walk into walls you don’t want to mine or if you use a pickaxe as a weapon you can very likely destroy your base unintentionally.

The Zone manager

The Zone manager (Y) allows you to set sorting zones to auto-sort your loot, deconstruct terrain or vehicles automatically, construction blueprints, or farm fish and chop trees. It is a powerful tool for minimizing keystrokes.

Zone activities

Using (O) your character can do zone activities once you have at least one zone.

Sorting

You need at least one unsorted loot zone to begin sorting things on the ground. You can set an entire house to be an unsorted loot zone and they can overlap. You can use zones on vehicle storage tiles but they can’t be multiple tiles, and even sort into your vehicle. You ONLY sort within unsorted loot zones, not within your inventory. You however use free inventory space to sort loot, so keep your bags clear.

Tips & common questions

  1. You can use TAB while in your inventory for selecting an entire category. I.E. using multidrop with d to drop all food at once.
  2. Rebinding keys can improve your ergonomics significantly, especially if you play with WASD.
  3. Use Safe mode. You can ignore monsters and If it bothers you too much then set proximity distance to something reasonable. Safe mod will save you.
  4. If you want to change crafting range, skill training speed, or experimental 3D vision, you can find it in options under the Debug category.

Updating the game

Do

  1. Get the game from https://github.com/cataclysmbn/Cataclysm-BN/releases
  2. Unpack the game
  3. Copy save and config from old game directory to the new directory
  4. (Optional) Copy the mods from the old game dir

Don’t

Unpack the new game over old directory

Unpacking the game over old directory can cause duplicate JSON entry errors. If you really want to do it, make sure to delete the old data directory before unpacking the new version.

Sometimes data files are deleted in the core. New version of the game will not have those files, but unpacking an archive doesn’t delete the old files. Old files will still be read and loaded, which can overwrite new entries.

Have custom mods in data/mods directory

Put them directly into mods directory, on the same level as data. This directory doesn’t exist by default, but the game will read it if it’s present.

This will allow you to copy the mods between game versions, while still allowing the “core mods” to update properly.

Releases

These are an incomplete list compiled for convenience, see releases for all changes.

Starts with revision 10614 (just before pockets) of CleverRaven/Cataclysm-DDA.

Stable 0.1

Gameplay

  • Victory condition:
    spoilersSomewhere in the rectangular region of the overmap from (0’0, 0’0) to (0’179, 0’179), there’s a central lab (accessible from a tile named “access shaft” on z = -1) that has a red-colored “L” tile at its bottom z-level. Find the lab, reach the bottom, then either sacrifice your own life or put in a mininuke.
  • (Currently WIP, but already functional) Electric grid system, without use of vehicles, but able to connect to them. See Electric Grids page for more info.
  • Lower height levels (z-levels) drawn.
  • Angled vehicles don’t develop “holes” in their normally-impenetrable walls. This affects all relevant game mechanics such as monster and player movement, line of sight calculation, light and scent propagation, etc.
  • Reworked helicopters:
    • Every character/profession can use helicopters
    • It is possible to build helicopters, if you scavenge the blades from an existing one
    • Reduced helicopters fuel consumption to allow flying for ingame hours
    • Rotors no longer break from collisions
    • Atomic Helicopter exist
  • Ranged in general:
    • Burst fire reworked: all shots fired at same accuracy, with recoil-dependent penalty to all of them. Penalty is of same magnitude as dispersion for most guns and can be 0 for lighter ones
    • Headshots downgraded to crits with 150% damage (from >200%), grazing shots upgraded to 50% (was 0%-25%)
    • Some shotgun ammunition provides cone-shaped aoe attack
  • Bows and crossbows:
    • Stats buffed (crossbows much more than bows)
    • Crossbows easier to craft
    • Removed special cases dependent on target hp
  • Buffed drugs roughly back to their pre-nerf stats
    • Except meth, this one provides a long term (12h), weak (5 speed, 1 per) buff and prevents sleepiness
    • Morale boosts from drugs last as long as drug effects themselves
  • Grabs:
    • Grab and pain penalties stack less
    • Physically damaging a grabbing enemy will often break the grab (100% chance for hits taking at least 10% of max hp)
    • Grabs don’t affect blocking and affect dodging much less
    • Grab attacks are faster and followed up by a free regular attack on hit
  • AoE attacks (from axes, spears and lajatangs) lose their requirements
  • Winded condition removed
  • Explosives rebalanced: lower ranges, blast damage rounded to 100%/50%/0%, shrapnel hits exactly once for damage not dependent on distance
    • “Rule Of Cool explosions” debug setting: explosions damage only terrain and creatures in their line of sight, so hiding behind a corner actually works now
  • Explosives, wheels and bullets no longer damage items. Strong enough explosions can still destroy them, and all 3 will pulp corpses that can revive.
  • Fires stack less, makes flamethrowers less damaging to player character
  • Mutations:
    • Trait costs rebalanced to reflect their actual impact better
    • Combat mutations (armor, claws) improved
    • Some “free points” traits removed from character generation (heavy sleeper, bad liar etc.)
    • Undirected mutations happen in bulk, their number based on time since last mutation.
    • Mutations tend towards “somewhat better than at start” point-wise, to compensate for the fact that most bad mutations are more bad than most good mutations are good
    • Mutant toxins redesigned: will cause mutations once accumulated high enough, but cause no penalties
  • CBM installation is now guaranteed, but after that failure effects may still appear. So even failed operation gives bionic to player in workable condition. CBM uninstallation still can fail completely. Autodoc can’t instantly kill the player due to operation failure - instead of doing fatal damage player will be infected. Damage to player body during operation failures is now affected by bionic installation difficulty.
  • Turrets return fire against silent attackers, but not against attackers outside range. Also the code respects turrets’ stats and skills better now.
  • Surgery trains first aid, scaling with target size and number of possible bionics.
  • Food:
    • Remove obesity mechanics and most of stomach mechanics
    • Starvation death now takes a week from fully fed
    • Removed slower hunger/thirst during sleep
  • Removed animal waste product mechanics
  • Removed tetanus, random cold and flu
  • Fungal spores no longer spawn fungaloids, fungal disease doesn’t break arms
  • Reworked food temerature mechanics. Removed “mushy” mechanics. Rot still affected by temperature. Note that freezers still work as intended and prevent rot, and fire makes you warm.

Quality of life

  • Crafting defaults to in inventory/on the ground, best workbench in radius is used anyway
  • Can read items on the floor, in vehicles etc. Reading doesn’t automatically pick up books, but leaves them on the spot.
  • Crafting in progress displays time left and crafting modifiers
  • Butchery uses tools in crafting radius, warns about problems
  • Deployable butchery furniture doesn’t require deployment, works in item form
  • Unloading no longer moves the item to inventory if it wasn’t there before
  • Can move items up and down z-levels in AIM (Advanced Inventory Management)
  • Target list (during shooting and reach attacks) allows shooting through windows and above vehicles (from a turret)
  • Sight range of at least 1 tile is guaranteed when not blind
  • Tile memory does not decay
  • Added accurate firearm dispersion/recoil stats that include all the modifiers (from skill, bionics, encumbrance and so on)

New content

  • Medical zombie tree, focused on debuffing
  • New automated gun turrets replacing CROWS based ones. Less deadly, but don’t drop tons of valuable rifle ammo.
  • Bionic scanner, to detect which corpses are worth cutting up

Performance

  • Fires do not produce hot air and smoke, no longer affected by wind
  • Option to disable event bus system (in Debug tab) - removes one big cycle hog, but also achievements and statistics
  • Food isn’t affected by radiant heat or hot air
  • Removed slow fd_clairvoyant check which only benefited Magiclysm, but slowed down everyone
  • Cache list of all vehicles on map, since getting it is slow in 3D mode

Ported from later versions of DDA

  • Ground vehicle z-level transitions and z+1 bridges. Ramps can be enabled through “Z-levels” world setting, new bridge generation - through “Elevated bridges” mod.
  • Graphical overmap drawn with SDL using sprites.
  • Improved autodrive.
  • Various under-the-hood improvements, such as refactors and optimizations.
  • Hundreds of bugfixes and small changes.

Other

  • 3rd party mods translation support
  • UnDeadPeople tileset included
  • Restored atomic cars
  • Restored MBR vests (with some rebalance). ESAPI vest removed

Stable 0.10

This summary lists the most significant changes from this release. This release includes 188 changes, including features and bugfixes.

Gameplay

  • NPC trade and dialogue interfaces were reworked to improve response selection and interaction flow
  • Added a world option for initial trait purification and cancellation
  • Climbing trees can trigger slips and heavy impacts can knock survivors off unstable terrain
  • Vehicle idle lift now reduces drag and supports floating at ground level
  • Added vehicle turret autoloaders

New Content

  • Added cargo ship overmap specials with non-square nested mapgen support
  • Mainlined additional MST Extra content into the core game
  • Added aluminum boat hulls and wooden wing tiles for vehicle construction
  • Added GUNSHY and Nyctophobia traits
  • Added gun enchantments and recreational furniture constructions

Balance

  • Mininuke damage was increased from 300 to 3000
  • CBM body slot costs were rebalanced and microreactor behavior was adjusted into atomic battery workflow
  • Plutonium cells were reworked to self-charge over time and battery compartments now accept military plutonium fuel cells
  • Medieval armor materials were adjusted to increase protection and autoloader power draw was reduced from 50 kJ to 5 kJ
  • Extended toolset was obsoleted and its repair and cauterize functions were moved to integrated toolset

Infrastructure

  • Android now uses a user-accessible mod directory
  • Bullet and thrown item sprites are now customizable through JSON
  • Item variables can now be defined in JSON
  • Lua now supports proper relative and absolute require paths with expanded NPC and dialogue hooks
  • Save format v2 is now current and v1 is marked legacy

Bugfixes

  • Fixed flying robots to be hackable again
  • Fixed crashes in training activities
  • Fixed Mycus fruit-eating crashes and progression blockers that could softlock Mycus characters
  • Fixed items disappearing when loading smoking racks and charcoal kilns
  • Fixed vehicle ladders so they function without install-order dependency

Ported from DDA

  • Ported the relentless hulk and NEMESIS content set including its scenario
  • Ported directed trap disarm changes that remove base difficulty checks

See full changelog here: https://github.com/cataclysmbn/Cataclysm-BN/releases/tag/v0.10.0

Stable 0.11.1

This release includes 186 commits.

Fluid Grids

You have seen electric grid, now we present you the fluid grid™. Water tanks, sinks, rain collectors, and purifiers are now usable, just like the founding fathers intended. To begin working with fluids, get hold of utility maintenance kit.

Credits

Better Performance

More multithreading! Far monsters use simpler AI so that also makes stuff happen faster. Item processing and crafting waste less time.

beforeafter
Credits

More vehicle (part)s

speedway beforespeedway after
Excavator and trencher beforeExcavator and trencher after
  • Large freezer and fridge vehicle parts for all your 30 kilograms of ice cream needs.
  • Carbon fiber vehicle parts added, ’cause your deathcopter can never be too light.
  • More vehicle redesigns to make them look better.
Credits

Map and location

Lookout towers, drive-ins, hunting lodges, lighthouse variants are added.

screenshots

Credits

UI cleanup

our glorious new night vision coloras the founding fathers intended
  • Night vision color can be configured
  • Repair chance, worn techniques added to UI
  • Hostile targets now prioritized when aiming
Credits

Bugfixes

JSON Modding

Tileset Compose/Decompose on web

Caution

experimental ATM, use at your own risk

You can now compose/decompose tilesets on docs site: https://docs.cataclysmbn.org/dev/reference/tileset_web_tool/.

Lua Modding

For more, read docs/en/mod/lua/tutorial/modding.md, docs/en/mod/lua/hooks.md, docs/en/mod/lua/reference/lua.md, docs/en/mod/lua/guides/cookbook.md, docs/en/mod/lua/guides/binding.md.

See full changelog here: https://github.com/cataclysmbn/Cataclysm-BN/releases/tag/v0.11.1

Stable 0.12.0

This release includes 617 commits

Construction and crafting menus

Construction blueprints are easier to read, construction categories are reorganized, and nested crafting categories make long recipe lists less painful.

Credits

NPC crafting

Companions can craft for you through a new NPC crafting interface. Give them supplies, pick a recipe, and let the camp get work done.

Credits

Map engine and performance

The map data overhaul adds dynamic reality bubbles, chunk loading, and multi-dimension support. Map loading, cache iteration, creature iteration, and mapgen now waste less time.

Credits

Aircraft, jets, and hover vehicles

screenshots: #8305, #8532, #8485, #8623, #8734, #8736

Cargo planes, passenger planes, bikeplanes, wooden planes, F-35 and F-15E jets, jet engines, and hover parts expand what can fly or skim across the Cataclysm.

Credits

Tanks and heavy vehicles

Most of Tankmod is now in-repo. Tankers, hover tanks, hover APCs, tankbots, and the Beagle UGV also received new spawns, sprites, and balance work.

Credits

Painting and vehicle colors

screenshots: #8713, #8783, #8788, #8797, #8801, #8807, #8944

Spray cans can paint vehicle parts, terrain, furniture, and items. Many vehicles now spawn with fitting color palettes, from police and construction fleets to farm vehicles, aircraft, military vehicles, and wooden planes.

Credits

New locations

screenshots: #8835, #8742, #8688, #8621

Trans Coast Logistics Centers, outlet malls, light industry sites, state police stations, military airfields, and military blacksites add more destinations worth planning a raid around.

Credits

Labs and finales

Labs are smaller and less samey, with new rooms, better loot, zombie admins, door override codes, new finales, and ice lab exclusive rooms.

Credits

Old Guard doctor questline

The Old Guard doctor questline has revamped missions 1–5, new Old Guard equipment rewards, and fixes for the final mission path.

Credits

Mutants and boss fights

Military outposts, labs, and mutation paths gained new threats and rewards: new bosses, medical and alpha samples, an elf-a mutant, shadow stingers, stronger Large and Huge mutations, and a more viable Chimera path.

Credits

More in-repo mods

Arcana and Magic Items is now an in-repo mod. Geomagnetic storms can also charge player bionics as optional mod content.

Credits

More quests, companions, and mounts

Wasp nests are rarer, the refugee center has a wasp exterminator quest, animals can train persistent bonuses, and combat mounts are available.

Credits

Weapons and combat tuning

media: #8301, #9154, #8471

Shotguns gained the DP-12 and pelletized ammo behavior, wearable guns arrived, cross-z melee is harder, and several launchers and rockets were tuned.

Credits

UI and quality of life

media: #8450, #8526
look around beforelook around after
extended info beforeextended info after

Look around and extended info menus show more useful details. Pickup, unload all, last spell recast, wait-time entry, map notes, and item tags also received cleanup.

Credits

SDL3 and platform fixes

The SDL3 migration landed, bitmap font loading was fixed, mods can define loading splash images, and Android can use the legacy storage directory again.

Credits

Bugfixes

More performance work

JSON Modding

Lua Modding

Mods

Other player-facing changes

Development, build, and docs

See the current comparison here: https://github.com/cataclysmbn/Cataclysm-BN/compare/v0.11.1...main

Stable 0.2

Gameplay

  • Rework teleglow, nether attention, stare monattack.
  • AI now can target and shoot moving cars.
  • Food items now show how temperature affects it rot.
  • Graphical overmap now enabled by default. Obsolete Graphical Overmap mod, rename to Larwick’s Overmap.
  • Reorganized mod resources. All Bright Nights resources now labeled with unique id.
  • Allows pushing vehicles over ramps.
  • Melee skill actually impacts attack stamina usage.
  • Add the ability to mark items as favorite from the multidrop menu.

Balance

  • Finished ammo and armor rebalance. Armour piercing ammunition now more effective agaisnt armored targets, but armor in certain cases provides somewhat better protection against gunshots. Changes included reworked power armor stats.
  • remove glare protection requirement for forged frames.
  • Make bicycle alternators (dynamos) craftable.
  • Allow repairing items with forges.
  • Allow easier installing/removing of some parts.
  • Robots no longer completely immune to lasers.
  • Prevents dodge gain exploit.
  • Wraith and shadow special attack updates.
  • Shadow and cult creature updates from Arcana.
  • Adjustments to mi-go locations, atmosphere field.

Quality of Life

  • Added ability Submit bug report directly from game.
  • Reduce blinking effects speed (300 -> 800ms), and add an option to change it in game.
  • Deactivate pet robots in pet menu instead of query.
  • While flying, warn when letting go of control or stop driving.

Infrastructure

  • Migrate to C++17.
  • Implement relic recharge.
  • Grid constructions now use workshop category.
  • Allow marking construction recipes as favorite, sort recipes by name in construction UI.

New Content

  • Added new electric grid appliances.
  • Adds grid forge rigs, chemistry sets, and chemlabs.
  • Added hauler bot.
  • Most of the building contains built in electric grids.
  • Add grid flag to more specials, mods in particular.
  • Added new helicopter parts group to helipad.
  • Add mountable autodoc and autodoc couch.

Ported from later versions of DDA

  • Port complete leash and lead system.
  • Port over fix for spellcasting monsters and summon spells.
  • Updated DinoMod.
  • Add in-game progression diary.
  • Cathedral overhaul.
  • add NPCs to biker_dump.
  • Port Barbaran Montante and rebalance.

Other

  • Add missing damage sources kills and suicide to kills list.

Stable 0.3

Gameplay

  • New scenario: Play as Feral and befriend with zombies (on certain conditions).
  • Added ability to manually connect and disconnect multiple power grids via voltmeter and some materials.
  • Added shields to the game.
  • Further improvements to Rule of Cool explosions:
    • Chain explosions.
    • Items turn into shrapnel.
    • Custom animations.

Balance

  • Improved mechs.
  • Added craftable helicopter rotors.
  • Water cannons can now fire acid.
  • Buffed water purification methods.
  • Yet more tweaks to bows (decreased damage, strength cap is now a soft cap).
  • Tweaked power armor spawn locations.

New content

  • Added new CBMs. Some CBMs ported from existing mods.
  • A lot of locations reworked and improved.
  • Expansion to the Old Guard faction.

Infrastructure

  • Lab Finale rework.
  • Updates to build files.
  • Weapon categories for martial arts and gunmods (eases mod integrations).
  • Allow NPCs to use all bionic weapons not just the hardcoded list.
  • Improve code for NPC method of attack, generally improving their ability to choose weapons and attacks. Allows them to reload magazines and perform combat reloads with single shot weapons.

Bugfixes

  • Multiple bugfixes related to NPC AI weapon selection and ranged attacks.
  • Fixes to off-road vehicle behavior.
  • Fix to the long-standing issue when not all overmap specials could spawn if there were too many mods enabled.
  • Fixes to monster attacks and movement over z-levels.

Ported from later versions of DDA

  • Feral humans (with additional tweaks).
  • Additional achievements.

Stable 0.4

Content

Balance

Bugfixes

Build

Features

Interface

Infrastructure

I18n

Performance

Mods

How it all started

Caution

spoiler alert

spoilers below!

Cataclysm

Many humans will remember the Cataclysm as a singular event, when the dead came to life and unimaginable horrors took to the streets to pour death and carnage onto the Earth. However, it was actually a fairly gradual process. Dimensional research, both by the United States and various other nations, slowly weakened the dimensional walls separating our reality from the Nethereum, at least on Earth. The effect of this was fairly gradual at first, with mutations becoming easier over time, revivication near portals becoming faster and stronger, so slowly over the years that few even noticed.

The tipping point however, was when XEDRA decided to open one of the largest portals of ever devised by their minds in New England. This weakened the dimensional walls enough for it to shatter, letting a deluge of both XE037 and it’s associated energies into our reality. The proceeding event is what is now known as the Cataclysm, as horrific portal storms and all the worst nightmares of a few dozen realities flooded onto our world for several days. By the time the tides settled, the Nethereum and ours finally reaching an equilibrium, the world had been devastated, governments had collapsed and civilization as we knew it was destroyed.

The various portals throughout the world keep ours and the Nethereum connected, but this is not a truly stable equilibrium. If the walls between our dimensions are not repaired, if not enough portals are closed or stabilized, eventually the Earth will suffer a local dimensional collapse, folding into itself like a used bandage to quarantine us and protect both the rest of our reality and the Nethereum from further dimensional destruction. (Timeline unknown because if it’s within a lifetime I guarantee you some player will wait until that date just to make a bug report that nothing happened.)

More expansion to follow.

Factions

Caution

spoiler alert

spoilers below!

Also worth noting these include future plans, and is a framework for what future additions/lore reworks should keep in mind, rather than what is currently already in the game.

America

Society

The future government of America is sensationalist, reckless, and in many ways quite dystopian. However, the average person’s life is pretty good, aside from the constant threat (or at least claims of a threat) of military attacks by some foreign power (usually China or Russia) that may or may not actually be plotting major military actions. The government has encouraged disaster preparedness among the population, and firearm restrictions are distinctly different than they are now. While not everyone can purchase and own a firearm, and firearm ownership is very closely tracked, it is also actively encouraged by the government to fight off any potential invaders, and higher caliber firearms and explosives are actually available on the civilian market.

Evac Shelters

The evac shelters were built as part of a government program to help improve both the morale of the populace at large (by convincing them the government was looking out for them) while also increasing the general sense of fear and danger (by convincing the populace such shelters were needed). They approved effective at these goals. The shelters were not, however, ever actually stocked - the funding fell out when the military realized both goals had been effectively accomplished, and no more money needed to be wasted on them. After all, in the event that the shelters would ever actually be needed, it is unlikely they would end up very useful - any major military attack was unlikely to leave many survivors. Standing as empty unstocked, relatively insecure buildings on the outskirts of the city reminding people of what could happen was the only service they were ever actually expected to provide.

Nether

The Nethereum is a transitive plane, sequestered between realities. It is constantly in flux as it mirrors the various worlds that it borders through XE037. The rules and constants between each reality vary wildly, and within the Nethereum it continuously swings between them, trying and failing to find a balance. The creatures within are no different, each is a reflection of some creature from another reality, distorted, incomplete and uncanny. Most are unintelligent or animalistic, incomplete snapshots. However, greater, intelligent life does exist within the Nethereum, their forms stretching across the void with an intelligence that regards us with the same foreign curiosity as a child. Unfortunately, any true contact would only cause madness, as they exist in accordance to concepts that make no logical sense, and indeed do not exist on our world. Fortunately, our world is as difficult for them to access as theirs is to ours, and they lack the focus and technology to ever succeed on their own.

Nether creatures are utterly alien to reality, their bodies rely on the nearby gashes in reality to sustain their impossible forms. Should the portals be closed and the bleed between realities stymied in some way, the more fantastical nethereum creatures would likely die where they stand.

The Nethereum itself has a strange connection to the subconscious mind of sapient life. In dreams and more traumatically, while in the throes of madness, it is possible to gain glimpses of the Nethereum’s chaotic plane. Such insights have inspired books across countless civilizations of eldritch horrors and creatures that haunt beyond the edge of reality. In the same way, most contact with the Nethereum outside of portals is mental, even with the fabric of reality degraded as it is. Sometimes information from beings beyond our realm, helpful or not, seeps in through these cracks, if one is capable of deciphering it.

Pocket dimensions are constantly forming within the Nethereum, echoes and reflections of worlds far beyond our ability to percieve. Portal storms are locations where these pocket dimensions bleed into our own, and if the correct conduit can be created, and enough energy gathered, it could be possible for humanity to reach into these broken reflections to seek out technologies and materials developed by other realities. Be cautious, such dark reflections may not function as originally intended, and it will be defended by dark reflections of other things as well…

Blob

Origin (What is it?)

The Blob, otherwise known as XE037, is the basic building block of the Nether, all creatures and structures within the Nethereum great and small are formed primarily of this substance. It displays properties that do not conform to the standard theory of matter, able to change it’s characteristics and restructure itself seemingly at random. As the Nethereum itself has very weak, if any immutable physical laws, XE037 structures itself in response to the weak interactions when the Nethereum and other planes intersect. It is also heavily affected by consciousness, and in the very rare occassions that minds intersect with the Nethereum it spawns worlds from their dreams… or nightmares. It is the primary contributor to the state of the Nether being a roiling storm of complete chaos. Post Cataclysm, the entirety of the Earth has been blanketed due to gashes in reality caused by the Cataclysm.

Infection and Effects on Living Hosts

“Infection” by the blob is caused when organisms take up the blob into their cells, replacing a portion of their regular mass with XE037. Saturation rates of XE037 in living creatures appears to be a ratio affected only slightly by exposure, even immersed within the Nethereum itself only a small portion of a creature’s mass will be replaced. For lower lifeforms, this has very little effect, XE037 functions as whatever mass it was meant to replace, seeming to stabilize in reaction to whatever has taken it up. For animals, XE037 has the effect of improving their functions, making them stronger, faster, more of whatever they were before, as well as improving their healing abilties. Insects however show the most drastic changes, as the improvement of their oxygen intake means that they grow much larger than we have seen in recent history, approaching or even exceeding prehistoric sizes.

In humans however, the effect is markedly different. XE037 appears capable of restructuring the body, from simple things like increased muscle mass, brain matter, or thickened skin to drastic changes like rapid bone restructuring, and growth of organs that do not typically exist in the species. Some of these effects appear to be the Blob reactivating dormant phenotypes (perhaps surprisingly gills are classified under these) or over/under expressing certain genes. However, many of the more drastic changes seem to use DNA that has never existed within the species, possibly some form of “memory” within XE037 regarding the other realities it has come into contact with before. While similar to their earth counterparts, many of these structures are subtly different. A subject’s sense of self and consciousness appears to be involved in the transformations, and to access transformational mutations a subject’s sense of self must be temporarily altered, this alteration however typically becomes permanent once the “threshold” has been crossed, causing the subject to permanently identify more closely with the target specimen. This strange limitation of ego has casually reignited philosophical questions of consciousness amongst the more fringe scientists, who suggest that this could be a sign of the soul. Animals and insects thus far have never been observed to have the same breadth of mutations, it is suggested that their inability to reinvent themselves mentally contributes to this.

Death of Hosts

On death however the seemingly artificial limitations on mutation are removed. Regeneration is initiated, with the corpse cannibalizing itself as the Blob takes drastic steps to reanimate the host. The host however, is no longer in control of their body, with the Blob driving them to feed and survive. The mutations begin to grow ever more bizarre, the Blob hijacking more and more of the cellular makeup of the host, repurposing toward more aggressive purposes (acid/spitter zombies, skeletal juggernauts, etc). The Blob in this state also seems capable of hijacking bionics within the body, utilizing power storage as sources of electrical shocks, electromagnet implants in industrial workers, or utilizing the martial art subroutines within Close Quarter Battle CBMs (explaining why bio-operatives seem capable of doing martial arts). It is theorised that the mutations integrating bionics may not be unique to “zombies”, but would require a human with a distorted sense of self that considers the human and machine parts of their body to be one and the same. Testing of this was prematurely halted by the Cataclysm (partially explaining the Prototype/Broken Cyborgs)

Ferals

In humans with abnormal mentation or brain damage, the changes wrought by XE037 are similar to that of zombification, but only partially. Such “ferals” retain a lot more of their human intelligence and tool use, and are not nearly as horrifically mutated, but are invariably psychotically violent to all other living creatures around them. Zombies appear to consider them kin, and they in turn are not violent to other zombies. It’s unknown if recovery is even possible for humans affected in this way, though it is theorized that XE037 may itself be trying to remedy the injury in it’s own undirected way. The proliferation and infiltration of XE037 into much of the host cells however, means that it is highly likely that any attempt to strip XE037 from the subject would result in death.

Player Interactions

As the Blob has no higher consciousness and no collective it cannot be fought in the conventional sense. However, humanity is capable of severely diminishing the threat of the Blob, at least in regards to reanimation and mutation. Research prior to the Cataclysm has revealed that the energy deficit incurred during reanimation and to some extent their activity after is sustained by nearby portal activity in a similar way to Nethereum creatures. A certain threshold of energy must be reached before reanimation is even possible, further explaining why only corpses of a certain size are able to reanimate. Deep underground in New England, a central lab exists with the largest working portal on the continent. It’s activation was the tipping point of our dimensional instability, leading to rapid global reanimation of corpses and accelerated mutation where prior cases had been limited to the local area within labs and near portals, and slow to ineffectual elsewhere. (Explaining how the Cataclysm could’ve gotten so out of control so quickly.) In the aftermath, once dimensional fatigue had settled to a more stable state, it now generates the portal energies needed to sustain much of the zombies throughout the continent. If this can be disabled, zombie activity would become much reduced, as would their evolution.

Mycus

Origin (What is it?)

The Mycus were once a species of parasitic brain fungus on their homeworld, taking control of various animals and using them to spread itself across the planet. Over time, the connection between brain and fungus became more and more tight knit, until eventually brain and fungus melted into one another, a symbiosis that subsumed their hosts and infiltrated into their very flesh. Their sapience was originally formed via weak telepathy between each animal they had infected, and since their existence they have never known the concept of individualism. There is only the Mycus.

Spreading across the universe, the Mycus found nothing, barren planets and occasionally more hosts, but no other minds for them to connect to, to commune. The Mycus turned their gaze beyond their reality, seeking others beyond their reality. Cautious about the world beyond, they never opened the physical portals into the Nethereum until they had perfected their understanding of it, instead only using it to observe other universes for sapient life. By luck, their first inhabited universe was our own, in the midst of the Cataclysm. The Mycus watched as civilization was sundered by the various Nether creatures and reanimated monstrosities, and mourned the passing of an intelligence that might have finally been their peer. Yet as they watched, the tiny fleshlings endured. Single fleshlings joined in communion with others, conclaves formed, yet were a pale shadow of their former glory, while others were lost, wandering into a doomed world.

The Mycus believe the intelligence must still remain, fragmented between their myriad of hosts, for them to be able to continue their function. If the fragments could be gathered, combined, they might yet survive the possibility of local dimensional collapse, and through this the Mycus would achieve Communion. They gathered their spores, readied their portals, and sent forth a legion of spores into the Nethereum, toward humanity. Any of their flesh hosts would not be able to survive the journey, but the spores would, even if many would be lost in the tumultous expanse all that was needed was a single main node. The Mycus would grow.

Goal

The goal of the Mycus is at its heart, altruistic, it wants to make humanity whole again. Unfortunately it has no understanding of individuality, and does not understand that humanity is not a hive mind like itself but a collection of individual minds working together (or against one another). It’s approach toward individual humans is much like the way one would treat a baby or frightened animal, it believes we have been fractured so badly that we no longer have the intelligence to comprehend it and have been reduced to hiding from the many monsters in our new world. It thus entices individuals and conclaves with fruit and the soothing promise of communion. It forgives humanity for attacking it and refusing communion because we just don’t know any better.

Blob Interactions

The Mycus is capable of subverting the blob, but only partially. As a majority of the blob’s effects are inhibited by a creature’s sense of self, a Mycus infection uses the Mycus’ own presence to take control of the body. This is only temporary, and as a result the Mycus weakens the zombies it infects to dispose of them more permanently later.

Player Interactions

The player should have several ways of dealing with this. The first is the obvious solution, to burn the Mycus to the ground, there is no Queen that controls the Mycus in its totality, but the destruction of groves, towers, and similar terrain will prevent the Mycus from properly regrouping or replenishing their numbers. Another method is for the player that decides humanity’s collective mind is best given to the Mycus, so that they may bring it back to their world where it will live with the Mycus forever more, all differences erased. The final solution is that of diplomacy, to convince the Mycus that we are both not a hive mind, and that our individuality is not a defect to be removed. If this can be achieved, the Mycus may be persuaded to enter a symbiotic relationship with humanity to aid it in its efforts to heal the world before it succumbs to dimensional collapse. Examples of such aid include companions, skills downloaded from the collective mind, resurrection using a prior template of one’s mind, or bombs to infect and weaken zombies via Mycus.

Migo

Origin (What are they?)

The Migo are a species of carapace covered humanoids with what appears to be an eusocial caste system. Each individual is uniquely adapted to it’s station, and if a unit is needed for a specific station a worker drone would be elevated to the appropriate position and properly augmented, though it would appear that such specialization is permanent. Their society is built on an ironclad sense of responsibility to the perpetuation of their species. Each Migo has a rudimentary telepathic bond with nearby Migo, allowing them to exchange thoughts and emotions but not memories, despite this they lack a true ego and will do anything up to and including self-sacrifice if it serves their interests as a whole.

Migo technology is highly advanced but bio-mechanically engineered, and cannot be directly used by non-migo. However, the underlying mechanisms and science can be replicated with the right materials and knowhow, allowing one with the appropriate knowledge to turn their weapons and technology onto their makers, whether this is resin production and manipulation or the reconstruction of their “slaver beams” all their technology is repurposable. Their bodies do not tolerate cold well, and generally function best in what would be charitably described as a sauna for humanity.

First Contact

In the distant past a group of Migo were stranded in the ice caps due to a failed dimensional jump. Prior to the Cataclysm the craft’s remnants and a few migo stuck in stasis, were recovered by the group that would eventually become XEDRA. The incomplete workings of the dimensional drive they used filled in gaps into the study of space and dimensional travel, though humanity is still a long way from the controlled travel that the migo themselves seem capable of now. Unbecknowst to them, meddling with the craft sent out a distress call, which called the Migo toward humanity.

When the Migo arrived, they originally were meant to function in secret, gathering information on humanity to assess their threat level to the Migo and provide countermeasures should they ever breach into true dimensional travel and meet the main body of the Migo civilization. It was during this operation that the Cataclysm began. In the ensuing chaos it became abundantly clear to the Migo that humanity had been compromised by an extradimensional threat. Further testing and several raids confirmed that the Nethereum and the blob were responsible.

As the Migo have mastered dimensional travel, their understanding of the blob is far above humanity. Enough so that they have countermeasures in place to prevent their reanimation and mutation. As this technology was designed for their biology it will not work on humanity without heavy modification, and integrated into Migo biology as it is it will not be noticable to all but the most dedicated of xenobiologists.

Goals

With the dimensional instability of the planet, the migo are cut off from their home, and much of their current purpose is to reestablish communication as well as create a safe portal with which to evacuate the planet prior to local dimensional collapse. The Cataclysm took them by surprise, as while they were aware of humanity’s experiments on dimensional travel, and had brought in a few of their own scientists to observe their results, they were not prepared for the absolutely monumental cock up XEDRA had facilitated. As such they lack the manpower and material with which to achieve their mission. To make up for this, they are experimenting with conversion of the local population, to manpower or material, such that they may form an appropriate beacon with which to escape Earth.

The Migo do not resent humanity for its role in experimenting on it’s units, as a society they are unable to hate due to a lack of ego and thus personal investment in their enemy is anathema. Despite this, the experimentation and mental instability displayed by remaining humans has caused them to classify humanity as a threat to the Migo, and actions will be taken to prevent humanity from threatening their home and their people.

Player Interactions

The player should mostly learn about the migo second hand, from things they find either in the towers, testimony from captives, etc. The migo should never enter into diplomatic contact with humanity, as it does not serve their goals, and in general humanity is considered too unstable for any sort of partnership. The player should however be able to recover their technology and repurpose it for their own use.

Triffids

Origins (What is it?)

The triffids are a species of humanoid plants, but it is more accurate to consider them an ecosystem unto themselves. The core of this ecosystem is the Triffid Heart, from it, a forest springs forth that creates the various triffid warriors, queens and other members of their ranks. Despite appearances, they are not sapient, in fact, it is difficult to say if the Triffids are even sentient. The triffid ecosystem functions entirely on instinct, it’s only purpose is to consume, grow, and propagate to another planet to continue the cycle. To this end, it’s various guardians roam about gathering materials to feed the construction of a biological cannon capable of launching a new heart into space.

Each stimuli triggers a response from the Triffid heart, causing it to pull blueprints and engineer instinctive responses into the next batch of guardians. The existence of fungus opponents triggers fungicidal guardians, while contact with the blob seems to have caused them to gain some kind of resistance to them. It is unknown how the Triffid could have come to possess such a feature, but if the speculation that the Triffids are a biological machine created by an alien faction are correct, then it suggests that this alien faction has had contact with the Blob before. Whether it’s downfall was precipitated by the Blob or not, it suggests that the Triffid’s creators were well aware of the risks the Blob can introduce into biological organisms.

Some scholars speculate that the Triffid Heart was the final time capsule of a dying race, designed to seed worlds with information for those advanced enough to learn it. The Triffid Heart is thus of much interest, it could contain incalculable knowledge, whether in regards to the blob, the nether, blueprints for weapons or the “magic” that the Triffid Queen wields, or perhaps other biological catalysts that could be of use to humanity.

Player Interactions

Players should be able to salvage Triffid Hearts and use them to unlock certain recipes or use them as components for certain recipes.

Xedra Notes

Caution

spoiler alert

spoilers below! All of this is to be revised to fit new lore introduced in Factions

Note #356-92-XE

Earlier conjecture that revivification occurred only in humans was premature. Thanks to the discover of the substances ability to revivify large canines, the properties of XE-037 in mammalian organisms is now far more clear.

From what we can tell so far, exposure introduces a persistent, low level infection in mammal subjects, regardless of size or nature. The substance seems to multiply within the body until it reaches a certain point, and then enters a form of stasis and ceases to grow. It is, as yet, unknown why this halting process occurs in mammals, but not in insects - further research is needed. The body does not seem to attempt to combat the invader, and in fact no defenses have been noted - the body simply ignores the presence of the substance.

The spread seems to halt at roughly 1% of body mass, though exact numbers are difficult to determine thanks to the risk of mid-autopsy revivification.

The reason why earlier reports confined revivification to humans was that the process requires a critical amount of XE-037 within the body, not as a percent but as pure weight. Around 250g seems to be enough to insure a post-mortem takeover. Animals small enough that 1% of body mass falls below this threshold thus fail to revivify, and the infection shrinks and then dies several hours after it’s host organism has passed. In larger animals, expiration seems to serve only to raise the cap on XE-037 within the body - expiration quickly leads to the XE-037 breaking down many of the now inactive bits of it’s host until it makes up almost 4% of body mass. At some point towards the end of this process, the host organism revives in the manner we are all, by now, familiar with, seemingly under the full control of the substance.

Note #376-92-XE

Infected subjects that sustain extreme trauma before death seem to exhibit lower growth level in internal XE-037, which can be lower than the expected 4%. Revivification of subjects in such cases is slower. This lead to the conclusion that XE-037 “prefers” less damaged corpses.
Additionally, damage beyond a certain threshold, such as the removal of several internal organs, quartering the corpse, or exposure to high explosive or heat, seems to overwhelm the XE-037 infection, causing the same dwindling and death behaviour seen in smaller organisms.

Note #377-92-XE

Observations that high-trauma revivification subjects are not noticeably different from low-trauma subjects have proven to be premature. The 93-XE series of studies has been designated for consolidating existing data and performing additional research after the labs have been repaired and personnel replaced.

Timeline

Caution

spoiler alert

spoilers below! Heavily to be revised for lore changes in Factions.

Timeline

T-6 Years

Drones (eyebots) used in police work.

T-4 Years

Personal bionics become commonplace for the wealthy, and for those withhigh-demand government positions.

T-3 Years

Escalations in China and DPRK lead to a “Cold War,” with both sides highly prioritizing defense research.

T-3 Years

Transposition along 4th axis discovered by DARPA researchers.

T-3 Years

Robotic police officers enter service in limited areas.

T-30 Months

4th dimensional topology mapped out. It’s found that certain areas are “lower” along the 4th axis, allowing for relatively low-energy transposition into areas of interest.

T-28 Months

Collection of materials along 4th axis commences. First contamination occurs but is confined to the two research labs with transposition equipment, and is in amounts so tiny (a few dozen molecules) that it is not remarked upon.

T-25 Months

Gun control laws greatly relaxed as a result of perceived increase in public safety.

T-20 Months

Robotic police officers are used in 95% of police precincts.

T-18 Months

A new federal agency, the Xenophysical Energy Defense Research Agency (XEDRA), is created to oversee the construction and operation of 12 new 4th axis research labs, scattered across the midwest.

Other agency names:

  • HYDRA (HYperdimensional Defense Research Agency)
  • ATMAR (Agency for Transitional Mechanics & Activity Research)
  • APRA (Abnormal Phenomena Research Agency)

T-16 Months

Plasma weapons developed in response to rising threat in China, DPRK

T-15 Months

Increases in extradimensional research leads to collection of living samples. This notably includes XE037 (blob). As time continues, larger and larger sub-prime monsters are retrieved.

T-15 Months to 5 Months

XEDRA becomes increasingly internally politicized, with different divisions competing for research dollars, and oversight staff conflicting in their opinions regarding the direction and goals of research.

T-13 Months

Short-range teleportation becomes a reality using fixed laboratory equipment.

T-12 Months to 6 Months

XEDRA begins storing sub-prime lifeforms, particularly XE037, and researching their potential as a possible super-weapon.

T-10 Months

Massive troop movements in China and DPRK provoke deployment by USAF. For the first time in history, a peacetime draft is instated.

T-10 Months

The successes of XEDRA lead to a greatly increased budgets and the construction of hundres of new research & production facilities in appropriate areas.

T-9 Months

Civil unrest regarding the drafts is widespread.

T-7 Months

Troops begin deploying with cutting-edge bionics systems. They are, according to intelligence, outpaced by Chinese developments.

T-6 Months

XEDRA gains increasingly unrestricted powers. Convicts with death sentences are used as subjects. Later, convicts with life sentences are used as well.

T-5 Months

Zombifying effect of XE037 discovered.

T-3 Months to T+0

Civil unrest progresses into wide-scale riots. Limited martial law instated in several areas. Deployment of robotic police is increased to maintain order.

T-4 Months to 1 Month

Corruption in XEDRA runs rampant and the legality of actions is frequently ignored. Due to the perceived importance of XEDRA, and the extenuating circumstances of public unrest and riots, these oversteps are mostly ignored.

T-30 Days

DPRK troop movements indicate an imminent attack. Missile launches batter South Korean port cities and act as a show of force. In response, US troop deployment is vastly increased, resulting in a much smaller military presence in mainland USA.

T-15 Days

XE037 surge occurs. XE037, a kind of sanguine hive mind, is responding to XEDRA’s probes. The surge occurs in all teleportation facilities simultaneously. During this event, XE037 contaminates the ground water and establishes “colonies” (slime pits). It is unknown whether Chinese/DPRK facilities experience this surge, as it is unknown whether they possess the equipment to perform transposition experiments.

T-15 Days to 5 Days

The first zombification incidents outside of labs occur. These are sometimes covered up by XEDRA; but often they aren’t even noticed, and the zombie is dismissed as a violent rioter and re-killed.

T-3 Days

Merging of XE037 and insect life occurs, resulting in rapid transformations.

T-3 Days to T+0

A series of terrorist attacks, including dirty bombs and biological weapons, is unleashed across the United States. NPRK & Chinese sleeper cells are expected.

T+0

Zombie outbreaks become widespread and critical mass is achieved; a zombie population which grows faster than it can be contained/killed.

T+18 Hours

Panic sets in; deaths are rapid and widespread.

T+36 Hours

50% zombification or death.

T+48 Hours

90% zombification or death.

T+56 Hours

Bombing of large US cities by an unknown aggressor commences. A crippled defense infrastructure is largely unable to respond.

T+60 Hours

A largely-defeated national guard retreats to fortified bunkers and air strips.

T+72 Hours

99% zombification or death.

T+5 Days

The game begins. Now you’re on your own.

Vehicle damage scaling factor

The Vehicle damage scaling factor world option (VEHICLE_DAMAGE) controls how damaged pre-spawned vehicles are. It ranges from 0.0 to 4.0 in steps of 0.1, and defaults to 1.0.

When it applies

The option only affects vehicles spawned with a non-mint status, i.e. status of -1 (light damage, the default) or 1 (disabled). See Spawning vehicles. Vehicles spawned with status: 0 are always intact.

Each vehicle part is rolled independently, so one vehicle usually has a mix of intact, damaged and broken parts.

How the roll works

For every part, the game computes two thresholds from the option value (chance) and rolls 4d8:

int broken = 8 * chance;  // truncated toward zero
int unhurt = 20 * chance; // truncated toward zero
int roll = dice( 4, 8 );  // 4..32, bell-shaped, mean 18
ConditionResulting part HP
roll >= unhurt100% (intact)
broken < roll < unhurt(roll - broken) / (unhurt - broken) of durability
roll <= broken0% (broken); batteries and fuel tanks are also emptied

Things to note:

  • Raising the option moves both thresholds up, so more of the bell curve falls into the damaged and broken ranges.
  • A damaged part never keeps 100% HP. Its highest HP is 1 - 1 / (unhurt - broken), so HP jumps to 100% at roll == unhurt.
  • Values below 0.25 leave unhurt at 4 or less. Since the lowest possible roll is 4, no damage happens at all.
  • At 4.0, broken is 32, which is the highest possible roll. Every part of a damaged vehicle is broken.

Reference values

Factorbroken / unhurtBrokenDamagedIntactExpected HP
0.00 / 00%0%100%100%
0.54 / 100.0%3.1%96.9%99.0%
0.86 / 160.4%29.5%70.1%89.9%
1.08 / 201.7%60.7%37.6%75.0%
1.512 / 3012.0%87.6%0.4%34.4%
2.016 / 4037.6%62.4%0%12.5%
3.024 / 6091.9%8.1%0%0.5%
4.032 / 80100%0%0%0%

Interactive chart

Try any other value with the chart below. Each row is one possible 4d8 result, from the highest roll at the top to the lowest at the bottom. The bar length is the chance of that roll, and its color is the outcome:

  • Intact: light green.
  • Damaged: green, yellow-green, yellow, orange or red, one color per 20% of remaining HP.
  • Broken: gray, like broken parts in the vehicle interface.
    roll distribution P(roll) HP

    Older worlds

    Before the range was reduced to 0.0-4.0, the option accepted values up to 10.0. Anything above 4.0 already broke every part of a damaged vehicle. A world saved with a value outside the new range loads with the default value 1.0 instead.

    first week

    Tip

    In order to maximize your ability to learn and chances of survival, Evac shelter is recommended and expected.

    While daunting, the game is a lot easier than some might think. You can do a great deal to prepare yourself for combat, but remember the zombies always get tougher thanks to evolution. It only gets more dangerous.

    First steps

    Makeshift crowbar

    If you’ve started in the evac shelter, grab a rock outside and smash a locker and a bench. A makeshift crowbar will help you open doors quietly and just takes a pipe and a tool with hammering.

    Cudgel (or other weapons)

    You need a good weapon, this is usually the cudgel in the early game. If you didn’t start with a knife, you can always make a stone knife with no skills. the makeshift crowbar lacks the hit bonus the cudgel has, which is why I recommend it. Optionally you can get a wooden spear but it takes some character skills and a fire. A self bow and crude arrows is weak but is not a bad opener to combat, any damage helps.

    Clothes

    You likely won’t start with the perfect insulation from the weather, so you need to manage your temperature as slowdown penalties from the heat or cold will kill you quickly via slowing you down in combat. If its too hot this is easy you just take off layers. If it’s too cold you’ll need to craft what clothes you can or loot what you can but don’t waste too much time on this. You’ll likely find the clothes you need.

    Note

    You want to minimize how many enemies you take on at once until you learn the game and the limits of your character, usually 1 enemy at a time is ideal

    Going into town

    Tools

    You can’t do anything without tools. Go for an anvil, metal sawing, wood sawing, welding, and soldering. The rest can be crafted fairly easily if you have to. The anvil is easy if you get a hacksaw or toolbox and a car for spare frames.

    Weapons

    Guns will keep you safe from the zombies through the entire game, and looting a gunstore is the easiest way to get geared. Otherwise, better melee weapons. You want fast hitting melee weapons and ideally a good to hit bonus unless your combat skills high enough to not worry about hitting.

    Backpack

    You can’t carry anything without a backpack, tailoring is the easiest way to just make one, but otherwise keep looking for any non-encumbering container.

    Books

    Books make the game a lot easier but are mainly needed for recipes. Find ones for medieval crafting, guns, electronics, chemistry, and skills that can’t be trained with crafting such as speaking or computers.

    Cars

    Finding one

    It’s safe to say, you need to find a good car sooner rather than later. It will make the game a lot easier and you will carry more loot with you. Rather than finding a broken down one, go for high condition with relatively few destroyed parts. You may get lucky and find one fully functional. You can find cars anywhere there is roads. You’ll get most of your tools from a mechanics garage or hardware store. Some homes may have garage tools.

    Welding

    You can’t do much with cars without a welder. Acetylene torches work for early game but look out for arc welders. An electric welder is the most important longterm solution, and attaching it to your car with a single solar panel provides unlimited welding potential. Weld before a break happens and you won’t take meaningful car damage.

    Hacksaw

    Without a hacksaw you can’t remove most parts. This means adding parts will be just as hard.

    Fuel

    Without fuel you won’t be going anywhere. Gas stations come to mind, but you can actually craft diesel with the right book and cooking level. You can also opt for a solar car but it won’t go far and you need a lot of panels and the electric motors.

    Note

    Your first week was a success if you lived long enough to loot a gun store, find a working car, and have otherwise kept up with your survival needs.

    Bonus Tasks

    Electric grid

    If you made it this far you may want to set up a functioning electric grid at an evac shelter, or just install more things onto your car. The evac shelter has a mounted battery and solar panel it just needs an oven, electric forge, welder, soldering iron, etc. You can add wind turbines via a vehicle on the roof connected with a jumper cable connector for even more power.

    Helicopter

    Geting a helicopter isn’t easy but if you stumble onto the parts you can install them on any vehicle. Gyrocopter is a fabrication 10 option. Finding a crash means ripping apart any still functional parts and repairing it so it can be attached to a better vehicle.

    Being brave

    There is a lot of more dangerous locations, monsters, and mods that add more dangerous locations and monsters. Labs, military bases, shipwrecks, mines, collapsed towers. You will want to explore, learn to take on more challenges. Remember that .50 BMG and being hit by a truck solves most enemy problems.

    forest survival

    Being the most difficult part of Cataclysm, surviving in the woods with nothing is one of the most rewarding experiences. This guide will cover a tasklist that should keep you alive. Should you fall behind, continue the previous steps before moving onto the next day’s tasks. The exception is day 1. Day 1 tasks are in order of severity.

    Caution

    This guide ASSUMES you are not playing with mods that changes this too much, specifically changing foraging drops. You’ll die if they removed trash from shrubs.

    Day 1 requirements

    • Fire drill (1 Survival) or any fire starting device
    • Fire ring (20 rocks)
    • A water source & cooking container
    • Improvised shelter (2 survival) or sleep will be hard

    Fire

    The reason you need a fire is you can’t see to craft at night, and the cold kills. You can’t boil water without fire. You don’t want to use fire without a fire ring, as it’s incredibly annoying. Fires outside a container randomly stop and don’t tell you how long they will last. You can break small boulders with long sticks. You can forage shrubs by activating them, and this will give you tons of litter and trash, including containers for liquids. You can find a glass/steel bottle or cans. Once you can boil and make fire you’ve survived short term.

    Firewood is not an issue in the short term as you can burn any plant or wood, including long sticks from young trees. Two or three long sticks will make a good fire.

    An improvised shelter makes sleeping easier and only requires a digging stick, 2 survival, and a lot of sticks and pine boughs. Place near a fire for temperature management.

    Natural resources

    Shrubs, Food trees, and Berry bushes

    Shrubs can be foraged once per season for trash, the most valuable resource of the woods as it is your only source of steel. Depending on your season, in spring and summer you will be relying on berries in trees for calories and possibly hydration but shrubs will give plenty of food later on.

    Fish

    If you can get fish it will be an excellent source of calories. You’ll need a river and a basic fishing rod.

    Young trees

    Young trees are how you get long sticks which you butcher into heavy sticks and then into splintered wood. Follow my first week guide for crafting tips, but in general it goes short cordage, stone knife, digging stick, wooden bead, wooden needle, stone adze, wooden clogs, stone shovel, stone axe. That will get you to survival of 4 and fabrication of 4.

    Grass tiles and Cattails

    Grass can be removed with a digging stick or shovel to give piles of straw, which can make cordage for your crafts, cattail plant fiber should be saved for making rags.

    Clay

    Clay terrain must be extracted in the construction menu. It can rarely be found from digging a large pit. You will need lots of it so find a river bank.

    Week 1 requirements

    Food preservation

    To preserve food you need a charcoal kiln and smoking rack to smoke meat or dehydrate what you farm. You need cooking 2 so boil some water and cook the assorted food you find, this will likely come without training. The kiln is fabrication 3 and requires you to dig soil but you likely have some if you made an improvised shelter. Place wood in the kiln and light it, you’ll get tons of charcoal once it’sd one.

    Water storage

    Storing lots of water either requires foraging many containers or crafting a lot of clay containers. Your easiest option is clay pots but they can’t be resealed. This means you can’t carry them with you while full.

    Weapons

    A wooden spear is your best early weapon, cudgels are practically free to make and better for when you can’t use a reach attack. You can upgrade to a quarterstaff if you get leather, with a working forge there will be tons of better weapons to make so these are temporary.

    Firewood

    Firewood is going to be from chopping trees into logs with a stone axe. You may want to save the food-bearing trees.

    Clothes

    Clothes are going to be made from rags made of plant fibers. Get knitting needles.

    Longterm goals

    Shelter

    Building a house is time consuming, painful, and not rewarding. If you choose to stay in the woods forever and not live in a pre-spawned structure or a car then you’ll want to do it eventually. With a pickaxe you can live in the ground but otherwise you’ll want to check a few of the walls and floors in the construction menu to see which kind of house to build. Log cabins are fairly sturdy and cheap but always at risk of fire. Mortar is not an obtainable item for you, so go with adobe mortar which limits you to stone walls or adobe brick.

    Working forge

    A forge is critical to get working. Building a rock forge and gaining charcoal from a kiln is easy. A clay crucible, metalworking chisel, metal tongs, and a hammer are all easy to make with the right requirements. An anvil is incredibly expensive. You’ll be searching shrubs forever, if you’re playing with the city still enabled you can smash a car into bits.

    Vehicles

    Depending on your mapgen you’ll either graduate to messing with real cars, or be stuck with wooden carts and horse carriages. Starting a vehicle is done in the construction menu. A canoe is a good idea, wooden frames take nails and planks, most wooden vehicle parts just need wood and nails. You’ll be grinding mechanics with wooden vehicle parts.

    Electronics

    Electronics is specifically listed as long as you are playing with normal mapgen. If it doesn’t spawn in your world you’re out of luck. See normal gameplay for how to get started, but the jist is to deconstruct electronic furniture in town and make any low level craft you can to advance, such as flash lights and electric firestarters. If you get a solar panel, mounted battery and oven you’ll be in a good position.

    Tip

    That’s about all you can do without going into the city.

    Translation file format (.po)

    Translations are stored in ".po" files (Portable Object), named with a language code specific to each language and country. So for example the translations for the Spanish spoken in Spain would be found in es_ES.po and for Spanish spoken in Mexico would be found in es_MX.po.

    It is a plain-text filetype, so you can edit it however you choose, but translators often prefer to use purpose-built translation editors (such as Poedit), or web-based translation tools (such as https://translations.launchpad.net).

    The format of ".po" files is a list of entries, with the english phrase to be translated, followed by the local translation. The english phrase is on the line or lines beginning with msgid, and the translated phrase goes on the line or lines beginning with msgstr.

    Before the msgid line there will be a comment line indicating where in the source code the word or phrase came from. This can often help when the meaning of the english is not obvious. There may also be comments left by the developers to make translation easier.

    Most entries will look something like this:

    #: action.cpp:421
    msgid "Construct Terrain"
    msgstr "niarreT tcurtsnoC"
    

    The english phrase here is “Construct Terrain”, and it comes from line 421 of the file “action.cpp”. The example translation is just a reversal of the english letters. With this, in stead of “Construct Terrain”, the game will display “niarreT tcurtsnoC”.

    Another exmple is:

    #: action.cpp:425 defense.cpp:635 defense.cpp:701 npcmove.cpp:2049
    msgid "Sleep"
    msgstr "pleeS"
    

    This is similar to the last example, except it is a more common phrase. It is used in the files action.cpp, defense.cpp (twice) and npcmove.cpp. The translation will replace every usage.

    File Header

    The header at the top of the ".po" file is the only part that differs from the comment/msgid/msgstr format.

    If you are working on an already established translation you will not have to modify it.

    For a new translation, it should be mostly set up for you, either by the editor you are using or by the msginit program which is the recommended way of initializing a translation (see TRANSLATING.md).

    If you are starting from another translation file however, you might need to change a few things. Just fill it in as best you are able.

    The header will look something like:

    # French translations for Cataclysm-BN package.
    # Copyright (C) 2013 CleverRaven and Cataclysm-BN contributors.
    # This file is distributed under the same license as the Cataclysm-BN package.
    # Administrator <EMAIL@ADDRESS>, 2013.
    #
    msgid ""
    msgstr ""
    "Project-Id-Version: 0.7-git\n"
    "Report-Msgid-Bugs-To: http://github.com/CleverRaven/Cataclysm-BN\n"
    "POT-Creation-Date: 2013-08-01 13:44+0800\n"
    "PO-Revision-Date: 2013-08-01 14:02+0800\n"
    "Last-Translator: YOUR NAME <[email protected]>\n"
    "Language-Team: French\n"
    "Language: fr\n"
    "MIME-Version: 1.0\n"
    "Content-Type: text/plain; charset=UTF-8\n"
    "Content-Transfer-Encoding: 8bit\n"
    "Plural-Forms: nplurals=2; plural=(n > 1);\n"
    

    If you are starting a new translation, or you are in charge of the existing translation, it is helpful if you include your name and e-mail address so that you can be contacted with any questions or issues regarding the translation.

    The only important part that cannot be easily filled out manually is the Plural-Forms section. It determines how different numbers of things are handled in your language. More on that later.

    Format strings and newlines

    Some strings will have special terms such as %s, %2$d and \n.

    \n represents a linebreak. Mostly these are unnecessary as the code wraps lines where it can, but sometimes these are used for placing things on different lines. Just use \n in your translation wherever a new line should go.

    %s and other similar terms are replaced with something else when the game is running. You might need to move them around, depending on the translation. It is important that every term beginning with % is kept in the translation.

    Here is an example which replaces a %d with a number:

    #: addiction.cpp:224
    #, c-format
    msgid ""
    "Strength - %d;   Perception - 1;   Dexterity - 1;\n"
    "Depression and physical pain to some degree.  Frequent cravings.  Vomiting."
    msgstr ""
    ";1 - ytiretxeD   ;1 - noitpecreP   ;%d - htgnertS\n"
    ".gnitimoV  .sgnivarc tneuqerF  .eerged emos ot niap lacisyhp dna noisserpeD"
    

    Here it is important that the %d was not reversed, and that the \n remained at the end of the line. In this case, %d will be replaced with the character’s strength modifier when the message is displayed.

    In some cases it might be necessary to change the order of terms. This can confuse the game. If the order of the % terms changes, you must add numbers to all of them, so that the game knows which was which. Some strings will already have these numbers, but some might not.

    As an example, if there is a string with %s shoots %s!, it might change in translation. Perhaps it will become something like %s is shot by %s!. But now it is the wrong way around, the shooter has swapped with the shootee.

    In this case, each %s should be numbered with a digit (1-9) then a dollar sign ($) between the % and the s. For example %1$s shoots %2$s! would be equivalent to %s shoots %s!. So the example translation above could be %2$s is shot by %1$s!, and this would work correctly.

    The game can figure out these %1$s %2$s parameters automatically, but you must make sure that (A): all of the % terms in the translation are numbered; and (B): the numbers are correct in terms of the original ordering in the english text.

    For example:

    #: map.cpp:680
    #, c-format
    msgid "%s loses control of the %s."
    msgstr "%2$s eht fo lortnoc sesol %1$s"
    

    would be displayed in-game as kcurt eht fo lortnoc sesol liagibA, assuming Abigail was driving a truck.

    Special tags in strings

    Some strings in the translation may have special tags in front of or inside them. These tags should be left as-is, and only the rest of the string translated.

    For example, the NPC and city names from “data/raw/names.json” are prefixed with <name> so as to avoid conflicts with words (such as Wood the material, and Wood the last name). For these, the <name> part should be left in.

    For example:

    #. ~ proper name; gender=female; usage=given
    #: lang/json/json_names.py:6
    msgid "<name>Abigail"
    msgstr "<name>liagibA"
    

    Names also have a comment above them, indicating what the name is used for in-game. In this case, Abigail is a possible first name for a female NPC.

    Plural forms

    Many languages use different terms for things depending on how many of them there are. These are supported using plural forms, defined by the Plural-Form line in the ".po" file header.

    For these, there will be multiple msgstr lines, intended for the different forms depending on number. The game will automatically choose the correct form depending on the number of things.

    For example:

    #: melee.cpp:913
    #, c-format
    msgid "%d enemy hit!"
    msgid_plural "%d enemies hit!"
    msgstr[0] "!tih ymene %d"
    msgstr[1] "!tih seimene %d"
    

    Here the first entry is for when there is only one enemy, the second is for when there are more than one enemies. The rules differ wildly between languages.

    General Style Guide

    Please follow these conventions when adding or editing in-game text:

    1. Use US English spelling.
    2. Use double sentence spacing after periods. This means that a period that ends a sentence should be followed by two spaces. If the sentence is the last in the block of text, there should be no spaces following it.
    3. Use second person point of view (eg. “you”).
    4. The names of traits, martial arts, and Compact Bionics Modules (CBM’s) should be in title case. This means that each word should be capitalized unless it is an article, preposition or conjunction.
    5. Items and entities with proper noun names should also be in title case.
    6. All other item and entity names should be in all lower-case letters.
    7. Use the serial comma (Oxford comma).
    8. Use ellipsis character (…) instead of three dots (…). Replace instances of three periods with the dedicated Unicode character for ellipsis, namely U+2026.

    German Style Guide

    Diese Datei enthält Anmerkungen für alle, die das Spiel ins Deutsche übersetzen wollen.


    Sprache

    Deutsch wie in Deutschland üblich (de_DE). Wir verwenden die neue deutsche Rechtschreibung.

    Zusammenfassung

    • Anführungszeichen: »Beispieltext«
    • Innere Anführungszeichen: ›Beispieltext‹
    • Anrede: Grundsätzlich mit »du«, mit Ausnahmen (s.u.)
    • Strings wie »the %s« oder »a %s« werden besonders übersetzt (s.u.)

    Anrede

    Grundsätzlich duzen sich alle. Auch der Spieler wird geduzt.

    Die Idee ist, dass nach der Apokalypse das »Sie« einfach aus der Mode kommt. Sind ja nicht mehr viele übrig. ;-)

    Die förmliche Anrede mit »Sie« wird nur in seltenen Ausnahmefällen benutzt. Diese Ausnahmefälle sind:

    • Alte Dokumente aus der Zeit vor der Apokalypse, wo die förmliche Anrede Sinn ergibt, z.B. alte Behördenprotokolle
    • Computer, Terminals und die meisten anderen Bedienelemente
    • Wenn es sinnvoll erscheint, auch bestimmte NPC-Dialoge, aber das dann bitte unbedingt im Spiel testen!

    Auf keinen Fall darf völlig grundlos zwischen »du« und »Sie« hin- und hergesprungen werden.

    Blöde Sonderregel für Artikel

    Es kommen sehr viele Strings vor, bei dem ein Artikel gefolgt von einem Platzhalter auftaucht. Das ist problematisch für uns, da deutsche Substantive ein Geschlecht haben.

    Zusammenfassung ###############

    Steht ein Artikel vor einem Platzhalter, wird er wie folgt übersetzt (naja):

    • »the %s« → »%s«
    • »a %s« → »1 %s«

    Beispiele:

    • »You hit the %s!« → »Du triffst %s!«
    • »You see a %s.« → »Du siehst 1 %s.«

    Ausnahmen sind natürlich erlaubt.

    Bestimmter Artikel »the« ########################

    Beispiel: »You hit the %s!«.

    Problematische Übersetzung:

    • »Du triffst das %s!«.

    So einfach ist das leider nicht, denn wir wissen ja nicht, welches Geschlecht das Wort für %s hat.

    Das funktioniert, wenn %s für »Monster« steht (»das Monster«). Aber wenn %s zu »Spinne« wird, dann kriegen wir »das Spinne«. Das ist blöd. :-(

    Wir haben uns daher angewöhnt, den Artikel einfach ganz wegzulassen. Also als ob %s ein Name wäre.

    Also:

    • »Du triffst %s!«

    Das ist zwar immer noch nicht schön, aber besser als »das Spinne«.

    Alternativ hat sich auch der Doppelpunkt bewährt. Also:

    • »Du triffst: %s«

    Bei kurzen Strings kann das sinnvoll sein, bei langen Strings eher nicht.

    Unbestimmter Artikel »a«/»an« #############################

    Beispiel: »On the ground you see a %s.«

    Problematische Übersetzung: »Auf dem Boden siehst du ein %s.«

    Wenn wieder die Spinne kommt, haben wir »ein Spinne«. Das ist doof. :-(

    Notlösung: Wir ersetzen einfach den unbestimmten Artikel mit »1«. Also:

    • »Auf dem Boden siehst du 1 %s.«

    Zugegeben, etwas gefudelt ist das schon. Aber es funktioniert! Irgendwie. :D

    Auch hier wäre der Ansatz mit dem Doppelpunkt denkbar, aber nur, wenn es sein muss.

    Anmerkung #########

    Beachte: All diese Ansätze sind nur Notlösungen!

    Eine echte Lösung des Problems kann es eigentlich nur geben, wenn die Art, wie C:BN diese Strings aufbaut, grundsätzlich ändert. :-(

    Problemwort: »bionics«

    C:BN verwendet »bionic« als Wort für eine Art Implantat, nicht für ein Konzept wie in Wikipedia beschrieben (s.u.).

    So übersetzen wir es:

    • »the bionic« → »das Bionik«
    • »the bionics« → »die Bioniken«

    »bionic« wird auch manchmal als Adjektiv eingesetzt:

    • »bionic« → »bionics«

    Aus der englischsprachigen Wikipedia: Bionics (also known as biomimicry, biomimetics, bio-inspiration, biognosis, and close to bionical creativity engineering) is the application of biological methods and systems found in nature to the study and design of engineering systems and modern technology

    Aus der deutschsprachigen Wikipedia: Die Bionik (auch Biomimikry, Biomimetik oder Biomimese) beschäftigt sich mit dem Übertragen von Phänomenen der Natur auf die Technik.

    Russian Style Guide

    This file contains notes/discussion regarding translation for Russian, written in Russian.


    Специфика:

    Старайтесь избавляться от англицизмов. Например, “Вы вытащили руки из своих карманов” следует заменить на “Вы вытащили руки из карманов”.

    После перевода перечитайте свой текст. Если по-русски он звучит странно, это повод его несколько подредактировать с сохранением изначального смысла.

    Замена слов на уменьшительно-ласкательные приветствуется, если они подходят по смыслу. Замена слов на русский сленг или придание словам большей экспрессии тоже приветствуется, если это соответствует контексту. Импровизация в рамках контекста и смысла допустима, если конечный текст выглядит лучше, чем дословный перевод.

    После многоточия, по правилам русского языка, следующее предложение начинается с большой буквы.

    Прямую речь следует писать по русским правилам, если она встречается в переводе.

    Иногда перед началом или в конце фразы стоят пробелы. Их очень плохо видно в редакторе Transifex, имейте это в виду. Особенно часто это бывает, если фраза не окончена или по смыслу имеет продолжение. Чтобы лучше видеть такие пробелы, можно зайти в настройки редактора и включить пункт “Показать пробелы”.

    Также не стоит забывать про букву Ё.

    Формы множественного числа

    В редакторе Transifex некоторые названия предметов требуется переводить для всех форм единственного и множественного числа. В игре, в зависимости от того, сколько у вас предметов, будет отображаться название предмета в нужной форме.

    1 — единственное число (например: яблоко) Несколько — нужно подобрать окончание так, чтобы оно соответствовало кол-ву 2-4 предмета (например: яблока) Много — нужно подобрать окончание так, чтобы оно соответствовало кол-ву 5-бесконечность предметов (например: яблок) Другое — простая форма множественного числа (например: яблоки)

    В разделе “Несколько”, при переводе прилагательных женского рода следует отдавать предпочтение варианту: две “стиральные машины”, а не две “стиральных машины”.

    Что касается книг и журналов. Слово копия и выпуск можно опустить. Как правило, если книги/журналы имеют множественное число, стоит переводить так: 1: книга «Война миров» Несколько (например, две): книги «Война миров» Много (например, сто): книг «Война миров» Другое: книги «Война миров»

    1: журнал «Плейбой» Несколько (например, два): журнала «Плейбой» Много (например, сто): журналов «Плейбой» Другое: журналы «Плейбой»

    Иногда встречаются такие слова, которые не стоит писать в единственном или во множественном числе, например, “фисташки”, “арахис” и т.д. Их надо оставлять в той форме, которая больше подходит по смыслу.

    Спецсимволы:

    Спецсимволы печатаются комбинацией клавиш. Для различных операционных систем эти комбинации разные. Для ОС Windows спецсимволы набираются на цифровой клавиатуре с помощью зажатой клавиши alt. Для ОС Linux существуют комбинации с кнопкой Compose. Для Mac ОС применяется комбинации с клавишей Option. Некоторые символы имеют свою специфику в русском языке, отличную от английского. Нужно использовать русскую интерпретацию, если это возможно.

    Стоит различать тире и дефис. Дефис ставится внутри слова, короткий, без пробелов (например: что-то, чёрно-белый и т.п.). Тире — пунктуационный знак, ставится между словами, длиннее, отделяется пробелами с обеих сторон. Дефис: - (минус) Тире: — WIN:(alt + 0151) LIN:(Сompose + - + –) MAC:(Option + Shift + -)

    Кавычки следует использовать ёлочки. Открывающая кавычка: « WIN:(alt + 0171) LIN:(Сompose + < + <) MAC:(Option + ) Закрывающая кавычка: » WIN:(alt + 0187) LIN:(Сompose + > + >) MAC:(Option + Shift + )

    Иногда, в тексте оригинала встречаются спецсимволы “%s”, “%2$d”, “\n”, а также цветовые теги с цифрами 1 и 2. Оставляете их как есть, подставляя по смыслу в нужное место. Стоит ставить пробелы перед и после спецсимволов, если они есть в оригинале. \n — перенос строки (эквивалентно клавише enter в текстовом редакторе) %2$d или %d — вместо этих символов в игре будет отображаться числовое значение %2$s или %s — вместо этих символов в игре будет отображаться какая-либо другая строка

    Поскольку шрифт в игре моноширинный, а у некоторых еще и квадратный, стоит соблюдать следующую специфику. Не стоит использовать три точки вместо многоточия, в игре это очень плохо выглядит. Есть свой спецсимвол. Многоточие: … WIN:(alt + 0133) LIN:(Сompose + . + .) MAC:(Option + ;)

    Также, в английском языке для текста игры принято правило разделять предложения двумя пробелами. В русском языке такого правила нет, поэтому после точки в конце предложения должен оставаться один пробел.

    Merging and managing translations for maintainers

    Several steps need to be done in the correct order to correctly merge and maintain the translation files.

    There are scripts available for these, so usually the process will be as follows:

    1. Download the translations in .po format.

    2. Put them in lang/incoming/, ensuring they are named consistently with the files in lang/po/.

    3. Run lang/update_pot.sh to update lang/po/cataclysm-BN.pot (requires python with polib and luaparser modules installed).

    4. Run lang/merge_po.sh to update lang/po/*.po. (This is only used to test translations locally as the project now uses Transifex for translation)

      This will also merge the translations from lang/incoming/.

    These steps should be enough to keep the translation files up-to-date.

    To compile the .po files into .mo files for use, run lang/compile_mo.sh. It will create a directory in lang/mo/ for each language found.

    Also note that both lang/merge_po.sh and lang/compile_mo.sh accept arguments specifying which languages to merge or compile. So to compile only the translation for, say, Traditional Chinese (zh_TW), one would run lang/compile_mo.sh zh_TW.

    After compiling the appropriate .mo file, if the language has been selected in game settings, the translations will be automatically used when you run cataclysm.

    When System language is selected in settings, the game tries to use language that matches system language based on language definitions file data/raw/languages.json.

    If you’re testing translations for a new language, or the language does not show up in settings, make sure it has its own entry in the definitions file.

    Translate third-party mods

    Intro

    This document aims to give a brief explanation on how to set up and operate mod translation workflow for Cataclysm: Bright Nights.

    For mod localization the game uses custom localization system that is similar to GNU gettext and is compatible with GNU gettext MO files.

    While it’s possible to use Transifex or any other platform or software that supports gettext, this document only gives examples on how to work with Poedit and command-line GNU gettext utilities.

    If you desire an in-depth explanation on PO/POT/MO files or how to work with them using GNU gettext utilities, see GNU gettext manual.

    To get some generic tips on translating strings for Cataclysm: Bright Nights and its mods, see translation API.

    A short glossary

    POT file

    Portable Object Template file (.pot).

    This is a text file that contains original (English) strings extracted from mod’s JSON and Lua source files. The POT file is a template used for creating empty or updating existing PO files of any language.

    PO file

    Portable Object file (.po).

    This is a text file that contains translated strings for one language. The PO files are what translators work with, and what will be compiled into a MO file.

    MO file

    Machine Object file (.mo).

    This is a binary file that contains translated strings for one language. The MO files are what the game loads, and where it gets translated strings from.

    Workflow overview

    The first translation workflow is as follows:

    1. Extract strings from mod JSON and Lua source files into a POT file
    2. Create PO file for target language from this POT
    3. Fill the PO file with translated strings
    4. Compile PO into MO
    5. Put the MO into your mod files

    As the mod changes with time, so may change its strings. Updating existing translations is done as follows:

    1. Extract strings from mod JSON and Lua source files into a new POT file
    2. Update existing PO file from the new POT file
    3. Add new or edit existing translated strings in the PO file
    4. Compile PO into MO
    5. Replace old MO in the mod files with new version

    Step 1 in both workflows requires you to set up environment for string extraction (see below).

    Steps 2-4 can be done using translation software either by the mod author/maintainer, or by the translator.

    Setting up environment for string extraction

    You’ll need Python 3 with polib and luaparser modules installed (available via pip).

    Scripts for string extraction can be found in the lang subdirectory of the repository:

    • extract_json_strings.py - main string extraction routines
    • dedup_pot_file.py - fixes errors in POT file produces by the 1st script
    • extract_mod_strings.bat (extract_mod_strings.sh for Linux/MacOS) - to automate the other 2 scripts

    Extracting strings

    Copy these 3 scripts into the mod’s folder and:

    • on Windows, double-click extract_mod_strings.bat
    • on Linux/MacOS, open terminal and run ./extract_mod_strings.sh

    If the process completed without errors, you’ll see a new lang folder with extracted_strings.pot file inside.

    Creating new PO

    Before creating PO file, you need to choose language id.

    Open data/raw/languages.json to see the list of languages supported by the game.

    In this list, each entry has its own id in form of ln_LN, where ln determines language and LN - dialect. You can either use full ln_LN for exact language+dialect match, or ln if you want the game to use your MO regardless of dialect.

    Poedit

    1. Open the POT file with Poedit
    2. Press “Create new translation” button (should show up near the bottom)
    3. In language selection dialog, enter language id you chose
    4. Save the file as path/to/mod/lang/LANG.po where LANG is the same language id

    msginit

    msginit -i lang/index.pot -o lang/LANG.po -l LANG.UTF-8 --no-translator
    

    Where LANG is the language id you chose

    Updating existing PO

    Poedit

    1. Open the PO file with Poedit
    2. Choose Catalog->Update from POT file... and select the new POT file
    3. Save the file

    msgmerge

    msgmerge lang/LANG.po lang/index.pot
    

    Compiling PO into MO

    Poedit

    1. Open the PO file with Poedit
    2. Make sure MO file will be encoded using UTF-8 (it should do so by default, you can double check in Catalog->Properties->"Translation properties" tab->Charset).
    3. By default, each time PO file is saved Poedit automatically compiles it into MO, but the same can also be done explicitly via File->Compile to MO...

    msgfmt

    msgfmt -o lang/LANG.mo lang/LANG.po
    

    Adding MO file to the mod

    Create lang directory in the mod files directory and put MOs there:

    mods/
        YourMod/
            modinfo.json
            lang/
                es.mo
                pt_BR.mo
                zh_CN.mo
    

    Note: Storing your POT/PO files in the same lang subdirectory may make it easier to keep track of them. The game ignores these files, and your mod folder structure will look like this:

    mods/
        YourMod/
            modinfo.json
            lang/
                extracted_strings.pot
                es.po
                es.mo
                pt_BR.po
                pt_BR.mo
                zh_CN.po
                zh_CN.mo
    

    Miscellaneous notes

    Is it possible to use arbitrary location or names for MO files, like with JSONs?

    No. The game looks for MO files with specific names that are located in the lang subdirectory of the mod’s path directory specified in modinfo.json (if not specified, path matches the mod’s directory).

    However, any mod will automatically try to use any other mod’s translation files to translate its strings. This makes it possible to create mods that are purely “translation packs” for other mods (or mod collections).

    Reloading translations in a running game

    Open debug menu and select Info...->Reload translations, and the game will reload all MO files from disk.

    This makes it easy to see how translated string looks in game, provided the translator has a way to compile MO files.

    Example workflow with Poedit:

    1. Translate a string
    2. Hit Ctrl+S
    3. Alt+Tab into the game
    4. Reload translation files via debug menu
    5. The game now displays translated string

    MO load order

    MO load order is as follows:

    1. First and always goes base game’s MO file, which contains translation strings for UI, hardcoded functionality, base “mod” (data/json/) and in-repo mods.
    2. Then MO files of mods are loaded, in same order as the mod load order.

    Dialects

    When loading MO files, the game first looks for the file with exact language and dialect match in its name. If such file is absent, then it looks for a file with no dialect.

    For example, when using Español (España) the selection order is

    1. es_ES.mo
    2. es.mo

    And when using Español (Argentina) the selection order is

    1. es_AR.mo
    2. es.mo

    Thus, es.mo would be loaded for either dialect of Spanish if the exact translation files are not present.

    What if 2 or more mods provide different translations for same string?

    Then the game selects which one to use according to this set of rules:

    1. If string A’s translation has plural forms, but string B’s translation does not, then translation A is used for both single and plural forms.
    2. If both translation A and B have (or both don’t have) plural forms, then the first loaded translation is used (see MO load order).

    If you want a different translation from the one in the base game, or don’t want it to conflict with a string from some other mod, add a translation context to the string in the corresponding JSON object (see here for which fields support translation context).

    PR that implements mod translations, for reference

    https://github.com/cataclysmbn/Cataclysm-BN/pull/505

    Example of the mod translation

    Edge cases

    There are issues specific to Cataclysm: BN which translators should be aware of. For example:

    Special Symbols

    Some translation texts will have special symbols or formatting, such as

    To learn more, please read the file format explanation.

    Language Specific Guidelines

    Check the following files for specific guidelines:

    Cataclysm: BN has more than 46,000 translatable strings (last updated at 2023-09-22 1), but don’t be discouraged. The more translators there are, the easier it becomes!


    1. Transifex API does not expose a public endpoint (at least without bearer token), so we were unable to update the number automatically.) ↩

    Grammatical gender

    For NPC dialogue (and potentially other strings) some languages may wish to have alternate translations depending on the gender of the conversation participants. This two pieces of initial configuration.

    1. The dialogue must have the relevant genders listed in the json file defining it. See the NPC docs.
    2. Each language must specify the genders it wishes to use via genders list of the language’s entry in data/raw/languages.json. Don’t add genders there until you’re sure you will need them, because it will make more work for you. Current choices are: m (male), f (female), n (neuter). If you need different genders than the ones currently supported, see relevant note in src/language.h.

    Having done this, the relevant dialogue lines will appear multiple times for translation, with different genders specified in the message context. For example, a context of npc:m would indicate that the NPC participant in the conversation is male.

    Because of technical limitations, all supported genders will appear as contexts, but you only need to provide translations for the genders listed in the grammatical gender list for your language.

    Other parts of the game have various ad hoc solutions to grammatical gender, so don’t be surprised to see other contexts appearing for other strings.

    Translation API

    Cataclysm: BN uses custom runtime library that works similarly to GNU gettext to display translated texts.

    Using gettext requires two actions:

    • Marking strings that should be translated in the source code.
    • Calling translation functions at run time.

    Marking translatable string allows for their automatic extraction. This process generates a file that maps the original string (usually in English) as it appears in the source code to the translated string. These mappings are used at run time by the translation functions.

    Note that only extracted strings can get translated, since the original string is acting as the identifier used to request the translation. If a translation function can’t find the translation, it returns the original string.

    Translation Functions

    In order to mark a string for translation and to obtain its translation at runtime, you should use one of the following functions and classes.

    String literals that are used in any of these functions are automatically extracted. Non-literal strings are still translated at run time, but they won’t get extracted.

    _()

    This function is appropriate for use on simple strings, for example:

    const char *translated = _( "text marked for translation" )
    

    It also works directly:

    add_msg( _( "You drop the %s." ), the_item_name );
    

    Strings from the JSON files are extracted by the lang/extract_json_strings.py script, and can be translated at run time using _(). If translation context is desired for a JSON string, class translation can be used instead, which is documented below.

    pgettext()

    This function is useful when the original string’s meaning is ambiguous in isolation. For example, the word “blue”, which can mean either a color or an emotion.

    In addition to the translatable string, pgettext receives a context which is provided to the translators, but is not part of the translated string itself. This function’s first parameter is the context, the second is the string to be translated:

    const char *translated = pgettext( "The color", "blue" );
    

    vgettext()

    Some languages have complex rules for plural forms. vgettext can be used to translate these plurals correctly. Its first parameter is the untranslated string in singular form, the second parameter is the untranslated string in plural form and the third one is used to determine which one of the first two should be used at run time:

    const char *translated = vgettext( "%d zombie", "%d zombies", num_of_zombies );
    

    vpgettext()

    Same as vgettext, but allows to specify translation context.

    const char *translated = vpgettext( "water source, not time of year", "%d spring", "%d springs", num_of_springs );
    

    translation

    There are times when you want to store a string for translation, maybe with translation context; Sometimes you may also want to store a string that needs no translation or has plural forms. class translation in translations.h|cpp offers these functionalities in a single wrapper:

    const translation text = to_translation( "Context", "Text" );
    
    const translation text = to_translation( "Text without context" );
    
    const translation text = pl_translation( "Singular", "Plural" );
    
    const translation text = pl_translation( "Context", "Singular", "Plural" );
    
    const translation text = no_translation( "This string will not be translated" );
    

    The string can then be translated/retrieved with the following code

    const std::string translated = text.translated();
    
    // this translates the plural form of the text corresponding to the number 2
    const std::string translated = text.translated( 2 );
    

    class translation can also be read from JSON. The method translation::deserialize() handles deserialization from a JsonIn object, so translations can be read from JSON using the appropriate JSON functions. The JSON syntax is as follows:

    "name": "bar"
    
    "name": { "ctxt": "foo", "str": "bar", "str_pl": "baz" }
    

    or

    "name": { "ctxt": "foo", "str_sp": "foo" }
    

    In the above code, "ctxt" and "str_pl" are both optional, whereas "str_sp" is equivalent to specifying "str" and "str_pl" with the same string. Additionally, "str_pl" and "str_sp" will only be read if the translation object is constructed using plural_tag or pl_translation(), or converted using make_plural(). Here’s an example:

    translation name{ translation::plural_tag() };
    jsobj.read( "name", name );
    

    If neither "str_pl" nor "str_sp" is specified, the plural form defaults to the singular form + “s”.

    You can also add comments for translators by writing it like below (the order of the entries does not matter):

    "name": {
        "//~": "as in 'foobar'",
        "str": "bar"
    }
    

    Do note that currently the JSON syntax is only supported for some JSON values, which are listed below. If you want other json strings to use this format, refer to translations.h|cpp and migrate the corresponding code. Afterwards you may also want to test update_pot.sh to ensure that the strings are correctly extracted for translation, and run the unit test to fix text styling issues reported by the translation class.

    Supported JSON values

    • Effect names
    • Item action names
    • Item category names
    • Activity verbs
    • Gate action messages
    • Spell names and descriptions
    • Terrain/furniture descriptions
    • Monster melee attack messages
    • Morale effect descriptions
    • Mutation names/descriptions
    • NPC class names/descriptions
    • Tool quality names
    • Score descriptions
    • Skill names/descriptions
    • Bionic names/descriptions
    • Terrain bash sound descriptions
    • Trap-vehicle collision sound descriptions
    • Vehicle part names/descriptions
    • Skill display type names
    • NPC dialogue u_buy_monster unique names
    • Spell messages and monster spell messages
    • Martial art names and descriptions
    • Mission names and descriptions
    • Fault names and descriptions
    • Plant names in item seed data
    • Transform use action messages and menu text
    • Template NPC names and name suffixes
    • NPC talk response text
    • Relic name overrides
    • Relic recharge messages
    • Speech text
    • Tutorial messages
    • Vitamin names
    • Recipe blueprint names
    • Recipe group recipe descriptions
    • Item names (plural supported) and descriptions
    • Recipe descriptions
    • Inscribe use action verbs/gerunds
    • Monster names (plural supported) and descriptions
    • Snippets
    • Bodypart names
    • Keybinding action names
    • Field level names

    Lua

    The 4 translation functions are exposed to the Lua code.

    Recommendations

    In Cataclysm: BN, some classes, like itype and mtype, provide a wrapper for the translation functions, called nname.

    When an empty string is marked for translation, it is always translated into debug information, rather than an empty string. On most cases, strings can be considered to be never empty, and thus always safe to mark for translation, however, when handling a string that can be empty and needs to remain empty after translation, the string should be checked for emptiness and only passed to a translation function when is non-empty.

    Error and debug messages must not be marked for translation. When they appear, the player is expected to report them exactly as they are printed by the game.

    See the gettext manual for more information.

    Translate BN with transifex

    Supported languages

    The official location for translating Cataclysm: BN is the Transifex translations project.

    Looking for a way to translate mods not included in game repository?

    Some of the currently supported languages are:

    • Arabic
    • Chinese (China)
    • Chinese (Taiwan)
    • Danish
    • Dutch
    • French
    • German
    • Greek
    • Hungarian
    • Icelandic
    • Indonesian
    • Italian (Italy)
    • Japanese
    • Korean
    • Norwegian Bokmål
    • Polish (Poland)
    • Portuguese (Brazil)
    • Russian (Russia)
    • Serbian
    • Slovak (Slovakia)
    • Spanish (Argentina)
    • Spanish (Spain)
    • Turkish
    • Ukrainian
    • Ukrainian (Ukraine)

    Don’t see your language in the list above? You can add it into the project at Transifex!

    Join the BN team

    To begin translating, head over the translation project and click on the Help Translate Cataclysm: BN button. This should take you to a page where you can either create a free account on Transifex, or login using GitHub, Google+ or LinkedIn.

    After you’ve created your account, return to the translation project and click on the “Join team” button. This will open a window where you can choose the language you are interested on translating, so pick one and click the “Join” button.

    Choose a language

    After this, the most straightforward thing to do is to reload the page, which should redirect you to the translation project’s dashboard. Here, you can click the “Languages” link on the sidebar to see the list of supported languages and the current progress of the translation effort.

    Note that you can request for the inclusion of additional languages, if the one you are interested in is not available on the list.

    From this list, you can click on the language of your choice, and then click on the “Translate” to get started right away. Otherwise, you can click on any other language and click on the “Join team” button, if you are interested in translating for that language as well.

    After clicking on the “Translate” button, you will be taken to the web editor. To begin, you need to choose a resource to translate. Most of the in-game text is contained in the cataclysm-bright-nights resource, so click on it to start.

    Using the editor

    At this point, the editor should show you the list of text available for translation, now you only need to click on the string you want to translate and type your translation on the translation area on the right side of the screen. Click on the “Save” button when you are satisfied with your translation.

    See Transifex’s documentation for more information.

    How to install the game

    Install the base game

    • Go here https://github.com/cataclysmbn/Cataclysm-BN
    • Under Executables, select the base game version you want
    1. Stable is less bug free, but you won’t have the latest content. There is a stable every few months
    2. Latest release is where the Nightlies are published (one release every night). You get the latest content, but they might be unstable image
    • In both cases Always back up your save before updating your game (preferably your whole game folder)

    • Select the right game version for your OS image

    • Create a new folder where you want the game to be installed (here called “CBN_TUTO_INSTALL”)

    • Double click on the game zip, select all the files, drag & drop them on the newly created folder image

    • Congratulations! The game is already installed, you can start the game by double clicking the file called cataclysm-bn-tiles

    Get external mods

    • Bright Night already includes enough mods for your first playthrough, but maybe you want even more

    • Go to https://mods.cataclysmbn.org/ , click on View all XXX mods image

    • Click on a mod that seems interesting to get more info about it image

    • Click on the link below Installation to download the mod image

    • Same as what we did for the base game, drag & drop the mod file(s) in /gamefolder/mods/

    • A mod folder must have a modinfo.json file, you need to drag & drop the folder that contains it image

    • The mod is installed!

    Get a real soundpack

    • First, check if there is folder with “otopack” in the name, in /gamefolder/data/sound/. If that’s the case you can skip this part, otherwise:

    • Go to https://mods.cataclysmbn.org/mods/otopack_bn_mk_2/

    • Repeat the process of Get external mods but this time we will put the files in /gamefolder/sound/

    • PS: Create the sound folder in /gamefolder/ if it doesn’t exist. You musn’t install anything in data, although it works too, this is reserved for the base game files image

    • The soundpack is installed!

    (optional) Get extra musics for the soundpack

    • If you want extra musics for this soundpack, click the link here https://github.com/leoCottret/cbn-leocottret-mods/tree/main/MUSICS for instructions

    Enable everything in game

    • To enable the soundpack in game, Settings > Options (Enter) >
      image

    • General > Choose soundpack “Otopack BN” > ESC key > Select Yes image

    • To start a game with a new mod, just press Enter on it while creating a world

    • World > Create World > Go on your mod > Press Enter image

    • Golden rule: from anywhere in the game, press ? to see (and change) the available keys in this specific context

    File location for Comestibles

    There are a large number of files in json/items/comestibles, and this guide will help you decide where to put your new comestible!

    List of special comestibles:

    med.json – comestible that has an addiction effect besides alcohol and caffeine, plus bandages and antiseptic type items.

    mre.json – items and comestibles related to MREs

    mutagen.json – comestible that has any mutagen effect

    carnivore.json – item that would normally be butchered from an animal or monster, and their cooked versions. examples: chunks of meat, tainted bones, boiled stomach

    protein.json – comestibles based on protein powder

    spice.json – comestibles that normally do not have nutrients, but are used to flavor a dish. examples: salt, thyme, black pepper

    frozen.json – comestibles best eaten frozen

    brewing.json – items used in the brewing process

    List of normal comestibles, in order of priority:

    When you have a comestible you want to add to the files, just go down this list, and the first filename you see in the list that matches the criteria is your choice!

    Liquid

    alcohol.json – “Drink” comestible with alcohol addiction

    soup.json – “Drink” comestible which is a soup. This is more of a “food” than a drink - you primarily want the calories from this

    drink.json – “Drink” comestible. This is your drink of choice when you’re thirsty! examples: tea, juice, water

    drink_other.json – “Drink” comestible that does not fit any other criteria. example: vinegar, mustard

    Solid

    junkfood.json – comestible with the “junk” material. examples: cake, sugary cereal, nachos

    sandwich.json – a “sandwich” is generally two slices of “bread” with something in between. examples: BLT, PB&J sandwich, fish sandwich

    offal_dishes.json – comestible made of various offals. the offal types are: liver, brain, kidney, sweetbread, stomach. This must be the primary part of the dish.

    seed.json – seeds

    meat_dishes_human.json – comestible made of human flesh. examples: hobo helper, tio taco

    meat_dishes.json – comestible made with meat.

    raw_veggy.json – comestible that is a vegetable in its raw form.

    irradiated_veggy.json – comestible that is an irradiated vegetable. has an indefinite shelf life.

    raw_fruit.json – comestible that is a fruit in its raw form.

    irradiated_fruit.json – comestible that is an irradiated fruit. has an indefinite shelf life.

    veggy_dishes.json – comestible made of vegetables.

    bread.json – comestible that is either a bread starter, or a cooked bread.

    wheat.json – either raw wheat, or made of wheat

    egg.json – either an egg, or made of egg

    dairy.json – made of milk

    mushroom.json – a mushroom or made of mushrooms

    nuts.json – a nut or made of nuts

    other.json – if you made it here, your comestible doesn’t fit any other category!

    Electric grids

    Electric grids are electric connections within a building, similar to how all parts of a vehicle share battery power.

    Features

    Currently, only the following furniture interacts with an electric grid:

    • Mounted solar panel (like the one on top of the Evac Center) produces energy
    • Mounted battery stores energy - when examining it, you receive information about power in a given battery and in the whole grid.
    • Battery charger works like vehicle battery charger/recharging station. Place rechargeable batteries or items containing them into the recharger and power will be drained from mounted batteries to recharge those.
    • You can use voltmeter to
      • tell electric grid connections
      • check amount of energy stored
      • extend electric grid connections
    • Ovens work like hotplates, but with charges equal to charges of the grid
    • Jumper cable connector connects a vehicle to an electric grid. To use, connect the jumper cable to the vehicle and then to the connector. Once connected, the vehicle and the grid will share power for most purposes, but will usually charge/discharge their own batteries before sending them through the connector
    • Fridges
    • Floor lamp
    • Electric Kiln
    • Food Dehydrator
    • Food Processor
    • Vaccuum Sealer
    • Arc Welder
    • Electric Forge
    • Electrolysis Kit

    Grid size

    For the purposes of an electric grid, a building is made out of overmap tiles (the tiles you see on the map opened with ‘M’ key, on the local map they are 24x24 tiles). Most city buildings have individual electric grids. For example, a house with a roof and a basement, with a solar panel on the roof, oven on the floor and a battery in the basement, will allow using the oven with the energy from the battery charged by the panel. Overmap tiles without buildings only have grids within their own overmap tile. There is currently no way of connecting grids together, other than by use of two connectors, two jumper cables, and a vehicle.

    Modding

    To create a furniture that uses the grid to power a fake item, create the fake item with a flag "USES_GRID_POWER" and then set furniture’s "crafting_pseudo_item" to that item’s ID. For example, the oven item is:

    {
      "id": "fake_oven",
      "copy-from": "fake_item",
      "type": "TOOL",
      "name": { "str": "oven" },
      "sub": "hotplate",
      "max_charges": 1000,
      "flags": ["USES_GRID_POWER"]
    }
    

    And the oven furniture uses it as:

    "crafting_pseudo_item": "fake_oven"
    

    Currently, the grid can only power fake items used as a part of a furniture.

    Manually Adding Grids (for map design)

    Warning: it is for map design. You can built grid in game without editing files. You just have to build the solars and battery. Jumper cable and connector can connect grid with vehicles. If you build a new house, you’ll find the new house doesn’t have any electric grid. To use electric grid in your new house, you should get and edit the overmap file, which is stored in your game’s save folder. It’s name is o.0.1 or similar. What you need is:

    "electric_grid_connections":[[[0,0,0]], ... ... ... ]}
    

    Add your coordinate in this place. If your home is at 0'113, 2'56, then your overmap file is o.0.2 and your coordinate to add is [113,56,0] (or your z-coordinate) To connect different floors, add coordinate as like this:

    "electric_grid_connections":[[[113,56,0],[0,0,1]],[[113,56,1],[0,0,-1]]... ... ... ]}
    

    [0,0,1] means this coordinate shares electricity with the upper stair, and [0,0,-1] means the opposite one. If your house is as big as an office tower or city hall, [0,1,0] or [1,0,0] will also work. It’s actually how the large building’s electric grid works.

    File descriptions

    Here’s a quick summary of what each of the JSON files contain, broken down by folder. This list is not comprehensive, but covers the broad strokes.

    data/json/

    FilenameDescription
    achievements.jsonachievements
    anatomy.jsona listing of player body parts - do not edit
    ascii_arts.jsonascii arts for item descriptions
    bionics.jsonbionics, does NOT include bionic effects
    body_parts.jsonan expansion of anatomy.json - do not edit
    clothing_mods.jsondefinition of clothing mods
    construction.jsondefinition of construction menu tasks
    default_blacklist.jsona standard blacklist of joke monsters
    doll_speech.jsontalk doll speech messages
    dreams.jsondream text and linked mutation categories
    disease.jsondisease definitions
    effects.jsoncommon effects and their effects
    emit.jsonsmoke and gas emissions
    flags.jsoncommon flags and their descriptions
    furniture.jsonfurniture, and features treated like furniture
    game_balance.jsonvarious options to tweak game balance
    gates.jsongate terrain definitions
    harvest.jsonitem drops for butchering corpses
    health_msgs.jsonmessages displayed when the player wakes
    item_actions.jsondescriptions of standard item actions
    item_category.jsonitem categories and their default sort
    item_groups.jsonitem spawn groups
    lab_notes.jsonlab computer messages
    martialarts.jsonmartial arts styles and buffs
    materials.jsonmaterial types
    monster_attacks.jsonmonster attacks
    monster_drops.jsonmonster item drops on death
    monster_factions.jsonmonster factions
    monstergroups.jsonmonster spawn groups
    monstergroups_egg.jsonmonster spawn groups from eggs
    monsters.jsonmonster descriptions, mostly zombies
    morale_types.jsonmorale modifier messages
    mutation_category.jsonmessages for mutation categories
    mutation_ordering.jsondraw order for mutation and CBM overlays in tiles mode
    mutations.jsontraits/mutations
    names.jsonnames used for NPC/player name generation
    overmap_connections.jsonconnections for roads and tunnels in the overmap
    overmap_terrain.jsonovermap terrain
    player_activities.jsonplayer activities
    professions.jsonprofession definitions
    recipes.jsoncrafting/disassembly recipes
    regional_map_settings.jsonsettings for the entire map generation
    road_vehicles.jsonvehicle spawn information for roads
    rotatable_symbols.jsonrotatable symbols - do not edit
    scent_types.jsontype of scent available
    scores.jsonscores
    skills.jsonskill descriptions and ID’s
    snippets.jsonflier/poster descriptions
    species.jsonmonster species
    speech.jsonmonster vocalizations
    statistics.jsonstatistics and transformations used to define scores and achievements
    start_locations.jsonstarting locations for scenarios
    techniques.jsongeneric for items and martial arts
    terrain.jsonterrain types and definitions
    test_regions.jsontest regions
    tips.jsontips of the day
    tool_qualities.jsonstandard tool qualities and their actions
    traps.jsonstandard traps
    tutorial.jsonmessages for the tutorial (that is out of date)
    vehicle_groups.jsonvehicle spawn groups
    vehicle_parts.jsonvehicle parts, does NOT affect flag effects
    vitamin.jsonvitamins and their deficiencies

    selected subfolders

    data/json/items/

    See below for specifics on the various items

    FilenameDescription
    ammo.jsoncommon base components like batteries and marbles
    ammo_types.jsonstandard ammo types by gun
    archery.jsonbows and arrows
    armor.jsonarmor and clothing
    bionics.jsonCompact Bionic Modules (CBMs)
    biosignatures.jsonanimal waste
    books.jsonbooks
    chemicals_and_resources.jsonchemical precursors
    comestibles.jsonfood/drinks
    containers.jsoncontainers
    crossbows.jsoncrossbows and bolts
    fake.jsonfake items for bionics or mutations
    fuel.jsonliquid fuels
    grenades.jsongrenades and throwable explosives
    handloaded_bullets.jsonrandom ammo
    melee.jsonanything that doesn’t go in the other item jsons, melee weapons
    migration.jsonconversions of non-existent items from save games to current items
    newspaper.jsonflyers, newspapers, and survivor notes. snippets.json for messages
    obsolete.jsonitems being removed from the game
    ranged.jsonguns
    software.jsonsoftware for SD-cards and USB sticks
    tool_armor.jsonclothes and armor that can be (a)ctivated
    toolmod.jsonmodifications of tools
    tools.jsontools and items that can be (a)ctivated
    vehicle_parts.jsoncomponents of vehicles when they aren’t on the vehicle

    data/json/items/comestibles

    data/json/requirements/

    Standard components and tools for crafting

    FilenameDescription
    ammo.jsonammo components
    cooking_components.jsoncommon ingredient sets
    cooking_requirements.jsoncooking tools and heat sources
    materials.jsonthread, fabric, and other basic materials
    toolsets.jsonsets of tools commonly used together
    uncraft.jsoncommon results of taking stuff apart
    vehicle.jsontools to work on vehicles

    data/json/vehicles/

    Groups of vehicle definitions with self-explanatory names of files:

    Filename
    bikes.json
    boats.json
    cars.json
    carts.json
    custom_vehicles.json
    emergency.json
    farm.json
    helicopters.json
    military.json
    trains.json
    trucks.json
    utility.json
    vans_busses.json
    vehicles.json

    Stat system scaling

    Minimum stat: 0 (should only happen due to penalties, instant failure in most scenarios)

    Nominal stat: 8 (“average” person)

    Very high stat: 14 (realistic world class human, maximum cost-effective in chargen)

    Maximal stat: 20 (higher may be achievable, but we’re not worried about balancing at that point.)

    Skill system scaling:

    Minimum skill: 0 (no training)

    Maximum skill: 10 (requires regular training to maintain, “professional” level)

    Monster melee skill scaling:

    Minimum skill: 0 (no melee potential; turret, fungal wall)

    Nominal skill: 4 (average critter; most zeds & giant insects)

    Notable skill: 6 (competent/carnivore; bear, wolf, police/survivor zeds)

    Very high skill: 8 (dangerous opponent; dark wyrm, vinebeast)

    Maximal skill: 10 (highest for balance purposes; jabberwock, tribot, shoggoth, gracken)

    Speeds:

    Zombies are a bit faster than “shambling”. Zombified versions of fast critters will remain fast, but in general the process slows the undead version. Further, under no circumstances should a zed be more than 50% faster than base character speed. Currently, this means “capped at 150”.

    Dodge System assumptions:

    Dodge chance is based on attacker’s melee skill and target’s dex stat and dodge skill.

    Successful dodges negate the attack and impose a cumulative penalty on dodges within the same turn.

    Dodge Use Cases:

    An individual with no skill and nominal stats in ideal circumstances against a basic opponent should occasionally be able to dodge.

    An individual with no skill and nominal stats in ideal circumstances against a skilled opponent should rarely if ever be able to dodge.

    An individual with world-class dodging ability, in ideal circumstances against a basic opponent should have a negligible chance of failure.

    An individual with world-class dodging ability, in ideal circumstances against a skilled opponent should have a moderate chance of failure.

    The effect of increasing dodge skill has a growth rate with diminishing returns that accelerates sharply at the point where you move beyond the dodge a “regular” character is likely to achieve (7 and above)

    The balance of melee versus dodge should favor dodge which, after all, isn’t effective against a wide variety of other types of attacks.

    Even a world class dodger should not be able to dodge continuously when attacked many times a turn.

    MELEE WEAPONS:

    To-Hit Bonuses

    To-hit bonuses start at ‘-2’ and are modified as follows for weapons that have the following properties:

    Grip

    Grip is a measure of how well you can control the weapon to quickly respond to situational changes.

    -1 - Particularly hard to grip items, (especially those that are innately slipper or very rounded with no obvious gripping edge) such as basketballs and barrels, or which are dangerous to hold because of very sharp edges, like scrap metal and broken glass.

    +0 - Any object that doesn’t fall into one of the categories below. Examples include 2x4s, computer monitors, wires, stingers and clothing. Basically, anything that has a grippable component, but which is too thick, too thin, or too flimsy to grab comfortably in a way that can reliably control the object.

    +1 - A weapon with a fairly solid grip, like a pipe, a rock, guitar neck, pool cue or a heavy stick.

    +2 - A weapon with a dedicated grip shaped to the hand, like a sword, axe, knife, or police baton, or that is strapped to the body (or is a piece of the body). Fists would get a +2 bonus here, bringing them to “0” total, since none of the others would apply.

    Length

    Length allows more surface area for potential contact, and reduces the need to control the positioning of the body to guarantee a hit. It also allows the player to strike from a safer distance, allowing them to worry more about trying to hit without being hit in return, and allows for swings with larger arcs, making dodging such a strike more difficult.

    +0 - Any object without a length bonus.

    +1 - Objects that, when held, extend over a foot (1/3 of a meter) in length from the hand. A normal American 12inch ruler is the handy boundary guide for when an item should switch over to a +1 bonus (the ruler, losing several inches when held, does not get one - unless you added a handle to it!).

    +2 - An object that is over 3 feet in length from the point where it is held. Includes swords, spears, quarterstaffs, poles, and a lot of other stuff.

    Striking Surface

    Some weapons need to strike in a certain way to be effective. Others are more difficult to use “incorrectly”.

    -2 - Single-Point weapons - Picks, spears, syringes. Any weapon that has a single point that must contact the enemy in a specific way in order to deal a decent amount of damage. Also, weapons with difficult attack angles, like scythes, where the damaging part of the weapon is faced away from the enemy.

    -1 - Line of damage weapons - Swords, knives, and other weapons that require a solid strike along a particular piece of the weapon, where the weapon can be said to have an attack angle, fall here. Weapons that have point attacks but are still effective without any solid hit, such as a nailboard, would also fall here.

    +0 - attack-anywhere weapons - Clubs, pipes, maces, etc, where the weapon will be dealing full damage with a solid blow no matter how it is angled, because every surface is a striking surface.

    +1 - Weapons that can still do significant damage even with glancing blows would fall here. Jagged tearing weapons and electric weapons like a stun baton would fall here.

    Balance

    A measure of how well-suited the item is for being swung/thrust/etc. This factors in overall balance of the weapon, weight is accounted for separately.

    -2 - Very clumsy or lopsided items ill-suited for swinging or thrusting. Characterized by requiring effort just to hold steady. frying pan or pot, chainsaw, chair, vacuum cleaner.

    -1 - Balance of the object is uneven, but in a way that at least doesn’t interfere with swinging. axes, sledgehammer, rifle, scythe, most polearms.

    +0 - Neutral balance, neither well nor poorly weighted for the typical use. Heavy stick, rock, pool stick, kitchen knives, claw hammer, metal pipe, crowbar, handguns.

    +1 - Well-balanced for swinging or stabbing. Baseball bat, golf club, swords, quarterstaff, knives.

    Damage

    Weapon’s relative strength is based on an approximate formula involving its damage, to-hit, techniques and few other factors.

    Damage per second

    A melee’s weapon damage per second (dps) is calculated past armor against a sample group of monsters with a range of dodge and armor values: a soldier zombie (low dodge, high bash and cut armor), a survivor zombie (medium dodge, some bash and cut armor), and a smoker zombie (high dodge, no armor). This should correctly weigh accuracy, criticals, and damage without over valuing any of them.

    In code, this is calculated using the item::effective_dps() function, which takes a character and a monster. It calculates the relative accuracy of the character and weapon against the monster’s defenses and determines the hit rate from a table lookup. It also determines the number of critical hits. Number of hits is hit rate * 10,000, and number of misses is 10,000 - number of hits.

    For both critical and non-critical hits, average damage is calculated based on the weapon’s stats and the user’s skill. Monster armor absorbs the damage, and then the damage is multiplied by the number of hits: either critical hits for the critical hit case, or total hits - critical hits for the non critical hit case. If the weapon has the rapid strike technique, the total damage is halved, and then the average damage is recalculated, multiplied by 0.66, and absorbed by monster armor again to account for rapid strikes.

    Number of moves is calculated as attack speed * ( number of misses + number of non-critical hits + number of critical hits ) for weapons without rapid strike, or attack speed * ( number of misses + number of non-critical hits / 2 + number of critical hits / 2 ) + attack speed / 2 * ( number of non-critical hits / 2 + number of critical hits / 2 ) for weapons without rapid strikes.

    Damage per second against a particular monster is total damage * 100 / number of moves (100 for the 100 moves/second). Overall dps is the average of the dps against the three reference monsters.

    Critical hits

    A double critical can occcur when a second hit roll is made against 1.5 * the monster’s dodge. Double critical hits have a higher chance of occurring than normal critical hits. For each hit, the chance of achieving either a double critical hit or a normal critical hit is calculated, and then if a random number is less than the critical chance, the critical occurs. Both double and normal critical hits have the same effect, but the chance of them occurring is different.

    Note The critical hit system is stupid and complicated and produces weird results. Double critical hits should have a chance of occuring when the original hit roll is more than 1 standard deviation above the mean, which is simple and faster to calculate than the current system.

    Other factors

    Reach is worth +20% at reach 2, +35% at reach 3.

    A weapon that is usuable by a known martial art is worth +50%.

    Weapon tiers

    Relative value should put the weapon into one of those categories:

    <2 - Not weapons. Those items may be pressed into service, but are unlikely to be better than fists. Plastic bottles, rocks, boots.

    2-5 - Tools not meant to strike and improvised weapons. Two-by-fours, pointy sticks, pipes, hammers.

    6-11 - Dangerous tools or crude dedicated weapons. Golf clubs, two-by-swords, wooden spears, knife spears, hatchets, switchblades, tonfas, quarterstaves.

    12-15 - Good dedicated weapons or the most dangerous of tools. Wood and fire axes, steel spears, electric carvers, kukris, bokken, machetes, barbed wire bats.

    20-35 - Weapons of war, well designed to kill humans. Wakizashis, katanas, broadswords, zweihanders, combat knifes, battle axes, war hammers, maces, morningstars.

    35+ - Sci-fi stuff. Diamond katanas, monomolecular blades, lightsabers and chainswords.

    Specific weapon balancing points: 20 - combat knifes 22 - short blades 24 - long blades, short axes, and short flails 26 - two handed blades, long axes, most spears 28 - two handed axes and polearms 30 - combat spears

    Improvised weapons generally have about 75% of the value of a real weapon.

    Other melee balancing factors

    Attack speed

    Out of two weapons with same dpt, the faster one is generally better. Faster weapons allow more damage granularity (less overkill), make it less likely to miss a turn (and thus dodge/block recharges) and make positioning easier. Slower weapons will pierce armor better, but currently most enemies are very lightly armored.

    Damage type

    At low skill, piercing damage suffers from scaling and bashing damage from damage limit due to low strength and skill. Cutting damage is not affected. At high skill, bashing damage is generally the strongest, but still suffers from the damage limit. Exotic damage types (currently only fire) do not scale with skills or crits.

    RANGE WEAPONS

    Automatic Fire

    Guns with automatic fire are balanced around 1-second of cyclic fire, unless the cyclic or practical fire rate is less than 1 every second. Rates of fire less than 1 shot every second are increased to 2.

    Gun Durability

    Gun durability is an integer usually between 1-9, but it can be higher. It is used for the following purposes:

    • chance of damage on failure to install gunmods
    • underwater misfire chance
    • malfunction chance

    It does NOT affect:

    • chance to gain fouling
    • chance of fouling to cause a malfunction or damage the gun

    Durability values

    10 and more - Perfectly reliable. Almost never malfunctions. Factory specification or milspec only, and extremely high quality on top. Most guns with this much durability also have the NEVER_JAMS flag, but if they don’t a pristine gun (not damaged, no fouling) will malfunction roughly once every 6000 shots.

    9 - Reliable. Rarely malfunctions. Factory specification or milspec only. A pristine gun will malfunction roughly once every 3000 shots.

    8 - Dependable. Malfunctions infrequently. Guns of very high quality. Highest durability possible for guns crafted without advanced fabricators. A pristine gun will malfunction roughly once every 1500 shots.

    7 - Serviceable. Malfunctions infrequently. Higher quality guns, or guns built to chew through lots of ammo, like the m249. A pristine gun will malfunction once every 768 shots, on average.

    6 - Acceptable. Malfunctions occasionally. Highest durability possible for guns crafted without gunsmithing tools. Includes lots of mass-produces guns, like glocks and m4a1 carbines. A pristine gun will malfunction once every 384 shots, on average.

    5 - Usable. Malfunctions frequently. Decently handmade guns, or infamously cheap guns like the sten. A pristine gun will malfunction once every 192 shots, on average.

    4 - Poor. Malfunctions often. Badly assembled guns. A pristine gun will malfunction once every 96 shots, on average.

    3 - Terrible. Malfunctions constantly. 3d printed guns, or haphazardly assembled pipe guns. A pristine gun will malfunction once every 48 shots, on average.

    2 or less - Unusuable. Extreme risk of malfunction. Not applied by default to any item.

    Fouling

    Normal shots increase fouling by 1, and cannot raise fouling above 7150. Blackpowder rounds will increase fouling much faster, and can increase fouling to 10000. Fouling can cause jams, the chance of which is not affected by gun durability. The formula for fouling-caused jams is exponential: 0.1% of the shots will jam at 1000 foul, 0.8% at 2000 foul, 2.7% at 3000, then 6.4%, 12.5%, 21.6%, and 34% at 7000 foul. This is in addition to the malfunction chance described above. Additionally, at high values (5000+), jams can damage the gun (3% chance per shot at 6000, 6% at 7000).

    Blackpowder_tolerance

    This is a value separate from gun durability. It indicates, as a percentage*, how resistant a gun is to fouling generated by blackpowder.

    8 - Default if unspecified, but not common. It takes 55 blackpowder shots to fully foul a gun. Badly made guns.

    24 - It takes 66 blackpowder shots to fully foul a gun. Pistols and SMGs.

    48 - It takes 96 blackpowder shots to fully foul a gun. Most rifles.

    72 - It takes 176 blackpowder shots to fully foul a gun. Durable guns or very old weapons, like the Mosin-Nagant or Marlin 39A.

    96 - It takes 1112 blackpowder shots to fully foul a gun. Flintlocks and other guns specifically designed to use blackpowder rounds.

    A note on “NEVER_JAMS”

    Guns with this will not suffer malfunction normally. However they can still build up fouling, and jam because of it. Additionally they can still malfunction underwater, keeping the durability value relevant.

    Magazines

    Reload times

    The overall balance is that magazines themselves are slow to reload whereas changing a magazine should be fast. For standard box magazines a default reload_time of 100 (per round) is appropriate with this value increasing for poor quality or extended magazines. Guns themselves should also specify reload of 100 (per magazine) unless their magazines are particularly awkward to reload (eg. ammo belts). The game logic intrinsically handles higher volume magazines consuming more time to attach to a gun so you need not consider this.

    Weight

    Increases proportional to capacity and should have a comparable ratio to similar magazines. Consider the base item to be a 10-round .223 factory specification box magazine which has a capacity:weight of 1:10. Increase the ratio markedly for poor quality magazines or more slightly for extended magazines. Smaller calibers should use a lower ratio. The material should have some effect, with plastic magazines weighing less.

    Volume

    Scaled based upon the capacity relative to the stack_size of the ammo. For example 223 has a stack size of 20 so for 10 and 30 round magazines the volume would be 1 and 2. Extended magazine should always have larger volume than the standard type and for very large drum magazines consider applying an extra penalty. By default most handgun magazines should be volume 1 and most rifle magazines volume 2. Ammo belts should not specify volume as this will be determined from their length.

    Reliability

    Should be specified first considering the below and then scaled against any equivalent magazines. For example if an extended version of a magazine exists place it one rank below the standard capacity version. Damaged guns or magazines will further adversely affect reliability.

    10 - Perfectly reliable. Factory specification or milspec only. Never extended magazines. Very rare.

    9 - Reliable. Failures only in burst fire. Factory or milspec magazines only. Never extended magazines. Uncommon.

    8 - Dependable. Failures infrequently in any fire mode. Highest reliability possible for extended magazines and those crafted using gunsmithing tools. Most common.

    7 - Serviceable. Fail infrequently in semi-automatic, more frequently in burst. Includes many extended and aftermarket gunsmithing tools. Common.

    6 - Acceptable. Failures can be problematic. Highest reliability possible for magazines crafted without gunsmithing tools. Includes most ammo belts.

    5 - Usable. Failures can be problematic and more serious. Mostly poor quality hand-crafted magazines.

    <4 - Poor. Significant risk of catastrophic failure. Not applied by default to any item but can be acquired by damage or other factors.

    Rarity

    Overall balance is that pistol magazines are twice as common as rifle magazines and that for guns that spawn with magazines these are always the standard capacity versions. Consider 9x19mm and .223 to be the defaults with everything else more rare. Some locations have more specific balance requirements:

    LocationDescriptionWith gunsDamagedExample
    Military siteOnly source of milspec magazines and ammo beltsNeverNeverLW-56, .223 ammo belt
    Gun storeStandard and extended capacity magazinesNeverNeverSTANAG-30, Glock extended
    Police armoryMostly pistol magazines, especially 9x19mm, never extendedSometimesNeverGlock, MP5 magazine
    SWAT truckPolice or military magazines, occasionally extendedSometimesRarelyMP5 extended
    Survivor basementAnything except milspec weighted towards common typesOftenSometimesSaiga mag, M1911 extended
    Military surplusOlder military magazines that are not current issueNeverRarelyM9 mag, STEN magazine
    Pawn shopAnything except milspec weighted towards unusual calibersNeverRarelyMakarov mag, AK-74 mag
    Everywhere elsePredominately 9mm and 223. Always with standard magazineOftenSometimesRuger 223 mag, M1911 mag

    Archery damage

    Bow damage is based on the momentum achieved in the projectile. Since arrows and bolts have sharp cutting surfaces, the penetration and therefore damage achieved is based on the projectile’s capacity for slicing through tissues. The arrow has a modifier based on construction, material and design, most critically centered around the effectiveness of the head. Base damage is calculated from momentum by taking momentum in Slug-foot-seconds, multiplying by 150 and subtracting 32. This was arrived at by taking well-regarded bowhunting guidelines and determining the damage numbers necessary for a kill of various game on a critical hit, see tests/archery_damage_test.cpp for details.

    Ammo stats

    Base Damage

    The damage (Dmg) of firearm ammunition starts with the square root of a round’s muzzle energy in joules (Energy, J) rounded to the nearest integer with an arbitrary increase or decrease to account for terminal ballistics. These numbers are modified depending on certain criteria (see Adjustment Criteria, below). Damage of handloaded ammo is set to 92% (rounded down) of their factory counterparts. A similar system for calculating recoil is planned but not currently being worked on. The figures used to calculate stats and any other relevant information are presented in table below.

    Base Barrel Length

    Each cartridge also has a Base Barrel Length (Base Brl) listed; this determines the damage for the connected guns. A firearm has its damage modifier determined by it’s real life barrel length; for every three inches between it and the listed baseline here, the gun takes a 1 point bonus or penalty, rounding to the nearest modifier. For example, a .45 ACP gun with a 7 inch barrel would get a +1 bonus (against a baseline of 5 inches).

    Ammo IDDescriptionEnergy, JDmgBase BrlApplied Modifiers / Comments
    .22 CB18gr CB bullet3967.87in
    .22LR40gr unjacketed bullet141126in
    .22LR FMJ30gr FMJ bullet277176in
    .32 ACP60gr JHP bullet218154in
    7.62x25mm85gr JHP bullet544234.7in
    7.62x25mm Type P120gr bullet245159.6inFired from the Type 64 SMG; need more data here
    9x18mm 57-N-181S93gr FMJ bullet251163.8in
    9x18mm SP-793gr bullet417203.8in
    9x18mm RG02893gr hardened steel core bullet317183.8indamage reduced by 4
    9x19mm FMJ115gr FMJ bullet420245.9in
    9x19mm JHP115gr JHP bullet533235.9indamage increased by 3
    9x19mm +P115gr JHP bullet632255.9in
    9x19mm +P+115gr JHP bullet678265.9in
    .38 Special130gr FMJ bullet256164in
    .38 FMJ130gr FMJ bullet256164in
    .38 Super147gr JHP bullet660264in
    10mm Auto180gr FMJ bullet960314in
    .40 S&W135gr JHP bullet575244in
    .40 FMJ180gr FMJ bullet598244in
    .44 Magnum240gr JHP bullet1570407.5in
    .45 ACP JHP185gr JHP bullet614255in
    .45 ACP FMJ230gr FMJ bullet447215in
    .45 ACP +P200gr JHP bullet702265in
    .454 Casull300gr JSP bullet2459507.5in
    .45 Colt JHP250gr JHP bullet610257.5in
    .500 S&W Magnum500gr bullet3056558.4in
    4.6x30mm31gr copper plated steel bullet505227.1indamage reduced by 4
    5.7x28mm SS19031gr AP FMJ bullet5342310.4indamage reduced by 3
    7.62x39mm123gr FMJ bullet21794616.3in
    7.62x39mm 57-N-231121.9gr steel core FMJ bullet20364516.3in
    7.62x39mm M67123gr FMJ bullet21414616.3inTODO
    5.45x39mm 7N1056gr FMJ bullet14023716.3indamage increased by 3
    5.45x39mm 7N2257gr steel core FMJ bullet14613816.3in
    .223 Remington36gr JHP bullet15243920inUses 5.56 NATO barrel baseline; damage increased by 5
    5.56x45mm M855A162gr copper core FMJBT bullet18434320in
    .300BLK supersonic125gr OTM18404316in
    ,300BLK subsonic220gr OTM6752616insubsonic
    7.62x54mmR150gr FMJ bullet36296028in
    .308 Winchester168gr hollow point bullet35706024in
    7.62x51mm NATO M80147gr FMJ bullet33045724in
    7.62x51mm NATO M62142gr tracer bullet32325724inBelt with 1/5 tracer rounds
    .270 Winchester130gr soft point bullet36636124in
    .30-06 Springfield165gr soft point bullet38946224indamage increased by 4
    .30-06 M2165.7gr AP bullet36766024indamage reduced by 10
    .30-06 M14A1Incendiary ammunition38946224indamage reduced by 10
    .45-70 Govt.300gr soft point bullet38676624indamage increased by 4
    .300 Winchester Magnum220gr JHP bullet52997324indamage increased by 5
    .700 NX1000gr JSP bullet1210011028in
    .50 BMG Ball750gr FMJ-BT bullet1708313145in
    .50 BMG M33 Ball706.7gr bullet1801313445in
    .50 BMG M903 SLAP355gr tungsten AP bullet1708313145inCan’t be used with M107A1
    .410 000 shot5 000 pellets15303918in

    ###Adjustment Criteria If the resulting base damage is below specific thresholds, apply one of three multipliers. If the base damage is less than 20, the multiplier is 1.333. Else, if the base damage less than 30, the multiplier is 1.222. Else, if the base damage is less than 40, the multiplier is 1.111. Ammunition with damage of 40 or higher will generally have no arbitrary multiplier given to its basic variant.

    For liminal cases where the base damage is 20, 30, or 40 there is room for discretion regarding which balance increase to apply, if any. Discretion should be exercised based on which solution makes that ammunition distinct from other ammunition of similar power, as having two different ammotypes with identical power should be avoided.

    As for terminal ballistics, hollowpoints variant should be at least 25% more effective against a completely unarmored target, in order for the difference to be considered relevant. Conversely, the base FMJ variation should have a combined damage and armor penetration whose total is at least 15% greater than the damage of the hollowpoint variant. This recommendation will inform how much armor penetration the two variants should have. Armor-piercing variants have seven-eigths the damage of the standard FMJ variant, and enough penetration to make the combined value 30% higher than the damage of hollowpoint.

    The relative combined damage plus armor penetration for each variant can likewise be summarized as follows:

    1. Hollowpoints are considered to have 100% combined damage (example: 100 damage, 0 arpen)
    2. Standard/FMJ variants are considered to have 115% combined damage, 80% damage and 35% arpen (example: 80 damage, 35 arpen)
    3. AP variants are considered to have 130% combined damage, 70% damage and 60% arpen (example: 70 damage, 60 arpen)

    Liquids

    Multi-charge items are weighed by the charge/use. If you have an item that contains 40 uses, it’ll weigh 40x as much (when found in-game) as you entered in the JSON. Liquids are priced by the 250mL unit, but handled in containers. This can cause problems if you create something that comes in (say) a gallon jug (15 charges) and price it at the cost of a jug’s worth: it’ll be 15x as expensive as intended.

    To that end, here’s a list of containers with non-one volume. If you have something spawn in ’em, divide the “shelf” price by this value to arrive at the correct price to list in the JSON.

    • plastic bottle: 2

    • glass jar: 2

    • glass bottle: 3

    • plastic canteen: 6

    • 3L glass jar: 12, as expected

    • gallon jug: 15

    Diamond weapons

    Diamond weapons should be uniform in their CVD machine requirements. Coal requirements are floor((weapon_volume+1)/2)*25. Hydrogen requirements are coal_requirements/2.5.

    In-Repo Mods (Outdated)

    Caution

    Current guideline is in favor of removing in-repo mods. This page is kept for historical purposes.

    BN is not only moddable, but ships with a number of mods available for users to select from even without having to obtain mods from a third party source.

    Why have in-repo mods?

    The benefits of having mods in the repository include:

    • Visibility to a large number of users and potential contributors
    • The ability to use the BN issue tracker to report problems, as well as manage pull requests for adding to or fixing mods in the repository
    • Mods in the BN repository that demonstrate usage of a game feature which exists only for mods (i.e. not used by the core BN game itself) help ensure that feature stays present in the game.

    There are however things that might be expected but are not guaranteed:

    • Guarantee of maintenance of content – core devs are mostly focused on the main game itself; although some might pick up mods as a side task, people who continue working on the core game tend to like the feel of the core game.
    • Guarantee of maintenance of used features – over the course of development it may become impossible to keep a feature, due to performance needs or maintenance burden.
    • Guarantee of sole authorship – once in the repository, the mod is considered community content. While the developers might defer to an active curator of a mod, if they become inactive anyone else can step forward.

    What kind of mods can be in the BN repository?

    There are three primary categories of mods:

    • Content mods, which provide some kind of distinct experience from the core BN game. This could be a change to lore, a change to a specific part of gameplay.
    • User Experience (UX) mods, which alter the look and feel of the game interface itself.
    • Development mods, which aren’t “mods” in the typical sense but are instead there to ease the transition between “incomplete feature” and “complete feature”, when a feature in the core game is sufficiently incomplete that the developers believe it needs to be optional to minimize disruption to players.

    What is necessary for a mod to be included in the repository?

    The most crucial criteria for a mod to be in the BN repository is that it has someone acting as a curator. This ensures that there is someone who is keeping an eye out for possible problems with the mod, and helping steer its development so that it continues to develop in accordance with its design purpose.

    Furthermore, there are additional criteria:

    • Content mods need to be providing some kind of curated experience. Either they introduce a set of locations, encounters, equipment, or progression mechanisms that do not fit the style of the core game, or they in some fashion modify the game according to some well-defined concept.
      • Mods which do not qualify as curated experiences: Grab bag mods with no defined purpose (i.e. adding a bunch of random guns), “settings” mods that just turn off a possibly undesired but working feature (acid ants).
    • Development mods need to have an associated work-in-progress feature that they exist to mitigate.

    What are the responsibilities of a mod curator?

    A mod curator’s role is to curate additions to mods and ensure they fit the concept of the mod. Curators are also responsible for at least acknowledging bug reports related to the mod: while curators don’t have to personally manage every bugfix, if a bug is reported, the curator should be around to comment and help to find someone to fix it.

    It’s important to understand that if a mod is in the repository, it is expected that people other than the curator are going to contribute to it, as with anything. On github, mod curators should Approve or Request Changes on PRs to the mod. If the curator has approved it, developers with merge permissions will treat that as a request to merge the changes.

    When do mods get removed?

    Mods that have no curator or have proven to be consistently some type of maintenance burden are potentially subject to removal. Additionally, mods which had a purpose which is no longer relevant (development mods whose accompanying feature has been finished) will generally be removed once they’re no longer deemed necessary. If a curator can’t be reached for comment on a bugfix or review on a PR’d change for about a month, and hasn’t left any indication of when they’ll be back, developers will assume they’ve left the project, and the mod is orphaned.

    Whenever a stable release occurs, mods which no longer qualify for inclusion will be marked ‘obsolete’. This doesn’t remove them from the repository, but it does prevent it from being used in new worlds (barring additional effort on the part of the player).

    Why do mods get removed?

    While it may be counterintuitive, simply having a mod in the repository increases maintenance burden for the team, even for the people who don’t use the mods itself.

    Furthermore, mods which are shipped with the game but are not working correctly for whatever reason reflect poorly on the project on the whole. While it might seem ‘easy’ to fix a mod, the development team is mostly focused on the core game itself. This is why mod curators are necessary.

    How can mods be rescued from removal?

    If the mod otherwise meets inclusion criteria but lacks a curator (ie. has been declared orphaned), it’s as simple as having someone else step forward as the new curator.

    Otherwise, it needs to either be made to meet the criteria, or it simply isn’t going to be staying in the BN repository.

    JSON Style Guide (Unstable)

    Like in C++ Code Style, the JSON styling policy is to update JSON as it is added or edited, and in relatively small chunks otherwise in order to prevent undue disruption to development.

    Why do we have a homegrown JSON formatter?

    DDA wrote their own JSON parser. It lives in tools/format/format.cpp and it leverages src/json.cppto parse and emit JSON.

    This isn’t optimal solution as it makes using existing JSON formatters (e.g deno fmt) impossible, but last attempt proved that the disadvantages outweighed possible benefits.

    JSON Example

    This example outlines most of the styling features:

    [
      {
        "type": "foo",
        "id": "example",
        "short_array": [1, 2, 3, 4, 5],
        "short_object": {
          "item_a": "a",
          "item_b": "b"
        },
        "long_array": [
          "a really long string to illustrate line wrapping, ",
          "which occurs if the line is longer than 120 characters"
        ],
        "nested_array": [
          [
            ["item1", "value1"],
            ["item2", "value2"],
            ["item3", "value3"],
            ["item4", "value4"],
            ["item5", "value5"],
            ["item6", "value6"]
          ]
        ]
      }
    ]
    

    Indention is two spaces. All JSON delimiters except comma and colon are surrounded by whitespace (either a space or a newline). Comma and colon are followed by whitespace. Object entries are always newline-separated. Array entries are newline-separated if the resulting array would exceed 120 characters otherwise (including indention). Line breaks occur after open brackets, close brackets, or entries.

    Formatting tool

    The formatting tool can be invoked through the CMake style-json target, directly as tools/format/json_formatter.cgi, or via cgi at http://dev.narc.ro/cataclysm/format.html

    If you’re using the Visual Studio solution, you can configure Visual Studio with commands to format all of the JSON in the project.

    1. Build the JsonFormatter project by either building the entire solution or just that project. This will create a tools/format/json_formatter.exe binary.
    2. Add a new external tool entry ( Tools > External Tools.. > Add ) and configure it as follows:
      • Title: Lint All JSON
      • Command: C:\windows\system32\windowspowershell\v1.0\powershell.exe
      • Arguments: -file $(SolutionDir)\style-json.ps1
      • Initial Directory: $(SolutionDir)
      • Use Output window: checked

    At this point, you can use the menu ( Tools > Lint All JSON ) to invoke the command and can look in the Output Window for the output of running it. Additionally, you can configure a keybinding for this command by navigating to Tools > Options > Environment > Keyboard, searching for commands containing Tools.ExternalCommand and pick the one that corresponds to the position of your command in the list (e.g. Tools.ExternalCommand1 if it’s the top item in the list) and then assign shortcut keys to it.

    For Single file

    To style one JSON file you can run json_formatter.exe path/to/file.json. This will style that one file. If it prints “needs linting”, the file wasn’t styled, but now should be. You can use drag&drop: drag the json file onto the json_formatter icon, then wait a few seconds.

    On *nix

    Run just fmt-json in the main repo directory. If just is unavailable, run build-scripts/format-json.sh instead.

    Loading Order

    All files here in data/json are read eventually, but the order in which they’re read can be important for objects with dependencies on other kinds of objects (e.g. recipes depend on skills). Ensuring the proper loading order will prevent surprises that, most often, manifest as crash-to-desktop with segfault (a very bad thing).

    The way Cataclysm finds and loads json files is by running a breadth-first search in the tree data/json/. This means data/json/whatever.json will always be read before data/json/subdir/whatever.json. This tells us how to ensure dependency loading order.

    For instance, if you have scenarios that depend on professions that depend on skills, you’ll want a directory structure such as the following:

    data/json/
      skills.json
      professions/
        professions.json
        scenarios/
          scenarios.json
    

    Which results in a loading order of: skills.json then professions.json and then scenarios.json.

    Same-depth loading order

    Note that, when files (or directories) are at the same depth (i.e. all in data/json/), they will be read in lexical order, which is more or less equivalent to alphabetical order for file names that use only ascii characters. For UTF-8 or otherwise non-ascii file names, the names will be ordered by codepoint.

    Melee balance spreadsheet

    This is documentation for the ‘Melee Weapons Evaluation.ods’ spreadsheet. This is the spreadsheet that drove the 0.E experimental melee weapon rebalance project. The original spreadsheet is available as a google doc but the static copy is preserved in case stuff moves.

    This is a complicated spreadsheet, with a lot of moving parts. The following are the tabs and the data flow:

    Raw

    Raw was the initial data dump, taken from some October 2019 version of the 0.D experimental using mlangsdorf’s usual mods (hence all the Blazemod stuff). Raw was slightly annoyed with some extra categories:

    • Weapon Class - this is a simple numeric rating. 0 is not a weapon, 1 is an explosive device, 2 is a ranged weapon or gun, 3 is a tool that makes a poor weapon like a cooking pot, 4 is a helmet, 5 is a tool that makes a good weapon like a sledgehammer, 6 is an improvised or fake weapon, and 7 is an actual dedicated weapon
    • Category - this is a categorization of items as weapons, to make it easier to compare similar weapons. Melee weapon categories are Ax, Ax2, Club, Club2, Flail, Flail2, Knife, Polearm, Spear, Staff, Shortsword, Sword, and Sword2. Categories that end with 2 are two-handed weapons.
    • Acc - this is a recaluclation of weapon accuracy based on the accuracy factors below, because review of the data showed that a lot of weapons have accuracy values that are not supported by the criteria in GAME_BALANCE.md.
    • Grip - the item’s grip, as described in GAME_BALANCE.md
    • Leng - the item’s leng, as described in GAME_BALANCE.md
    • Surf - the item’s striking surface, as described in GAME_BALANCE.md.
    • Bal - the item’s balance, as described in GAME_BALANCE.md. Additional categories beyond Clumsy were added and assigned by eye.

    Filter

    Filter takes the initial data from raw and a weapon class (in cell B1) and filters out items with a lower weapon class to make further analysis easier.

    New Formula

    This calculates the new weapon evaluation formaula on the inital stats. This is complicated.

    The first 7 rows have some header data. The bulk of the calculation starts on row 8.

    The weapons were evaluated using a Strength 10, Dexterity 10, Perception 10 survivor with skill 4 in all weapons. The base hit, stat crit, skill crit, bash mult, cut mult, and stab mult values are derived from the relevant bits of src/melee.cpp.

    • Columnn A “Average” is the new weapon evaluation value for the weapon, on the edge of the sheet for easy reference.
    • Columns B-J are the weapon’s original stats, taken from the Raw tab via the Filter tab.
    • Column K “roll_hit” is sum of the evaluator’s base_hit and the weapon’s acc.
    • Column L “Wpn Crit” is weapon’s contribution to critical hits.
    • Columns M-N “3 Crit” and “2 Crit” are the chances of a triple and double critical hit occuring, based on skill, accuracy, and stats.
    • Columns O-Q “Average Non-Crit” damage are the weapon’s calculated average damage before armor for non-critical hits in each of the 3 categories.

    All that is pretty straightforward. The next three blocks are where it gets complicated. Columns S-Z are repeated as AB-AI and AK-AR with different monster stats.

    • Row S “Hits” is the expected number of hits per 1000 attacks, calculated against a normal distribution with a mean value of 5 * ( roll_hit - monster Dodge ) and a standard deviation of 25.
    • Row T “Crit %s” is the percentage of those hits that should be critical hits.
    • Row U “Dmg” is the average expected damage past armor. This is simply the sum of max( 0, damage type - armor amount ) for each of the 3 damage types.
    • Row V “Crit” is the average expected critical damage past armor. This is the sum of the critical damage - armor amount for each of the three damage amounts, but the formula is substantially more complicated because the 3 damage types have different critical damage multipliers and reduce effective armor by different amounts on a critical.
    • Rows W-Y repeat damage and critical damage, but for rapid strikes where the base damage is multiplied by 2/3rds.
    • Row Z “Dmg/Turn” is either: ** 100 * ( Dmg * ( Hits - num crits ) + Crit Dmg * ( num hits ) ) / ( 1000 * Moves ) - ie, sum of damage per hit for each normal hit + crit damage for each critical hit divided by the number of moves in 1000 attacks, multiplied by 100 moves/second, OR ** 100 * ( Dmg * ( Hits - num crits ) / 2 + Crit Dmg * ( num hits ) / 2 + rapid strike Dmg * ( Hits - num crits ) / 2 + rapid strike Crit Dmg * ( num hits ) / 2 ) / ( 1000 - ( hits / 2 ) * Moves + Hits * 0.33 * Moves ) - same as above, but accounting for rapid strike reduced damage and movement cost.

    Finally,

    • Column AT “Weapon” is a repeat of the weapon name for refernce
    • Column Au “Value” is the average of columns Z, AI, and AR, multiplied by 1.5 for Reach 2 weapons and 1.75 for Reach 3 weapons.

    New Formula Sorted

    This compares the old weapon values versus the values from the new formula, and sorts weapons by decreasing new value by weapon category to make it easier to spot weapons that are unsually good (I’m looking at you, broadsword) or bad for their category.

    Proposed Values

    This repeats the New Formula tab, except that Columns C-J were copied over and pasted as values, and then adjusted to make the numbers nice.

    • Accuracy was adjusted to the new values based on grip, length, striking surface, and balance from the Raw tab. That means a bunch of previously accurate weapons like bionic claws got a nerf, and inappropriately inaccurate weapons like katanas got a buff.
    • Weapons in the same category were generally adjusted to have roughly the same evaluation, though with different values. In general, European weapons get more of their damage from bash and less from cut, and are often heavier and slower, than Asian weapons. This is a little arbitrary and not entirely realistic, but everyone seems to expect it. As a case in point, the Japanese two-handed sword “nodachi” has 164 attack speed, bash 6, and cut 47, while the European two-handed sword zweihander has 169 attack speed, base 18, cut 39. They both have values of about 26.
    • Inferior weapons got a 1 step penalty in balance compared to the real weapon, and half of the cut/pierce damage is moved to bash, and the cut/pierce damage is 1/4th’s the real weapons. Ie, an inferior pike does Bash 30, Stab 11 to a pike’s Bash 8, Stab 44.
    • Fake weapons are as badly balanced as the inferior version of a weapon, but are basically blunt so the striking surface usually got upgraded to “every”, ironically making them as accurate or more accurate than the real version of the weapon. Bash damage was halved from the inferior version, and cut/pierce damage was again reduced to 1/4th of the inferior version, which is 1/16th the real version. A fake pike does Bash 15, Stab 3.
    • A lot of weapons got damage boosts to bring up their evaluated value. A lot of low damage weapons with rapid strike were being drastically overvalued, but the damage past armor tests showed that rapid strike often just lets you bounce off armor twice as fast.
    • Spears got some rough formula for pierce damage based on weight that I can’t recover anymore, but in general the differences between spears are more minor than they used to be.
    • Polearms got the same rough damage as Ax2 at range 2, but got a separate balance line at range 1 with the raw damage reduced by 0.7. This makes polearms very impressive at range, but slightly worse than quarterstaffs against adjacent targets.

    Poposed Values Sorted

    This is another comparison tab like New Formula Sorted, but used the data from Proposed Values.

    Comparison

    This is a summary tab.

    In columns A-P, each weapon from the filter tab gets it’s current and proposed stats, it’s original value, value under the new formula, and value under the new formula using the proposed values. For proposed values, values that improved are highlighted in green and those that got worse are in red. Ideally, this will make it easy to compare changes and catch mistakes.

    Columns S-AH repeat the process, but cells S1, T1, U1, and V1 can be used to specify category names, and then the subtotal shows a selected subset of weapons that match those categories. This simplifies comparing things.

    Building UDP tileset

    UndeadPeople-style unpacked tilesets are composed with the TypeScript tileset tool.

    Links:

    The old compose.py setup used Python, Libvips, and pyvips. Those links are kept for historical reference only: https://www.python.org/downloads/, https://github.com/libvips/build-win64-mxe/releases, https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/.

    Setup

    1. Install Deno.
    2. Get an unpacked tileset repository.
    3. From a Cataclysm: Bright Nights working copy, run the pack command with the unpacked tileset directory as input:
    deno run -A scripts/tileset.ts --pack path/to/UndeadPeopleUnpacked path/to/UndeadPeoplePacked
    

    The first path is the unpacked tileset root. It should contain files such as tileset.txt, tile_info.json, and pngs_* directories. The second path is where the composed tile_config.json and tilesheet PNG files will be written.

    For more detail, see Tilesets. For small checks in a browser, see the Tileset Web Tool.

    Adding Json Roof Guide

    Adding json roofs to a building involves using a few more files to link the roof and building together during mapgen.

    Files that will be edited:

    data/json/mapgen/[name of building].json : the map of the building and roof.

    data/json/overmap_terrain.json : defines the building’s overmap characteristics.

    data/json/regional_map_settings.json : defines the building’s overmap spawn settings.

    data/json/overmap/multietile_city_buildings.json : links the building layers together.

    Making the Roof Map

    Refer to MAPGEN for creating the map if you are new to map creation.

    Open the file that contains the map for the building data/json/mapgen/[name of building].json Add a new entry for the roof. You can copy the building entry since you want the same foundation footprint for the roof.

    Give the roof a unique om_terrain ID. Below is an example of the main floor and roof om_terrain IDs

    "om_terrain": [ "abstorefront" ],
    "om_terrain": [ "abstorefront_roof" ],
    

    Note: If you are adding a roof to an existing building that shares a common om_terrain ID with other maps, you will need to change the om_terrain ID for the existing floor to be unique.

    Keep the outline of the walls from the original floor, Add t_open_air outside the building and a t_flat_roof over the building’s footprint. There are a few flat roof terrains to choose from in terrain.json.

    There are a number of terrains and furniture structures for roofs including gutters, chimneys, and roof turbine vents. Browse json/terrain.json and furniture.json for ideas. Consider roof access, you can use ladders, stairs and gutters. Some furniture is also climbable.

    There is a set of optional nested map chunks at data/json/mapgen/nested_chunks_roof.json if you’d like to incorporate them. Add any new nested chunks for roofs here as well.

    Sample roof entry:

    {
      "type": "mapgen",
      "method": "json",
      "om_terrain": "abstorefront_roof",
      "weight": 200,
      "object": {
        "fill_ter": "t_flat_roof",
        "rows": [
          "                        ",
          " |....................3 ",
          " |....................3 ",
          " |....................3 ",
          " |....................3 ",
          " |....................3 ",
          " |....................3 ",
          " |....................3 ",
          " |....................3 ",
          " |....................3 ",
          " |....................3 ",
          " |....................3 ",
          " |......&.............3 ",
          " |....................3 ",
          " |....................3 ",
          " |-----------------5--3 ",
          "                        ",
          "                        ",
          "                        ",
          "                        ",
          "                        ",
          "                        ",
          "                        ",
          "                        "
        ],
        "terrain": {
          ".": "t_flat_roof",
          " ": "t_open_air",
          "|": "t_gutter_west",
          "-": "t_gutter_south",
          "3": "t_gutter_east",
          "5": "t_gutter_drop"
        },
        "furniture": { "&": "f_roof_turbine_vent" },
        "place_items": [
          { "item": "roof_trash", "x": [2, 21], "y": [3, 14], "chance": 50, "repeat": [1, 3] }
        ],
        "place_nested": [
          {
            "chunks": [
              ["null", 50],
              ["roof_4x4_party", 15],
              ["roof_4x4_holdout", 5],
              ["roof_4x4_utility", 40],
              ["roof_5x5_coop", 5]
            ],
            "x": [3, 15],
            "y": [3, 7]
          }
        ]
      }
    }
    

    Linking the main floor and the roof

    Navigate to json/overmap/multitile_city_buildings.json or json/overmap/multitile_buildings_terrain.json for buildings taking up more then one overmap tile per z level (schools, mansions). Add an entry for the main floor. The point coordinates define to the x, y, z positions of the building. The 1 places the roof one z level above the ground floor. Append north for rotating buildings to orient the z levels.

    {
      "type": "city_building",
      "id": "abstorefront",
      "locations": ["land"],
      "overmaps": [
        { "point": [0, 0, 0], "overmap": "abstorefront_north" },
        { "point": [0, 0, 1], "overmap": "abstorefront_roof_north" }
      ]
    }
    

    Overmap Specials

    Overmap specials are handled a little differently. They use json/overmap/specials.json for both linking z levels and overmap spawning. A special won’t need an entry in data/json/regional_map_settings.json

    Overmap special example:

    {
      "type": "overmap_special",
      "id": "Evac Shelter",
      "overmaps": [
        { "point": [0, 0, 0], "overmap": "shelter" },
        { "point": [0, 0, -1], "overmap": "shelter_under" },
        { "point": [0, 0, 1], "overmap": "shelter_roof" }
      ],
      "connections": [
        { "point": [0, -1, 0], "terrain": "road" }
      ],
      "locations": ["wilderness"],
      "city_distance": [5, 10],
      "city_sizes": [4, 12],
      "occurrences": [1, 3],
      "rotate": false,
      "flags": ["CLASSIC"]
    }
    

    Adding the overmap_terrain entry

    Navigate to data/json/overmap_terrain.json Every z level gets an entry that defines how it appears on the overmap. The name field will determine what is displayed in the in-game overmap. The entries should share the same color and symbol.

      {
        "type": "overmap_terrain",
        "id": "abandonedwarehouse",
        "copy-from": "generic_city_building",
        "name": "abandoned warehouse",
        "sym": 119,
        "color": "brown"
      },
      {
        "type": "overmap_terrain",
        "id": "abandonedwarehouse_roof",
        "copy-from": "generic_city_building",
        "name": "abandoned warehouse roof",
        "sym": 119,
        "color": "brown"
    }
    

    Adding to regional_map_settings

    Navigate to data/json/regional_map_settings.json

    This determines the spawn frequency and location of non-special buildings. Find the appropriate category for your building and add either the overmap_special ID or the city_building ID and include a spawn weight.

    "abandonedwarehouse": 200,
    

    When testing you can increase the spawn rate if you want to survey your work using natural spawns.

    Finally, always lint your additions before submitting.

    How to give items a sensible postapoc_price value

    Pricing philosophy

    Prices were based on the philosophy that there is a decent portion of humanity unwilling to regularly brave the risks of city scavenging, that are always on the lookout for supplies to stay alive. This mean food and medicine are relatively quite valuable compared to the goods you would use to acquire them.

    The standard unit of currency, the free merchants note, is priced to be the equivalent to one piece of meat jerky (250 cents).

    One piece of meat jerky will stay fresh for 24 days, a decent time, and contains 347 calories.

    A survivor that bring back 2000 cents worth of goods back to the merchants every day is doing well enough to eke out a subsistence living.

    A survivor that brings back 4000 cents worth of goods every day is doing quite well for himself.

    Items are priced on a combination of their availability and their utility.

    Raw materials tend to either be worthless, or only somewhat worthwhile if you can get them in bulk ~(0-25)/kg.

    Common items with no utility are worthless.

    Common items with some theoretical utility are worth very little (~10).

    Common items that are useful tend to be in the ~(250-2000) price range.

    Rare items with no utility have some small value ~(10-50).

    Rare items with some theoretical utility are worth ~(100-500).

    Rare items with considerable use tend to have the highest variety in prices ~(1000-15000).

    No item should be worth more than 150000. They might be worth more if the economy was larger but that’s pretty much the most anyone will be willing to spend on any one thing, no matter how nice it is.

    Currently Implemented faction currencies

    "id": "FMCNote",
    "description": "The Free Merchant Certified Note, also known by names such as a 'c-note' or 'merch', is a currency based on old American bills.  Fifty dollar bills and larger are printed with a promissory note signed by the treasurer of the Free Merchants, along with a complex design.  The note explains that this can be exchanged for food, water, and other services through the Free Merchants in the Refugee Center.",
    "name": { "str": "Merch" }, 
    "price_postapoc": 250
    
    
    "id": "RobofacCoin",
    "name": { "str": "Hub 01 Gold Coin" },
    "description": "This is a small but surprisingly heavy gold coin.  One side is etched with circuitry and the other side reads 'Hub 01 exchange currency'.",
    "price_postapoc": 5000
    
    
    "id": "FlatCoin",
    "name": { "str": "FlatCoin" },
    "description": "This is a coin that has been flattened in a novelty coin flattening machine.  The machine has been somewhat crudely altered so that the design - which appears to once have been Mickey Mouse - is overlaid with a handwritten emblem of a book.  There is some text that faintly reads 'Campus Exchange Token'.",
    "price_postapoc": 250
    
    
    "id": "signed_chit",
    "name": { "str": "chit" },
    "description": "This is a slip of paper signed by the issuer.",
    "price_postapoc": 250
    
    
    "id": "icon",
    "name": { "str": "icon" },
    "description": "This is a small picture, about the same size as an ID card, symbolizing a religious figure.  On the back, there is a text that faintly reads 'New England Church Community'.",
    "price_postapoc": 250
    
    Some benchmark prices
    {
      "id": "antibiotics",
      "name": { "str_sp": "antibiotics" },
      "description": "A strong antibacterial medication designed to prevent or stop the spread of infection.  It's the safest way to cure any infections you might have.  One dose lasts twelve hours.",
      "price_postapoc": 40000,
      "charges": 15,
      "stack_size": 200,
      "flags": [ "NPC_SAFE", "IRREPLACEABLE_CONSUMABLE" ]
    },
    {
      "id": "boltcutters",
      "type": "TOOL",
      "name": { "str": "pair of bolt cutters", "str_pl": "pairs of bolt cutters" },
      "description": "This is a large pair of bolt cutters.  You could use them to cut padlocks or heavy gauge wire.",
      "price_postapoc": 250,
    },
    {
      "id": "armor_lightplate",
      "name": { "str": "plate armor" },
      "description": "A suit of Gothic plate armor.",
      "price_postapoc": 12000,
    },
    {
      "id": "bat_metal",
      "name": { "str": "aluminum bat" },
      "description": "An aluminum baseball bat, lighter than a wooden bat and a little easier to swing as a result.",
      "price_postapoc": 1250,
    },
    

    Food pricing

    Food is priced mostly for a combination of calories, how preservable they are, and how nutritious they are.

    Meat jerky is 250.

    Food that has more calories, is canned, and is very nutritious might be 500.

    Food that has less calories, goes bad quickly, and is junk food, might be 50.

    Stack size

    For items that have a stack size, you need to divide the price by stack size find the price per unit of the item.

    Writing Lab JSON

    Labs are heavily randomized but have very few actual overmap terrain tiles, meaning that variety in the maps gets almost entirely using JSON. In particular, labs use place_nested extensively to randomly select submaps, such as new lab rooms.

    Quick Guide for new lab areas:

    In lab_floorplans.json add a new mapgen json with om_terrain of lab_4side.

    Keep the middle 2 spaces of each border clear, because that’s where doors open out to. Some or all of the border spaces will be turned into 1-width walls between lab sections, so make sure the map ‘works’ whether or not the outermost spaces are created or not (by keeping them clear, or having ‘disposable’ furniture like counters, lockers, broken consoles, etc). Allow rotation.

    To add a lab finale instead, use the om_terrain of lab_finale_1level and put your JSON in lab_floorplans_finale1level.json instead.

    Quick Guide for new lab dead-ends:

    In lab_floorplans_1side.json add a new mapgen json with om_terrain of lab_1side.

    Make the area facing north, keeping the 2 middle spaces of the northern border clear because that’s where doors open out to. If you want to have a locked area, set the floor to ‘t_strconc_floor’ and stairs won’t appear there (this floor is ‘,’ in the lab_palette). Use place_nested to place ‘lab_1side_border_doors’ at coords [0, 0]. Do not allow rotation.

    Quick Guide for new lab rooms:

    In lab_rooms.json add a new mapgen json with a nested_mapgen_id of lab_room_7x7 or lab_room_9x9 with a mapgensize of [7, 7] or [9, 9].

    In some rare cases the first row or column of terrain may be replaced with a border wall, so prefer layouts that look intact even if that occurs.

    If your layout needs to know where the doors of the room will open up into, instead use a nested_mapgen_id of lab_room_7x7_crossdoors and lab_room_9x9_crossdoors which will ensure that doors only appear in the exact middle of a wall.

    Lab JSON Full Guide

    How area mapgen json works

    A lab is mostly made out of overmap tiles of type ‘lab’, ‘lab_stairs’, and typically one ‘lab_finale’.

    Lab terrain needs special treatment: stairs, border walls, dead-ends, and more, so JSON instead uses three ‘fake’ overmap tile types. Create a JSON mapgen object with om_terrain set to one of these, and the code will convert it and place it correctly on the map.

    • lab_1side - placed when exactly one lab is adjacent, maps should assume a north-facing entrance. Do not allow rotation.
    • lab_finale_1level - placed at the bottom of a lab on terrain types. Rotation optional.
    • lab_4side - all the other maps. Rotation optional.

    Border walls

    Labs have unusual borders: 1-width walls between lab areas, laid out on the south and east side of those tiles, potentially with metal doors in the middle of them, like so:

    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       M",
    "                       M",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "                       |",
    "-----------MM----------|"
    

    If a north or west neighbor isn’t a lab, the entire side gets needs to be overwritten with a wall, replacing whatever was normally there. If the east or south neighbor isn’t a lab, that door needs to be overwritten with a wall.

    Some JSON maps can start from the above layout, disable rotation, and call place_nested with the ‘lab_border_walls’ chunk in JSON. In this case, borders will be perfect and no additional code will fire.

    But if borders have not been managed (determined by checking for the presence of an east-facing door/wall), then the code will create the lab border walls and doors on all four directions.

    ‘lab_border_walls’ does not work on rotated maps, so rotated maps need to rely on hardcoded border wall generation. This is preferable because it creates more variety. So if a map layout is amenable to not knowing if the final 1x1 border around it will be placed or not, it is preferable to allow rotation and not place ‘lab_border_walls’.

    One middle-ground: If just part of the map needs to cares about where the border wall is to look correct, put a wall on the east-side of the map and only allow rotation of [0, 1]. That will ensure the wall gets placed on the east or south side of the map in the final rotation. See the “electricity room” floorplan for an example of this.

    Other hardcoded map generation

    Labs will have a small chance of randomly getting lights, the central & tower labs will always get them. Stairs will be placed on any empty thconc_floor space if the overmap indicated stairs. There’s also a 10% chance of special effects like flooding, portals, radiation accidents, etc. Ant-infested labs will get bashed in.

    None of these require json changes to enact, but JSON-ideas for lab special effects in rooms can be added to the spawn tables in lab_maybe_effects_7x7 and lab_maybe_effects_9x9. Currently this just adds spider-infestations.

    Room generation

    The most common source of randomness within a map is to create a 7x7 or 9x9 room and give it random contents by using place_nested. Don’t place rooms directly, instead we use an intermediate map chunk called a ‘spawn’ which encodes more information and randomizes between all the kinds of rooms that would satisify those requirements.

    • lab_spawn_7x7 - a 7x7 room with no guarantees on where the doors are.
    • lab_spawn_7x7_crossdoors - a 7x7 room with doors only in the middle of each border wall.
    • lab_spawn_9x9 - a 9x9 room with no guarantees on where the doors are.
    • lab_spawn_9x9_crossdoors - a 9x9 room with doors only in the middle of each borders wall.

    Selecting a spawn will randomize between: lab_room_[size] plus the _rare variants, and the _crossdoors variants if applicable.

    If your room is also amenable to having two of its walls redefined, you can also use these spawns to add in more randomized rooms that might modify the walls by adding windows, replacing walls with chainlink, or creating multiple doors and interior walls. These templates assume that there are no doors on the two walls which are not part of this submap. Note these submaps are sized 8x8 and 10x10 because they include the walls to be modified.

    • lab_spawn_7x7_wall_nw
    • lab_spawn_7x7_wall_sw
    • lab_spawn_9x9_wall_nw
    • lab_spawn_9x9_wall_sw

    Use the most specific spawn possible.

    Directory

    • lab_central.json - hardcoded maps for the top of central lab.
    • lab_common.json - terrain palette, loot palettes, common json objects.
    • lab_escape.json - maps specifically for lab challenge escape, these are special placed on lvl 4 of a lab.
    • lab_floorplan_cross.json - cross floorplans are unusual for having rock infill when bordering the edge of the lab, with rare vaults.
    • lab_floorplans.json - the main source of lab layouts.
    • lab_floorplans_1side.json - dead-end floor plans.
    • lab_floorplans_finale1level.json - finale floorplans.
    • lab_rooms.json - randomized rooms.
    • lab_rooms_wall.json - randomized rooms which rewrite the wall borders.
    • lab_trains.json - tiles for the lab science train which rarely happens on levels 2 & 4.

    Guide for basic mapgen

    This guide will cover the basics of mapgen, which files you need to edit, the tags in each file and the differences in creating specials or regular city buildings.

    For full technical information about mapgen entries, visit here

    First, lets cover some basic concepts and the files you’ll add or edit.

    General comments:

    CDDA mapgen is surprisingly powerful once you get used to working with it. You can use lots of tricks to add variability and interest to your maps. Most advanced mapgen techniques will go into a different tutorial. This one covers basic concepts and how to create a basic single OMT (overmap terrain tile)sized building. We will touch on palette usage and how to add a roof as well.

    Specials vs. city buildings:

    A special is a building that spawns outside the city and requires additional information to spawn, like its distance from cities and valid OMT terrain types. They also used to be the only multi-tile buildings in the game until recent changes allowed special type buildings to spawn inside cities. Examples of specials are: farms, cabins, LMOE, etc.

    City buildings can be single or multi-tile in size and have their spawns limited to the city boundaries. A building can be both a city building and a special but would require both sets of entries to spawn for both types. Some motels are examples of this (see: 2fmotel_city & 2fmotel).

    Important policy: since the roof project, all buildings are now multi-tile across z levels. All new buildings should always get a JSON roof added. Soon, all basements will also be custom fit to the ground floor mapgen, so it is good practice to include dedicated downstairs if you want a basement.

    The Files & their purpose:

    1. You will add a new mapgen file in: data/json/mapgen or one of its sub-folders. If you are using an existing foundation shape for the building, you may append it to that building’s file.

      • This is the blueprint for the building. It can also hold all the building’s data for adding furniture and loot (see palette for an alternative).
    2. You will add entries for each z level you create in the appropriate overmap_terrain file (data/json/overmap/overmap_terrain).

      • These entries will define what your building looks like in the overmap, its symbol, color, and spawn requirements like adding sidewalks, it will also control flags for some mapgen functions.
    3. You will add an entry into either specials.json or multitile_city_buildings.json depending on if it is a special or a city building.

      • For multitile_city_buildings this will link the various z levels &/or multiple OMTs of your building.
      • For specials, this will link the various z levels or multiple OMTs of your building, define any needed road/subway/etc. connections, and define its spawning parameters.
    4. Add an entry into regional_settings.json for city buildings. This will allow them to spawn in the world.

    5. Optional but recommended for any large project: adding a new palette file into mapgen_palettes folder (you may use any existing palette too).

      • This is a file that can be shared among several maps that holds a portion of the mapgen file data. It is commonly used for defining terrain and furniture. You can also put in loot, vehicle, monster spawns and any other data that normally goes in the "object" tag of the mapgen file.
      • Please avoid editing existing mapgen palettes because you may affect existing maps using a combination of the palette and the mapgen file.

    Starting the mapgen entry:

    When I start a new map project, I generally will add in all the entries I need for it to spawn in game from the outset. This way I can test it as I work on it and adjust it as needed. So, I recommend setting up all the needed files when you begin your project.

    Before beginning you’ll want to make some decisions:

    1. What size will it be overall (how many OMTs?)

    2. Where will it spawn?

    3. Will I use a palette or put everything in the mapgen file.

      • If you use a palette, define as much of it as possible from the outset.
    4. Advanced questions:

      • Will I use nested maps?
      • Do I want it to connect to the subways or roads?
      • Will I be using the mapgen object data in combination with a palette (see the mall 2nd floor if you want a master class in combined usage of both types)?

    The mapgen map:

    This covers the mapgen file map flags and what they do in layman’s terms. You can get more extensive information from MAPGEN.

    the mapgen file has some meta data tags and the "object" data which defines everything to make the map.

    The metadata:

    Sample:

    "type": "mapgen",
    "method": "json",
    "om_terrain": "s_restaurant_coffee",
    "weight": 250,
    
    1. "type" will always be mapgen (we’ll cover other map types in future tutorials), the "method" will always be JSON. This data tells the program how to treat this file.

    2. "om_terrain": this is basically your internal name for the map (not the name that shows up on the overmap). It should usually be unique unless you plan on having multiple variants of the same map which share the same building foundation shape (note: I mean the actual shape of the building’s foundation).

    3. "weight": This entry is the weight of this particular map compared to others sharing the same om_terrain name. So, say you have one version of a house then you make an identical house with different spawns (like a fully furnished house and an abandoned version). This weight will determine how often each spawns in relation to the other. Say the furnished house is at 100, and the abandoned one is at 20. So, it’ll spawn 5x less than the furnished house.

    The object data:

    This is the section of tags that defines your map, its terrains, furniture, and various spawn types. There are several ways to place items (and nested maps). These deserve their own tutorial. For this document we’ll be using “explicit symbol” placement for loot spawns, the easiest to use. Everything in the object section can be placed in a mapgen_palette except rows and fill_ter.

    Sample object segment: everything in the object needs to fall within the object’s {} braces or it won’t be included. If you misplace the end bracket, you probably won’t get a loading error.

    Sample:

    "object": {
      "fill_ter": "t_floor",
      "rows": [
        "S___________SSTzzzzzzzTS",
        "S_____,_____SSzMbMbMbMzS",
        "S_____,_____SSSSSSSS/MzS",
        "S_____,_____SSSSSSSS/MzS",
        "S_____,_____SSzzzSSS/MzS",
        "S_____,_____SS||V{{{V||S",
        "S_____,_____SS|D     <|S",
        "SSSSSSSSSSSSSS|r      OS",
        "SSSSSSSSSSSSSS|r      |S",
        "SVVVVVVVz./Mzz|   #W##|S",
        "SVD>>>>Vz./bMzV   #ww%|S",
        "SV BBB>Vz.b/..{   xwwF|S",
        "SV   B>Vz.Mb..{   flwl|S",
        "SV   B>Vz....zV   flwU|S",
        "SV   B>Vzbbbzz|X  #wwG|S",
        "S|B ^||||||||||^  ||I||S",
        "SO6  B|=;|;=|99  r|FwC|S",
        "S|B  6|=A|A=|9   r|Fwc|S",
        "S|   B|+|||+|9   D|!ww|S",
        "S|B               |Lwl|S",
        "SO6   6 6 6   B66B|Lwl|S",
        "S|B ^???????^ B66B|Lwl|S",
        "S|||||||||||||||||||3||S",
        "S4SSSSSSSSSSSSSSSSSSSSSS"
      ],
      "terrain": {
        " ": "t_floor",
        "!": "t_linoleum_white",
        "#": "t_linoleum_white",
        "%": "t_linoleum_white",
        "+": "t_door_c",
        ",": "t_pavement_y",
        ".": "t_grass",
        "/": "t_dirt",
        "3": [ "t_door_locked", "t_door_locked_alarm" ],
        ";": "t_linoleum_white",
        "=": "t_linoleum_white",
        "A": "t_linoleum_white",
        "C": "t_linoleum_white",
        "F": "t_linoleum_white",
        "G": "t_linoleum_white",
        "I": "t_door_locked_interior",
        "L": "t_linoleum_white",
        "M": "t_dirt",
        "O": "t_window",
        "S": "t_sidewalk",
        "U": "t_linoleum_white",
        "V": "t_wall_glass",
        "W": "t_fencegate_c",
        "_": "t_pavement",
        "b": "t_dirt",
        "c": "t_linoleum_white",
        "f": "t_linoleum_white",
        "l": "t_linoleum_white",
        "w": "t_linoleum_white",
        "x": "t_console_broken",
        "z": "t_shrub",
        "{": "t_door_glass_c",
        "|": "t_wall_b",
        "<": "t_stairs_up",
        "4": "t_gutter_downspout",
        "T": "t_tree_coffee"
      },
      "furniture": {
        "#": "f_counter",
        "%": "f_trashcan",
        "/": "f_bluebell",
        "6": "f_table",
        "9": "f_rack",
        ">": "f_counter",
        "?": "f_sofa",
        "A": "f_sink",
        "B": "f_chair",
        "C": "f_desk",
        "D": "f_trashcan",
        "F": "f_fridge",
        "G": "f_oven",
        "L": "f_locker",
        "M": "f_dahlia",
        "U": "f_sink",
        "X": "f_rack",
        "^": "f_indoor_plant",
        "b": "f_dandelion",
        "f": "f_glass_fridge",
        "l": "f_rack",
        "r": "f_rack"
      },
      "toilets": { ";": {  } },
      "items": {
        "#": { "item": "coffee_counter", "chance": 10 },
        "6": { "item": "coffee_table", "chance": 35 },
        "9": { "item": "coffee_display_2", "chance": 85, "repeat": [ 1, 8 ] },
        ";": { "item": "coffee_bathroom", "chance": 15 },
        "=": { "item": "coffee_bathroom", "chance": 35 },
        ">": { "item": "coffee_table", "chance": 25 },
        "A": { "item": "coffee_bathroom", "chance": 35 },
        "C": { "item": "office", "chance": 70 },
        "D": { "item": "coffee_trash", "chance": 75 },
        "F": { "item": "coffee_fridge", "chance": 80, "repeat": [ 1, 8 ] },
        "G": { "item": "oven", "chance": 35 },
        "L": { "item": "coffee_locker", "chance": 75 },
        "U": { "item": "coffee_dishes", "chance": 75 },
        "X": { "item": "coffee_newsstand", "chance": 90, "repeat": [ 1, 8 ] },
        "f": { "item": "coffee_freezer", "chance": 85, "repeat": [ 1, 8 ] },
        "l": { "item": "coffee_prep", "chance": 50 },
        "r": { "item": "coffee_condiments", "chance": 80, "repeat": [ 1, 8 ] }
      },
      "monsters": { "!": { "monster": "GROUP_COFFEE_SHOP_ZOMBIE", "chance": 1 } },
      "place_monsters": [ { "monster": "GROUP_ZOMBIE", "x": [ 3, 17 ], "y": [ 13, 18 ], "chance": 1 } ],
      "vehicles": { "c": { "vehicle": "swivel_chair", "chance": 100, "status": 1 } }
    }
    
    1. The "fill_ter": this tag defines the default terrain/flooring for use under furniture and for undefined symbols in your rows. Generally, pick the terrain that has the most furniture associated with it.

    2. The "rows": this is the actual blueprint for your building. A standard OMT tile (overmap tile) is 24x24 tiles. Rows begin their x,y coordinates at 0,0 which is the upper left corner of your map.

      • tip: if you cross stitch or are familiar with cross stitch patterns, this should all look very familiar. You have the map and the “legend” areas.
    3. "terrain": this defines what all those letters in the rows mean when they are terrains. A symbol can return a single terrain, or, it can offer a chance to spawn from a selection of terrains. Here are some quick examples:

    "*": "t_door_c",: this will make every * in the rows a closed wooden door.

    "*": [ [ "t_door_locked_peep", 2 ], "t_door_locked_alarm", [ "t_door_locked", 10 ], "t_door_c" ],: this array will randomly choose from a selection of doors. Some are weighted to have a higher chance to spawn then others. Locked doors will be most common, then peephole doors. Finally closed & locked/alarmed have the same basic weight and will spawn the least.

    Note: in my example, the fill_ter is for floor. So if you have furniture that you want to spawn with a different floor, you must use that same symbol that you’ve given the furniture and also define it as a terrain for your new flooring. In the above example, several furniture symbols are using white linoleum for their flooring. If you don’t do this step, your furniture will end up having the wrong flooring which will be especially noticeable if you smash it. I often do a final map check where I go around in game and smash furniture to check their terrains before submitting my maps. This can be quite cathartic.

    1. "furniture" tag: Like terrain, this is a list of the furniture ID’s and their map symbols. It can handle the same sort of arrays as terrain.

    2. "toilets" and other specially defined furniture: you’ll run into some specially defined common furniture which allows for some easier placement. In our sample map the entry: "toilets": { ";": { } }, defines the symbol entry and will also auto-place water in your toilets. There are a few other specialty furniture entries.

    The other most common one is: "vendingmachines": { "D": { "item_group": "vending_drink" }, "V": { "item_group": "vending_food" } } this assigns two symbols for vending machines and makes one for food & one for drinks. note: you can put any item_group into the machines, like those bullet ones.

    1. Item spawns: There are many ways to place items. This tutorial will only cover explicit symbol placement which is the easiest. There is documentation all about loot spawns you can read for further information. See: ITEM_SPAWN.md.

    our sample uses “items”: for its tag. others include: “place_item”, “place_items”, “place_loot”. Some of these allow for individual item placement and others groups, or both. This will be covered in another tutorial.

    For now lets break this one apart:

    "items": {
          "a": { "item": "stash_wood", "chance": 30, "repeat": [ 2, 5 ] },
          "d": [
            { "item": "SUS_dresser_mens", "chance": 50, "repeat": [ 1, 2 ] },
            { "item": "SUS_dresser_womens", "chance": 50, "repeat": [ 1, 2 ] }
           ]
          }
    

    “a” in this case is a fireplace as defined in its map. So, in the fireplace I want to add the stash_wood item_group. By defining the group under “a”, every fireplace in my map will get this group. This is particularly powerful for common item_groups like in houses where every fridge is going to get the same item_group. The chance is its spawn chance and repeat means that it will repeat the roll for that chance 2-5 times, so this fireplace can be extra stocked or have a little bit or nothing if it fails its chance rolls.

    the “d” entry is a dresser. I wanted the dressers to pull from two possible item groups, one a man’s selection and the other women’s. So, there is an array [ ... ] which encompasses all possible item_groups for this symbol.

    You can add as many item_groups to the array as you’d like. This is one of my racks in the generic house palette:

    "q": [
            { "item": "tools_home", "chance": 40 },
            { "item": "cleaning", "chance": 30, "repeat": [ 1, 2 ] },
            { "item": "mechanics", "chance": 1, "repeat": [ 1, 2 ] },
            { "item": "camping", "chance": 10 },
            { "item": "tools_survival", "chance": 5, "repeat": [ 1, 2 ] }
          ],
    

    Note: When using explicit symbol placements, remember your group has a chance to spawn in every furniture using that symbol, so it can end up being quite generous. If you want two bookcases with different item spawns, give each bookcase its own symbol, or, use an alternate item spawn format, like the one using x,y coordinates for placement.

    1. Monster spawns: our example has two types of monster spawns listed.
    "monsters": { "!": { "monster": "GROUP_COFFEE_SHOP_ZOMBIE", "chance": 1 } },
    "place_monsters": [ { "monster": "GROUP_ZOMBIE", "x": [ 3, 17 ], "y": [ 13, 18 ], "chance": 1 } ],
    

    The first entry is using that explicit symbol placement technique. The end entry is using a range x,y coordinates to place monsters. Note: We are moving away from putting monsters in the mapgen file in favor of overmap_terrain entries, so only use this if you want a specific monster group to spawn for specific reasons. See overmap_terrain section for more information.

    1. Vehicle spawns:
    "vehicles": { "c": { "vehicle": "swivel_chair", "chance": 100, "status": 1 } }
    

    Our vehicle happens to be a swivel chair using explicit symbol placement.

    This next example uses vehicle_groups and x,y placement. It also includes rotation and status. The rotation is which direction the vehicle will spawn on the map, and that status is its overall condition. Fuel is pretty self explanatory. Always test your vehcile spawns in game, they can be rather picky in their placement and the rotation doesn’t really match what you’d expect the numbers to mean. The 0,0 point of vehicles can vary so you’ll have to experiment to get the spawns in the right spots, especially in tight spaces.

    "place_vehicles": [
            { "chance": 75, "fuel": 0, "rotation": 270, "status": 1, "vehicle": "junkyard_vehicles", "x": 12, "y": 18 },
            { "chance": 75, "fuel": 0, "rotation": 270, "status": 1, "vehicle": "junkyard_vehicles", "x": 19, "y": 18 },
            { "chance": 90, "fuel": 0, "rotation": 0, "status": -1, "vehicle": "engine_crane", "x": 28, "y": 3 },
            { "chance": 90, "fuel": 0, "rotation": 90, "status": -1, "vehicle": "handjack", "x": 31, "y": 3 },
            { "chance": 90, "fuel": 30, "rotation": 180, "status": -1, "vehicle": "welding_cart", "x": 34, "y": 3 },
            { "chance": 75, "fuel": 0, "rotation": 180, "status": -1, "vehicle": "junkyard_vehicles", "x": 31, "y": 9 },
            { "chance": 75, "fuel": 0, "rotation": 270, "status": 1, "vehicle": "junkyard_vehicles", "x": 28, "y": 18 },
            { "chance": 75, "fuel": 0, "rotation": 270, "status": 1, "vehicle": "junkyard_vehicles", "x": 35, "y": 18 }
          ]
    
    1. Liquids in furniture: this entry is for a standing tank. I’ve defined the tank in the furniture entry as “g”.

    "liquids": { "g": { "liquid": "water_clean", "amount": [ 0, 100 ] } },

    This places clean water in the tank, and a range of amount to spawn.

    1. There are other specialty placement techniques that you’ll pick up as you look at more maps. One of my favorites is for the new planters:

    Since the planter is a “sealed item” you define what’s going into that container. This example places seeds (ready to harvest) in the planters. Note the first one will place a seedling, the others are harvest ready. I’ve given each planter type an explicit symbol for quicker placement.

    "sealed_item": {
          "1": { "item": { "item": "seed_rose" }, "furniture": "f_planter_seedling" },
          "2": { "item": { "item": "seed_chamomile" }, "furniture": "f_planter_harvest" },
          "3": { "item": { "item": "seed_thyme" }, "furniture": "f_planter_harvest" },
          "4": { "item": { "item": "seed_bee_balm" }, "furniture": "f_planter_harvest" },
          "5": { "item": { "item": "seed_mugwort" }, "furniture": "f_planter_harvest" },
          "6": { "item": { "item": "seed_tomato" }, "furniture": "f_planter_harvest" },
          "7": { "item": { "item": "seed_cucumber" }, "furniture": "f_planter_harvest" },
          "8": { "item": { "item": "soybean_seed" }, "furniture": "f_planter_harvest" },
          "9": { "item": { "item": "seed_zucchini" }, "furniture": "f_planter_harvest" }
        }
    
    1. Best practices:
    • If you are making a new house please use this palette: “standard_domestic_palette”. The loots are already assigned and it covers a wide range of domestic furniture. This will keep your house in sync with all the other houses for loot spawns.
    • All buildings should also get roof entries.
    • While entry placement for json doesn’t really matter, try to keep your mapgen files ordered like the majority existing maps. Be kind to future contributors. Add meta data at the top of the file. Object entry comes second. Within the object entry it is generally: palette, set_points, terrain, furniture, random special entries like toilets, item spawns, vehicle spawns, monster spawns.
    • All buildings should at least get one “t_gutter_downspout” for roof access. Players would love at least 2. if you’re adding gutters to a multi-z level building, don’t forget the intermediate floors. You’ll need to stagger the downspouts to players can climb up (like ladders).
    • If you put things on your roof that would be difficult to get up there, make sure to provide better roof access via ladders and stairs.
    • For your basic grass cover outside please use: "t_region_groundcover_urban", to maintain consistency across map boundaries. Here are my standard flora entries for grass, shrubs & trees:
    ".": "t_region_groundcover_urban",
    "A": [ "t_region_shrub", "t_region_shrub_fruit", "t_region_shrub_decorative" ],
    "Z": [ [ "t_region_tree_fruit", 2 ], [ "t_region_tree_nut", 2 ], "t_region_tree_shade" ],
    

    finally for flowers (which are furniture):

    "p": "f_region_flower"
    

    Adding the roof!

    Almost all CDDA buildings are now roof-capable and we’d love to keep it that way. Make sure to submit a roof map with your building. This can go into the same file as your ground floor and any other floors that share the same building shape/foundation.

    So, this is super easy compared to the building we just went over. It has all the same basic components. I recommend you start by using the rows from your ground floor map and converting it to the "roof_palette" symbol set. Basically your just going to trace the outline in gutters, add a t_gutter_drop next to your t_gutter_spout below and toss some infrastructure up there. I used nests extensively in commercial building roofs and we’ll cover that in advanced mapgen.

    sample roof:

    {
      "type": "mapgen",
      "method": "json",
      "om_terrain": "house_01_roof",
      "object": {
        "fill_ter": "t_shingle_flat_roof",
        "rows": [
          "                        ",
          "                        ",
          "                        ",
          "  |222222222222222223   ",
          "  |.................3   ",
          "  |.................3   ",
          "  |.............N...3   ",
          "  5.................3   ",
          "  |.................3   ",
          "  |.................3   ",
          "  |........&........3   ",
          "  |.................3   ",
          "  |......=..........3   ",
          "  |.................3   ",
          "  |----------------53   ",
          "                        ",
          "                        ",
          "                        ",
          "                        ",
          "                        ",
          "                        ",
          "                        ",
          "                        ",
          "                        "
        ],
        "palettes": ["roof_palette"],
        "terrain": { ".": "t_shingle_flat_roof" }
      }
    }
    
    1. I always just append _roof to the buildings ID.
    2. See how the palette takes the place of all that data from our earlier example. So clean and easy.
    3. There is no "weight" entry because this will only spawn with its building (once linked).
    4. My palette uses “t_flat_roof” as its default roof. For houses, I wanted shingles. So, I added the “t_shingle_flat_roof” in this mapgen which will override the palettes entry for ".": "t_flat_roof". (more on this in advanced mapgen).

    I have a separate roof document at: JSON_ROOF_MAPGEN.

    Linking various mapgen maps using multitile_city_buildings.json

    This file is found at: data/json/overmap/multitile_city_buildings.json.

    Remember this file is for city buildings only, not specials

    A standard entry:

    {
      "type": "city_building",
      "id": "house_dogs",
      "locations": [ "land" ],
      "overmaps": [
        { "point": [ 0, 0, 0 ], "overmap": "house_dogs_north" },
        { "point": [ 0, 0, 1 ], "overmap": "house_dogs_roof_north" },
        { "point": [ 0, 0, -1 ], "overmap": "basement" }
      ]
    },
    
    1. The "type" won’t change. It should always be “city_building”.
    2. "id": This ID is often the same as your mapgen ID but it doesn’t have to be the same. We could use something more generic like “house”. This ID will be used in regional settings for spawns, so keep in mind how many buildings are using the ID. I prefer distinct ID’s because it makes debug spawning much, much easier.
    3. "locations": defines where this building can be place by overmap terrain type. Land is the default.
    4. "overmaps": this is the bit where you define how the maps fit together, so lets break it up: { "point": [ 0, 0, 0 ], "overmap": "house_dogs_north" }, point: its point in relation to the other mapgen files for your building. The coordinates are [ x, y, z ]. In this example, x,y are 0 because we only have one map per z level. Zero for y means this is the ground level. Note the roof above is at 1 and the basement is -1.
    5. appending _north to the ID’s:
      • If your building rotates you need this compass point so the floors can match up correctly. This is the generic basement mapgen group and thus doesn’t get _north (this will change as we add dedicated stairs to our houses).

    Setting overmap spawns using regional_map_settings.json

    data/json/regional_map_settings.json

    1. For city buildings and houses you’ll scroll down to the "city": flag.
    2. Find your appropriate subtag, "houses" or "shops" usually.
    3. Add your ID from the multitile_city_buildings entry. This can also accept the mapgen ID and not complain which is why the are often the same name.
    4. Choose a good weight for your building.

    Linking and spawning specials:

    Put the entry in: data/json/overmap/overmap_special/specials.json.

    This entry does the job of both the regional_map_settings and multitile_city_buildings plus other fun overmap stuff.

    Example:

    {
      "type": "overmap_special",
      "id": "pump_station",
      "overmaps": [
        { "point": [0, 0, 0], "overmap": "pump_station_1_north" },
        { "point": [0, 0, 1], "overmap": "pump_station_1_roof_north" },
        { "point": [0, 1, 0], "overmap": "pump_station_2_north" },
        { "point": [0, 1, 1], "overmap": "pump_station_2_roof_north" },
        { "point": [0, -1, -1], "overmap": "pump_station_3_north" },
        { "point": [0, 0, -1], "overmap": "pump_station_4_north" },
        { "point": [0, 1, -1], "overmap": "pump_station_5_north" }
      ],
      "connections": [
        { "point": [0, -1, 0], "connection": "local_road", "from": [0, 0, 0] },
        { "point": [1, -1, -1], "connection": "sewer_tunnel", "from": [0, -1, -1] },
        { "point": [-1, -1, -1], "connection": "sewer_tunnel", "from": [0, -1, -1] },
        { "point": [-1, 1, -1], "connection": "sewer_tunnel", "from": [0, 1, -1] }
      ],
      "locations": ["land"],
      "city_distance": [1, 4],
      "city_sizes": [4, 12],
      "occurrences": [0, 1],
      "flags": ["CLASSIC"]
    }
    
    1. "type": is overmap_special.
    2. "id" is your buildings ID for the overmap. It also displays on the overmap in game.
    3. "overmaps" this works the same way as it does in the city building entries. Note that the pump station is bigger then 1 OMT on the ground, so the y coordinate changes as well.
    4. "connections": this places road, sewer, subway connections for your map.
    5. "locations": valid OMT types this building can be placed on.
    6. "city_distance", "city_sizes" both are parameters for where this spawns in relation to cities.
    7. "occurrences": [ 0, 1 ],: Ok so occurrences can mean two things depending on if it uses the “UNIQUE” flag or not. When the flag is absent, this simply translates to how many times this special can spawn PER overmap. So 0 to 1 in this case. If you use the UNIQUE flag, this becomes a percentage so [ 1, 10 ] wouldn’t be 1 to 10 times per overmap but a 1 in 10% chance to spawn on the overmap. So 10% chance to spawn once per overmap.
    8. "flags": These are flags you can use to further define the special. For a list of flags see: json_flags.

    Read: OVERMAP for more details.

    Overmap_terrain entries:

    Choose a file for your building type at: data/json/overmap/overmap_terrain.

    This set of entries defines how your building will look on the overmap. It supports copy-from. Example:

    {
      "type": "overmap_terrain",
      "id": "s_music",
      "copy-from": "generic_city_building",
      "name": "music store",
      "sym": "m",
      "color": "brown",
      "mondensity": 2,
      "extend": { "flags": [ "SOURCE_LUXURY" ] }
    },
    {
      "type": "overmap_terrain",
      "id": "s_music_roof",
      "copy-from": "generic_city_building",
      "name": "music store roof",
      "sym": "m",
      "color": "brown"
    }
    

    You need one entry per mapgen ID:

    1. "type" will always be overmap_terrain.
    2. "id" will be the same ID you used in your mapgen file.
    3. "copy-from" this will copy any data from another entry, excepting what you define here.
    4. "name" how the name displays on the overmap.
    5. "sym" the symbol displayed on the overmap. If left out, the carrots will be used v<>^
    6. "color" color for overmap symbol.
    7. "mondesntiy" sets the default monster density for this overmap tile. You’ll use this for general zombie spawns and reserve the mapgen monster entries for special spanwns for that location (e.g. a pet store’s pets).
    8. "extend" many of these flags will be used by NPCs in the future for their AI, try to add flags appropriate for your location. Others further define the mapgen, like having sidewalks generate.

    For further information see: Overmap Terrain section of OVERMAP.

    Palettes:

    As mentioned earlier, palettes can hold almost all the information that the object entry contains, except for rows and fill_ter. Their main purpose is to reduce the need to add the same basic data to related maps and to maintain symbol consistency.

    Entries that are added to the mapgen file’s object will over ride the same symbol used in the palette. In this way, you can use a palette and make select alterations to each mapgen as needed. This is especially useful for multiple ground terrains like carpets, concrete, etc.

    Terrain works very well when you substitute it via the mapgen file. I’ve had less success overriding furniture but need to test it more to clarify when it works as intended. I have recently noticed that if your palette symbol uses an array of values, the mapgen entry can’t override it.

    Example: Entry for the mapgen file object: "palettes": [ "roof_palette" ],

    The palette metadata:

    "type": "palette",
    "id": "roof_palette",
    

    Everything else will look like a series of object entries, for example the roof_palette:

    {
      "type": "palette",
      "id": "roof_palette",
      "terrain": {
        ".": "t_flat_roof",
        " ": "t_open_air",
        "o": "t_glass_roof",
        "_": "t_floor",
        "2": "t_gutter_north",
        "-": "t_gutter_south",
        "3": "t_gutter_east",
        "4": "t_gutter_downspout",
        "|": "t_gutter_west",
        "5": "t_gutter_drop",
        "#": "t_grate",
        "&": "t_null",
        ":": "t_null",
        "X": "t_null",
        "=": "t_null",
        "A": "t_null",
        "b": "t_null",
        "c": "t_null",
        "t": "t_null",
        "r": "t_null",
        "L": "t_null",
        "C": "t_null",
        "Y": "t_null",
        "y": "t_null"
      },
      "furniture": {
        "&": "f_roof_turbine_vent",
        "N": "f_TV_antenna",
        ":": "f_cellphone_booster",
        "X": "f_small_satelitte_dish",
        "~": "f_chimney",
        "=": "f_vent_pipe",
        "A": "f_air_conditioner",
        "b": "f_bench",
        "c": "f_counter",
        "t": "f_table",
        "r": "f_rack",
        "L": "f_locker",
        "C": ["f_crate_c", "f_cardboard_box"],
        "Y": "f_stool",
        "s": "f_sofa",
        "S": "f_sink",
        "e": "f_oven",
        "F": "f_fridge",
        "y": ["f_indoor_plant_y", "f_indoor_plant"]
      },
      "toilets": { "T": {} }
    }
    

    If you want to look at more complex palettes, the standard_domestic_palette in data/json/mapgen_palettes/house_general_palette.json is a good look at a palette designed to work across all CDDA houses. It includes the loot spawns and accounts for most furniture that will be used in a house. I also left a list of symbols open to be used in the mapgen file for specific location needs.

    Finally, the series of house_w palettes at data/json/mapgen_palettes/house_w_palette.json are designed to work together for houses using nested mapgen. There is a palette devoted to the foundation, another for the nests, and finally another one I’ve designed for domestic outdoor nested chunks.

    Final comments:

    The information here should be enough for you got get around mapgen and start making maps but there are a lot of variations that will be covered in focused.

    Not covered in this document:

    • Nested maps and their placement.
    • NPC spawns.
    • Advanced terrain tricks for complex floor options.
    • traps, terrain and you.
    • update_mapgen (NPC and player triggered map updates).
    • field emitting furniture.

    Enchantments

    Enchantments make it possible to specify custom effects provided by item, bionic or mutation.

    Fields

    id

    (string) Unique identifier for this enchantment.

    conditions

    (string array) How an enchantment determines if it should be active

    All conditions must pass for it to be valid, if there are no conditions it is automatically true

    For all basegame values see here

    emitter

    (string) Identifier of an emitter that’s active as long as this enchantment is active. Default: no emitter.

    ench_effects

    (array) Grants effects of specified intensity as long as this enchantment is active.

    Syntax for single entry:

    {
      // (required) Identifier of the effect
      "effect": "effect_identifier",
    
      // (required) Intensity. Setting to 1 works for effects that do not actually have intensities.
      "intensity": 2
    }
    

    hit_you_effect

    (array) List of spells that may be cast when enchantment is active and character melee attacks a creature.

    Syntax for single entry:

    {
      // (required) Identifier of the spell
      "id": "spell_identifier",
    
      // If true, the spell is centered on the character's location.
      // If false, the spell is centered on the attacking creature.
      // Default: false
      "hit_self": false,
    
      // Chance to trigger, one in X.
      // Default: 1
      "once_in": 1,
    
      // Message for when the spell is triggered for you.
      // %1$s is your name, %2$s is creature's
      // Default: no message
      "message": "You pierce %2$s with Magic Piercing!",
    
      // Message for when the spell in triggered for an NPC.
      // %1$s is their name, %2$s is creature's
      // Default: no message
      "npc_message": "%1$s pierces %2$s with Magic Piercing!",
    
      // TODO: broken?
      "min_level": 1,
    
      // TODO: broken?
      "max_level": 2
    }
    

    hit_me_effect

    (array) List of spells that may be cast when enchantment is active and character gets melee attacked by a creature.

    Same syntax as for hit_you_effect.

    mutations

    (array) List of mutations temporarily granted while enchantment is active.

    intermittent_activation

    (object) Rules that specify random effects which occur while enchantment is active.

    Syntax:

    {
      // List of checks to run on every turn while enchantment is active.
      "effects": [
        {
          // Average activation frequency.
          // The exact chance to pass is "one in (X converted to turns)" per turn.
          "frequency": "5 minutes",
    
          // List of spells to cast if the check passed.
          "spell_effects": [
            {
              // (required) Identifier of the spell
              "id": "nasty_random_effect",
    
              // TODO: broken?
              "min_level": 1,
    
              // TODO: broken?
              "max_level": 5
              // TODO: other fields appear to be loaded, but unused
            }
          ]
        }
      ]
    }
    

    values

    (array) List of miscellaneous character/item values to modify.

    Syntax for single entry:

    {
      // (required) Value ID to modify, refer to list below.
      "value": "VALUE_ID_STRING",
    
      // Additive bonus. Optional integer number, default is 0.
      "add": 13,
    
      // Alternatively, all of these can be based off character resources
      "add": {
        "val": "hungry", // Scale based off hunger
        "per": 0.1 // Every 10 hunger, add 1 to the value
      },
    
      // Multiplicative bonus. Optional, default is 0.
      "multiply": -0.3
    }
    

    Additive bonus is applied separately from multiplicative, like so:

    bonus = add + base_value * multiply
    

    Thus, a multiply value of -0.8 is -80%, and a multiply of 2.5 is +250%. When modifying integer values, final bonus is rounded towards 0 (truncated).

    When multiple enchantments (e.g. one from an item and one from a bionic) modify the same value, their bonuses are added together without rounding, then the sum is rounded (if necessary) before being applied to the base value.

    Since there’s no limit on number of enchantments the character can have at a time, the final calculated values have hardcoded bounds to prevent unintended behavior.

    For all basegame values see here

    Flags

    (array) of enchantment_flag_id values

    For all basegame values see here

    Flags

    (array) of enchantment_vision_id values

    For reference on how to make one see here

    Immune Effects

    (array) of effect_type_id values

    Prevents recieving these effects, but any present effects will persist

    Immune Fields

    (array) of field_type_id values

    Prevents environmental effects of fields from being applied

    Fake Items

    (array) of itype_id values

    Adds these items to the crafting inventory. Can use bionic power with USES_BIONIC_POWER

    Examples

    [
      {
        "//": "On-hit effect for ink glands mutation, implemented via enchantment.",
        "type": "enchantment",
        "id": "MEP_INK_GLAND_SPRAY",
        "hit_me_effect": [
          {
           "id": "generic_blinding_spray_1",
            "hit_self": false,
            "once_in": 15,
            "message": "Your ink glands spray some ink into %2$s's eyes.",
            "npc_message": "%1$s's ink glands spay some ink into %2$s's eyes."
          }
        ]
      },
      {
        "//": "This one would look good on a katana for an anime mod.",
        "type": "enchantment",
        "id": "ENCH_ULTIMATE_ASSKICK",
        "has": "WIELD",
        "condition": "ALWAYS",
        "ench_effects": [{ "effect": "invisibility", "intensity": 1 }],
        "hit_you_effect": [{ "id": "AEA_FIREBALL" }],
        "hit_me_effect": [{ "id": "AEA_HEAL" }],
        "mutations": ["KILLER", "PARKOUR"],
        "values": [{ "value": "STRENGTH", "multiply": 1.1, "add": -5 }],
        "intermittent_activation": {
          "effects": [
            {
              "frequency": "1 hour",
              "spell_effects": [
                { "id": "AEA_ADRENALINE" }
              ]
            }
          ]
        },
        "flags": ["FOOD_POISON_IMMUNE"],
        "immune_fields": ["fd_fire"],
        "immune_effects": ["poison"],
        "fake_items": ["fake_burrowing"]
        }
      }
    ]
    

    Enchantment Values

    {
      "id": "CLIMATE_CONTROL", // Id of enchantment
      "type": "enchantment_value", // Needed type
      "can_add": true, // Weather adding to the enchantment value will do anything; Default true
      "can_mult": true, // Weather multiplying to the enchantment value will do anything; Default true
      "can_max": false, // Weather getting the maximum value of this type will do anything; Default false
      "suffixes": [ // All of the suffixes this is quite literally the most complicated part
        [
          { "suffix": "COOLING", "desc_insert": [ "hot", "" ] }, // These show up as `CLIMATE_CONTROL_XXX`
          { "suffix": "HEATING", "desc_insert": [ "cold", "" ] } // Desc insert overwrites the below `desc_insert`, desc can also be replaced
        ],
        [ // Then you can define a second set, there can be as many sets as you want
          { "suffix": "TORSO", "replace": { "desc_insert": { "idx": 1, "val": "Torse" } } }, // Replace replaces based off starting at 0 index, so this replaces "" with "Torso"
          {
            "suffix": "ARM", 
            "replace": { "desc_insert": { "idx": 1, "val": "Arm" } },
            "suffixes": [ // These are a list of further suffix specific suffixes
              { "suffix": "L", "replace": { "desc_insert": { "idx": 1, "val": "Left Arm" } } }, // These suffixes could have additional nested suffixes too
              { "suffix": "R", "replace": { "desc_insert": { "idx": 1, "val": "Right Arm" } } } // These only show up as `CLIMATE_CONTROL_XXX_ARM_XXX`, never will they be applied to another type
            ]
          },
        ] // See below for further explination on why there are multiple sets
      ],
      "desc": "Keeps you comfortable against %1$s temperatures ( %2$s )", // Description, with support for formatting in additional strings
      "desc_insert": [ "all bodyparts", "" ], // The additional strings to format in
      "unsupported_conditions": ["character", "item_and_character"] // These values are called where these conditions cannot ever be used
    },
    

    Suffixes Explination

    Start by examining the above tree There are two groups:

    • COOLING and HEATING
    • TORSO and ARM ( With Arm’s children )

    Order matters here, because COOLING came first, whenever you need the COOLING specifier, it must be first I.E. CLIMATE_CONTROL_COOLING_ARM works, but CLIMATE_CONTROL_ARM_COOLING is invalid.

    The chain produced from the above json is as follows

    • CLIMATE_CONTROL
      • CLIMATE_CONTROL_COOLING
        • CLIMATE_CONTROL_COOLING_ARM
          • CLIMATE_CONTROL_COOLING_ARM_L -> References CLIMATE_CONTROL_ARM_L
          • CLIMATE_CONTROL_COOLING_ARM_R -> References CLIMATE_CONTROL_ARM_R
      • CLIMATE_CONTROL_HEATING
        • CLIMATE_CONTROL_HEATING_ARM
          • CLIMATE_CONTROL_HEATING_ARM_L -> References CLIMATE_CONTROL_ARM_L
          • CLIMATE_CONTROL_HEATING_ARM_R -> References CLIMATE_CONTROL_ARM_R
      • CLIMATE_CONTROL_ARM -> Does not reference CLIMATE_CONTROL to prevent stacking effects
        • CLIMATE_CONTROL_ARM_L
        • CLIMATE_CONTROL_ARM_R

    This can be done with as many chains as wanted, but it gets increasingly complicated as more chains are added

    In the docs, only the chain groups will be referenced, not the full list of enchantment values, due to the increasing number of enchantment children

    When referencing these values in c++ or lua you always want to use the most specific value, the lower tiers are autofilled. I.E. CLIMATE_CONTROL_COOLING_ARM_R should be what you reference, never CLIMATE_CONTROL_ARM_R, or CLIMATE_CONTROL_ARM when getting a value

    Standard suffixes

    Bodyparts

    This is a standard set of suffixes for all bodyparts Includes

    • HEAD
    • TORSO
    • EYES
    • MOUTH
    • ARM
      • L
      • R
    • LEG
      • L
      • R
    • HAND
      • L
      • R
    • FOOT
      • L
      • R

    Skills

    Used for all skill levels

    • BARTER
    • SPEECH
    • COMPUTER
    • FIRSTAID
    • MECHANICS
    • TRAPS
    • DRIVING
    • SWIMMING
    • FABRICATION
    • COOKING
    • TAILOR
    • SURVIVAL
    • ELECTRONICS
    • ARCHERY
    • GUN
    • LAUNCHER
    • PISTOL
    • RIFLE
    • SHOTGUN
    • SMG
    • THROW
    • MELEE
    • BASHING
    • CUTTING
    • DODGE
    • STABBING
    • UNARMED

    Damage Types

    Basegame Enchantment Value ID List

    Character values

    STRENGTH

    Strength stat. base_value here is the base stat value. The final value cannot go below 0.

    DEXTERITY

    Dexterity stat. base_value here is the base stat value. The final value cannot go below 0.

    PERCEPTION

    Perception stat. base_value here is the base stat value. The final value cannot go below 0.

    INTELLIGENCE

    Intelligence stat. base_value here is the base stat value. The final value cannot go below 0.

    STRENGTH_PERMANENT

    Affects base strength stat. base_value here is the base stat value. The final value cannot go below 0.

    DEXTERITY_PERMANENT

    Affects base dexterity stat. base_value here is the base stat value. The final value cannot go below 0.

    PERCEPTION_PERMANENET

    Affects base perception stat. base_value here is the base stat value. The final value cannot go below 0.

    INTELLIGENCE_PERMANENT

    Affects base intelligence stat. base_value here is the base stat value. The final value cannot go below 0.

    HEALTH_POINTS

    Hit points stat. base_value here is the base health value, The final value cannot go below 1.

    These are the children.

    SetValuesUse
    BodypartsTORSO, HEAD, ARM ( L, R ), LEG ( L, R )The specific bodypart that is affected
    SPEED

    Character speed. base_value here is character speed including pain/hunger/weight penalties. Final speed value cannot go below 25% of base speed.

    ATTACK_COST

    Melee attack cost. The lower, the better. base_value here is attack cost for given weapon including modifiers from stats and skills. The final value cannot go below 25.

    MOVE_COST

    Movement cost. base_value here is tile movement cost including modifiers from clothing and traits. The final value cannot go below 20.

    FLAT_MOVE_COST

    Movement cost effect on flat ground. base_value here is movement cost partially through processing. The final value cannot go below 20 like MOVE_COST. This stacks with MOVE_COST

    OBSTACLE_MOVE_COST

    Movement cost effect on obstacles. base_value here is initial move cost. The final value cannot go below 100. Stacks with MOVE_COST, done before it.

    SWIM_MOVE_COST

    Movement cost effect while swimming The fianl value cannot go below 30. This does NOT stack with MOVE_COST

    READING_SPEED

    Speed of reading books. base_value is final reading speed in moves. The final value cannot go below 1 second.

    CRAFTING_SPEED

    Crafting speed. base_value is a multiplier of crafting speed. Calculated after all other multipliers

    CONSTRUCTION_SPEED

    Construction speed. base_value is a multiplier of construction speed for vehicles and furniture/terrain. Calculated after all other multipliers

    SetValuesUse
    Construction TypeCON, VEHWeather construction or vehicle construction speed is affected
    METABOLISM

    Metabolic rate. This modifier ignores add field. base_value here is PLAYER_HUNGER_RATE modified by traits. The final value cannot go below 0.

    MANA_CAP

    Mana capacity. base_value here is character’s base mana capacity modified by traits. The final value cannot go below 0.

    MANA_REGEN

    Mana regeneration rate. This modifier ignores add field. base_value here is character’s base mana gain rate modified by traits. The final value cannot go below 0.

    STAMINA_CAP

    Stamina capacity. This modifier ignores add field. base_value here is character’s base stamina capacity modified by traits. The final value cannot go below 10% of PLAYER_MAX_STAMINA.

    STAMINA_REGEN

    Stamina regeneration rate. This modifier ignores add field. base_value here is character’s base stamina gain rate modified by mouth encumbrance. The final value cannot go below 0.

    THIRST

    Thirst gain rate. base_value here is character’s base thirst gain rate. The final value cannot go below 0.

    FATIGUE

    Fatigue gain rate. base_value here is character’s base fatigue gain rate. The final value cannot go below 0.

    MENDING_MULT

    Edits the multiplier to broken limb mending rate. base_value is regen mod post mutations ( default 0.25 ) Final value range is 0.0 to 1.0

    HEARING

    Multiplier to hearing. base_value is the final multiplier to hearing. Final value cannot go below 0.

    NOISE

    Footstep noise value. base_value is the post-mutaiton multiplier to noise. Final value cannot go below 0.

    SCENT

    Scent value. base_value is the post-mutation scent value Final value cannot go below 0

    STEALTH

    Stealth modifier value higher value increases stealth, lower value decreases it. base_value is the post mutation value Clamped between 20 and 160. With 160 being 60% more visible and 20 being 80% less visible

    MOTION_ALARM

    From how far away will you be notified of approaching creatures. base_value is always 0. This is a maxed value for tile range of notification.

    BODYTEMP_X

    Modifier to bodytemp accepted ranges Appropriate values are BODYTEMP_MIN: minimum temp for comfort BODYTEMP_MAX: maximum temp for comfort

    BODYTEMP_SLEEP

    Additional bodytemp given during sleep base_value is the mutation/previous enchantment values There is no limit

    BODYTEMP_SPEED

    Additional speed change for COLDBLOOD4 characters base_value is the mutation value or 0 There is no current limit

    SLEEP_PAIN_THRESHOLD

    Additional pain required for being woken up base_value is the base sleep pain value Minimum value is 1

    SLEEP_DB_RESIST

    Modifier to the amount of noise above environemental required to be woken up base_value is 20 There is no minimum nor maximum value

    CLIMATE_CONTROL

    Moves temperature felt by the player towards a point. base_value is the current temperature felt by the player It will increase or decrease based off if it is below or above normal temperature ( including mutations ) It has two children:

    SetValuesUse
    TemperatureCOOLING, HEATINGWeather it applies increase in heat or decrease in heat towards ideal temp
    BodypartSee general bodypart enchantments hereBodypart that it applies to

    That would only heat or cool respectively

    LIE

    Modifier to Lie chance base_value is post skill effects Under 0 and above 100 has no change

    PERSUADE

    Same as LIE but for persuasion

    INTIMIDATE

    Same as LIE but for intimidation

    HEALTHY_MULT

    Edit to healthy. base_value is 1

    FALL_DAMAGE_MULT

    Modifier to fall damage multiplier, base_value is post mutations and other modifiers Cannot go below 0

    CARRY_STORAGE

    Modifier to carryable storage. base_value is current storage in mililiters Cannot go below 0

    CARRY_WEIGHT

    Modifier to carryable weight. base_value is current storage in mililiters Cannot go below 0

    WEIGHTMOD

    Modifier to the current weight of the player. base_value is the respective weight of one of the categories listed below. Minimum is 0, maximum is uncapped

    SetValuesUse
    CategoryBIONICS, WEAPON, INVENTORY, BODY, WORNWhat part of player weight it is applied to
    OVERMAP_SIGHT

    Modifier to overmap sight. base_value is the best mutation value. Maximum is 3

    EFFECTIVE_FOCUS

    Modifier to focus. base_value is current focus There is no limit

    MELEE_HIT

    Modifier to melee hit rating. base_value is the value after all modifiers. There are no limits.

    OVERKILL

    Modifier to after death damage on a zombie. base_value is the current overkill damage Minimum value of 0.

    FOOD_FUN

    Modifier to food morale. base_value is current food morale There is no limit.

    VOMIT_MOD

    Modifier to chance to vomit. base_value is always 1. Minimum value of 0.

    PAIN

    Modifier to shifts in pain. base_value is the pain mod.

    SetValuesUse
    TypeGAIN, LOSSApply specifically to increases or decreases.
    PAIN_MOD

    Modifier to current amount of pain, constant shift. base_value is current pain. Minimum value of 0

    CHRONIC_PAIN_MOD

    Modifier to pain from the CHRONIC_PAIN option. base_value is the chronic pain. Minimum value of 0 after being added to value after PAIN_MOD

    PERCEIVED_PAIN_MOD

    Modifier to percieved pain. base_value is current pain after PAIN_MOD. Minimum value of 0

    SetValuesUse
    StatSPD, STR, DEX, INT, PERApply only to speed, strength, dexterity, intellegence and perception respectively.
    PAIN_PENALTY

    Affects the stat penalty from high amounts of pain. base_value is the current penalty. Maximum value of 0 ( no effect )

    ADDICTION_STRENGTH

    Modifier to likelyhood to gain another addiction intensity. base_value is the strength of the added addiction. There is no limit.

    ADDICTION_TIME_PER_ADDITION

    Modifier to how long addiction applications increase addition time. base_value is base time added each time additions are applied in seconds. There is no limit.

    ADDICTION_TIME_PER_INTENSITY

    Modifier to how long addictions last. base_value is time to remove one addiction stack. Reducing increases addiction time, adding reduces addiction time There is no limit.

    UNCANNY_DODGE

    0-100 chance to dodge bullets. base_value is 0. Each uncanny dodge takes 100 stamina. Any values below 0 or above 1 will have the same effect as at 0 and at 1 respectively

    BONUS_DODGE

    Additional dodges per turn before dodge penalty kicks in. base_value here is character’s base dodges per turn before penalty (usually 1). The final value can go below 0, which results in penalty to dodge roll.

    FORCEFIELD

    0-100 chance to block damage of a damage type. base_value is 0.

    SetValuesUse
    Damage TypeSee general damage type suffixes hereDamage Type that it applies to
    CROWD_CRUSH_RESIST

    Modifier to how likely it is to get crowd crushed base_value is 5, it is always 5. Increasing it reduces the chance to get crowd crushed From 0 ( no chance to resist ) to 95 ( 5% chance to not resist )

    BLISTER_COUNT

    Effective heat armor modifier to gaining the blister effect. base_value is the number of blisters. The final value can go below 0, which would never blister the character. Or it could go higher and always blister the character.

    LUMINATION

    Lumination around the player when active. You cannot add nor multiply this enchantment, only max value works. The final value will not go below 0, and the maximum value is uncapped.

    NIGHT_VISION

    Night vision value for the player. EFFECT_NIGHT_VISION or GNV_EFFECT is 10.0 while GNVE_EFFECT is 18.0 Only max works, and it will take the highest of enchantment and other night vision effects

    CLAIRVOYANCE

    Clairvoyance value for the player. CLAIRVOYANCE_SUPER is 40.0 while CLAIRVOYANCE_PLUS is 8.0 And CLAIRVOYANCE is 3 Only max works, and it will take the highest of enchantment and other clairvoyance effects

    FLASH_PROTECTION

    Flash protection value for the player. Item and effect flags give 3. Only max works, and it will take the highest of enchantment, item and effect effects.

    GROUNDED_CREATURE_SIGHT

    Sight that passes through walls of grounded creatures in the form of infrared. Number of tiles it works on. Only max works.

    REACH_RANGE

    Value that adds reach to all melee attacks ( unarmed or armed ). base_value is always 0. Only max works

    SetValuesUse
    TypeUNARMED, ARMEDApply only to armed or unarmed attacks.
    ARMOR_X

    Incoming damage modifier. Applied after Active Defense System bionic but before the damage is absorbed by items. Note that base_value here is incoming damage value of corresponding type, so positive add and greater than 1 mul will increase damage received by the character.

    SetValuesUse
    Damage TypeSee general damage type suffixes hereDamage Type that it applies to
    SKILL_LEVEL

    Character wide skill level modifier. base_value is the current skill level of the player

    SetValuesUse
    Skill TypeSee general skill suffixes hereSkill that it applies to
    SKILL_EXP

    Character wide skill exp gain modifier. base_value is the exp gained by whatever is being done Warning: this value can only be multiplied, not added

    SetValuesUse
    Skill TypeSee general skill suffixes hereSkill that it applies to
    Encumbrance

    Character wide encumbrance modifier, children modify certain bodyparts.

    SetValuesUse
    BodypartSee general bodypart enchantments hereBodypart that it applies to
    MELEE_DAMAGE

    Character wide melee damage modifier ( reach attacks included ), children modify only certain damage types.

    SetValuesUse
    Damage TypeSee general damage type suffixes hereDamage Type that it applies to
    MELEE_ARMOR_PENETRATION

    Character wide melee armor penetration modifier. Children modify certain damage types.

    SetValuesUse
    Damage TypeSee general damage type suffixes hereDamage Type that it applies to

    Item values

    ITEM_ATTACK_COST

    Attack cost (melee or throwing) for this item. Ignores condition / location, and is always active. base_value here is base item attack cost. Note that the final value cannot go below 0.

    ITEM_DAMAGE_X

    Melee damage of this item. Ignores condition / location, and is always active. base_value here is base item damage of corresponding type. Note that the final value cannot go below 0. There is the global damage modifier ITEM_DAMAGE in addition to the supported damage types:

    SetValuesUse
    Damage TypeSee general damage type suffixes hereDamage Type that it applies to
    ITEM_ARMOR_PENETRATION_X

    Armor penetration of this item. base_value here is base armor penetration of corresponding type. Note that the final value cannot go below 0. There is the global modifier ITEM_ARMOR_PENTRATION in addition to the supported damage types:

    SetValuesUse
    Damage TypeSee general damage type suffixes hereDamage Type that it applies to
    ITEM_ARMOR_X

    Incoming damage modifier for this item, applied before the damage is absorbed by the item. Note that base_value here is incoming damage value of corresponding type, so positive add and greater than 1 mul will increase damage received by the character. Each damage type has its own enchant value, in addition to the global ITEM_ARMOR:

    SetValuesUse
    Damage TypeSee general damage type suffixes hereDamage Type that it applies to
    ITEM_REACH_RANGE

    Modifier to item reach range, max value between this and any item flags.

    Enchantment Flag

    {
      "id": "NEARSIGHTED",               // Id of the enchantment flag
      "type": "enchantment_flag",        // Needed type
      "parents": [ "BLIND" ],            // Array of other enchantment_flags it also gives
      "conflicts": [ "FIX_NEARSIGHTED" ] // Array of other enchantment_flags of which it cancels
      "info": "<bad>Causes nearsightedness</bad>" // Info string showed in enchantment info
    },
    

    All noted effects apply to the character in possession of the enchantment granting thing

    Basegame Enchantment Flag ID List

    Sight

    UNDERWATER_SIGHT

    Makes sight underwater uninhibited

    SLEEP_SIGHT

    Allows sight while sleeping

    NEARSIGHTED

    Restricts vision greatly, solved by some glasses

    FIX_NEARSIGHTED

    Conflict to NEARSIGHTED, cures and removes it

    BLIND

    Prevents seeing any tile, bumping into walls does reveal them

    FIX_BLIND

    Conflict to BLIND, cures and removes it

    INFRARED_VISION

    Gain infrared vision

    ELECTROSENSE

    Can see robots and electrical creatures through walls

    SONAR

    Can see burrowing creatures with the INFRARED_VISION sprite

    ANTIGLARE

    Prevents glare effects from sunlight and such

    Consumption

    EAT_ROTTEN

    Gives the ability to eat rotten food safely.

    ONLY_EAT_ROTTEN

    Gives significant penalty to eating fresh food, still allows drinking fresh liquids

    EAT_ROTTEN_MORALE

    Gives no morale penalty to eating rotten food

    CONSUME_UNCLEAN

    Gives the ability to drink unclean liquids and eat unclean foods

    FOOD_PARASITE_IMMUNE

    Prevents gaining parasites from consuming food

    FOOD_POISON_IMMUNE

    Prevents gaining poison from consuming food

    Miscellaneous

    ALARMCLOCK

    Gives the ability to set an alarm while sleeping

    INTENAL_ALARMCLOCK

    Has the effects of ALARMCLOCK, but does not produce sound It also should prevent sleeping through it.

    VIEW_DRONE_CAM

    Allows viewing any creature with effect_drone_marker, generally applied by PHOTOGRAPH robots

    RADIO

    Gives the effects of having a radio

    THERMOMETER

    Gives the effects of having a themometer

    WATCH

    Gives the ability to see the precise time

    FIRE_FIELD_IMMUNE

    Provides immunity to fire fields.

    SILENT

    Prevents player sound from movement

    NO_THERMAL_WAKE

    Extreme temperatures will not wake up the player

    NO_DAMAGE_WAKE

    Taking damage will not wake up the player

    NO_LIGHT_WAKE

    Lights will not wake up the player

    Enchantment Condition

    {
      "id": "WORN", // Id of condition
      "type": "enchantment_condition", // Mandatory Type
      "condition_type": "item_and_character", // Type of condition, `global`, `item`, `character` and `item_and_character` are possible values
      "condition_function": "worn", // What function to use, generally references a hardcode or lua function
      "condition_info": "While worn", // Enchantment condition info to display on items
    }
    

    Basegame Enchantment Condition ID List

    Item and Character

    HELD

    When in your inventory

    WIELD

    When wielded in your hand

    WORN

    When worn as armor

    Global

    ALWAYS

    Always active ( Obsolete but supported: Comes out to be true, thus no condition is needed )

    NIGHT

    When it is night time

    DUSK

    When it is dusk

    DAY

    When it is day time

    DAWN

    When it is dawn

    ACTIVE

    Whenever the item, mutation, bionic, or whatever the enchantment is attached to is active.

    INACTIVE

    The opposite of ACTIVE

    Character

    INSIDE

    When the owner of the item is inside

    OUTSIDE

    When the owner of the item is outside

    UNDERGROUND

    When the owner of the item is below Z-level 0

    ABOVEGROUND

    When the owner of the item is at or above Z-level 0

    UNDERWATER

    When the owner is in swimmable terrain

    Enchantment Vision

    The following is enchantment vision definitions. All conditions must pass to show

    {
      "id": "ELECTROSENSE",                          // Id of the enchantment flag
      "type": "enchantment_vision",                  // Needed type
      "desc": "Allows Sight Of Electric Creatures",  // Info string showed in enchantment info
      "distance": 5,                                 // Max tile distance that this works
      "same_z_level": false,                         // Show across z-levels
      "require_los": true,                           // Require line of sight
      "detect_heat": true,                           // Require `is_warm`
      "show_with_species": [ "ROBOT" ],              // List of species, any being true -> pass
      "show_with_flag": [ "ELECTRIC" ],              // List of monster flags, any true -> pass
      "show_without_any_flag": [ "FLIES" ],          // List of monster flags, any true -> fail
      "show_with_effect": [ "drone_marker" ],        // List of effects, any true -> pass
      "show_without_any_effect": [ "drone_marker" ], // List of effects, any true -> fail
      "show_normal": true,                           // Shows the monster normally, this or vision desc must be used
      "vision_desc": {                               // Can be an array or object
        "tile_id": "infrared_creature",              // Tile to display
        "description": "You sense electricity."      // Message to show on examine of any size
      },
      "vision_desc": [ // Must define one for each of `TINY`, `SMALL`, `MEDIUM`, `LARGE` and `HUGE`
        {
          "tile_id": "infrared_creature",                     // Tile id
          "description": "You sense tiny bits of electricity" // Message to show on examine
          "size": "TINY"                                      // Size enum of the creature
        }
      ]
    },
    

    In-game debugging tools

    The game features a number of inbuilt tools that aim to aid in debugging issues and testing fixes or new additions.

    Below are listed some major ones.

    Debug Message

    Also known as debugmsg, or “Red text over black screen”. Shows up when the game encounters an error in data files or an inconsistency within its internal state.

    Severity varies, from harmless, pedantic warnings to unrecoverable crashes. A copy of each message is saved in the debug log, usually prepended with backtrace that describes where (in the code) the error originated from.

    You can press space to dismiss the message, or i to dismiss the message and all its subsequent occurences until game restart.

    You can suppress (at your own risk) all debug messages by running the game executable with --dont-debugmsg command line option.

    In code, you can invoke a debug message like this:

    #include "debug.h" // See this header for details
     . . .
    // 1st argument is a format string, see `string_formatter.h` for details
    debugmsg( "Failed to open file, code %d", 123 );
    

    Debug log

    Debug log contains various status messages produced by the game, including general info, warnings or hard errors. It’s usually the go-to place for initial diagnostic of most bugs.

    It’s contained in a single file named debug.log which is located in user’s config folder.

    You can manually control debug log verbosity in game options (Options -> Debug tab -> Logging submenu).

    In code, you can print to the log like this:

    #include "debug.h" // See this header for details
     . . .
    // 1st argument is severity level, 2nd argument is category
    // Don't append a newline at the end, it will be done automatically.
    DebugLogFL( DL::Info, DC::Map ) << "My " << "logged" << " info!";
    

    Crash log

    Crash log contains backtrace after game crash. It’s extremely helpful for solving crashes, as it essentially holds the info about what code (and where) experienced the crash.

    It’s contained in a single file named crash.log which is located in user’s config folder.

    Sometimes, if crash is “weird” enough, or the executable was compiled without backtrace support, crash log is not generated.

    In code, you don’t have to add any special logic for crash traces, but the build must have backtraces enabled. Some builds also support optional libbacktace that may make the backtraces more readable. If it takes a long time (up to half a minute) to generate backtraces on Linux, consider compiling with clang++ instead of g++.

    Debug mode

    Not to be confused with debug menu, debug mode makes the game produce a lot of noisy messages in the log, and enables additional functionality in some UI windows.

    For example, additional info such as item id, tags and charges will be shown when examining an item, and vehicle details menu will show pivot point, center of mass and cursor position (in vehicle coords).

    Debug messages are mostly pertaining to vehicle, effect, sound and NPC processing.

    To access debug mode switch, bind Toggle Debug Mode action to some key while in “default” mode (terrain view with character in the center who you control). Reminder: you can access keybinds list by pressing ?.

    In code, you can check for debug mode via debug_mode variable found in cached_options.h.

    Debug menu

    Also known as “cheat menu”, not to be confused with debug mode. The best friend when it comes to testing.

    It’s hidden by default. To access it, bind Debug Menu action to any key (backtick key ` is the usual choice), and then either press that key, or select Debug Menu entry from Esc menu.

    Most of the functionality there is clearly labeled and split into categories, feel free to explore.

    There’s a somewhat hidden feature called “Debug Mutations”, which resembles cheat codes in older games and grants your character immunity to some game mechanics. To quickly access them, press p(Player)->u(Mutate)->/(Filter) and enter Debug in the search box.

    Additional JSON checks

    It’s possible to enable additional JSON data checks, mostly useful for content makers. The list includes, but not limited to, the following:

    1. Unused fields, such as caused by a typo in JSON or a deprecated field being removed from the game.
    2. Deprecation warnings and migration advice.
    3. Checks for potential weird behavior.

    Old or infrequently maintained mods may trigger hundreds of these, so the option is disabled by default. You can enable it in game options (Options -> Debug tab -> Report unused JSON fields).

    If you’d like to propose your changes to BN, keep in mind that both the testing executable tests/cata_test[.exe] and automated PR checks in the repository are run with this option enabled.

    TODO: rename the option to imply all listed checks, maybe also enable it by default.

    Tileset reload and report

    Useful for tileset makers, this feature reloads the active tileset from disk, redraws the screen and writes completeness report to the debug log.

    To use the feature, you’ll have to bind Reload Tileset action to any key and press it.

    JSON Flags

    Example

    {
      "type": "json_flag", // Required type
      "id": "GENERIC_FLAG", // Flag ID
      "context": [], // Fluff field that does nothing but is required to exist
      "craft_inherit": true, // Items made with it will keep this flag
      "requires_flag": true, // Used by vehicle part flags, requires another part with this ID on the tile
      "inherit": true, // Item mods will pass this flag down to the item
      "use_method": "USE_METHOD_ID", // This flag gives the connected item this use method if it doesn't already have it
      "tag": "string", // Translatable string appended to the item's UI display name, if the item has this flag
      "dynamic_color": "c_brown" // Curses color string to use in inventory when this flag is dynamically applied to an item
    }
    

    Notes

    • Some flags (items, effects, vehicle parts) have to be defined in flags.json or vp_flags.json (with type: json_flag) to work correctly.
    • Many of the flags intended for one category or item type, can be used in other categories or item types. Experiment to see where else flags can be used.
    • Offensive and defensive flags can be used on any item type that can be wielded.
    • use_method needs to be on the item, so if it’s on a mod flag, that flag also needs to set inherit to true.

    Inheritance

    When an item is crafted, it can inherit flags from the components that were used to craft it. This requires that the flag to be inherited has the "craft_inherit": true entry. If you don’t want a particular item to inherit flags when crafted, specify the member delete_flags, which is an array of strings. Flags specified there will be removed from the resultant item upon crafting. This will override flag inheritance, but will not delete flags that are part of the item type itself.

    TODO

    • Descriptions for Special attacks under Monsters could stand to be more descriptive of exactly what the attack does.
    • Ammo effects under Ammo need more descriptive details, and some need to be double-checked for accuracy.

    Ammo

    Ammo type

    These are handled through ammo_types.json. You can tag a weapon with these to have it chamber existing ammo, or make your own ammo there. The first column in this list is the tag’s “id”, the internal identifier BN uses to track the tag, and the second is a brief description of the ammo tagged. Use the id to search for ammo listings, as ids are constant throughout BN’s code. Happy chambering! :-)

    • 120mm 120mm HEAT
    • 12mm 12mm
    • 20x66mm 20x66mm Shot (and relatives)
    • 223 .223 Remington (and 5.56 NATO)
    • 22 .22LR (and relatives)
    • 3006 30.06
    • 300 .300 WinMag
    • 308 .308 Winchester (and relatives)
    • 32 .32 ACP
    • 36paper .36 cap & ball
    • 38 .38 Special
    • 40 10mm
    • 40mm 40mm Grenade
    • 44 .44 Magnum
    • 44paper .44 cap & ball
    • 45 .45 ACP (and relatives)
    • 50 .50 BMG
    • 5x50 5x50 Dart
    • 66mm 66mm HEAT
    • 762R 7.62x54mm
    • 762 7.62x39mm
    • 84x246mm 84x246mm HE
    • 8x40mm 8mm Caseless
    • 9mm 9x19mm Luger (and relatives)
    • BB BB
    • RPG-7 RPG-7
    • UPS UPS charges
    • ammo_flintlock Flintlock ammo
    • ampoule Ampoule
    • arrow Arrow
    • battery Battery
    • blunderbuss Blunderbuss
    • bolt Bolt
    • charcoal Charcoal
    • components Components
    • dart Dart
    • diesel Diesel
    • fish_bait Fish bait
    • fishspear Speargun spear
    • fusion Laser Pack
    • gasoline Gasoline
    • homebrew_rocket homebrew rocket
    • lamp_oil Lamp oil
    • laser_capacitor Charge
    • m235 M235 TPA (66mm Incendiary Rocket)
    • metal_rail Rebar Rail
    • money Cents
    • muscle Muscle
    • nail Nail
    • pebble Pebble
    • plasma Plasma
    • plutonium Plutonium Cell
    • rebreather_filter Rebreather filter
    • shot Shotshell
    • signal_flare Signal Flare
    • tape Duct tape
    • thread Thread
    • thrown Thrown
    • unfinished_char Semi-charred fuel
    • water Water

    The following ammo types are (or will soon be) available in in-repo mods exotic_ammo:

    • 454 .454 Casull
    • 500 .500 Magnum
    • 57 5.7 mm
    • 46 4.6 mm
    • 762x25 7.62x25mm (Tokarev)
    • 9x18 9x18mm
    • 700nx .700 Nitro Express
    • 38super .38 super
    • 460 .460 Rowland
    • 545x39 5.45x39mm
    • 270win .270 winchester

    Armor

    Covers

    • ARMS … same ARM_L and ARM_R
    • ARM_L
    • ARM_R
    • EYES
    • FEET … same FOOT_L and FOOT_R
    • FOOT_L
    • FOOT_R
    • HANDS … same HAND_L and HAND_R
    • HAND_L
    • HAND_R
    • HEAD
    • LEGS … same LEG_L and LEG_R
    • LEG_L
    • LEG_R
    • MOUTH
    • TORSO

    Flags

    Some armor flags, such as WATCH and ALARMCLOCK are compatible with other item types. Experiment to find which flags work elsewhere.

    • ACTIVE_CLOAKING While active, drains UPS to provide invisibility.
    • ALARMCLOCK Has an alarm-clock feature.
    • ALLOWS_NATURAL_ATTACKS Doesn’t prevent any natural attacks or similar benefits from mutations, fingertip razors, etc., like most items covering the relevant body part would.
    • AURA This item goes in the outer aura layer, intended for metaphysical effects.
    • BAROMETER This gear is equipped with an accurate barometer (which is used to measure atmospheric pressure).
    • BELTED Layer for backpacks and things worn over outerwear.
    • BLIND Blinds the wearer while worn, and provides nominal protection v. flashbang flashes.
    • BLOCK_WHILE_WORN Allows worn armor or shields to be used for blocking attacks. See also the Techniques section.
    • BULLET_IMMNUE Wearing an item with this flag makes you immune to bullet damage
    • CLIMATE_CONTROL This piece of clothing has climate control of some sort, keeping you warmer or cooler depending on ambient and bodily temperature.
    • COLLAR This piece of clothing has a wide collar that can keep your mouth warm.
    • DEAF Makes the player deaf.
    • DRONE_CAM Allows you to see targets marked by friendly drones such as eyebots.
    • ELECTRIC_IMMUNE This gear completely protects you from electric discharges.
    • FANCY Wearing this clothing gives a morale bonus if the player doesn’t have the Fashion Deficient trait.
    • FIX_FARSIGHT This gear corrects farsightedness.
    • FIX_NEARSIGHT This gear corrects nearsightedness.
    • FLOTATION Prevents the player from drowning in deep water. Also prevents diving underwater.
    • FRAGILE This gear is less resistant to damage than normal.
    • HELMET_COMPAT Items that are not SKINTIGHT or OVERSIZE but can be worn with a helmet.
    • HOOD Allow this clothing to conditionally cover the head, for additional warmth or water protection., if the player’s head isn’t encumbered
    • HYGROMETER This gear is equipped with an accurate hygrometer (which is used to measure humidity).
    • NO_TAKEOFF Item with that flag can’t be taken off.
    • NO_QUICKDRAW Don’t offer to draw items from this holster when the fire key is pressed whilst the players hands are empty
    • ONLY_ONE You can wear only one.
    • OUTER Outer garment layer.
    • OVERSIZE Can always be worn no matter encumbrance/mutations/bionics/etc., but prevents any other clothing being worn over this.
    • PARTIAL_DEAF Reduces the volume of sounds to a safe level.
    • PERSONAL This item goes in the personal aura layer, intended for metaphysical effects.
    • POCKETS Increases warmth for hands if the player’s hands are cold and the player is wielding nothing.
    • POWERARMOR_EXO Marks the item as the main exoskeleton for power armor.
    • POWERARMOR_EXTERNAL Marks the item as external pieces that cover body parts the exoskeleton doesn’t.
    • POWERARMOR_PLATING Marks the item as external armor plates that are worn over the exoskeleton.
    • POWERARMOR_MOD Marks the item as a power armour mod that is worn onto an exoskeleton/external piece.
    • POWERARMOR_COMPATIBLE Makes item compatible with power armor despite other parameters causing failure.
    • PLATE_CARRIER Marks the item as a plate carrier which allows armor plates to be worn.
    • ARMOR_PLATE Marks the item as a set of armor plates, which can only be worn when the player is wearing an item with the PLATE_CARRIER flag. One set of armor plates can be worn per plate carrier.
    • PSYSHIELD_PARTIAL 25% chance to protect against fear_paralyze monster attack when worn.
    • RAD_PROOF This piece of clothing completely protects you from radiation.
    • RAD_RESIST This piece of clothing partially protects you from radiation.
    • RAINPROOF Prevents the covered body-part(s) from getting wet in the rain.
    • REQUIRES_BALANCE Gear that requires a certain balance to be steady with. If the player is hit while wearing, they have a chance to be downed.
    • RESTRICT_HANDS Prevents the player from wielding a weapon two-handed, forcing one-handed use if the weapon permits it.
    • ROLLER_ONE A less stable and slower version of ROLLER_QUAD, still allows the player to move faster than walking speed.
    • ROLLER_QUADThe medium choice between ROLLER_INLINE and ROLLER_ONE, while it is more stable, and moves faster, it also has a harsher non-flat terrain penalty then ROLLER_ONE.
    • ROLLER_INLINE Faster, but less stable overall, the penalty for non-flat terrain is even harsher.
    • SEMITANGIBLE Prevents the item from participating in the encumbrance system when worn.
    • COMPACT Prevents the item from participating in the layering encumbrance system when worn.
    • SKINTIGHT Undergarment layer.
    • SLOWS_MOVEMENT This piece of clothing multiplies move cost by 1.1.
    • SLOWS_THIRST This piece of clothing multiplies the rate at which the player grows thirsty by 0.70.
    • STURDY This clothing is a lot more resistant to damage than normal.
    • SUN_GLASSES Prevents glaring when in sunlight.
    • SUPER_FANCY Gives an additional moral bonus over FANCY if the player doesn’t have the Fashion Deficient trait.
    • SWIM_GOGGLES Allows you to see much further under water.
    • THERMOMETER This gear is equipped with an accurate thermometer (which is used to measure temperature).
    • VARSIZE Can be made to fit via tailoring.
    • WAIST Layer for belts other things worn on the waist.
    • WATCH Acts as a watch and allows the player to see actual time.
    • WATERPROOF Prevents the covered body-part(s) from getting wet in any circumstance.
    • WATER_FRIENDLY Prevents the item from making the body part count as unfriendly to water and thus causing negative morale from being wet.
    • WORN_GUN Allows the gun to be fired while worn as armor.
    • ALLOWS_FLIGHT While active, drains UPS to provide flight.
    • ALWAYS_ALLOWS_FLIGHT Always allow flight.

    Bionics

    • BIONIC_ARMOR_INTERFACE This bionic can provide power to powered armor.
    • BIONIC_FAULTY This bionic is a “faulty” bionic.
    • BIONIC_GUN This bionic is a gun bionic and activating it will fire it. Prevents all other activation effects.
    • BIONIC_NPC_USABLE The NPC AI knows how to use this CBM and it can be installed on an NPC.
    • BIONIC_POWER_SOURCE This bionic is a power source bionic.
    • BIONIC_SLEEP_FRIENDLY This bionic won’t prompt the user to turn it off if they try to sleep while it’s active.
    • BIONIC_TOGGLED This bionic only has a function when activated, else it causes it’s effect every turn.
    • BIONIC_WEAPON This bionic is a weapon bionic and activating it will create (or destroy) bionic’s fake_item in user’s hands. Prevents all other activation effects.
    • BIONIC_SHOCKPROOF This bionic can’t be incapacitated by electrical attacks.
    • BIONIC_FLIGHT This bionic allows flight when active.
    • MULTIINSTALL This bionic can be installed multiple times
    • INITIALLY_ACTIVE This bionic is active at the point of installation
    • BIONIC_TOOLS This bionic has tools, on activate it will reload the avaliable things to craft with

    Books

    • BOOK_CANNIBAL Reading this book converts negative morale to positive morale for characters with the CANNIBAL, PSYCHOPATH, or SAPIVORE trait flags.
    • INSPIRATIONAL Reading this book grants bonus morale to characters with the SPIRITUAL trait flag.
    • MORBID Reading this book converts negative morale to positive morale for characters with the PSYCHOPATH trait flag.

    Use actions

    • ACIDBOMB_ACT Get rid of it or you’ll end up like that guy in Robocop.
    • ACIDBOMB Pull the pin on an acid bomb.
    • AUTOCLAVE Sterilize one CBM by autoclaving it.
    • ARROW_FLAMABLE Light your arrow and let fly.
    • BELL Ring the bell.
    • BOLTCUTTERS Use your town key to gain access anywhere.
    • BREAK_STICK Breaks long stick into two.
    • C4 Arm the C4.
    • ‘C4_BREACHING’ Arm the C4 breaching charge.
    • CABLE_ATTACH This item is a cable spool. Use it to try to attach to a vehicle.
    • CAN_GOO Release a little blob buddy.
    • CAPTURE_MONSTER_ACT Capture and encapsulate a monster. The associated action is also used for releasing it.
    • CROWBAR Pry open doors, windows, man-hole covers and many other things that need prying.
    • DIG Clear rubble.
    • DIRECTIONAL_ANTENNA Find the source of a signal with your radio.
    • DIVE_TANK Use compressed air tank to breathe.
    • DOG_WHISTLE Dogs hate this thing; your dog seems pretty cool with it though.
    • DOLLCHAT That creepy doll just keeps on talking.
    • ELEC_CHAINSAW_OFF Turn the electric chainsaw on.
    • ELEC_CHAINSAW_ON Turn the electric chainsaw off.
    • EXTINGUISHER Put out fires.
    • FIRECRACKER_ACT The saddest Fourth of July.
    • FIRECRACKER_PACK_ACT Keep the change you filthy animal.
    • FIRECRACKER_PACK Light an entire packet of firecrackers.
    • FIRECRACKER Light a singular firecracker.
    • FLASHBANG Pull the pin on a flashbang.
    • GEIGER Detect local radiation levels.
    • GRANADE_ACT Assaults enemies with source code fixes?
    • GRANADE Pull the pin on Granade.
    • GRENADE Pull the pin on a grenade.
    • HACKSAW Cut metal into chunks.
    • HAMMER Pry boards off of windows, doors and fences.
    • HEATPACK Activate the heatpack and get warm.
    • HEAT_FOOD Heat food around fires.
    • HOTPLATE Use the hotplate.
    • JACKHAMMER Bust down walls and other constructions.
    • JET_INJECTOR Inject some jet drugs right into your veins.
    • LAW Unpack the LAW for firing.
    • LIGHTSTRIP Activates the lightstrip.
    • LUMBER Cut logs into planks.
    • MAKEMOUND Make a mound of dirt.
    • MANHACK Activate a manhack.
    • MATCHBOMB Light the matchbomb.
    • MILITARYMAP Learn of local military installations, and show roads.
    • MININUKE Set the timer and run. Or hit with a hammer (not really).
    • MOLOTOV_LIT Throw it, but don’t drop it.
    • MOLOTOV Light the Molotov cocktail.
    • MOP Mop up the mess.
    • MP3_ON Turn the mp3 player off.
    • MP3 Turn the mp3 player on.
    • NOISE_EMITTER_OFF Turn the noise emitter on.
    • NOISE_EMITTER_ON Turn the noise emitter off.
    • NONE Do nothing.
    • PACK_CBM Put CBM in special autoclave pouch so that they stay sterile once sterilized.
    • PHEROMONE Makes zombies ignore you.
    • PICK_LOCK Pick a lock on a door. Speed and success chance are determined by skill, ‘LOCKPICK’ item quality and ‘PERFECT_LOCKPICK’ item flag
    • PICKAXE Does nothing but berate you for having it (I’m serious).
    • PLACE_RANDOMLY This is very much like the flag in the manhack iuse, it prevents the item from querying the player as to where they want the monster unloaded to, and instead choses randomly.
    • PORTABLE_GAME Play games.
    • PORTAL Create portal traps.
    • RADIO_OFF Turn the radio on.
    • RADIO_ON Turn the radio off.
    • RAG Stop the bleeding.
    • RESTAURANTMAP Learn of local eateries, and show roads.
    • ROADMAP Learn of local common points-of-interest and show roads.
    • SCISSORS Cut up clothing.
    • SEED Asks if you are sure that you want to eat the seed. As it is better to plant seeds.
    • SEW Sew clothing.
    • SHELTER Put up a full-blown shelter.
    • SHOCKTONFA_OFF Turn the shocktonfa on.
    • SHOCKTONFA_ON Turn the shocktonfa off.
    • SIPHON Siphon liquids out of vehicle.
    • SMOKEBOMB_ACT This may be a good way to hide as a smoker.
    • SMOKEBOMB Pull the pin on a smoke bomb.
    • SOLARPACK_OFF Fold solar backpack array.
    • SOLARPACK Unfold solar backpack array.
    • SOLDER_WELD Solder or weld items, or cauterize wounds.
    • SPRAY_CAN Graffiti the town.
    • SURVIVORMAP Learn of local points-of-interest that can help you survive, and show roads.
    • TAZER Shock someone or something.
    • TELEPORT Teleport.
    • TOGGLE_HEATS_FOOD Gives the item the HEATS_FOOD flag if it lacks it, or vice-versa. Used to enable/disable automatically reheating food with that item when eating.
    • TOGGLE_UPS_CHARGING Gives the item the USE_UPS flag if it lacks it, or vice-versa. Used to enable/disable recharging that item from a UPS, advanced UPS, Unified Power System CBM, etc.
    • TELEPORT Teleport.
    • TORCH Light a torch.
    • TOURISTMAP Learn of local points-of-interest that a tourist would like to visit, and show roads.
    • TOWEL Dry your character using the item as towel.
    • TOW_ATTACH This is a tow cable, activate it to attach it to a vehicle.
    • TURRET Activate a turret.
    • WATER_PURIFIER Purify water.

    Comestibles

    Comestible type

    • DRINK
    • FOOD
    • MED

    Addiction type

    • alcohol
    • amphetamine
    • caffeine
    • cocaine
    • crack
    • nicotine
    • opiate
    • sleeping pill

    Use action

    • ALCOHOL_STRONG Greatly increases drunkenness. Adds disease drunk.
    • ALCOHOL_WEAK Slightly increases drunkenness. Adds disease drunk
    • ALCOHOL Increases drunkenness. Adds disease drunk.
    • ANTIBIOTIC Helps fight infections. Removes disease infected and adds disease recover.
    • BANDAGE Stop bleeding.
    • BIRDFOOD Makes a small bird friendly.
    • BLECH Causes vomiting.
    • BLECH_BECAUSE_UNCLEAN Causes warning.
    • CATFOOD Makes a cat friendly.
    • CATTLEFODDER Makes a large herbivore friendly.
    • CHEW Displays message “You chew your %s”, but otherwise does nothing.
    • CIG Alleviates nicotine cravings. Adds disease cig.
    • COKE Decreases hunger. Adds disease high.
    • CRACK Decreases hunger. Adds disease high.
    • DISINFECTANT Prevents infections.
    • DOGFOOD Makes a dog friendly.
    • FIRSTAID Heal.
    • FLUMED Adds disease took_flumed.
    • FLUSLEEP Adds disease took_flumed and increases fatigue.
    • FUNGICIDE Kills fungus and spores. Removes diseases fungus and spores.
    • HALLU Adds disease hallu.
    • HONEYCOMB Spawns wax.
    • INHALER Removes disease asthma.
    • IODINE Adds disease iodine.
    • MARLOSS “As you eat the berry, you have a near-religious experience, feeling at one with your surroundings…”
    • METH Adds disease meth
    • NONE “You can’t do anything of interest with your [x].”
    • PKILL Reduces pain. Adds disease pkill[n] where [n] is the level of flag PKILL_[n] used on this comestible.
    • PLANTBLECH Causes vomiting if player does not contain plant mutations
    • POISON Adds diseases poison and foodpoison.
    • PROZAC Adds disease took_prozac if not currently present, otherwise acts as a minor stimulant. Rarely has the took_prozac_bad adverse effect.
    • PURIFIER Removes negative mutations.
    • ROYAL_JELLY Alleviates many negative conditions and diseases.
    • SEWAGE Causes vomiting and a chance to mutate.
    • SLEEP Greatly increases fatigue.
    • THORAZINE Removes diseases hallu, visuals, high. Additionally removes disease formication if disease dermatik isn’t also present. Has a chance of a negative reaction which increases fatigue.
    • VACCINE Greatly increases health.
    • VITAMINS Increases healthiness (not to be confused with HP)
    • WEED Makes you roll with Cheech & Chong. Adds disease weed_high.
    • XANAX Alleviates anxiety. Adds disease took_xanax.

    Flags

    • ACID when consumed using the BLECH function, penalties are reduced if acidproof.
    • CARNIVORE_OK Can be eaten by characters with the Carnivore mutation.
    • CAN_PLANT_UNDERGROUND If this is a seed, it can be planted when below z-level zero, regardless of the ambient temperature.
    • CANT_HEAL_EVERYONE This med can’t be used by everyone, it require a special mutation. See can_heal_with in mutation.
    • EATEN_COLD Morale bonus for eating cold.
    • EATEN_HOT Morale bonus for eating hot.
    • NO_COOKING_BUFF prevents cooking skill from increasing calories of this food when the player cooks it
    • INEDIBLE Inedible by default, enabled to eat when in conjunction with (mutation threshold) flags: BIRD, CATTLE.
    • FERTILIZER Works as fertilizer for farming, of if this consumed with the PLANTBLECH function penalties will be reversed for plants.
    • FUNGAL_VECTOR Will give a fungal infection when consumed.
    • HIDDEN_HALLU … Food causes hallucinations, visible only with a certain survival skill level.
    • HIDDEN_POISON … Food displays as poisonous with a certain survival skill level. Note that this doesn’t make items poisonous on its own, consider adding "use_action": "POISON" as well, or using FORAGE_POISON instead.
    • IS_BLOOD Will be scanned if placed in a centrifuge, in hospitals, labs, etc.
    • MELTS Provides half fun unless frozen. Edible when frozen.
    • MILLABLE Can be placed inside a mill, to turn into flour.
    • MYCUS_OK Can be eaten by post-threshold Mycus characters. Only applies to mycus fruits by default.
    • NEGATIVE_MONOTONY_OK Allows negative_monotony property to lower comestible fun to negative values.
    • NO_INGEST Administered by some means other than oral intake.
    • PKILL_1 Minor painkiller.
    • PKILL_2 Moderate painkiller.
    • PKILL_3 Heavy painkiller.
    • PKILL_4 “You shoot up.”
    • PKILL_L Slow-release painkiller.
    • RAW Reduces kcal by 25%, until cooked (that is, used in a recipe that requires a heat source). Should be added to all uncooked food, unless that food derives more than 50% of its calories from sugars (i.e. many fruits, some veggies) or fats (i.e. butchered fat, coconut). TODO: Make a unit test for these criteria after fat/protein/carbs are added.
    • SMOKABLE Accepted by smoking rack.
    • SMOKED Not accepted by smoking rack (product of smoking).
    • USE_EAT_VERB “You drink your %s.” or “You eat your %s.”
    • USE_ON_NPC Can be used on NPCs (not necessarily by them).
    • ZOOM Zoom items can increase your overmap sight range.

    Furniture and Terrain

    List of known flags, used in both terrain.json and furniture.json.

    Flags

    • ALARMED Sets off an alarm if smashed.

    • ALIGN_WORKBENCH (only for furniture) A hint to the tiles display that the sprite for this furniture should face toward any adjacent tile with a workbench quality.-

    • ALLOW_FIELD_EFFECT Apply field effects to items inside SEALED terrain/furniture.

    • AUTO_WALL_SYMBOL (only for terrain) The symbol of this terrain will be one of the line drawings (corner, T-intersection, straight line etc.) depending on the adjacent terrains.

      Example: - and | are both terrain with the CONNECT_TO_WALL flag. O does not have the flag, while X and Y have the AUTO_WALL_SYMBOL flag.

      X terrain will be drawn as a T-intersection (connected to west, south and east), Y will be drawn as horizontal line (going from west to east, no connection to south).

      -X-    -Y-
       |      O
      
    • ADV_DECONSTRUCT This cannot be deconstructed using normal deconstruction; a specially-defined construction action is necessary. Most of these fall under the “advanced_object_deconstruction” group.

    • BARRICADABLE_DOOR_DAMAGED

    • BARRICADABLE_DOOR_REINFORCED_DAMAGED

    • BARRICADABLE_DOOR_REINFORCED

    • BARRICADABLE_DOOR Door that can be barricaded.

    • BARRICADABLE_WINDOW_CURTAINS

    • BARRICADABLE_WINDOW Window that can be barricaded.

    • BASH_TRANSFORM If this furniture possesses the transform examine action, bashing has a chance to trigger (e.g. flipping tables).

    • BASHABLE Players + Monsters can bash this.

    • BLOCK_WIND This terrain will block the effects of wind.

    • BURROWABLE Burrowing monsters can travel under this terrain, while most others can’t (e.g. graboid will traverse under the chain link fence, while ordinary zombie will be stopped by it).

    • BUTCHER_EQ Butcher’s equipment - required for full butchery of corpses.

    • CAN_SIT Furniture the player can sit on. Player sitting near furniture with the “FLAT_SURF” tag will get mood bonus for eating.

    • CHIP Used in construction menu to determine if wall can have paint chipped off.

    • COLLAPSES Has a roof that can collapse.

    • CONNECT_TO_WALL (only for terrain) This flag has been superseded by the JSON entry connects_to, but is retained for backward compatibility.

    • CONSOLE Used as a computer.

    • CONTAINER Items on this square are hidden until looted by the player.

    • DECONSTRUCT Can be deconstructed.

    • DEEP_WATER Deep enough to submerge things

    • WATER_CUBE Water tile that is entirely water

    • DESTROY_ITEM Items that land here are destroyed. See also NOITEM

    • DIFFICULT_Z Most zombies will not be able to follow you up this terrain ( i.e a ladder )

    • DIGGABLE_CAN_DEEPEN Diggable location can be dug again to make deeper (e.g. shallow pit to deep pit).

    • DIGGABLE Digging monsters, seeding monster, digging with shovel, etc.

    • DOOR Can be opened (used for NPC path-finding).

    • EASY_DECONSTRUCT Player can deconstruct this without tools.

    • ELEVATOR Terrain with this flag will move player, NPCs, monsters, and items up and down when player activates nearby elevator controls.

    • EMITTER This furniture will emit fields automatically as defined by its emissions entry

    • FIRE_CONTAINER Stops fire from spreading (brazier, wood stove, etc.)

    • FLAMMABLE_ASH Burns to ash rather than rubble.

    • FLAMMABLE_HARD Harder to light on fire, but still possible.

    • FLAMMABLE Can be lit on fire.

    • FLAT_SURF Furniture or terrain with a flat hard surface (e.g. table, but not chair; tree stump, etc.).

    • FLAT Player can build and move furniture on.

    • FORAGE_HALLU This item can be found with the HIDDEN_HALLU flag when found through foraging.

    • FORAGE_POISION This item can be found with the HIDDEN_POISON flag when found through foraging.

    • FRIDGE This item refrigerates items inside. Preserving them. Unlike vehicle parts, any furniture with this flag constantly functions.

    • FREEZER This item freezes items inside. Preserving them extremely well. Unlike vehicle parts, any furniture with this flag constantly functions.

    • GOES_DOWN Can use > to go down a level.

    • GOES_UP Can use < to go up a level.

    • GROWTH_SEED This plant is in its seed stage of growth.

    • GROWTH_SEEDLING This plant is in its seedling stage of growth.

    • GROWTH_MATURE This plant is in a mature stage of a growth.

    • GROWTH_HARVEST This plant is ready for harvest.

    • HARVESTED Marks the harvested version of a terrain type (e.g. harvesting an apple tree turns it into a harvested tree, which later becomes an apple tree again).

    • HIDE_PLACE Creatures on this tile can’t be seen by creatures not standing on adjacent tiles

    • INDOORS Has a roof over it; blocks rain, sunlight, etc.

    • LADDER This piece of furniture that makes climbing easy (works only with z-level mode).

    • LIQUIDCONT Furniture that contains liquid, allows for contents to be accessed in some checks even if SEALED.

    • LIQUID Blocks movement, but isn’t a wall (lava, water, etc.)

    • MINEABLE Can be mined with a pickaxe/jackhammer.

    • MOUNTABLE Suitable for guns with the MOUNTED_GUN flag.

    • NANOFAB_BODY A terrain/furniture with this flag is required within range 1 for nanofab use action to work

    • NANOFORGE_BODY A terrain/furniture with this flag is required within range 1 for nanoforge use action to work

    • NOCOLLIDE Feature that simply doesn’t collide with vehicles at all.

    • NOITEM Items cannot be added here but may overflow to adjacent tiles. See also DESTROY_ITEM

    • NO_FLOOR Things should fall when placed on this tile

    • NO_SIGHT Creature on this tile have their sight reduced to one tile

    • NO_SCENT This tile cannot have scent values, which prevents scent diffusion through this tile

    • OPENCLOSE_INSIDE If it’s a door (with an ‘open’ or ‘close’ field), it can only be opened or closed if you’re inside.

    • PAINFUL May cause a small amount of pain.

    • PERMEABLE Permeable for gases.

    • PLACE_ITEM Valid terrain for place_item() to put items on.

    • PLANT A ‘furniture’ that grows and fruits.

    • PLANTABLE This terrain or furniture can have seeds planted in it.

    • PLOWABLE Terrain can be plowed.

    • RAMP_END

    • RAMP Can be used to move up a z-level

    • REDUCE_SCENT Reduces scent diffusion (not total amount of scent in area); only works if also bashable.

    • ROAD Flat and hard enough to drive or skate (with rollerblades) on.

    • ROUGH May hurt the player’s feet.

    • RUG Enables the Remove Carpet Construction entry.

    • SALT_WATER Source of salt water (works for terrains with examine action “water_source”).

    • SEALED Can’t use e to retrieve items; must smash them open first.

    • SEEN_FROM_ABOVE Visible from a higher level (provided the tile above has no floor)

    • SHARP May do minor damage to players/monsters passing through it.

    • SHOOT_ME Players can aim at terrain or furniture with this flag like they can with tr_practice_target to train marksmanship.

    • SHORT Feature too short to collide with vehicle protrusions. (mirrors, blades).

    • SIGN Show written message on examine.

    • SMALL_PASSAGE This terrain or furniture is too small for large or huge creatures to pass through.

    • SOURCE_CLAY Enables the Extract Clay Construction entry.

    • SOURCE_IRON Enables the Extract Iron Construction entry.

    • SOURCE_SAND Enables the Extract Sand Construction entry.

    • SUN_ROOF_ABOVE This furniture (terrain is not supported currently) has a “fake roof” above, that blocks sunlight. Special hack for #44421, to be removed later.

    • SUPPORTS_ROOF Used as a boundary for roof construction.

    • SUPPRESS_SMOKE Prevents smoke from fires; used by ventilated wood stoves, etc.

    • SWIMMABLE Player and monsters can swim through it.

    • THIN_OBSTACLE Passable by players and monsters; vehicles destroy it.

    • TINY Feature too short to collide with vehicle undercarriage. Vehicles drive over them with no damage, unless a wheel hits them.

    • TRANSPARENT Players and monsters can see through/past it. Also sets ter_t.transparent.

    • UNSTABLE Walking here cause the bouldering effect on the character.

    • USABLE_FIRE This terrain or furniture counts as a nearby fire for crafting.

    • VEH_TREAT_AS_BASH_BELOW Vehicles will not collide with this even if it counts as rough terrain, like floor with bash_below does. Used for terrain meant to be turned into other terrain when smashed instead of destroying the tile beneath it.

    • WALL This terrain is an upright obstacle. Used for fungal conversion, and also implies CONNECT_TO_WALL.

    • WELDABLE_DOOR The “weld shut metal door” construction will convert this terrain into t_door_metal_welded.

    • WELDABLE_BARS As above, but converts to t_door_metal_welded_bars instead. If you want it to convert into specific terrain instead, add a separate construction entry to the weld_shut_metal_door construction group that uses pre_terrain instead of pre_flags.

    • WINDOW This terrain is a window, though it may be closed, broken, or covered up. Used by teh tiles code to align furniture sprites away from the window.

    Examine Actions

    • aggie_plant Harvest plants.
    • autodoc Brings the autodoc consoles menu. Needs the AUTODOC flag to function properly and an adjacent furniture with the AUTODOC_COUCH flag.
    • autoclave_empty Start the autoclave cycle if it contains faulty CBM, and the player has enough water.
    • autoclave_full Check on the progress of the cycle, and collect sterile CBM once cycle is completed.
    • bars Take advantage of AMORPHOUS and slip through the bars.
    • cardreader Use the cardreader with a valid card, or attempt to hack.
    • chainfence Hop over the chain fence.
    • controls_gate Controls the attached gate.
    • dirtmound Plant seeds and plants.
    • elevator Use the elevator to change floors.
    • fault Displays descriptive message, but otherwise unused.
    • flower_poppy Pick the mutated poppy.
    • fswitch Flip the switch and the rocks will shift.
    • fungus Release spores as the terrain crumbles away.
    • gaspump Use the gas-pump.
    • none None
    • pedestal_temple Opens the temple if you have a petrified eye.
    • pedestal_wyrm Spawn wyrms.
    • pit_covered Uncover the pit.
    • pit Cover the pit if you have some planks of wood.
    • portable_structure Take down a tent or similar portable structure.
    • recycle_compactor Compress pure metal objects into basic shapes.
    • rubble Clear up the rubble if you have a shovel.
    • safe Attempt to crack the safe.
    • shelter Take down the shelter.
    • shrub_marloss Pick a marloss bush.
    • shrub_wildveggies Pick a wild veggies shrub.
    • slot_machine Gamble.
    • toilet Either drink or get water out of the toilet.
    • trap Interact with a trap.
    • water_source Drink or get water from a water source.

    Fungal Conversions Only

    • FLOWER This furniture is a flower.
    • FUNGUS Fungal covered.
    • ORGANIC This furniture is partly organic.
    • SHRUB This terrain is a shrub.
    • TREE This terrain is a tree.
    • YOUNG This terrain is a young tree.

    Furniture Only

    • AUTODOC This furniture can be an autodoc console, it also needs the autodoc examine action.
    • AUTODOC_COUCH This furniture can be a couch for a furniture with the autodoc examine action.
    • BLOCKSDOOR This will boost map terrain’s resistance to bashing if str_*_blocked is set (see map_bash_info)

    Generic

    Flags

    • BIONIC_NPC_USABLE … Safe CBMs that NPCs can use without extensive NPC rewrites to utilize toggle CBMs.
    • BIONIC_TOGGLED … This bionic only has a function when activated, instead of causing its effect every turn.
    • BIONIC_POWER_SOURCE … This bionic is a source of bionic power.
    • BIONIC_SHOCKPROOF … This bionic can’t be incapacitated by electrical attacks.
    • BIONIC_FAULTY … This bionic is a “faulty” bionic.
    • BIONIC_WEAPON … This bionic is a weapon bionic and activating it will create (or destroy) bionic’s fake_item in user’s hands. Prevents all other activation effects.
    • BIONIC_ARMOR_INTERFACE … This bionic can provide power to powered armor.
    • BIONIC_SLEEP_FRIENDLY … This bionic won’t provide a warning if the player tries to sleep while it’s active.
    • BIONIC_GUN … This bionic is a gun bionic and activating it will fire it. Prevents all other activation effects.
    • CRAFT_WITH_FULL_MAG … This item crafts with a full set of ammo
    • COMBAT_NPC_ON … The “on” state for Items that NPCs will use in combat
    • COMBAT_NPC_USE … Items and CBMs that NPCs will activate when in combat
    • CORPSE … Flag used to spawn various human corpses during the mapgen.
    • DANGEROUS … NPCs will not accept this item. Explosion iuse actor implies this flag. Implies “NPC_THROW_NOW”.
    • DESTROY_ON_DECHARGE … This item should be destroyed if loses charges.
    • DESTROY_ON_DROP … When dropped on the ground, it will be destroyed.
    • DURABLE_MELEE … Item is made to hit stuff and it does it well, so it’s considered to be a lot tougher than other weapons made of the same materials.
    • FAKE_MILL … Item is a fake item, to denote a partially milled product by @ref Item::process_fake_mill, where conditions for its removal are set.
    • FAKE_SMOKE … Item is a fake item generating smoke, recognizable by @ref item::process_fake_smoke, where conditions for its removal are set.
    • FIREWOOD … This item can serve as a firewood. Items with this flag are sorted out to “Loot: Wood” zone
    • FLY_STRAIGHT … This thrown item flies straight without rotating in the air, maintaining its aerodynamic orientation. Typically used for javelins, spears, and darts.
    • FRAGILE_MELEE … Fragile items that fall apart easily when used as a weapon due to poor construction quality and will break into components when broken.
    • GAS_DISCOUNT … Discount cards for the automated gas stations.
    • IS_PET_ARMOR … Is armor for a pet monster, not armor for a person
    • LEAK_ALWAYS … Leaks (may be combined with “RADIOACTIVE”).
    • LEAK_DAM … Leaks when damaged (may be combined with “RADIOACTIVE”).
    • NEEDS_UNFOLD … Has an additional time penalty upon wielding. For melee weapons and guns this is offset by the relevant skill. Stacks with “SLOW_WIELD”.
    • MISSION_ITEM … will always spawn as loot regardless item spawn rate settings.
    • NO_PACKED … This item is not protected against contamination and won’t stay sterile. Only applies to CBMs.
    • NO_REPAIR … Prevents repairing of this item even if otherwise suitable tools exist.
    • NO_SALVAGE … Item cannot be broken down through a salvage process. Best used when something should not be able to be broken down (i.e. base components like leather patches).
    • NO_STERILE … This item is not sterile. Only applies to CBMs.
    • NPC_ACTIVATE … NPCs can activate this item as an alternative attack. Currently by throwing it right after activation. Implied by “BOMB”.
    • NPC_ALT_ATTACK … Shouldn’t be set directly. Implied by “NPC_ACTIVATE” and “NPC_THROWN”.
    • NPC_THROWN … NPCs will throw this item (without activating it first) as an alternative attack.
    • NPC_THROW_NOW … NPCs will try to throw this item away, preferably at enemies. Implies “TRADER_AVOID” and “NPC_THROWN”.
    • PERFECT_LOCKPICK … Item is a perfect lockpick. Takes only 5 seconds to pick a lock and never fails, but using it grants only a small amount of lock picking xp. The item should have “LOCKPICK” quality of at least 1.
    • PSEUDO … Used internally to mark items that are referred to in the crafting inventory but are not actually items. They can be used as tools, but not as components. Implies “TRADER_AVOID”.
    • BIONIC_TOOLS … Used by pseudo bionic tools to make clear that they need to use bionic power
    • RADIOACTIVE … Is radioactive (can be used with LEAK_*).
    • RAIN_PROTECT … Protects from sunlight and from rain, when wielded.
    • REDUCED_BASHING … Gunmod flag; reduces the item’s bashing damage by 50%.
    • REDUCED_WEIGHT … Gunmod flag; reduces the item’s base weight by 25%.
    • REQUIRES_TINDER … Requires tinder to be present on the tile this item tries to start a fire on.
    • SHATTERS … This item can potentially shatter as if it as made of glass when used as a weapon, thrown, bashed, etc.
    • SLEEP_AID … This item helps in sleeping.
    • SLEEP_IGNORE … This item is not shown as before-sleep warning.
    • SLOW_WIELD … Has an additional time penalty upon wielding. For melee weapons and guns this is offset by the relevant skill. Stacks with “NEEDS_UNFOLD”.
    • SECRET_ENCHANTMENTS … Enchantments on this item aren’t shown in item info.
    • TACK … Item can be used as tack for a mount.
    • TIE_UP … Item can be used to tie up a creature.
    • TINDER … This item can be used as tinder for lighting a fire with a REQUIRES_TINDER flagged firestarter.
    • TRADER_AVOID … NPCs will not start with this item. Use this for active items (e.g. flashlight (on)), dangerous items (e.g. active bomb), fake item or unusual items (e.g. unique quest item).
    • UNBREAKABLE … Armor with this flag will never take damage when taking hits for the wearer.
    • UNBREAKABLE_MELEE … Does never get damaged when used as melee weapon.
    • UNRECOVERABLE … Cannot be recovered from a disassembly.
    • TOBACCO … When lit, this item gives the cigarette effect every puff.
    • MARIJUANA … When lit, this item gives the marijuana effect every puff.

    Guns

    • BACKBLAST Causes a small explosion behind the person firing the weapon. Currently not implemented?
    • BIPOD Handling bonus only applies on MOUNTABLE map/vehicle tiles. Does not include wield time penalty (see SLOW_WIELD).
    • CHARGE Has to be charged to fire. Higher charges do more damage.
    • COLLAPSIBLE_STOCK DEPRECATED: Use volume_multiplier in gunmod definitions instead. Previously reduced weapon volume proportional to the base size of the gun (excluding any mods). volume_multiplier: 0.67 replicates the old behavior. Does not include wield time penalty (see NEEDS_UNFOLD).
    • CONSUMABLE Makes a gunpart have a chance to get damaged depending on ammo fired, and definable fields ‘consume_chance’ and ‘consume_divisor’.
    • CROSSBOW Counts as a crossbow for the purpose of gunmod compatibility. Default behavior is to match the skill used by that weapon.
    • DISABLE_SIGHTS Prevents use of the base weapon sights
    • FIRE_20 Uses 20 shots per firing.
    • FIRE_50 Uses 50 shots per firing.
    • FIRE_100 Uses 100 shots per firing. See also the ammo_to_fire property to specify any amount of ammo usage per shot desired. These flags will override ammo_to_fire if present.
    • HEAVY_WEAPON_SUPPORT Wearing this will let you hip-fire heavy weapons without needing terrain support, like Large or Huge mutants can.
    • FIRE_TWOHAND Gun can only be fired if player has two free hands.
    • IRREMOVABLE Makes so that the gunmod cannot be removed.
    • MECH_BAT This is an exotic battery designed to power military mechs.
    • MOUNTED_GUN Gun can only be used on terrain / furniture with the “MOUNTABLE” flag, if you’re a normal human. If you’re an oversized mutant (Inconveniently Large, Large, Freakishly Huge, Huge), you can fire it regularly in exchange for dispersion and recoil penalties. Wearing something with the HEAVY_WEAPON_SUPPORT flag also works.
    • NEVER_JAMS Never malfunctions.
    • NO_UNLOAD Cannot be unloaded.
    • PRIMITIVE_RANGED_WEAPON Allows using non-gunsmith tools to repair it (but not reinforce).
    • PUMP_ACTION Gun has a rails on its pump action, allowing to install only mods with PUMP_RAIL_COMPATIBLE flag on underbarrel slot.
    • PUMP_RAIL_COMPATIBLE Mod can be installed on underbarrel slot of guns with rails on their pump action.
    • RELOAD_AND_SHOOT Firing automatically reloads and then shoots.
    • RELOAD_EJECT Ejects shell from gun on reload instead of when fired.
    • RELOAD_ONE Only reloads one round at a time.
    • STR_DRAW If the weapon also has a strength requirement, lacking the requirement will penalize damage, range, and dispersion until you’re unable to fire if below 50% the listed strength, instead of being a strict limit like it normally would be.
    • STR_RELOAD Reload speed is affected by strength.
    • UNDERWATER_GUN Gun is optimized for usage underwater, does perform badly outside of water.
    • USE_PARENT_GUN For gunmods with gun_data meant to represent extra magazines on a gun, e.g. KSG. Will make fouling apply to the gun it’s installed on instead of itself, check for suppressors installed on the parent item, and apply brass catcher behavior if present on parent item.
    • WATERPROOF_GUN Gun does not rust and can be used underwater.

    Firing modes

    • MELEE Melee attack using properties of the gun or auxiliary gunmod
    • NPC_AVOID NPC’s will not attempt to use this mode
    • SIMULTANEOUS All rounds fired concurrently (not sequentially) with recoil added only once (at the end)

    Faults

    Flags

    • SILENT Makes the “faulty “ text NOT appear next to item on general UI. Otherwise the fault works the same.

    Parameters

    • turns_into Causes this fault to apply to the item just mended.
    • also_mends Causes this fault to be mended (in addition to fault selected) once that fault is mended.

    Magazines

    • MAG_BULKY Can be stashed in an appropriate oversize ammo pouch (intended for bulky or awkwardly shaped magazines)
    • MAG_COMPACT Can be stashed in an appropriate ammo pouch (intended for compact magazines)
    • MAG_DESTROY Magazine is destroyed when the last round is consumed (intended for ammo belts). Has precedence over MAG_EJECT.
    • MAG_EJECT Magazine is ejected from the gun/tool when the last round is consumed
    • SPEEDLOADER Acts like a magazine, except it transfers rounds to the target gun instead of being inserted into it.

    MAP SPECIALS

    • mx_bandits_block … Road block made by bandits from tree logs.
    • mx_burned_ground … Fire has ravaged this place.
    • mx_point_burned_ground … Fire has ravaged this place. (partial application)
    • mx_casings … Several types of spent casings (solitary, groups, entire overmap tile)
    • mx_clay_deposit … A small surface clay deposit.
    • mx_clearcut … All trees become stumps.
    • mx_collegekids … Corpses and items.
    • mx_corpses … Up to 5 corpses with everyday loot.
    • mx_crater … Crater with rubble (and radioactivity).
    • mx_drugdeal … Corpses and some drugs.
    • mx_dead_vegetation … Kills all plants. (aftermath of acid rain etc.)
    • mx_point_dead_vegetation … Kills all plants. (aftermath of acid rain etc.) (partial application)
    • mx_grove … All trees and shrubs become a single species of tree.
    • mx_grave … A grave in the open field, with a corpse and some everyday loot.
    • mx_helicopter … Metal wreckage and some items.
    • mx_jabberwock … A chance of a jabberwock.
    • mx_looters … Up to 5 bandits spawn in the building.
    • mx_marloss_pilgrimage A sect of people worshiping fungaloids.
    • mx_mayhem … Several types of road mayhem (firefights, crashed cars etc).
    • mx_military … Corpses and some military items.
    • mx_minefield … A military roadblock at the entry of the bridges with landmines scattered in the front of it.
    • mx_null … No special at all.
    • mx_pond … A small pond.
    • mx_portal_in … Another portal to neither space.
    • mx_portal … Portal to neither space, with several types of surrounding environment.
    • mx_roadblock … Roadblock furniture with turrets and some cars.
    • mx_roadworks … Partially closed damaged road with chance of work equipment and utility vehicles.
    • mx_science … Corpses and some scientist items.
    • mx_shia … A chance of Shia, if Crazy Catalcysm is enabled.
    • mx_shrubbery … All trees and shrubs become a single species of shrub.
    • mx_spider … A big spider web, complete with spiders and eggs.
    • mx_supplydrop … Crates with some military items in it.

    Material Phases

    • GAS
    • LIQUID
    • NULL
    • PLASMA
    • SOLID

    Melee

    Flags

    • ALWAYS_TWOHAND Item is always wielded with two hands. Without this, the items volume and weight are used to calculate this.
    • DIAMOND Diamond coating adds 30% bonus to cutting and piercing damage
    • MESSY Creates more mess when pulping
    • NO_CVD Item can never be used with a CVD machine
    • NO_RELOAD Item can never be reloaded (even if has a valid ammo type).
    • NO_UNWIELD Cannot unwield this item.
    • POLEARM Item is clumsy up close and does 70% of normal damage against adjacent targets. Should be paired with REACH_ATTACK. Simple reach piercing weapons like spears should not get this flag.
    • REACH_ATTACK Allows to perform reach attack.
    • SHEATH_KNIFE Item can be sheathed in a knife sheath, it applicable to small/medium knives (with volume not bigger than 2)
    • SHEATH_SWORD Item can be sheathed in a sword scabbard
    • SPEAR When making reach attacks intervening THIN_OBSTACLE terrain is not an obstacle. Should be paired with REACH_ATTACK.
    • STAB A legacy flag that converts an weapon’s damage type into pierce. This is a hack as we cannot use the damage object used by ammo to specify the damage type of melee weapon.
    • UNARMED_WEAPON Wielding this item still counts as unarmed combat.
    • WHIP Has a chance of disarming the opponent.
    • FLAMING Deals a random amount of fire damage on hit
    • SHOCKING Deals a random amount of electric damage on hit
    • ACIDIC Deals a random amount of acid damage on hit

    Monster Groups

    The condition flags limit when monsters can spawn.

    Seasons

    Multiple season conditions will be combined together so that any of those conditions become valid time of year spawn times.

    • AUTUMN
    • SPRING
    • SUMMER
    • WINTER

    Time of day

    Multiple time of day conditions will be combined together so that any of those conditions become valid time of day spawn times.

    • DAWN
    • DAY
    • DUSK
    • NIGHT

    Monsters

    Flags used to describe monsters and define their properties and abilities.

    Anger, Fear and Placation Triggers

    • FIRE There’s a fire nearby.
    • FRIEND_ATTACKED A monster of the same type was attacked. Always triggers character aggro.
    • FRIEND_DIED A monster of the same type died. Always triggers character aggro.
    • HURT The monster is hurt. Always triggers character aggro.
    • MEAT Meat or a corpse is nearby.
    • NULL Source use only?
    • PLAYER_CLOSE The player gets within a few tiles distance. Triggers character aggro <anger>% of the time.
    • PLAYER_WEAK The player is hurt.
    • SOUND Heard a sound.
    • STALK Increases when following the player.

    Categories

    • CLASSIC Only monsters we expect in a classic zombie movie.
    • NULL No category.
    • WILDLIFE Natural animals.

    Death Functions

    Multiple death functions can be used. Not all combinations make sense.

    • ACID Acid instead of a body. Not the same as the ACID_BLOOD flag. In most cases you want both.
    • AMIGARA Removes hypnosis if the last one.
    • BLOBSPLIT Creates more blobs.
    • BOOMER_GLOW Explodes in glowing vomit.
    • BOOMER Explodes in vomit.
    • BRAINBLOB Spawns 2 blobs.
    • BROKEN_AMMO Gives a message about destroying ammo and then calls “BROKEN”.
    • BROKEN Spawns a broken robot item, its id calculated like this: the prefix “mon_” is removed from the monster id, then the prefix “broken_” is added. Example: mon_eyebot -> broken_eyebot.
    • CONFLAGRATION Explode in a huge fireball.
    • DARKMAN Sight returns to normal.
    • DETONATE Self destructs.
    • DISAPPEAR Hallucination disappears.
    • DISINTEGRATE Falls apart.
    • EXPLODE Damaging explosion.
    • FIREBALL 10 percent chance to explode in a fireball.
    • FOCUSEDBEAM Blinding ray.
    • FUNGALBURST Explode with a cloud of fungal haze.
    • FUNGUS Explodes in spores.
    • GAMEOVER Game over man! Game over! Defense mode.
    • GAS Explodes in toxic gas.
    • GUILT Moral penalty. There is also a flag with a similar effect.
    • JABBERWOCKY Snicker-snack!
    • JACKSON Reverts dancers.
    • KILL_BREATHERS All breathers die.
    • KILL_VINES Kill all nearby vines.
    • MELT Normal death, but melts.
    • NORMAL Drop a body, leave gibs.
    • PREG_ROACH Spawn some cockroach nymphs.
    • RATKING Cure verminitis.
    • SMOKEBURST Explode like a huge smoke bomb.
    • SPLATTER Explodes in gibs and chunks.
    • THING Turn into a full thing.
    • TRIFFID_HEART Destroys all roots.
    • VINE_CUT Kill adjacent vine if it’s cut.
    • WORM Spawns 2 half-worms.

    Flags

    • ABSORBS_SPLITS Consumes objects it moves over, and if it absorbs enough it will split into a copy.
    • ABSORBS Consumes objects it moves over. (Modders use this).
    • ACIDPROOF Immune to acid.
    • ACIDTRAIL Leaves a trail of acid.
    • ACID_BLOOD Makes monster bleed acid. Fun stuff! Does not automatically dissolve in a pool of acid on death.
    • ANIMAL Is an animal for purposes of the Animal Empathy trait.
    • AQUATIC Confined to water.
    • ARTHROPOD_BLOOD Forces monster to bleed hemolymph.
    • ATTACKMON Attacks other monsters.
    • BADVENOM Attack may severely poison the player.
    • BASHES Bashes down doors.
    • BILE_BLOOD Makes monster bleed bile.
    • BIOPROOF Makes monster immune to Bio damage (A damage type mostly used by magic mods)
    • COLDPROOF Makes monster immune to Cold damage (A damage type mostly used by magic mods)
    • COMBAT_MOUNT Makes pet able to approach combat without becoming immobile nor knocking the player off
    • DARKPROOF Makes monster immune to Dark damage (A damage type completely used by magic mods)
    • LIGHTPROOF Makes monster immune to Light damage (A damage type completely used by magic mods)
    • PSIPROOF Makes monster immune to Psionic damage (A damage type mostly used by magic mods)
    • BIRDFOOD Becomes friendly / tamed with bird food.
    • BLEED Causes the player to bleed.
    • BONES May produce bones and sinews when butchered.
    • BORES Tunnels through just about anything (15x bash multiplier: dark wyrms’ bash skill 12->180)
    • CAN_BE_ORDERED This creature can be directed to not attack enemies, if friendly.
    • CAN_DIG Can dig and walk.
    • CAN_OPEN_DOORS Can open doors on its path.
    • CANPLAY This creature can be played with if it’s a pet.
    • CANT_TRAIN This creature cannot be trained for combat
    • CATFOOD Becomes friendly / tamed with cat food.
    • CATTLEFODDER Becomes friendly / tamed with cattle fodder.
    • CBM_CIV May produce a common CBM a power CBM when butchered.
    • CBM_OP May produce a CBM or two from ‘bionics_op’ item group when butchered.
    • CBM_POWER May produce a power CBM when butchered, independent of CBM.
    • CBM_SCI May produce a CBM from ‘bionics_sci’ item group when butchered.
    • CBM_SUBS May produce a CBM or two from bionics_subs and a power CBM when butchered.
    • CBM_TECH May produce a CBM or two from ‘bionics_tech’ item group and a power CBM when butchered.
    • CHITIN May produce chitin when butchered.
    • CLIMBS Can climb.
    • CURRENT this water is flowing.
    • DESTROYS Bashes down walls and more. (2.5x bash multiplier, where base is the critter’s max melee bashing)
    • DIGS Digs through the ground.
    • DOGFOOD Becomes friendly / tamed with dog food.
    • DRIPS_GASOLINE Occasionally drips gasoline on move.
    • DRIPS_NAPALM Occasionally drips napalm on move.
    • ELECTRIC Shocks unarmed attackers.
    • ELECTRONIC e.g. A Robot; affected by emp blasts and other stuff.
    • FAT May produce fat when butchered.
    • FEATHER May produce feathers when butchered.
    • FIREPROOF Immune to fire.
    • FIREY Burns stuff and is immune to fire.
    • FISHABLE It is fishable.
    • FLAMMABLE Monster catches fire, burns, and spreads fire to nearby objects.
    • FLIES Can fly (over water, etc.)
    • FUR May produce fur when butchered.
    • GOODHEARING Pursues sounds more than most monsters.
    • GRABS Its attacks may grab you!
    • GROUP_BASH Gets help from monsters around it when bashing.
    • GROUP_MORALE More courageous when near friends.
    • GUILT You feel guilty for killing it.
    • HARDTOSHOOT It’s one size smaller for ranged attacks, no less then MS_TINY. Ammo with the WIDE, SHOT, or BOUNCE ammo effects will negate this.
    • HEARS It can hear you.
    • HIT_AND_RUN Flee for several turns after a melee attack.
    • HUMAN It’s a live human, as long as it’s alive.
    • MF_CARD_OVERRIDE Not a mech, but can be converted to friendly using an ID card in the same way that mechs can.
    • CONSOLE_DESPAWN Despawns when a nearby console is properly hacked.
    • IMMOBILE Doesn’t move & doesn’t use non-special attacks (e.g. turrets)
    • STATIONARY Stationary, but will fight back (e.g. training dummies )
    • ID_CARD_DESPAWN Despawns when a science ID card is used on a nearby console
    • INTERIOR_AMMO Monster contains ammo inside itself, no need to load on launch. Prevents ammo from being dropped on disable.
    • IRRADIATED Melee attacks from the monster will irradiate targets. Scales with how much damage the attack would deal before armor. Radiation-resistant gear only protects against this if the attack dealt zero damage, otherwise bypasses protection outright.
    • KEENNOSE Keen sense of smell.
    • LARVA Creature is a larva. Currently used for gib and blood handling.
    • LEATHER May produce leather when butchered.
    • LOUDMOVES Mkes move noises as if ~2 sizes louder, even if flying.
    • MECH_RECON_VISION This mech grants you night-vision and enhanced overmap sight radius when piloted.
    • MECH_DEFENSIVE This mech can protect you thoroughly when piloted.
    • MILITARY_MECH Will demand a military ID card instead of an industrial one. Doesn’t actually have to be a mech.
    • MILKABLE Produces milk when milked.
    • NIGHT_INVISIBILITY Monster becomes invisible if it’s more than one tile away and the lighting on its tile is LL_LOW or less. Visibility is not affected by night vision.
    • CAMOUFLAGE Monster becomes invisible at a range greater than the player’s current perception + half of survival skill rounded down.
    • UNCANNY_DODGE Monster is able to uncanny dodge.
    • NOGIB Does not leave gibs / meat chunks when killed with huge damage.
    • NOHEAD Headshots not allowed!
    • NO_BREATHE Creature can’t drown and is unharmed by gas, smoke or poison.
    • NO_BREED Creature doesn’t reproduce even though it has reproduction data - useful when using copy-from to make child versions of adult creatures
    • NO_FUNG_DMG Creature is immune to fungal spores and can’t be fungalized.
    • NO_VEHICLE_COLLISION Vehicles pass through the monster without hitting or damaging it.
    • PAY_BOT Creature can be turned into a pet for a limited time in exchange of e-money.
    • PET_MOUNTABLE Creature can be ridden or attached to an harness.
    • PET_HARNESSABLECreature can be attached to an harness.
    • POLICE_EYEBOT Changes the behavior of the PHOTOGRAPH special attack. Without it, the attack will only do anything if the user is friendly, with it non-friendly bots can summon reinforcements.
    • MOUNTABLE_STAIRS Player can go up/down stairs while riding this creature.
    • MOUNTABLE_LADDER Player can go up/down stairs that have the difficult_z flag while riding this creature.
    • MOUNTABLE_OBSTACLES Player can travel over fences/doors while riding this creature.
    • MOUNTABLE_DOORS Player can open/close doors while riding this creature.
    • MOUNTABLE_LEDGE Player can jump down ledges while riding this creature.
    • NULL Source use only.
    • PACIFIST That monster will never do melee attacks.
    • KEEP_DISTANCE Monster will try to keep tracking_distance number of tiles between it and its current target.
    • PARALYZE Attack may paralyze the player with venom.
    • PLASTIC Reduces Bashing damage taken by 50%, 66% or 75%. Randomly selected with each hit.
    • POISON Poisonous to eat.
    • PUSH_MON Can push creatures out of its way.
    • QUEEN When it dies, local populations start to die off too.
    • REVIVES Monster corpse will revive after a short period of time.
    • RIDEABLE_MECH This monster is a mech suit that can be piloted.
    • SEES It can see you (and will run/follow).
    • SHEARABLE This monster can be sheared for wool.
    • SLUDGEPROOF Ignores the effect of sludge trails.
    • SLUDGETRAIL Causes the monster to leave a sludge trap trail when moving.
    • SMELLS It can smell you.
    • STUMBLES Stumbles in its movement.
    • SUNDEATH Dies in full sunlight.
    • SWARMS Groups together and form loose packs.
    • SWIMS Treats water as 50 movement point terrain.
    • VENOM Attack may poison the player.
    • VERMIN Obsolete flag for inconsequential monsters, now prevents loading.
    • VOLATILE Hitting this with fire damage always ignites it and has a high chance to deal massive damage, bullet and electric damage also have a chance to deal increased damage and set this monster on fire.
    • FACTION_MEMORY Calculate anger against factions separately, so that anger against one faction (e.g zombie) doesn’t spill into another (e.g player). In other words, truly neutral towards players until attacked. Use case: making extremely dangerous monsters spawned in streets to prevent crushing newbie players into pulp.
    • WARM Warm blooded.
    • WEBWALK Doesn’t destroy webs.
    • WOOL May produce wool when butchered.

    Monster Defense and Attacks

    • ACIDSPLASH Splash acid on the attacker.
    • NONE No special attack-back.
    • RETURN_FIRE Blind fire on unseen attacker.
    • REVENGE_AGGRO Make allies aggro on target.
    • ZAPBACK Shock attacker on hit.

    Sizes

    • HUGE Tank
    • LARGE Cow
    • MEDIUM Human
    • SMALL Dog
    • TINY Squirrel

    Special attacks

    Some special attacks are also valid use actions for tools and weapons. See monsters.json for examples on how to use these attacks. Also see monster_attacks.json for more special attacks, for example, impale and scratch.

    • ACID_ACCURATE Shoots acid that is accurate at long ranges, but less so up close.
    • ACID_BARF Barfs corroding, blinding acid.
    • ACID Spit acid.
    • ANTQUEEN Hatches/grows: egg > ant > soldier.
    • BIO_OP_BIOJUTSU Attack with a random special martial art maneuver.
    • BIO_OP_TAKEDOWN Attack with special martial art takedown maneuver.
    • BIO_OP_DISARM Attack with a special martial art disarm maneuver.
    • BIO_OP_IMPALE Attack with a strong martial art maneuver.
    • BITE Bite attack that can cause deep infected wounds.
    • BMG_TUR Barrett .50BMG rifle fires.
    • BOOMER_GLOW Spit glowing bile.
    • BOOMER Spit bile.
    • BRANDISH Brandish a knife at the player.
    • BREATHE Spawns a breather
    • CALLBLOBS Calls 2/3 of nearby blobs to defend this monster, and sends 1/3 of nearby blobs after the player.
    • CHICKENBOT LEGACY - Robot can attack with tazer, M4, or MGL depending on distance.
    • COPBOT Cop-bot alerts and then tazes the player.
    • DANCE Monster dances.
    • DARKMAN Can cause darkness and wraiths to spawn.
    • DERMATIK_GROWTH Dermatik larva grows into an adult.
    • DERMATIK Attempts to lay dermatik eggs in the player.
    • DISAPPEAR Hallucination disappears.
    • DOGTHING The dog thing spawns into a tentacle dog.
    • FEAR_PARALYZE Paralyze the player with fear.
    • FLAMETHROWER Shoots a stream of fire.
    • FLESH_GOLEM Attack the player with claw, and inflict disease downed if the attack connects.
    • FORMBLOB Spawns blobs?
    • FRAG_TUR MGL fires frag rounds.
    • FUNGUS_BIG_BLOSSOM Spreads fire suppressing fungal haze.
    • FUNGUS_BRISTLE Perform barbed tendril attack that can cause fungal infections.
    • FUNGUS_CORPORATE Used solely by Crazy Cataclysm. This will cause runtime errors if used without out, and spawns SpOreos on top of the creature.
    • FUNGUS_FORTIFY Grows Fungal hedgerows, and advances player on the mycus threshold path.
    • FUNGUS_GROWTH Grows a young fungaloid into an adult.
    • FUNGUS_HAZE Spawns fungal fields.
    • FUNGUS_INJECT Perform needle attack that can cause fungal infections.
    • FUNGUS_SPROUT Grows a fungal wall.
    • FUNGUS Releases fungal spores and attempts to infect the player.
    • GENERATOR Regenerates health.
    • GENE_STING Shoot a dart at the player that causes a mutation if it connects.
    • GRAB GRAB the target, and drag it around.
    • GRAB Grabs the player, slowing on hit, making movement and dodging impossible and blocking harder.
    • GROWPLANTS Spawns underbrush, or promotes it to > young tree > tree.
    • GROW_VINE Grows creeper vines.
    • HOWL “an ear-piercing howl!”
    • JACKSON Converts zombies into zombie dancers.
    • LASER Laser turret fires.
    • LEAP leap away to an unobstructed tile.
    • LONGSWIPE Does high damage claw attack, which can even hit some distance away.
    • LUNGE Perform a jumping attack from some distance away, which can down the target.
    • MULTI_ROBOT Robot can attack with tazer, flamethrower, M4, MGL, or 120mm cannon depending on distance.
    • NONE No special attack.
    • PARA_STING Shoot a paralyzing dart at the player.
    • PARROT Parrots the speech defined in speech.json, picks one of the lines randomly. “speaker” points to a monster id.
    • PARROT_AT_DANGER Performs the same function as PARROT, but only if the creature sees an angry monster from a hostile faction.
    • PAID_BOT For creature with PAY_BOT flag, removes the ally status when the pet effect runs out.
    • PHOTOGRAPH If friendly, scans the surrounding area to mark targets for the player. If non-friendly, photographs the player and summons reinforcements if user has the POLICE_EYEBOT flag, otherwise no effect.
    • PLANT Fungal spores take seed and grow into a fungaloid.
    • PULL_METAL_WEAPON Pull weapon that’s made of iron or steel from the player’s hand.
    • RANGED_PULL Pull targets towards attacker.
    • RATKING Inflicts disease rat
    • RATTLE “a sibilant rattling sound!”
    • RESURRECT Revives the dead–again.
    • RIFLE_TUR Rifle turret fires.
    • RIOTBOT Sprays teargas or relaxation gas, can handcuff players, and can use a blinding flash.
    • SCIENCE Various science/technology related attacks (e.g. manhacks, radioactive beams, etc.)
    • SEARCHLIGHT Tracks targets with a searchlight.
    • SHOCKING_REVEAL Shoots bolts of lightning, and reveals a SHOCKING FACT! Very fourth-wall breaking. Used solely by Crazy Cataclysm.
    • SHOCKSTORM Shoots bolts of lightning.
    • SHRIEK_ALERT “a very terrible shriek!”
    • SHRIEK_STUN “a stunning shriek!”, causes a small bash, can cause a stun.
    • SHRIEK “a terrible shriek!”
    • SLIMESPRING Can provide a morale boost to the player, and cure bite and bleed effects.
    • SMASH Smashes the target for massive damage, sending it flying for a number of tiles equal to ("melee_dice" * "melee_dice_sides" * 3) / 10.
    • SMG SMG turret fires.
    • SPIT_SAP Spit sap.
    • STARE Stare at the player and inflict teleglow.
    • STRETCH_ATTACK Long ranged piercing attack.
    • STRETCH_BITE Long ranged bite attack.
    • SUICIDE Dies after attacking.
    • TAZER Shock the player.
    • TENTACLE Lashes a tentacle at the player.
    • TRIFFID_GROWTH Young triffid grows into an adult.
    • TRIFFID_HEARTBEAT Grows and crumbles root walls around the player, and spawns more monsters.
    • UPGRADE Upgrades a regular zombie into a special zombie.
    • VINE Attacks with vine.
    • VORTEX Forms a vortex/tornado that causes damage and throws creatures around.

    Mutations

    Mutation Flags

    Mutation flags use a different JSON type from other flags, see json/flags_mutation.json. Primary difference is that conflicts and requires are the only additional properties that can be added to them.

    The following show all trait flags that are currently used by the game’s code. Trait flags must also be defined in JSON if they are to be used in NPC dialogue conditions.

    • CANNIBAL No morale penalty from butchering human corpses, converts negative morale of books with the BOOK_CANNIBAL flag into positive, skips warning you about human meat. NOTE: this only skips the warning, the actual morale effects of eating human flesh still require one of the relevant traits. Custom traits with this flag will skip the warning and suffer the morale penalty.
    • NEED_ACTIVE_TO_MELEE A mutation with this flag will only provide unarmed bonuses if it’s been toggled on.
    • NO_RADIATION This mutation grants immunity to radiations.
    • NO_THIRST Your thirst is not modified by food or drinks.
    • NON_THRESH Mutations with this flag will not count towards the mutation strength (and thus ability to breach a mutation threshold) of any categories it counts as belonging to.
    • PRED1 Reduces morale impact of enzlaving zombie corpses, reduces morale impact of killing monsters with the GUILT flag.
    • PRED2 Increases EXP gain from combat, negates skill rust of combat skills (if skill rust is enabled), reduces morale impact of enzlaving zombie corpses, reduces morale impact of killing monsters with the GUILT flag.
    • PRED3 Increases EXP gain from combat, negates skill rust of combat skills (if skill rust is enabled), increases tolerance for enzlaving zombies while already depressed, negates morale impact of killing monsters with the GUILT flag.
    • PRED4 Increases EXP gain from combat, prevents EXP gain from combat from affecting focus, negates skill rust of combat skills (if skill rust is enabled), negates morale impact of enzlaving zombie corpses, increases tolerance for enzlaving zombies while already depressed, negates morale impact of killing monsters with the GUILT flag.
    • PSYCHOPATH No morale penalty from butchering human corpses, converts negative morale of books with the BOOK_CANNIBAL and MORBID flags into positive.
    • SAPIVORE No morale penalty from butcheing human corpses, converts negative morale of books with the BOOK_CANNIBAL flag into positive.
    • SILENT_SPELL Negates the negative impact of mouth encumbrance on spells with the VERBAL flag.
    • SPIRITUAL Grants bonus morale from reading books with the INSPIRATIONAL flag, converting to positive if negative.
    • SUBTLE_SPELL Negates the negative impact of arm encumbrance on spells with the SOMATIC flag.
    • UNARMED_BONUS You get a bonus to unarmed bash and cut damage equal to unarmed_skill/2 up to 4.
    • MUTATION_FLIGHT Grants flight for the user, in exchange for the specified cost.
    • FLIGHT_ALWAYS_ACTIVE Grants flight for the user, all the time.

    Categories

    These branches are also the valid entries for the categories of dreams in dreams.json

    • MUTCAT_ALPHA “You feel…better. Somehow.”
    • MUTCAT_BEAST “Your heart races and you see blood for a moment.”
    • MUTCAT_BIRD “Your body lightens and you long for the sky.”
    • MUTCAT_CATTLE “Your mind and body slow down. You feel peaceful.”
    • MUTCAT_CEPHALOPOD “Your mind is overcome by images of eldritch horrors…and then they pass.”
    • MUTCAT_CHIMERA “You need to roar, bask, bite, and flap. NOW.”
    • MUTCAT_ELFA “Nature is becoming one with you…”
    • MUTCAT_FISH “You are overcome by an overwhelming longing for the ocean.”
    • MUTCAT_INSECT “You hear buzzing, and feel your body harden.”
    • MUTCAT_LIZARD “For a heartbeat, your body cools down.”
    • MUTCAT_MEDICAL “Your can feel the blood rushing through your veins and a strange, medicated feeling washes over your senses.”
    • MUTCAT_PLANT “You feel much closer to nature.”
    • MUTCAT_RAPTOR “Mmm…sweet bloody flavor…tastes like victory.”
    • MUTCAT_RAT “You feel a momentary nausea.”
    • MUTCAT_SLIME “Your body loses all rigidity for a moment.”
    • MUTCAT_SPIDER “You feel insidious.”
    • MUTCAT_TROGLOBITE “You yearn for a cool, dark place to hide.”

    Overmap

    Overmap connections

    • ORTHOGONAL The connection generally prefers straight lines, avoids turning wherever possible.

    Overmap specials

    Flags

    • BEE Location is related to bees. Used to classify location.
    • BLOB Location should “blob” outward from the defined location with a chance to be placed in adjacent locations.
    • CLASSIC Location is allowed when classic zombies are enabled.
    • FUNGAL Location is related to fungi. Used to classify location.
    • TRIFFID Location is related to triffids. Used to classify location.
    • LAKE Location is is placed on a lake and will be ignored for placement if the overmap doesn’t contain any lake terrain.
    • RIVER Location is is placed on a lake and will be ignored for placement if the overmap doesn’t contain any lake terrain.
    • UNIQUE Location is unique and will only occur once per overmap. occurrences is overridden to define a percent chance (e.g. "occurrences" : [75, 100] is 75%)
    • ENDGAME Location will have highest priority during special placement, and won’t be affected by any occurrences normalizations.
    • RESTRICTED Location will never be spawned as starting locations. Intended(but not limited) to use with incomplete nested specials.

    Overmap terrains

    Flags

    • KNOWN_DOWN There’s a known way down.
    • KNOWN_UP There’s a known way up.
    • LINEAR For roads etc, which use ID_straight, ID_curved, ID_tee, ID_four_way.
    • NO_ROTATE The terrain can’t be rotated (ID_north, ID_east, ID_south, and ID_west instances will NOT be generated, just ID).
    • RIVER It’s a river tile.
    • SIDEWALK Has sidewalks on the sides adjacent to roads.
    • IGNORE_ROTATION_FOR_ADJACENCY When mapgen for this OMT performs neighbour checks, the directions will be treated as absolute, rather than rotated to account for the rotation of the mapgen itself. Probably only useful for hardcoded mapgen.
    • LAKE Consider this location to be a valid lake terrain for mapgen purposes.
    • LAKE_SHORE Consider this location to be a valid lake shore terrain for mapgen purposes.
    • SOURCE_FUEL For NPC AI, this location may contain fuel for looting.
    • SOURCE_FOOD For NPC AI, this location may contain food for looting.
    • SOURCE_FARMING For NPC AI, this location may contain useful farming supplies for looting.
    • SOURCE_FABRICATION For NPC AI, this location may contain fabrication tools and components for looting.
    • SOURCE_GUN For NPC AI, this location may contain guns for looting.
    • SOURCE_AMMO For NPC AI, this location may contain ammo for looting.
    • SOURCE_BOOKS For NPC AI, this location may contain books for looting.
    • SOURCE_WEAPON For NPC AI, this location may contain weapons for looting.
    • SOURCE_FORAGE For NPC AI, this location may contain plants to forage.
    • SOURCE_COOKING For NPC AI, this location may contain useful tools and ingredients to aid in cooking.
    • SOURCE_TAILORING For NPC AI, this location may contain useful tools for tailoring.
    • SOURCE_DRINK For NPC AI, this location may contain drink for looting.
    • SOURCE_VEHICLES For NPC AI, this location may contain vehicles/parts/vehicle tools, to loot.
    • SOURCE_ELECTRONICS For NPC AI, this location may contain useful electronics to loot.
    • SOURCE_CONSTRUCTION For NPC AI, this location may contain useful tools/components for construction.
    • SOURCE_CHEMISTRY For NPC AI, this location may contain useful chemistry tools/components.
    • SOURCE_CLOTHING For NPC AI, this location may contain useful clothing to loot.
    • SOURCE_SAFETY For NPC AI, this location may be safe/sheltered and a good place for a base.
    • SOURCE_ANIMALS For NPC AI, this location may contain useful animals for farming/riding.
    • SOURCE_MEDICINE For NPC AI, this location may contain useful medicines for looting.
    • SOURCE_LUXURY For NPC AI, this location may contain valuable/feel-good items to sell/keep.
    • SOURCE_PEOPLE For NPC AI, this location may have other survivors.
    • RISK_HIGH For NPC AI, this location has a high risk associated with it - labs/superstores etc.
    • RISK_LOW For NPC AI, this location is secluded and remote, and appears to be safe.
    • GENERIC_LOOT This is a place that may contain any of the above, but at a lower frequency - usually a house.
    • IS_BRIDGE Will be expanded to a bridge in mapgen, terrains with the id of this object followed by _under, _road, head_ground and head_ramp must be defined, and _center_under may also be defined.

    Mapgen

    Flags

    • ERASE_ALL_BEFORE_PLACING_TERRAIN In the name, removes vehicles fields furniture and items before placing terrain down

    Recipes

    Categories

    • CC_AMMO
    • CC_ARMOR
    • CC_CHEM
    • CC_DRINK
    • CC_ELECTRONIC
    • CC_FOOD
    • CC_MISC
    • CC_WEAPON

    Flags

    • ALLOW_ROTTEN Explicitly allow rotten components when crafting non-perishables.
    • BLIND_EASY Easy to craft with little to no light.
    • BLIND_HARD Possible to craft with little to no light, but difficult.
    • SECRET Not automatically learned at character creation time based on high skill levels.
    • UNCRAFT_LIQUIDS_CONTAINED Spawn liquid items in its default container.
    • FULL_MAGAZINE If this recipe requires magazines, it needs one that is full. For deconstruction recipes, it will spawn a full magazine when deconstructed.

    Scenarios

    Flags

    • ALLOW_OUTSIDE Allows placing player outside of building, useful for outdoor start.
    • BAD_DAY Player starts the game drunk, depressed and sick with the flu.
    • BOARDED Start in boarded building (windows and doors are boarded, movable furniture is moved to windows and doors).
    • BORDERED Initial start location is bordered by an enormous wall of solid rock.
    • CHALLENGE Game won’t choose this scenario in random game types.
    • CITY_START Scenario is available only when city size value in world options is more than 0.
    • FIRE_START Player starts the game with fire nearby.
    • HELI_CRASH Player starts the game with various limbs wounds.
    • INFECTED Player starts the game infected.
    • LONE_START If starting NPC spawn option is switched to “Scenario-based”, this scenario won’t spawn a fellow NPC on game start.
    • SCEN_ONLY Profession can be chosen only as part of the appropriate scenario.
    • VEH_GROUNDED Profession vehicle is forced to be on the ground even if it can float

    Season Flags

    • AUT_START … start in autumn.
    • SPR_START … start in spring.
    • SUM_ADV_START … start second summer after Cataclysm.
    • SUM_START … start in summer.
    • WIN_START … start in winter.

    Skills

    Tags

    • combat_skill The skill is considered a combat skill. It’s affected by “PACIFIST”, “PRED1”, “PRED2”, “PRED3”, and “PRED4” traits.
    • contextual_skill The skill is abstract, it depends on context (an indirect item to which it’s applied). Neither player nor NPCs can possess it.
    • unaffected_by_focus Exercising this skill does not drain focus, and conversely focus does not affect how fast this skill levels up (positively OR negatively).
    • weapon_skill Used by NPCs to decide what class of weapon they should generate with.

    Techniques

    Techniques may be used by tools, armors, weapons and anything else that can be wielded.

    • See contents of data/json/techniques.json.
    • Techniques are also used with martial arts styles, see data/json/martialarts.json.

    WBLOCK_X

    The following weapon techniques have some additional usage. These are defensive techniques that allow the item to assist in blocking attacks in melee, with some additional special uses.

    • WBLOCK_1 “Medium blocking ability”
    • WBLOCK_2 “High blocking ability”
    • WBLOCK_3 “Very high blocking ability”

    An item with one of these techniques can be wielded to provide a bonus to damage reduced by blocking compared, or armor with the BLOCK_WHILE_WORN flag can also provide the use of this bonus while wearing the item, serving as a shield. Additionally, wielding or wearing an item with a combination of one of these techniques plus said flag will allow the item to block projectiles aimed at body parts the item otherwise does not cover (or is not covering, in the case of wielded items that meet those prerequisites). The chance that this will happen is based on the coverage percentage of the item used for its normal armor value, reduced by a penalty that depends on which blocking technique it possesses. The chance of it intercepting shots that strike the legs (again, unless the armor was set to cover the legs by default already, in which case it uses coverage as normal) is furtther penalized. The feet will always be vulnerable unless (for whatever reason a JSON author may devise, forcefield items for example) an item happens to be a shield that already covers the feet as armor.

    TechniqueChance to intercept (head, torso, opposing arm, etc)Chance to intercept (legs)
    WBLOCK_190% of default coverage value75% of default coverage value
    WBLOCK_290% of default coverage value75% of default coverage value
    WBLOCK_390% of default coverage value75% of default coverage value

    Tools

    Flags

    Melee flags are fully compatible with tool flags, and vice versa.

    • ACT_ON_RANGED_HIT The item should activate when thrown or fired, then immediately get processed if it spawns on the ground.
    • ALLOWS_REMOTE_USE This item can be activated or reloaded from adjacent tile without picking it up.
    • BELT_CLIP The item can be clipped or hooked on to a belt loop of the appropriate size (belt loops are limited by their max_volume and max_weight properties)
    • BOMB It can be a remote controlled bomb.
    • CABLE_SPOOL This item is a cable spool and must be processed as such. It has an internal “state” variable which may be in the states “attach_first” or “pay_out_cable” – in the latter case, set its charges to max_charges - dist(here, point(vars["source_x"], vars["source_y"])). If this results in 0 or a negative number, set its state back to “attach_first”.
    • CANNIBALISM The item is a food that contains human flesh, and applies all applicable effects when consumed.
    • CHARGEDIM If illuminated, light intensity fades with charge, starting at 20% charge left.
    • DIG_TOOL If wielded, digs thorough terrain like rock and walls, as player walks into them. If item also has POWERED flag, then it digs faster, but uses up the item’s ammo as if activating it.
    • FIRESTARTER Item will start fire with some difficulty.
    • FIRE Item will start a fire immediately.
    • FISH_GOOD When used for fishing, it’s a good tool (requires that the matching use_action has been set).
    • FISH_POOR When used for fishing, it’s a poor tool (requires that the matching use_action has been set).
    • HAS_RECIPE Used by the E-Ink tablet to indicates it’s currently showing a recipe.
    • IS_UPS Item is Unified Power Supply. Used in active item processing
    • LIGHT_[X] Illuminates the area with light intensity [X] where [X] is an intensity value. (e.x. LIGHT_4 or LIGHT_100). Note: this flags sets itype::light_emission field and then is removed (can’t be found using has_flag);
    • MC_MOBILE, MC_RANDOM_STUFF, MC_SCIENCE_STUFF, MC_USED, MC_HAS_DATA Memory card related flags, see iuse.cpp
    • NO_DROP Item should never exist on map tile as a discrete item (must be contained by another item)
    • NO_UNLOAD Cannot be unloaded.
    • POWERED If turned ON, item uses its own source of power, instead of relying on power of the user
    • RADIOCARITEM Item can be put into a remote controlled car.
    • RADIOSIGNAL_1 Activated per radios signal 1 (Red).
    • RADIOSIGNAL_2 Activated per radios signal 2 (Blue).
    • RADIOSIGNAL_3 Activated per radios signal 3 (Green).
    • RADIO_ACTIVATION Item can be activated by a remote control (also requires RADIOSIGNAL_*).
    • RADIO_INVOKE_PROC After being activated via radio signal the item will have its charges removed. Can be used for bypassing bomb countdown.
    • RADIO_CONTROLLABLE It can be moved around via a remote control.
    • RADIO_MODABLE Indicates the item can be made into a radio-activated item.
    • RADIO_MOD The item has been made into a radio-activated item.
    • RECHARGE Gain charges when placed in a cargo area with a recharge station.
    • SAFECRACK This item can be used to unlock safes.
    • USES_BIONIC_POWER The item has no charges of its own, and runs off of the player’s bionic power.
    • USE_UPS Item is charges from an UPS / it uses the charges of an UPS instead of its own.
    • NAT_UPS Silences the (UPS) suffix from USE_UPS.
    • WATER_EXTINGUISH Is extinguishable in water or under precipitation. Converts items (requires “reverts_to” or use_action “transform” to be set).
    • WATER_DISABLE Will revert and deactivate item if it is submerged in water.
    • WET Item is wet and will slowly dry off (e.g. towel).
    • WIND_EXTINGUISH This item will be extinguished by the wind.
    • WRITE_MESSAGE This item could be used to write messages on signs.

    Flags that apply to items

    These flags do not apply to item types.

    Those flags are added by the game code to specific items (that specific welder, not all welders).

    • COLD Item is cold (see EATEN_COLD).
    • DIRTY Item (liquid) was dropped on the ground and is now irreparably dirty.
    • FIELD_DRESS_FAILED Corpse was damaged by unskillful field dressing. Affects butcher results.
    • FIELD_DRESS Corpse was field dressed. Affects butcher results.
    • FIT Reduces encumbrance by one.
    • FROZEN Item is frozen solid (used by freezer).
    • HIDDEN_ITEM This item cannot be seen in AIM.
    • HOT Item is hot (see EATEN_HOT).
    • LITCIG Marks a lit smoking item (cigarette, joint etc.).
    • NO_PARASITES Invalidates parasites count set in food->type->comestible->parasites
    • QUARTERED Corpse was quartered into parts. Affects butcher results, weight, volume.
    • REVIVE_SPECIAL … Corpses revives when the player is nearby.
    • SPAWN_FRIENDLY Applied to eggs laid by pets and to pet bots reverted to items. Any monster that hatches from said egg will also spawn friendly, and deployable bots flagged with this will skip checking for player skills since it’s already been configured correctly once already.
    • SPAWN_HOSTILE place_monster items with this flag will always deploy a monster that’s always hostile, such as for a target dummy; Inverse of SPAWN_FRIENDLY
    • USE_UPS The tool has the UPS mod and is charged from an UPS.
    • WARM A hidden flag used to track an item’s journey to/from hot, buffers between HOT and cold.
    • WET Item is wet and will slowly dry off (e.g. towel).

    Vehicle Prototypes

    Flags

    • VEHICLE_HOTWIRE Marks a vehicle to always requiring hotwiring controls
    • VEHICLE_NO_HOTWIRE Marks a vehicle to never require hotwiring controls (e.g bycicles)
    • VEHICLE_UNLOCKED Marks a vehicle to always spawn unlocked, but possibly requiring hotwiring
    • VEHICLE_LOCKED Marks a vehicle to always spawn locked, and possibly requiring hotwiring
    • VEHICLE_NO_LOCKS Marks a vehicle to not get locks installed automatically

    Vehicle Parts

    Flags

    • ADVANCED_PLANTER This planter doesn’t spill seeds and avoids damaging itself on non-diggable surfaces.
    • AISLE_LIGHT
    • AISLE Player can move over this part with less speed penalty than normal.
    • ALTERNATOR Recharges batteries installed on the vehicle. Can only be installed on a part with E_ALTERNATOR flag.
    • ANCHOR_POINT Allows secure seatbelt attachment.
    • ANIMAL_CTRL Can harness an animal, need HARNESS_bodytype flag to specify bodytype of animal.
    • ARMOR Protects the other vehicle parts it’s installed over during collisions.
    • ATOMIC_LIGHT
    • AUTOCLAVE Acts as an autoclave.
    • AUTOPILOT This part will enable a vehicle to have a simple autopilot.
    • BALLOON Acts as a lifting balloon, requires the height field
    • BATTERY_MOUNT
    • BED A bed where the player can sleep.
    • BEEPER Generates noise when the vehicle moves backward.
    • BELTABLE Seatbelt can be attached to this part.
    • BIKE_RACK_VEH Can be used to merge an adjacent single tile wide vehicle, or split a single tile wide vehicle off into its own vehicle.
    • BOARDABLE The player can safely move over or stand on this part while the vehicle is moving.
    • CAMERA_CONTROL
    • CAMERA
    • CAPTURE_MOSNTER_VEH Can be used to capture monsters when mounted on a vehicle.
    • CARGO_LOCKING This cargo area is inaccessible to NPCs. Can only be installed on a part with LOCKABLE_CARGO flag.
    • DOOR_LOCKING This part is unopenable to non-faction NPCs and monsters if enabled from the electronics menu. Can only be installed on a part with OPENABLE flag.
    • CARGO Cargo holding area.
    • CHIMES Generates continuous noise when used.
    • CIRCLE_LIGHT Projects a circular radius of light when turned on.
    • CONE_LIGHT Projects a cone of light when turned on.
    • CONTROL_ANIMAL These controls can only be used to control a vehicle pulled by an animal (such as reins etc).
    • CONTROLS Can be used to control the vehicle.
    • COOLER There is separate command to toggle this part.
    • COVERED Prevents items in cargo parts from emitting any light.
    • CRAFTER Allows integrated tools to be defined under the “integrated_tools” list-field
    • CTRL_ELECTRONIC Controls electrical and electronic systems of the vehicle.
    • CONTROL_WITHOUT_HANDS Allows you to fire two-handed weapons while driving. Can only be installed on a part with STEERABLE flag.
    • CURTAIN Can be installed over a part flagged with WINDOW, and functions the same as blinds found on windows in buildings.
    • DIFFICULTY_REMOVE
    • DOME_LIGHT
    • DOOR_MOTOR Can only be installed on a part with OPENABLE flag.
    • DROPPER Allows cargo to be dropped out of the adjacent cargo space
    • E_ALTERNATOR Is an engine that can power an alternator.
    • E_COLD_START Is an engine that starts much slower in cold weather.
    • E_COMBUSTION Is an engine that burns its fuel and can backfire or explode when damaged.
    • E_HEATER Is an engine and has a heater to warm internal vehicle items when on.
    • E_HIGHER_SKILL Is an engine that is more difficult to install as more engines are installed.
    • E_NO_POWER_DECAY Engines with this flag do not affect total vehicle power suffering diminishing returns.
    • E_STARTS_INSTANTLY Is an engine that starts instantly, like food pedals.
    • EMITTER Emits while enabled (emissions are defined by emissions entry).
    • ENABLED_DRAINS_EPOWER Produces epower watts while enabled (use negative numbers to drain power). This is independent from reactor power production.
    • ENGINE Is an engine and contributes towards vehicle mechanical power.
    • EVENTURN Only on during even turns.
    • EXTENDABLE A protusion which can attach to other extendable protusions
    • EXTENDS_VISION Extends player vision (cameras, mirrors, etc.)
    • EXTRA_DRAG tells the vehicle that the part exerts engine power reduction if the part is enabled. The part needs to be set to permanently enabled in C++ or made able to be switched on in C++.
    • FAUCET
    • FLAT_SURF Part with a flat hard surface (e.g. table).
    • FLOATS Provide buoyancy to boats
    • FLUIDTANK Is a fluid tank.
    • FOLDABLE
    • FREEZER Can freeze items in below zero degrees Celsius temperature.
    • FRIDGE Can refrigerate items.
    • FUNNEL
    • HALF_CIRCLE_LIGHT Projects a directed half-circular radius of light when turned on.
    • HARNESS_bodytype Replace bodytype with any to accept any type, or with the targeted type.
    • HORN Generates noise when used.
    • HOTPLATE Gives the hotplate action.
    • INITIAL_PART When starting a new vehicle via the construction menu, this vehicle part will be the initial part of the vehicle (if the used item matches the item required for this part). The items of parts with this flag are automatically added as component to the vehicle start construction.
    • INTERNAL Can only be installed on a part with CARGO flag.
    • LADDER Ladder to get down from a flying vehicle
    • LIGHT
    • LOCKABLE_CARGO Cargo containers that are able to have a lock installed.
    • MOUNTABLE Player can fire mounted weapons from here.
    • MUFFLER Muffles the noise a vehicle makes while running.
    • MULTISQUARE Causes this part and any adjacent parts with the same ID to act as a singular part.
    • MUSCLE_ARMS Power of the engine with such flag depends on player’s strength (it’s less effective than MUSCLE_LEGS).
    • MUSCLE_LEGS Power of the engine with such flag depends on player’s strength.
    • NAILABLE Attached with nails
    • NEEDS_BATTERY_MOUNT
    • NEEDS_WHEEL_MOUNT_HEAVY Can only be installed on a part with WHEEL_MOUNT_HEAVY flag.
    • NEEDS_WHEEL_MOUNT_LIGHT Can only be installed on a part with WHEEL_MOUNT_LIGHT flag.
    • NEEDS_WHEEL_MOUNT_MEDIUM Can only be installed on a part with WHEEL_MOUNT_MEDIUM flag.
    • NEEDS_WINDOW Can only be installed on a part with WINDOW flag.
    • NO_JACK
    • NOCOLLIDE
    • NOCOLLIDEABOVE Feature that simply doesn’t collide when going up a z-level, or something goes down onto it, requires NOCOLLIDE.
    • NOCOLLIDEBELOW Feature that simply doesn’t collide when going down a z-level, or something goes up onto it, requires NOCOLLIDE.
    • NOSMASH
    • NOINSTALL Cannot be installed.
    • NOFIELDS Prevents fields ( smoke radiation etc ) from affecting anything on the same tile
    • NOREMOVE_SECURITY Cannot be uninstalled if the vehicle has a working security system.
    • NOREMOVE_OPEN Cannot be uninstalled if there’s an open OPENABLE part in the same tile.
    • NOREMOVE_CLOSED Cannot be uninstalled if there’s a closed OPENABLE part in the same tile.
    • NOREMOVE_INSIDE Cannot be uninstalled from inside the vehicle.
    • NOREMOVE_LOCKED Cannot be uninstalled if there’s an enabled DOOR_LOCKING part on the same tile.
    • NOREMOVE_OUTSIDE Cannot be uninstalled from outside the vehicle.
    • OBSTACLE Cannot walk through part, unless the part is also OPENABLE.
    • ODDTURN Only on during odd turns.
    • ON_CONTROLS Can only be installed on a part with CONTROLS flag.
    • ON_ROOF - Parts with this flag could only be installed on a roof (parts with ROOF flag).
    • OPAQUE Cannot be seen through.
    • OPENABLE Can be opened or closed.
    • OPENCLOSE_INSIDE Can be opened or closed, but only from inside the vehicle.
    • OVER Can be mounted over other parts.
    • PERPETUAL If paired with REACTOR, part produces electrical power without consuming fuel.
    • PLANTER Plants seeds into tilled dirt, spilling them when the terrain underneath is unsuitable. It is damaged by running it over non-DIGGABLE surfaces.
    • PLOW Tills the soil underneath the part while active. Takes damage from unsuitable terrain at a level proportional to the speed of the vehicle.
    • POWERED_BY_ENGINE tells the vehicle that the part exerts engine power reduction. Does not require the part to be enabled in C++.
    • POWER_TRANSFER Transmits power to and from an attached thingy (probably a vehicle).
    • PROPELLER Part that is a propeller rotor, needs propeller_diameter field
    • PROTRUSION Part sticks out so no other parts can be installed over it.
    • RAIL This wheel allows vehicle to move on rails.
    • REACTOR When enabled, part consumes fuel to generate epower.
    • REAPER Cuts down mature crops, depositing them on the square.
    • RECHARGE Recharge items with the same flag. ( Currently only the rechargeable battery mod. )
    • REMOTE_CONTROLS
    • REVERSIBLE Removal has identical requirements to installation but is twice as quick
    • ROOF Covers a section of the vehicle. Areas of the vehicle that have a roof and roofs on surrounding sections, are considered inside. Otherwise they’re outside.
    • ROTOR Allows vehicle to generate lift. Actual lift depends on engine power sum of all rotor’s diameters.
    • SCOOP Pulls items from underneath the vehicle to the cargo space of the part. Also mops up liquids.
    • SEAT A seat where the player can sit or sleep.
    • SEATBELT Helps prevent the player from being ejected from the vehicle during an accident. Can only be installed on a part with BELTABLE flag.
    • SEAT_REQUIRES_BALANCE The player may fall off once they run into something determined by a strength roll. TRAIT_DEFT and TRAIT_PROF_SKATER makes it harder to be thrown from vehicle.
    • SECURITY
    • SHARP Striking a monster with this part does cutting damage instead of bashing damage, and prevents stunning the monster.
    • SOLAR_PANEL Recharges vehicle batteries when exposed to sunlight. Has a 1 in 4 chance of being broken on car generation.
    • SPACE_HEATER There is separate command to toggle this part.
    • STABLE Similar to WHEEL, but if the vehicle is only a 1x1 section, this single wheel counts as enough wheels.
    • STEERABLE This wheel is steerable.
    • STEREO
    • TOOL_NONE Can be removed/installed without any tools
    • TOOL_SCREWDRIVER Attached with screws, can be removed/installed with a screwdriver
    • TOOL_WRENCH Attached with bolts, can be removed/installed with a wrench
    • TOWEL Can be used to dry yourself up.
    • TRACK Allows the vehicle installed on, to be marked and tracked on map.
    • TRACKED Contributes to steering effectiveness but doesn’t count as a steering axle for install difficulty and still contributes to drag for the center of steering calculation.
    • TRANSFORM_TERRAIN Transform terrain (using rules defined in transform_terrain).
    • TURRET_CONTROLS If part with this flag is installed over the turret, it allows to set said turret’s targeting mode to full auto. Can only be installed on a part with TURRET flag.
    • TURRET_MOUNT Parts with this flag are suitable for installing turrets.
    • TURRET Is a weapon turret. Can only be installed on a part with TURRET_MOUNT flag.
    • UNMOUNT_ON_DAMAGE Part breaks off the vehicle when destroyed by damage. Item is new and typically undamaged.
    • UNMOUNT_ON_MOVE Dismount this part when the vehicle moves. Doesn’t drop the part, unless you give it special handling.
    • VARIABLE_SIZE Has ‘bigness’ for power, wheel radius, etc.
    • VEHICLEPART_NO_LOCKS Doors with this flag won’t generate with locks installed on spawn. Players can still manually add locks to these parts during gameplay.
    • VISION
    • WATER_WHEEL Recharges vehicle batteries when in flowing water.
    • WELDRIG Gives the welding repair action
    • WHEEL Counts as a wheel in wheel calculations.
    • WIDE_CONE_LIGHT Projects a wide cone of light when turned on.
    • WIND_POWERED This engine is powered by wind ( sails etc ).
    • WIND_TURBINE Recharges vehicle batteries when exposed to wind.
    • WINDOW Can see through this part and can install curtains over it.
    • WING Part that is an aircraft wing, needs lift_coff field
    • WORKBENCH Can craft at this part, must be paired with a workbench json entry.

    Vehicle parts requiring other vehicle parts

    The requirement for other vehicle parts is defined for a json flag by setting requires_flag for the flag. requires_flag is the other flag that a part with this flag requires.

    Fuel types

    • NULL None
    • battery Electrifying.
    • diesel Refined dino.
    • gasoline Refined dino.
    • plasma Superheated.
    • plutonium 1.21 Gigawatts!
    • water Clean.
    • wind Wind powered.

    JSON INFO

    Note

    This document is being split into multiple pages.

    Caution

    Many of the JSON files are not documented yet or is outdated. Check relevent source files to be sure.

    This document describes the contents of the json files used in Cataclysm: Dark days ahead. You are probably reading this if you want to add or change content of Catacysm: Dark days ahead and need to learn more about what to find where and what each file and property does.

    A lot of the JSON involves cross-references to other JSON entities. To make it easier to navigate, we provide a script tools/json_tools/cddatags.py that can build a tags file for you.

    To run the script you’ll need Python 3. On Windows you’ll probably need to install that, and associate .py files with Python. Then open a command prompt, navigate to your CDDA folder, and run tools\json_tools\cddatags.py.

    To use this feature your editor will need ctags support. When that’s working you should be able to easily jump to the definition of any entity. For example, by positioning your cursor over an id and hitting the appropriate key combination.

    • In Vim, this feature exists by default, and you can jump to a definition using ^\].
    • In Notepad++ go to “Plugins” -> “Plugins Admin” and enable the “TagLEET” plugin. Then select any id and press Alt+Space to open the references window.

    The type Property

    Entries are distinguished by their type property. This property is mandatory for all entries. Setting this entry to ‘armor’ for example means the game will expect properties specific to armor in that entry. Also ties in with copy-from, if you want to inherit properties of another object, it must be of the same tipe.

    Formatting

    When editing JSON files make sure you apply the correct formatting as shown below.

    Time duration

    A string containing one or more pairs of number and time duration unit. Number and unit, as well as each pair, can be separated by an arbitrary amount of spaces. Available units:

    • “hours”, “hour”, “h” - one hour
    • “days”, “day”, “d” - one day
    • “minutes”, “minute”, “m” - one minute
    • “turns”, “turn”, “t” - one turn,

    Examples:

    • “ +1 day -23 hours 50m “ (1*24*60 - 23*60 + 50 == 110 minutes)
    • “1 turn 1 minutes 9 turns” (1 minute and 10 seconds because 1 turn is 1 second)

    Other formatting

    "//" : "comment", // Preferred method of leaving comments inside json files.
    

    The game also loads .jsonc files. Put // and /* */ comments and trailing commas in .jsonc files. If you format a .json file with the JSON formatter, you lose its comments.

    Some json strings are extracted for translation, for example item names, descriptions, etc. The exact extraction is handled in lang/extract_json_strings.py. Apart from the obvious way of writing a string without translation context, the string can also have an optional translation context (and sometimes a plural form), by writing it like:

    "name": { "ctxt": "foo", "str": "bar", "str_pl": "baz" }
    

    or, if the plural form is the same as the singular form:

    "name": { "ctxt": "foo", "str_sp": "foo" }
    

    You can also add comments for translators by adding a “//~” entry like below. The order of the entries does not matter.

    "name": {
        "//~": "as in 'foobar'",
        "str": "bar"
    }
    

    Currently, only some JSON values support this syntax.

    In a .jsonc file, you can also write a translator comment as a //~ line comment. Put it on the line before the string. Use more //~ lines for a longer comment.

    //~ as in 'foobar'
    "name": { "ctxt": "foo", "str": "bar" },
    //~ shown in the item info window
    "description": "A bar.",
    

    Description and content of each JSON file

    This section describes each json file and their contents. Each json has their own unique properties that are not shared with other Json files (for example ‘chapters’ property used in books does not apply to armor). This will make sure properties are only described and used within the context of the appropriate JSON file.

    data/json/ JSONs

    Ascii_arts

    IdentifierDescription
    idUnique ID. Must be one continuous word, use underscores if necessary.
    pictureArray of string, each entry is a line of an ascii picture and must be at most 42 columns long.
    {
      "type": "ascii_art",
      "id": "cashcard",
      "picture": [
        "",
        "",
        "",
        "       <color_white>╔═══════════════════╗",
        "       <color_white>║                   ║",
        "       <color_white>║</color> <color_yellow>╔═   ╔═╔═╗╔═║ ║</color>   <color_white>║",
        "       <color_white>║</color> <color_yellow>║═ ┼ ║ ║═║╚╗║═║</color>   <color_white>║",
        "       <color_white>║</color> <color_yellow>╚═   ╚═║ ║═╝║ ║</color>   <color_white>║",
        "       <color_white>║                   ║",
        "       <color_white>║   RIVTECH TRUST   ║",
        "       <color_white>║                   ║",
        "       <color_white>║                   ║",
        "       <color_white>║ 555 993 55221 066 ║",
        "       <color_white>╚═══════════════════╝"
      ]
    }
    

    Body_parts

    IdentifierDescription
    id(mandatory) Unique ID. Must be one continuous word, use underscores if necessary.
    name(mandatory) In-game name displayed.
    accusative(mandatory) Accusative form for this bodypart.
    heading(mandatory) How it’s displayed in headings.
    heading_multiple(optional) Plural form of heading. (default: heading value)
    hp_bar_ui_text(optional) How it’s displayed next to the hp bar in the panel. (default: empty string)
    encumbrance_text(optional) Description of effect when encumbered. (default: empty string)
    main_part(optional) What is the main part this one is attached to. (default: self)
    base_hp(optional) The amount of hp this part has before any modification. (default: 60)
    opposite_part(optional) What is the opposite part ot this one in case of a pair. (default: self)
    essential(optional) Whether the character dies if this part drops to 0 HP.
    hit_size(optional) Float. Size of the body part when doing an unweighted selection. (default: 0.)
    hit_size_relative(optional) Float. Hit sizes for attackers who are smaller, equal in size, and bigger. (default: [ 0, 0, 0 ]
    hit_difficulty(optional) Float. How hard is it to hit a given body part, assuming “owner” is hit. Higher number means good hits will veer towards this part, lower means this part is unlikely to be hit by inaccurate attacks. Formula is chance *= pow(hit_roll, hit_difficulty) (default: 0)
    side(optional) Which side this body part is on. Default both.
    stylish_bonus(optional) Mood bonus associated with wearing fancy clothing on this part. (default: 0)
    hot_morale_mod(optional) Mood effect of being too hot on this part. (default: 0)
    cold_morale_mod(optional) Mood effect of being too cold on this part. (default: 0)
    bionic_slots(optional) How many bionic slots does this part have.
    {
      "id": "torso",
      "type": "body_part",
      "name": "torso",
      "accusative": { "ctxt": "bodypart_accusative", "str": "torso" },
      "heading": "Torso",
      "heading_multiple": "Torso",
      "hp_bar_ui_text": "TORSO",
      "encumbrance_text": "Dodging and melee is hampered.",
      "main_part": "torso",
      "opposite_part": "torso",
      "hit_size": 45,
      "hit_size_relative": [20, 33.33, 36.57],
      "hit_difficulty": 1,
      "side": "both",
      "legacy_id": "TORSO",
      "stylish_bonus": 6,
      "hot_morale_mod": 2,
      "cold_morale_mod": 2,
      "base_hp": 60,
      "bionic_slots": 80
    }
    

    Dreams

    IdentifierDescription
    messagesList of potential dreams.
    categoryMutation category needed to dream.
    strengthMutation category strength required (1 = 20-34, 2 = 35-49, 3 = 50+).
    {
      "messages": [
        "You have a strange dream about birds.",
        "Your dreams give you a strange feathered feeling."
      ],
      "category": "MUTCAT_BIRD",
      "strength": 1
    }
    
    ### Item Category
    
    When you sort your inventory by category, these are the categories that are displayed.
    | Identifier      | Description
    |---              |---
    | id              | Unique ID. Must be one continuous word, use underscores if necessary
    | name            | The name of the category. This is what shows up in-game when you open the inventory.
    | zone            | The corresponding loot_zone (see loot_zones.json)
    | sort_rank       | Used to sort categories when displaying.  Lower values are shown first
    | priority_zones  | When set, items in this category will be sorted to the priority zone if the conditions are met. If the user does not have the priority zone in the zone manager, the items get sorted into zone set in the 'zone' property. It is a list of objects. Each object has 3 properties: ID: The id of a LOOT_ZONE (see LOOT_ZONES.json), filthy: boolean. setting this means filthy items of this category will be sorted to the priority zone, flags: array of flags
    |spawn_rate       | Sets amount of items from item category that might spawn.  Checks for `spawn_rate` value for item category.  If `spawn_chance` is less than 1.0, it will make a random roll (0.1-1.0) to check if the item will have a chance to spawn.  If `spawn_chance` is more than or equal to 1.0, it will add a chance to spawn additional items from the same category.  Items will be taken from item group which original item was located in.  Therefore this parameter won't affect chance to spawn additional items for items set to spawn solitary in mapgen (e.g. through use of `item` or `place_item`).
    
    ```C++
    {
      "id":"armor",
      "name": "ARMOR",
      "zone": "LOOT_ARMOR",
      "sort_rank": -21,
      "priority_zones": [ { "id": "LOOT_FARMOR", "filthy": true, "flags": [ "RAINPROOF" ] } ],
    }
    

    Disease

    IdentifierDescription
    idUnique ID. Must be one continuous word, use underscores if necessary.
    min_durationThe minimum duration the disease can last. Uses strings “x m”, “x s”,“x d”.
    max_durationThe maximum duration the disease can last.
    min_intensityThe minimum intensity of the effect applied by the disease
    max_intensityThe maximum intensity of the effect.
    health_thresholdThe amount of health above which one is immune to the disease. Must be between -200 and 200. (optional )
    symptomsThe effect applied by the disease.
    affected_bodypartsThe list of bodyparts on which the effect is applied. (optional, default to num_bp)
    {
      "type": "disease_type",
      "id": "bad_food",
      "min_duration": "6 m",
      "max_duration": "1 h",
      "min_intensity": 1,
      "max_intensity": 1,
      "affected_bodyparts": ["TORSO"],
      "health_threshold": 100,
      "symptoms": "foodpoison"
    }
    

    Names

    { "name" : "Aaliyah", "gender" : "female", "usage" : "given" }, // Name, gender, "given"/"family"/"city" (first/last/city name).
    

    Named Colors

    {
      "type": "named_color", // As you expect
      "name": "Cataclysm Red", // Name to display
      "value": "#622625" // Hex value of color
    }
    

    Scent_types

    IdentifierDescription
    idUnique ID. Must be one continuous word, use underscores if necessary.
    receptive_speciesSpecies able to track this scent. Must use valid ids defined in species.json
    {
      "type": "scent_type",
      "id": "sc_flower",
      "receptive_species": ["MAMMAL", "INSECT", "MOLLUSK", "BIRD"]
    }
    

    Scores and Achievements

    Scores are defined in two or three steps based on events. To see what events exist and what data they contain, read event.h.

    Each event contains a certain set of fields. Each field has a string key and a cata_variant value. The fields should provide all the relevant information about the event.

    For example, consider the gains_skill_level event. You can see this specification for it in event.h:

    template<>
    struct event_spec<event_type::gains_skill_level> {
        static constexpr std::array<std::pair<const char *, cata_variant_type>, 3> fields = {{
                { "character", cata_variant_type::character_id },
                { "skill", cata_variant_type::skill_id },
                { "new_level", cata_variant_type::int_ },
            }
        };
    };
    

    From this, you can see that this event type has three fields:

    • character, with the id of the character gaining the level.
    • skill, with the id of the skill gained.
    • new_level, with the integer level newly acquired in that skill.

    Events are generated by the game when in-game circumstances dictate. These events can be transformed and summarized in various ways. There are three concepts involved: event streams, event statistics, and scores.

    • Each event_type defined by the game generates an event stream.
    • Further event streams can be defined in json by applying an event_transformation to an existing event stream.
    • An event_statistic summarizes an event stream into a single value (usually a number, but other types of value are possible).
    • A score uses such a statistic to define an in-game score which players can see.

    event_transformation

    An event_transformation can modify an event stream, producing another event stream.

    The input stream to be transformed is specified either as an "event_type", to use one of the built-in event type streams, or an "event_transformation", to use another json-defined transformed event stream.

    Any or all of the following alterations can be made to the event stream:

    • Add new fields to each event based on event field transformations. The event field transformations can be found in event_field_transformation.cpp.
    • Filter events based on the values they contain to produce a stream containing some subset of the input stream.
    • Drop some fields which are not of interest in the output stream.

    Here are examples of each modification:

    "id": "avatar_kills_with_species",
    "type": "event_transformation",
    "event_type": "character_kills_monster", // Transformation acts upon events of this type
    "new_fields": { // A dictionary of new fields to add to the event
        // The key is the new field name; the value should be a dictionary of one element
        "species": {
            // The key specifies the event_field_transformation to apply; the value specifies
            // the input field whose value should be provided to that transformation.
            // So, in this case, we are adding a new field 'species' which will
            // contain the species of the victim of this kill event.
            "species_of_monster": "victim_type"
        }
    }
    
    "id": "moves_on_horse",
    "type": "event_transformation",
    "event_type" : "avatar_moves", // An event type.  The transformation will act on events of this type
    "value_constraints" : { // A dictionary of constraints
        // Each key is the field to which the constraint applies
        // The value specifies the constraint.
        // "equals" can be used to specify a constant string value the field must take.
        // "equals_statistic" specifies that the value must match the value of some statistic (see below)
        "mount" : { "equals": "mon_horse" }
    }
    // Since we are filtering to only those events where 'mount' is 'mon_horse', we
    // might as well drop the 'mount' field, since it provides no useful information.
    "drop_fields" : [ "mount" ]
    

    event_statistic

    As with event_transformation, an event_statistic requires an input event stream. That input stream can be specified in the same was as for event_transformation, via one of the following two entries:

    "event_type" : "avatar_moves" // Events of this built-in type
    "event_transformation" : "moves_on_horse" // Events resulting from this json-defined transformation
    

    Then it specifies a particular stat_type and potentially additional details as follows:

    The number of events:

    "stat_type" : "count"
    

    The sum of the numeric value in the specified field across all events:

    "stat_type" : "total"
    "field" : "damage"
    

    The maximum of the numeric value in the specified field across all events:

    "stat_type" : "maximum"
    "field" : "damage"
    

    The minimum of the numeric value in the specified field across all events:

    "stat_type" : "minimum"
    "field" : "damage"
    

    Assume there is only a single event to consider, and take the value of the given field for that unique event:

    "stat_type": "unique_value",
    "field": "avatar_id"
    

    Regardless of stat_type, each event_statistic can also have:

    // Intended for use in describing scores and achievement requirements.
    "description": "Number of things"
    

    score

    Scores simply associate a description to an event for formatting in tabulations of scores. The description specifies a string which is expected to contain a %s format specifier where the value of the statistic will be inserted.

    Note that even though most statistics yield an integer, you should still use %s.

    If the underlying statistic has a description, then the score description is optional. It defaults to “: ”.

    "id": "score_headshots",
    "type": "score",
    "description": "Headshots: %s",
    "statistic": "avatar_num_headshots"
    

    achievement

    Achievements are goals for the player to aspire to, in the usual sense of the term as popularised in other games.

    An achievement is specified via requirements, each of which is a constraint on an event_statistic. For example:

    {
      "id": "achievement_kill_zombie",
      "type": "achievement",
      // The achievement name and description are used for the UI.
      // Description is optional and can provide extra details if you wish.
      "name": "One down, billions to go\u2026",
      "description": "Kill a zombie",
      "requirements": [
        // Each requirement must specify the statistic being constrained, and the
        // constraint in terms of a comparison against some target value.
        { "event_statistic": "num_avatar_zombie_kills", "is": ">=", "target": 1 }
      ]
    },
    

    The "is" field must be ">=", "<=" or "anything". When it is not "anything" the "target" must be present, and must be an integer.

    There are further optional fields:

    "hidden_by": [ "other_achievement_id" ]
    

    Give a list of other achievement ids. This achievement will be hidden (i.e. not appear in the achievements UI) until all of the achievements listed have been completed.

    Use this to prevent spoilers or to reduce clutter in the list of achievements.

    "skill_requirements": [ { "skill": "archery", "is": ">=", "level": 5 } ]
    

    This allows a skill level requirement (either an upper or lower bound) on when the achievement can be claimed. The "skill" field uses the id of a skill.

    Note that like "time_constraint" below achievements can only be captured when a statistic listed in "requirements" changes.

    "kill_requirements": [ { "faction": "ZOMBIE", "is": ">=", "count": 1 }, { "monster": "mon_sludge_crawler", "is": ">=", "count": 1 } ],
    

    This allows a kill requirement (either an upper or lower bound) on when the achievement can be claimed. Can be defined with either "faction" or "monster" as a target, using species ids from species.json or a specific monster id.

    Only one of the "monster"/"faction" fields can be used per entry. If neither are used, any monster will fulfill the requirements.

    NPCs cannot currently be defined as a target.

    Note that like "time_constraint" below achievements can only be captured when a statistic listed in "requirements" changes.

    "time_constraint": { "since": "game_start", "is": "<=", "target": "1 minute" }
    

    This allows putting a time limit (either a lower or upper bound) on when the achievement can be claimed. The "since" field can be either "game_start" or "cataclysm". The "target" describes an amount of time since that reference point.

    Note that achievements can only be captured when a statistic listed in their requirements changes. So, if you want an achievement which would normally be triggered by reaching some time threshold (such as “survived a certain amount of time”) then you must place some requirement alongside it to trigger it after that time has passed. Pick some statistic which is likely to change often, and add an "anything" constraint on it. For example:

    {
      "id": "achievement_survive_one_day",
      "type": "achievement",
      "description": "The first day of the rest of their unlives",
      "time_constraint": { "since": "game_start", "is": ">=", "target": "1 day" },
      "requirements": [ { "event_statistic": "num_avatar_wake_ups", "is": "anything" } ]
    },
    

    This is a simple “survive a day” but is triggered by waking up, so it will be completed when you wake up for the first time after 24 hours into the game.

    requirements

    The requirements system in Cataclysm defines reusable sets of components, tools, and qualities needed for crafting, construction, and other game mechanics. Requirements are defined in JSON format and located in data/json/requirements/.

    JSON Structure

    Basic Format

    {
      "id": "unique_id",
      "type": "requirement",
      "//": "Optional comment",
      "components": [
        [
          ["gasoline", 1],
          ["diesel", 1],
          ["biodiesel", 1]
        ]
      ],
      "tools": [
        [
          ["soldering_iron", 1],
          ["soldering_ethanol", 10],
          ["toolset", 1]
        ]
      ],
      "qualities": [
        { "id": "CUT", "level": 1 },
        { "id": "HAMMER", "level": 2 }
      ]
    }
    

    Format

    Any of the three last arrays is optional, as long as one of them is present (a requirement must depend on something after all!)

    Components are organized as nested arrays representing alternatives and requirements:

    "components": [
      [ /* Group 1: ONE of these required */ ],
      [ /* Group 2: ONE of these required */ ]
    ]
    
    • [ "item_id", quantity ] - Specific item
    • [ "item_id", quantity, "LIST" ] - References another requirement definition

    Tools specify items that are used but not consumed, along with charge costs:

    "tools": [
      [
        [ "tool_id", charges ],
        [ "alternative", charges, "LIST" ]
      ]
    ]
    

    charges can be a positive integer, in which case it references the number of charges consumed, or -1 to signify that no charges are used.

    Qualities specify minimum tool quality levels needed:

    "qualities": [
      { "id": "QUALITY_ID", "level": min_level }
    ]
    
    #### Usage in Recipes
    
    Here is an example of a requirement in a recipe:
    
    ```json
    "using": [ [ "requirement_id", multiplier ] ]
    

    Multiple requirements:

    "using": [
      [ "welding_standard", 1 ],
      [ "forging_standard", 2 ]
    ]
    

    You can explore the files in the /data/json/requirements folder to see common examples of requirements for certain types of items or components. Make sure that your requirements do not form any circular dependencies.

    Skills

    "id" : "smg",  // Unique ID. Must be one continuous word, use underscores if necessary
    "name" : "submachine guns",  // In-game name displayed
    "description" : "Your skill with submachine guns and machine pistols. Halfway between a pistol and an assault rifle, these weapons fire and reload quickly, and may fire in bursts, but they are not very accurate.", // In-game description
    "tags" : ["gun_type"]  // Special flags (default: none)
    

    Missions

    (optional, array of mission ids)

    List of starting missions for this profession/hobby.

    Example:

    "missions": [ "MISSION_LAST_DELIVERY" ]
    

    json/ JSONs

    Harvest

    {
        "id": "jabberwock",
        "type": "harvest",
        "message": "You messily hack apart the colossal mass of fused, rancid flesh, taking note of anything that stands out.",
        "entries": [
          { "drop": "meat_tainted", "type": "flesh", "mass_ratio": 0.33 },
          { "drop": "fat_tainted", "type": "flesh", "mass_ratio": 0.1 },
          { "drop": "jabberwock_heart", "base_num": [ 0, 1 ], "scale_num": [ 0.6, 0.9 ], "max": 3, "type": "flesh" }
        ],
    },
    {
      "id": "mammal_large_fur",
      "//": "drops large stomach",
      "type": "harvest",
      "entries": [
        { "drop": "meat", "type": "flesh", "mass_ratio": 0.32 },
        { "drop": "meat_scrap", "type": "flesh", "mass_ratio": 0.01 },
        { "drop": "lung", "type": "flesh", "mass_ratio": 0.0035 },
        { "drop": "liver", "type": "offal", "mass_ratio": 0.01 },
        { "drop": "brain", "type": "flesh", "mass_ratio": 0.005 },
        { "drop": "sweetbread", "type": "flesh", "mass_ratio": 0.002 },
        { "drop": "kidney", "type": "offal", "mass_ratio": 0.002 },
        { "drop": "stomach_large", "scale_num": [ 1, 1 ], "max": 1, "type": "offal" },
        { "drop": "bone", "type": "bone", "mass_ratio": 0.15 },
        { "drop": "sinew", "type": "bone", "mass_ratio": 0.00035 },
        { "drop": "fur", "type": "skin", "mass_ratio": 0.02 },
        { "drop": "fat", "type": "flesh", "mass_ratio": 0.07 }
      ]
    },
    {
      "id": "CBM_SCI",
      "type": "harvest",
      "entries": [
        {
          "drop": "bionics_sci",
          "type": "bionic_group",
          "flags": [ "NO_STERILE", "NO_PACKED" ],
          "faults": [ "fault_bionic_salvaged" ]
        },
        { "drop": "meat_tainted", "type": "flesh", "mass_ratio": 0.25 },
        { "drop": "fat_tainted", "type": "flesh", "mass_ratio": 0.08 },
        { "drop": "bone_tainted", "type": "bone", "mass_ratio": 0.1 }
      ]
    },
    

    id

    Unique id of the harvest definition.

    type

    Should always be harvest to mark the object as a harvest definition.

    message

    Optional message to be printed when a creature using the harvest definition is butchered. May be omitted from definition.

    entries

    Array of dictionaries defining possible items produced on butchering and their likelihood of being produced. drop value should be the id string of the item to be produced.

    type value should be a string with the associated body part the item comes from. Acceptable values are as follows: flesh: the “meat” of the creature. offal: the “organs” of the creature. these are removed when field dressing. skin: the “skin” of the creature. this is what is ruined while quartering. bone: the “bones” of the creature. you will get some amount of these from field dressing, and the rest of them from butchering the carcass. bionic: an item gained by dissecting the creature. not restricted to CBMs. bionic_group: an item group that will give an item by dissecting a creature. not restricted to groups containing CBMs.

    flags value should be an array of strings. It’s the flags that will be added to te items of that entry upon harvesting.

    faults value should be an array of fault_id strings. It’s the faults that will be added to te items of that entry upon harvesting.

    For every type other then bionic and bionic_group following entries scale the results: base_num value should be an array with two elements in which the first defines the minimum number of the corresponding item produced and the second defines the maximum number. scale_num value should be an array with two elements, increasing the minimum and maximum drop numbers respectively by element value * survival skill. max upper limit after bas_num and scale_num are calculated using mass_ratio value is a multiplier of how much of the monster’s weight comprises the associated item. to conserve mass, keep between 0 and 1 combined with all drops. This overrides base_num, scale_num and max

    For types: bionic and bionic_group following enrties can scale the results: max this value (in contrary to max for other types) corresponds to maximum butchery roll that will be passed to check_butcher_cbm() in activity_handlers.cpp; view check_butcher_cbm() to see corresponding distribution chances for roll values passed to that function

    Weapon Category

    Used to classify weapons (guns or melee) into groups, mainly for use in martial arts.

    {
      "type": "weapon_category",
      "id": "WEAP_CAT",
      "name": "Weapon Category"
    }
    

    "name" is a translatable string used for UI display in martial arts UI, while ID is used for JSON entries.

    Obsoletion and migration

    For maps, you remove the item from all the places it can spawn, remove the mapgen entries, and add the overmap terrain id into data/json/obsoletion/migration_oter_ids.json, to migrate oter_id underground_sub_station and sewer_sub_station into their rotatable versions, note that if mapgen has already generated this area this will only alter the tile shown on the overmap:

    {
      "type": "oter_id_migration",
      "//": "obsoleted in 0.4",
      "old_directions": false,
      "new_directions": false,
      "oter_ids": {
        "underground_sub_station": "underground_sub_station_north",
        "sewer_sub_station": "sewer_sub_station_north"
      }
    }
    

    If old_directions option is enabled each entry will create four migrations: for old_north, old_west, old_south, and old_east. What they will be migrated to depends of value of new_directions option. If it is set to true then terrains will be migrated to same directions: old_north to new_north, old_east to new_east and such. If new_directions is set to false, then all four terrains will be migrated to one plain new. For both of those cases you only need to specify plain old and new names in oter_ids map, without any suffixes.

    Mod Compatability

    Explaination

    The mod_interactions folder in the base of the data folder has special loading logic. Within that folder, place a folder with a mod id. Anything within that folder will only be loaded when the other mod is loaded. All loading in that folder occurs after both mods have loaded, and the loading of interactions happens in standard load order.

    Example

    For example Mod 1: Arcana Has the folder mod_interactions in root Then the folder crt_expansion in mod interactions. When crt_expansion is loaded, it adds all the present files, such as professions.json adding the C.R.I.T. Anomaly Investigator

    Notesi

    Nested mod interactions are currently unsupported, you cannot have it load if mod A and B is present.

    Nor can you do something like mod A or mod B being present load something

    Mod source is the base mod

    MOD_INFO

    Also see MODDING.md.

    Object with MOD_INFO type describes the mod itself. Each mod must have exactly one MOD_INFO, and unlike other types of objects from mods it is loaded on game launch, before the title screen shows up. As such, any and all errors related to it will show up before the title screen shows up.

    Current convention is to put your MOD_INFO in mod_info.json file within the root directory of the mod.

    Example:

    [
      {
        "type": "MOD_INFO",
    
        // Mod's unique identifier, prefer to use only ASCII letters, numbers and underscore for clarity.
        "id": "better_zeds",
        // Mod's category, see MODDING.md for list of supported values.
        "category": "content",
        // Mod's display name, in English.
        "name": "Better Zombies",
        // Mod's description, in English.
        "description": "Reworks all base game zombies and adds 100+ new variants.",
        // Mod's license. Non-FOSS should (usually) use "All Rights Reserved" or "Source Available"
        "license": "CC-BY-SA 4.0 Unported",
        // Original author(s) of the mod.
        "authors": ["That Guy", "His Friend"],
        // If the author(s) abandoned the mod for some reason, this entry lists current maintainers.
        "maintainers": ["Mr. BugFixer", "BugFixer Jr."],
        // Optional loading screen image paths. Entries may name an image file or a directory to search recursively.
        // Paths are resolved relative to the mod's "path" directory when present, and the modinfo.json directory is also searched for compatibility.
        // Supported image extensions are .png, .jpg, .jpeg, .bmp, .gif, and .webp.
        // The author credit is taken from the image filename before the first underscore, e.g. "foo_rest.png" displays "by foo" in white text with a black outline.
        "loading_images": ["load_1.png", "load_2.png", "some_directory"],
        // Mod version string. This is for users' and maintainers' convenience, so you can use whatever is most convenient here (e.g. date).
        "version": "2021-12-02",
        // List of mod's dependencies. Dependencies are guaranteed to be loaded before the mod is loaded.
        "dependencies": ["bn", "zed_templates"],
        // List of mods that are incompatible with this mod.
        "conflicts": ["worse_zeds"],
        // Special flag for core game data, can only be used by total overhaul mods. Only 1 core mod can be loaded at a time.
        "core": false,
        // Marks mod as obsolete. Obsolete mods don't show up in mod selection list by default, and have a warning on them.
        "obsolete": false,
        // Path of mod's files relative to the modinfo.json file. The game automatically loads all files from the folder with modinfo.json,
        // and all the subfolders, so this field is only useful when you for whatever reason want to stick your modinfo.json in a subfolder of your mod.
        "path": "../common-data/",
        // Path to mod options
        "options_path": "options"
      }
    ]
    

    Options

    Option Group

    Adds a new group to the options menu

    KeyDescription
    typeAlways OPTION_GROUP
    idid of the group
    pagegeneral interface graphics performance world_default debug or android
    titleVisible Option Name
    descExtended option description

    Option Space

    Adds a new space to the options menu

    KeyDescription
    typeAlways OPTION_SPACE
    pagegeneral interface graphics performance world_default debug or android

    Option

    Adds an option to the options menu

    KeyDescription
    typeAlways OPTION
    idUnique option id
    stypeType of option
    pagegeneral interface graphics performance world_default debug or android
    groupOptional group id it is under
    menu_textText displayed for option value
    tooltipExtra info displayed for option
    defaultDefault value
    default_androidDefault value on android
    minminimum value for integers / floats
    maxMaximum value for integers / floats
    stepStep for floats in menu
    hideHides with none, always, sdl_hide ( with sdl ), curses_hide ( with curses ), no_sound_hide ( without sound ), android_only ( when not android )
    depsArray of option ( other option id ) and values ( valid option values ) to use the config

    Professions

    Profession

    Fields

    IdentifierDescription
    id(mandatory) Unique id of the profession
    name(mandatory) Object with male and female names, or a string for both genders to be set to it
    description(mandatory) Description of the profession, same across both genders
    vehicle(optional) Vehicle Prototype Id for the profession to start with
    pets(optional) Array of name ( monster ids ) and amount ( count of monster id ) objects for starting pets
    spells(optional) Array of id ( spell ids ) and level ( level of spell ) objects for starting spells.
    points(mandatory) Point cost of getting the profession
    items(mandatory) Three different item groups or arrays of string ids ( technically legacy ). male for male only female for female only both for both genders
    no_bonus(optional) Array prevents gaining these items from profession item substitution bonuses
    starting_cash(optional) Amount of cash the profession starts with
    skills(optional) Array of level ( skill level ) and name ( skill id ) objects
    addictions(optional) Array of type ( addiction type ) and intensity ( integer addiction intensity ) objects
    CBMs(optional) Array of bionic ids for bionics the profession gains
    traits(optional) Array of trait ids for traits the profession gains
    perks(optional) Array of perk ids for perks the profession gains
    forbidden_traits(optional) Array of trait ids that cannot be chosen on start
    allowed_traits(optional) Array of trait ids for non starting traits which can be chosen on start
    forbidden_bionics(optional) Array of bionic ids that cannot be chosen on start
    allowed_bionics(optional) Array of bionic ids for non starting bionics which can be chosen on start
    forbids_bionics(optional) Boolean to prevent choosing any bionic on start
    forbidden_spells(optional) Array of spell ids that cannot be chosen on start
    allowed_spells(optional) Array of spell ids for non starting spells which can be chosen on start
    forbids_spells(optional) Boolean to prevent choosing any spell on start
    flags(optional) Array of flags which are profession compatible
    missions(optional) Array of mission ids ( and thus missions ) to start with
    npcs(optional) Array of npc class ids ( and thus npcs of that class ) to start with
    age(optional) Object of min and max for starting age range, or just an int for only one possible age

    Example

    {
      "type": "profession",
      "id": "wolfpack_mutant",
      "name": "Mutant Pack Leader",
      "description": "They treated you like an animal in that lab.  Now that you're free, you wonder if they had the right idea.  Your new friends don't seem afraid of you like they are of humans, after all.",
      "vehicle": "covered_wagon",
      "pets": [ { "name": "mon_wolf", "amount": 2 } ],
      "spells": [ { "id": "summon_zombie", "level": 1 }, { "id": "necrotic_gaze", "level": 1 } ],
      "points": 4,
      "items": { "both": [ "subsuit_xl" ], "male": [ "briefs" ], "female": [ "bra", "panties" ] },
      "no_bonus": [ "glasses_eye" ]
      "starting_cash": 0,
      "skills": [ { "level": 1, "name": "survival" } ],
      "addictions": [ { "intensity": 10, "type": "nicotine" } ],
      "CBMs": [ "bio_batteries", "bio_lockpick", "bio_fingerhack", "bio_power_storage_mkII" ],
      "traits": [ "LUPINE_FUR", "TAIL_FLUFFY", "LUPINE_EARS", "THRESH_LUPINE" ],
      "forbidden_traits": [ "CARRY_PERMIT" ],
      "allowed_traits": [ "MUZZLE" ],
      "forbidden_bionics": [ "bio_power_storage" ],
      "allowed_bionics": [ "bio_razors" ],
      "flags": [ "SCEN_ONLY" ],
      "missions": [ "MISSION_HEIST_DRIVER" ],
      "npcs": [ "NC_PROF_ESCAPIST_LAB", "NC_PROF_ESCAPIST_LAB", "NC_PROF_ESCAPIST_LAB" ],
      "age": { "min": 17, "max": 35 }
    },
    

    Skill Level Framework

    These are general breakpoints for skill starting values when adding professions. Remember that these are just rough guidelines, and you can certainly change things around if you feel like its fun. Also, remember that you can assign points to skills at character creation, so make sure to judge skills based on the profession, not just on potential backstory.

    0: NO EXPERIENCE The default level of knowledge obtained through interaction with society and general day to day tasks. Example: An average US high school graduate, without regard for hobbies, advanced courses, jobs, etc, would have 0 in all skills.

    1: MINIMAL EXPERIENCE You have extremely rudimentary training in the topic, or are somewhat interested in the topic with a small amount of real experience. Example: A person who reads magazines about guns and has gone to the range once or twice would have 1 in marksmanship.

    2: BASIC TRAINING You have basic training in the topic, or are a dedicated hobbyist. Example: A person who visits the range somewhat frequently would have 2 in marksmanship. A soldier just finished with basic training would have 2 first aid, as they are trained but it is not their specialty, vs something like a combat medic who would have higher first aid.

    3: ENTHUSIAST You have basic training in the topic and some real experience, or are an enthusiast. Example: A person who takes classes at the range and has a decent amount of experience shooting would have 3 in marksmanship.

    4: TRAINED You are trained in that skill as a specialization to an average degree. About the level of an associate’s degree. Example: A soldier just finished with infantry training would have 4 in marksmanship.

    5: Previous, but with some real experience Example: A veteran would have 5 marksmanship as opposed to 4 due to having some experience applying those skills in real life scenarios outside of training.

    6: HIGHLY TRAINED You are trained in that skill as a specialization to an advanced degree. About the level of a bachelor’s degree. Example: A soldier just finished with marksman training would have 6 in marksmanship.

    7: Previous, but with some real experience

    8: EXPERT You are trained in that skill as a specialization to an expert degree. About the level of a graduate degree. Example: A soldier just finished with sniper training would have 8 in marksmanship.

    9: Previous, but with some real experience

    10: VETERAN You are trained to an expert degree and have years of experience as well as talent surpassing others in the field. Example: A renowned professional athlete would have 10 in athletics. A tier one spec ops would have 10 in marksmanship. A high profile chemist would have 10 in cooking.

    Profession Item Substitutions

    Substitutions

    Trait Based

    {
      "type": "profession_item_substitutions", // Mandatory type
      "trait": "WOOLALLERGY", // Trait that is required
      "sub": [
        {
          "item": "blazer", // Item to replace
          "new": ["jacket_leather_red"], // Items that replace it. One for one ratio
        },
        {
          "item": "hat_hunting", // Item to replace
          "new": [{
            "item": "hat_cotton", // Item that replaces it
            "ratio": 2, // For every item, give 2 to replace
          }],
        },
      ],
    }
    

    In the above example. With WOOLALLERGY trait. blazer is replaced with 1 jacket_leather_red. And hat_hunting is replaced with 2 hat_cotton items.

    Item based

    {
      "type": "profession_item_substitutions", // Mandatory type
      "item": "sunglasses", // Item to replace
      "sub": [
        {
          "present": [ "HYPEROPIC" ], // Must have all of these traits
          "absent": [ "MYOPIC" ], // Cannot have any of these traits
          "new": [ "fitover_sunglasses" ] // Replaced with these
        },
        {
          "present": [ "MYOPIC" ], // Must have all these traits
          "new": [ { "fitover_sunglasses", "ratio": 2 } ] // Also supports ratio replaces
        }
      ]
    }
    

    Thus if you have HYPEROPIC you get one fitover sunglasses And MYOPIC gives 2 fitover sunglasses in all cases even with HYPEROPIC

    Bonuses

    Itemgroup

    {
      "type": "profession_item_substitutions", // Needed type
      "item_group": "profession_carry_bonus",  // Itemgroup to give
      "bonus": { "present": [ "CARRY_PERMIT" ] } // Works with both present and absent as above
    },
    

    This grants a free spawn from itemgroup profession_carry_bonus to characters with the CARRY_PERMIT trait.

    Item

    {
      "type": "profession_item_substitutions", // Needed type
      "item": "glasses_eye",                   // Item to give
      "bonus": { "present": [ "MYOPIC" ], "absent": [ "HYPEROPIC" ] } // As above present and absent works
    },
    

    This grants a free item glasses_eye to characters with the MYOPIC trait, but not HYPEROPIC.

    Scenarios

    Scenarios are specified as JSON object with type member set to scenario.

    {
        "type": "scenario",
        "id": "schools_out",
        ...
    }
    

    The id member should be the unique id of the scenario.

    The following properties (mandatory, except if noted otherwise) are supported:

    description

    (string)

    The in-game description.

    name

    (string or object with members “male” and “female”)

    The in-game name, either one gender-neutral string, or an object with gender specific names. Example:

    "name": {
        "male": "Runaway groom",
        "female": "Runaway bride"
    }
    

    points

    (integer)

    Point cost of scenario. Positive values cost points and negative values grant points.

    items

    (optional, object with optional members “both”, “male” and “female”)

    Items the player starts with when selecting this scenario. One can specify different items based on the gender of the character. Each lists of items should be an array of items ids. Ids may appear multiple times, in which case the item is created multiple times.

    Example:

    "items": {
        "both": [
            "pants",
            "rock",
            "rock"
        ],
        "male": [ "briefs" ],
        "female": [ "panties" ]
    }
    

    This gives the player pants, two rocks and (depending on the gender) briefs or panties.

    Mods can modify the lists of an existing scenario via “add:both” / “add:male” / “add:female” and “remove:both” / “remove:male” / “remove:female”.

    Example for mods:

    {
      "type": "scenario",
      "id": "schools_out",
      "edit-mode": "modify",
      "items": {
        "remove:both": ["rock"],
        "add:female": ["2x4"]
      }
    }
    

    surround_groups

    (optional, array with group and density number)

    This replaces the SUR_START flag for scenarios, specifies groups of monsters which spawn in the area surrounding the scenario’s staritng location.

    "surround_groups": [ [ "GROUP_BLACK_ROAD", 70.0 ] ],
    

    The string defines the ID of which monstergroup will be spawned in the surrounding area, while the number is the density of spawns. 70.0 replicates the value of the original SUR_START behavior.

    flags

    (optional, array of strings)

    A list of flags. TODO: document those flags here.

    Mods can modify this via “add:flags” and “remove:flags”.

    cbms

    (optional, array of strings)

    A list of CBM ids that are implanted in the character.

    Mods can modify this via “add:CBMs” and “remove:CBMs”.

    "traits", "forced_traits", "forbidden_traits

    (optional, array of strings)

    Lists of trait/mutation ids. Traits in “forbidden_traits” are forbidden and can’t be selected during the character creation. Traits in “forced_traits” are automatically added to character. Traits in “traits” enables them to be chosen, even if they are not starting traits.

    "bionics", "forced_bionics", "forbidden_bionics

    (optional, array of strings)

    Lists of bionics ids. Bionics in “forbidden_bionics” are forbidden and can’t be selected during the character creation. bionics in “forced_bionics” are automatically added to character. Bionics in “bionics” enables them to be chosen, even if they are not starting bionics.

    "forced_perks"

    (optional, array of strings)

    Lists of perk ids. Perks in “forced_perks” are automatically added to character.

    "spells", "forbidden_spells

    (optional, array of strings)

    Lists of trait/mutation ids. Spells in “forbidden_spells” are forbidden and can’t be selected during the character creation. Spells in spells“ enables them to be chosen, even if they are not starting spells.

    forbids_bionics

    (optional, bool)

    Prohibits players from adding bionics through the bionics chargen tab

    allowed_locs

    (optional, array of strings)

    A list of starting location ids (see start_locations.json) that can be chosen when using this scenario.

    start_name

    (string)

    The name that is shown for the starting location. This is useful if the scenario allows several starting locations, but the game can not list them all at once in the scenario description. Example: if the scenario allows to start somewhere in the wilderness, the starting locations would contain forest and fields, but its “start_name” may simply be “wilderness”.

    professions

    (optional, array of strings)

    A list of allowed professions that can be chosen when using this scenario. The first entry is the default profession. If this is empty, all professions are allowed.

    map_special

    (optional, string)

    Add a map special to the starting location, see json_flags for the possible specials.

    missions

    (optional, array of strings)

    A list of mission ids that will be started and assigned to the player at the start of the game. Only missions with the ORIGIN_GAME_START origin are allowed. The last mission in the list will be the active mission, if multiple missions are assigned.

    Soundpacks

    A soundpack can be installed in the data/sound directory. It has to be a subdirectory that contains at least a file named soundpack.txt. It can include any number of json files which add any number of sound_effect or playlist.

    soundpack.txt format

    The soundpack.txt file format needs 2 values, a NAME and a VIEW. The NAME value should be unique. The VIEW value will be shown in the options menu. Every line starting with a # is a comment line.

    #Basic provided soundpack
    #Name of the soundpack
    NAME: basic
    #Viewing name of the soundpack
    VIEW: Basic
    

    JSON format

    Sound effects

    Sound effects can be included with a format like this:

    [
      {
        "type": "sound_effect",
        "id": "menu_move",
        "volume": 100,
        "files": [
          "nenadsimic_menu_selection_click.wav"
        ]
      },
      {
        "type": "sound_effect",
        "id": "fire_gun",
        "volume": 90,
        "variant": "bio_laser_gun",
        "files": [
          "guns/energy_generic/weapon_fire_laser.ogg"
        ]
      }
    ]
    

    Adding variety: If for a certain id’s variant multiple files are defined, they will be chosen at random when variant is played.

    The volume key may range from 0-100.

    Cataclysm has its own set of user-controllable volumes that will additionally affect the sound. These range from 0-128, and the default is 100. This means that at default volume, any sound that Cataclysm plays will default to playing at about 78% of the maximum; if you are working on sounds in an external audio editor, expect Cataclysm at default volume settings to play that sound file back more-quietly than your editor does.

    Preloading SFX

    Sound effects can be included for preloading with a format like this:

    [
      {
        "type": "sound_effect_preload",
        "preload": [
          { "id": "fire_gun", "variant": "all" },
          { "id": "environment", "variant": "daytime" },
          { "id": "environment" }
        ]
      }
    ]
    

    "variant": "all" will be treated specially and load all variants of the given id.

    Warning

    "variant": "all" uses unoptimal algorithm (because the dev was dumb and lazy and used hacks) and will slow down game loading time.

    If "variant" is omitted, it defaults to "default".

    Playlist

    A playlist can be included with a format like this:

    [
      {
        "type": "playlist",
        "playlists": [
          {
            "id": "title",
            "shuffle": false,
            "files": [
              {
                "file": "Dark_Days_Ahead_demo_2.wav",
                "volume": 100
              },
              {
                "file": "cataclysmthemeREV6.wav",
                "volume": 90
              }
            ]
          }
        ]
      }
    ]
    

    Each sound effect is identified by an id and a variant. If a sound effect is played with a variant that does not exist in the json files, but a variant “default” exists, then the “default” variant is played instead. The file name of the sound effect is relative to the soundpack directory, so if the file name is set to “sfx.wav” and your soundpack is in data/sound/mypack, the file must be placed at data/sound/mypack/sfx.wav.

    Sound effects list

    A full list of sound effect id’s and variants is given in the following. Each line in the list has the following format:

    id variant1|variant2

    Where id describes the id of the sound effect, and a list of variants separated by | follows. When the variants are omitted, the variant “default” is assumed. Where the variants do not represent literal strings, but variables, they will be enclosed in < >. For instance, <furniture> is a placeholder for any valid furniture ID (as in the furniture definition JSON).

    # open/close doors
    

    Starting locations

    Starting locations are specified as JSON object with “type” member set to “start_location”:

    {
        "type": "start_location",
        "id": "field",
        "name": "An empty field",
        "target": "field",
        ...
    }
    

    The id member should be the unique id of the location.

    The following properties (mandatory, except if noted otherwise) are supported:

    name

    (string)

    The in-game name of the location.

    target

    (string)

    The id of an overmap terrain type (see overmap_terrain.json) of the starting location. The game will chose a random place with that terrain.

    flags

    (optional, array of strings)

    Arbitrary flags. Mods can modify this via “add:flags” / “remove:flags”. TODO: document them.

    Unicode chars palette

    2460—24FF Enclosed Alphanumerics

    ①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳
    ⑴⑵⑶⑷⑸⑹⑺⑻⑼⑽⑾⑿⒀⒁⒂⒃⒄⒅⒆⒇
    ⒈⒉⒊⒋⒌⒍⒎⒏⒐⒑⒒⒓⒔⒕⒖⒗⒘⒙⒚⒛
    ⒜⒝⒞⒟⒠⒡⒢⒣⒤⒥⒦⒧⒨⒩⒪⒫⒬⒭⒮⒯⒰⒱⒲⒳⒴⒵
    ⒶⒷⒸⒹⒺⒻⒼⒽⒾⒿⓀⓁⓂⓃⓄⓅⓆⓇⓈⓉⓊⓋⓌⓍⓎⓏ
    ⓐⓑⓒⓓⓔⓕⓖⓗⓘⓙⓚⓛⓜⓝⓞⓟⓠⓡⓢⓣⓤⓥⓦⓧⓨⓩ
    ⓪⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴
    ⓵⓶⓷⓸⓹⓺⓻⓼⓽⓾⓿
    

    2500—257F Box Drawing

    ─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟
    ┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿
    ╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟
    ╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿
    

    2580—259F Block Elements

    ▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏
    ▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟
    

    25A0—25FF Geometric Shapes

    ■□▢▣▤▥▦▧▨▩
    ▪▫▬▭▮▯▰▱
    ▲△▴▵▶▷▸▹►▻▼▽▾▿◀◁◂◃◄◅
    ◆◇◈◉◊○◌◍◎●◐◑◒◓◔◕◖◗
    ◘◙◚◛◜◝◞◟◠◡◢◣◤◥◦
    ◧◨◩◪◫◬◭◮◯
    ◰◱◲◳◴◵◶◷◸◹◺◻◼◽◾◿
    

    2600—26FF Miscellaneous Symbols

    ☀☁☂☃☄★☆☇☈☉☊☋☌☍☎☏☐☑☒☓☔☕☖☗☘☙☚☛☜☝☞☟☠☡☢☣☤☥☦☧☨☩☪☫☬☭☮☯☰☱☲☳☴☵☶☷☸☹☺☻☼☽☾☿♀♁♂♃♄♅♆♇♈♉♊♋♌♍♎♏♐♑♒♓♔♕♖♗♘♙♚♛♜♝♞♟♠♡♢♣♤♥♦♧♨♩♪♫♬♭♮♯♰♱♲♳♴♵♶♷♸♹♺♻♼♽♾♿⚀⚁⚂⚃⚄⚅⚆⚇⚈⚉⚊⚋⚌⚍⚎⚏⚐⚑⚒⚓⚔⚕⚖⚗⚘⚙⚚⚛⚜⚝⚞⚟⚠⚡⚢⚣⚤⚥⚦⚧⚨⚩⚪⚫⚬⚭⚮⚯⚰⚱⚲⚳⚴⚵⚶⚷⚸⚹⚺⚻⚼⚽⚾⚿⛀⛁⛂⛃⛄⛅⛆⛇⛈⛉⛊⛋⛌⛍⛎⛏⛐⛑⛒⛓⛔⛕⛖⛗⛘⛙⛚⛛⛜⛝⛞⛟⛠⛡⛢⛣⛤⛥⛦⛧⛨⛩⛪⛫⛬⛭⛮⛯⛰⛱⛲⛳⛴⛵⛶⛷⛸⛹⛺⛻⛼⛽⛾⛿
    

    2700—27BF Dingbats

    ✀✁✂✃✄✅✆✇✈✉✊✋✌✍✎✏✐✑✒
    ✓✔✕✖✗✘✙✚✛✜✝✞✟✠✡✢✣✤✥
    ✦✧✨✩✪✫✬✭✮✯✰✱✲✳✴✵✶✷✸
    ✹✺✻✼✽✾✿❀❁❂❃❄❅❆❇❈❉❊❋
    ❌❍❎❏❐❑❒❓❔❕❖❗❘❙❚
    ❛❜❝❞❟❠❡❢❣❤❥❦❧❨❩❪❫❬❭❮❯❰❱❲❳❴❵
    ❶❷❸❹❺❻❼❽❾❿
    ➀➁➂➃➄➅➆➇➈➉
    ➊➋➌➍➎➏➐➑➒➓
    ➔➕➖➗➘➙➚➛
    ➜➝➞➟➠➡➢➣➤➥➦➧➨
    ➩➪➫➬➭➮➯➰➱➲
    ➳➴➵➶➷➸➹➺➻➼➽➾➿
    

    27C0—27EF Miscellaneous Mathematical Symbols-A

    ⟀⟁⟂⟃⟄⟅⟆⟇⟈⟉⟊⟋⟌⟍⟎⟏⟐⟑⟒⟓⟔⟕⟖⟗⟘⟙⟚⟛⟜⟝⟞⟟⟠⟡⟢⟣⟤⟥⟦⟧⟨⟩⟪⟫⟬⟭⟮⟯
    

    27F0—27FF Supplemental Arrows-A

    ⟰⟱⟲⟳⟴⟵⟶⟷⟸⟹⟺⟻⟼⟽⟾⟿
    

    2800—28FF Braille Patterns

    ⠀⠁⠂⠃⠄⠅⠆⠇⠈⠉⠊⠋⠌⠍⠎⠏⠐⠑⠒⠓⠔⠕⠖⠗⠘⠙⠚⠛⠜⠝⠞⠟⠠⠡⠢⠣⠤⠥⠦⠧⠨⠩
    ⠪⠫⠬⠭⠮⠯⠰⠱⠲⠳⠴⠵⠶⠷⠸⠹⠺⠻⠼⠽⠾⠿⡀⡁⡂⡃⡄⡅⡆⡇⡈⡉⡊⡋⡌⡍⡎⡏⡐⡑⡒⡓
    ⡔⡕⡖⡗⡘⡙⡚⡛⡜⡝⡞⡟⡠⡡⡢⡣⡤⡥⡦⡧⡨⡩⡪⡫⡬⡭⡮⡯⡰⡱⡲⡳⡴⡵⡶⡷⡸⡹⡺⡻⡼⡽
    ⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⢈⢉⢊⢋⢌⢍⢎⢏⢐⢑⢒⢓⢔⢕⢖⢗⢘⢙⢚⢛⢜⢝⢞⢟⢠⢡⢢⢣⢤⢥⢦⢧
    ⢨⢩⢪⢫⢬⢭⢮⢯⢰⢱⢲⢳⢴⢵⢶⢷⢸⢹⢺⢻⢼⢽⢾⢿⣀⣁⣂⣃⣄⣅⣆⣇⣈⣉⣊⣋⣌⣍⣎⣏⣐⣑
    ⣒⣓⣔⣕⣖⣗⣘⣙⣚⣛⣜⣝⣞⣟⣠⣡⣢⣣⣤⣥⣦⣧⣨⣩⣪⣫⣬⣭⣮⣯⣰⣱⣲⣳⣴⣵⣶⣷⣸⣹⣺⣻
    ⣼⣽⣾⣿
    

    2900—297F Supplemental Arrows-B

    ⤀⤁⤂⤃⤄⤅⤆⤇⤈⤉⤊⤋
    ⤌⤍⤎⤏⤐⤑⤒⤓⤔⤕⤖⤗⤘⤙⤚⤛⤜
    ⤝⤞⤟⤠
    ⤡⤢⤣⤤⤥⤦⤧⤨⤩⤪⤫⤬⤭⤮⤯⤰⤱⤲
    ⤳⤴⤵⤶⤷⤸⤹⤺⤻⤼⤽⤾⤿
    ⥀⥁⥂⥃⥄⥅⥆⥇⥈⥉
    ⥊⥋⥌⥍⥎⥏⥐⥑⥒⥓⥔⥕⥖⥗⥘⥙⥚⥛⥜⥝⥞⥟⥠⥡
    ⥢⥣⥤⥥⥦⥧⥨⥩⥪⥫⥬⥭⥮⥯
    ⥰⥱⥲⥳⥴⥵⥶⥷⥸⥹⥺⥻⥼⥽⥾⥿
    

    2980—29FF Miscellaneous Mathematical Symbols-B

    ⦀⦁⦂⦃⦄⦅⦆⦇⦈⦉⦊⦋⦌⦍⦎⦏⦐⦑⦒⦓⦔⦕⦖⦗⦘⦙⦚⦛⦜⦝⦞⦟⦠⦡⦢⦣⦤⦥⦦⦧⦨⦩⦪⦫⦬⦭⦮⦯⦰⦱⦲⦳⦴⦵⦶⦷⦸⦹⦺⦻⦼⦽⦾⦿⧀⧁⧂⧃⧄⧅⧆⧇⧈⧉⧊⧋⧌⧍⧎⧏⧐⧑⧒⧓⧔⧕⧖⧗⧘⧙⧚⧛⧜⧝⧞⧟⧠⧡⧢⧣⧤⧥⧦⧧⧨⧩⧪⧫⧬⧭⧮⧯⧰⧱⧲⧳⧴⧵⧶⧷⧸⧹⧺⧻⧼⧽⧾⧿
    

    2A00—2AFF Supplemental Mathematical Operators

    ⨀⨁⨂⨃⨄⨅⨆⨇⨈⨉
    ⨊⨋⨌⨍⨎⨏⨐⨑⨒⨓⨔⨕⨖⨗⨘⨙⨚⨛⨜
    ⨝⨞⨟⨠⨡⨢⨣⨤⨥⨦⨧⨨⨩⨪⨫⨬⨭⨮⨯⨰⨱⨲⨳⨴⨵⨶⨷⨸⨹⨺⨻
    ⨼⨽⨾⨿⩀⩁⩂⩃⩄⩅⩆⩇⩈⩉⩊⩋⩌⩍⩎⩏⩐
    ⩑⩒⩓⩔⩕⩖⩗⩘⩙⩚⩛⩜⩝⩞⩟⩠⩡⩢⩣⩤⩥
    ⩦⩧⩨⩩⩪⩫⩬⩭⩮⩯⩰⩱⩲⩳⩴⩵⩶⩷⩸
    ⩹⩺⩻⩼⩽⩾⩿⪀⪁⪂⪃⪄⪅⪆⪇⪈⪉⪊⪋⪌⪍⪎⪏⪐⪑⪒⪓⪔
    ⪕⪖⪗⪘⪙⪚⪛⪜⪝⪞⪟⪠⪡⪢⪣⪤⪥⪦⪧⪨⪩
    ⪪⪫⪬⪭⪮⪯⪰⪱⪲⪳⪴⪵⪶⪷⪸⪹⪺⪻⪼
    ⪽⪾⪿⫀⫁⫂⫃⫄⫅⫆⫇⫈⫉⫊⫋⫌⫍⫎⫏⫐⫑⫒⫓⫔⫕⫖⫗⫘
    ⫙⫚⫛⫝̸⫝⫞⫟⫠⫡⫢⫣⫤⫥⫦⫧⫨⫩⫪⫫⫬⫭
    ⫮⫯⫰⫱⫲⫳⫴⫵⫶⫷⫸⫹⫺⫻⫼⫽⫾⫿
    

    2B00—2BFF Miscellaneous Symbols and Arrows

    ⬀⬁⬂⬃⬄⬅⬆⬇⬈⬉⬊⬋⬌⬍
    ⬎⬏⬐⬑⬒⬓⬔⬕⬖⬗⬘⬙
    ⬚⬛⬜⬝⬞⬟⬠⬡⬢⬣⬤⬥⬦⬧⬨⬩⬪⬫⬬⬭⬮⬯
    ⬰⬱⬲⬳⬴⬵⬶⬷⬸⬹⬺⬻⬼⬽⬾⬿⭀⭁⭂⭃⭄⭅⭆⭇⭈⭉⭊⭋⭌
    ⭍⭎⭏⭐⭑⭒⭓⭔⭕⭖⭗⭘⭙⭚⭛⭜⭝⭞⭟
    ⭠⭡⭢⭣⭤⭥⭦⭧⭨⭩⭪⭫⭬⭭⭮⭯⭰⭱⭲⭳⭴⭵
    ⭶⭷⭸⭹⭺⭻⭼⭽⭾⭿⮀⮁⮂⮃⮄⮅⮆⮇
    ⮈⮉⮊⮋⮌⮍⮎⮏⮐⮑⮒⮓⮔⮕⮖⮗⮘⮙⮚⮛⮜⮝⮞⮟
    ⮠⮡⮢⮣⮤⮥⮦⮧⮨⮩⮪⮫⮬⮭⮮⮯⮰⮱⮲⮳⮴⮵⮶⮷⮸
    ⮹⮺⮻⮼⮽⮾⮿⯀⯁⯂⯃⯄⯅⯆⯇⯈⯉⯊⯋⯌⯍⯎⯏
    ⯐⯑⯒⯓⯔⯕⯖⯗⯘⯙⯚⯛⯜⯝⯞⯟⯠⯡⯢⯣⯤⯥⯦⯧
    ⯨⯩⯪⯫⯬⯭⯮⯯⯰⯱⯲⯳⯴⯵⯶⯷⯸⯹⯺⯻⯼⯽⯾⯿
    

    Bionics

    Warning

    Many bionics have effects defined solely in the code and are not listed here

    When adding a new bionic, if it’s not included with another one, you must also add the corresponding CBM item as described here. Even for a faulty bionic.

    Fields

    IdentifierDescription
    id(mandatory) Unique string id
    name(mandatory) In game name of the bionic
    description(mandatory) In game description of the bionic
    flags(optional) Array of json flags. See the list
    capacity(optional) Bionic power gained from this bionic
    act_cost(optional) Power cost to activate bionic.
    deact_cost(optional) Power cost to deactivate bionic.
    trigger_cost(optional) Power cost on triggering bionic effect.
    kcal_trigger_cost(optional) Calorie cost on triggering bionic effect
    react_cost(optional) How much power to consume every time ticks
    time(optional) How long between consuming react_cost power
    stat_bonus(optional) Array of arrays, interior array is ["STAT", integer bonus]
    fuel_options(optional) Itype Ids accepted for fueling this bionic
    fuel_capacity(optional) Charges of fuel stored by the bionic
    fuel_efficiency(optional) Multiplier on the power generated by consuming fuel
    fuel_multiplier(optional) Multiplies the amount of fuel loaded into the bionic per charge
    passive_fuel_efficiency(optional) fuel_efficiency but the bionic is inactive, also used for PERPETUAL fuels
    coverage_power_gen_penalty(optional) multiplies fuel_efficiency by coverage from items of occupied_bodyparts and this value ( 50% bodypart coverage + )
    exothermic_power_gen(optional) If fuel not converted to power is converted to heat
    remote_fuel_draw(optional) Power draw from a connected exterior cable ( I.E. Cable Charger System )
    power_gen_emission(optional) field id to produce while making power
    weight_capacity_modifier(optional) Multiplier on weight capacity
    weight_capacity_bonus(optional) Addition on weight capacity
    upgraded_bionic(optional) Bionic id which can be upgraded by installing this bionic
    required_bionics(optional) Array of bionic ids that are required to install it
    included_bionics(optional) Array of bionic ids given upon installing it
    included(optional) boolean, is this bionic included by another bionic
    available_upgrades(optional) Array of bionic ids this can upgrade to
    env_protec(optional) Array of arrays, interior array is ["bodypart", integer], where integer is environmental protection on bodypart
    bash_protec(optional) Array of arrays, interior array is ["bodypart", integer], where integer is bash protection on bodypart
    cut_protec(optional) Array of arrays, interior array is ["bodypart", integer], where integer is cut protection on bodypart
    bullet_protec(optional) Array of arrays, interior array is ["bodypart", integer], where integer is ballistic protection on bodypart
    occupied_bodyparts(optional) Array of arrays, interior array is ["bodypart", integer], where integer is bionic slots occupied on bodypart
    encumbrance(optional) Array of arrays, interior array is ["bodypart", integer], where integer is encumbrance on bodypart
    canceled_mutations(optional) Array of trait ids which are canceled on install and prevented afterwards
    learned_spells(optional) Array of arrays, interior array is ["spell", integer], where integer is the level you learn the spell
    enchantments(optional) Array of enchantment ids to give with the bionic
    bio_enchantments(optional) Array of inline enchantments to give with the bionic
    fake_item(optional) Item that the bionic gives. With BIONIC_TOOLS it gives it as a tool, with BIONIC_TOGGLED it will be wielded, and with BIONIC_GUN it will be fired
    can_uninstall(optional) If the bionic can be uninstalled
    no_uninstall_reason(optional) Required with can_uninstall, message displayed with inability to uninstall
    starting_bionic(optional) If true can start with the bionic
    points(optional) Number of points it takes on character creation
    {
      "id": "bio_chaos",
      "name": "Complete Chaos",
      "description": "This does a lot of things that makes little sense",
      "flags": ["BIONIC_TOGGLED", "BIONIC_NPC_USABLE", "COMBAT_NPC_USE"],
      "capacity": "100 kJ",
      "act_cost": "5 J",
      "deact_cost": "5 J",
      "trigger_cost": "5 J",
      "react_cost": "5 J",
      "kcal_trigger_cost": 5,
      "time": 1,
      "stat_bonus": [["STR", 2]],
      "fuel_options": ["gasoline"],
      "fuel_capacity": 500,
      "fuel_efficiency": 0.25,
      "fuel_multiplier": 2,
      "coverage_power_gen_penalty": 0.5,
      "passive_fuel_efficiency": 0.125,
      "exothermic_power_gen": true,
      "remote_fuel_draw": "1 kJ",
      "powergen_emission": "fd_fire",
      "weight_capacity_modifier": 2.0,
      "weight_capacity_bonus": "20 kg",
      "upgraded_bionic": "bio_chaos_v1",
      "required_bionics": ["bio_chaos_base"],
      "included_bionics": ["bio_chaos_stuff", "bio_chaos_morestuff"],
      "included": false,
      "available_upgrades": ["bio_chaos_v50"],
      "env_protec": [["eyes", 7]],
      "bash_protec": [["eyes", 3]],
      "cut_protec": [["eyes", 3]],
      "bullet_protec": [["eyes", 3]],
      "occupied_bodyparts": [["torso", 1]],
      "encumbrance": [["mouth", 10]],
      "canceled_mutations": ["ASTHMA"],
      "learned_spells": [["mint_breath", 2]],
      "enchantments": ["ENCH_UNCANNY_DODGE"],
      "bio_enchantments": [
        { "condition": "ALWAYS", "values": [{ "value": "SPEED", "multiply": 0.1 }] },
      ],
      "can_uninstall": false,
      "no_uninstall_reason": "The telescopic lenses are part of the patient's eyes now, remove them and the patient would become blind",
      "starting_bionic": true,
      "points": 1,
    }
    

    Paired Item Definition

    {
      "id": "bio_adrenaline", // Must match the bionic id exactly
      "copy-from": "bionic_general", // There are a few variants of this but this is the basic thing
      "type": "BIONIC_ITEM", // Required type
      // The rest is general item fields
      "name": { "str": "Adrenaline Pump CBM" },
      "looks_like": "bio_int_enhancer",
      "description": "A stimulator system that is implanted alongside the adrenal glands, allowing the user to trigger their body's adrenaline response at the cost of some bionic power.",
      "price": "40 USD",
      "weight": "250 g",
      "difficulty": 6
    },
    

    Character Values

    Character Values

    Jsonized value for accessing character wide bounded values within other places.

    Fields

    IdentifierDescription
    id(mandatory) Unique string id
    desc(optional) Info for how this will scale, used in enchantment desc.
    var_value(optional) Reads the integer of this character value as the value
    drain_resource(optional) Hardcode character value that is used, see references below
    min_value(optional) Minimum value that this resource can have. Used for capping effects
    max_value(optional) Maximum value that this resource can have. Used for capping effects

    Hardcode Character Values

    IdentifierDescription
    STRCurrent modified strength of the character
    DEXCurrent modified dexterity of the character
    INTCurrent modified intelligence of the character
    PERCurrent modified perception of the character
    HEALTHCurrent health value of the character
    HPHealth points of the limb with the most health
    MANACurrently availiable mana stores
    STAMINACurrently available stamina stores
    BIONIC_POWERCurrent bionic power in kilojoules
    FATIGUECurrent fatigue of the character
    THIRSTCurrent thirst of the character
    PAINCurrent unmodified pain ( I.E. before painkillers ) of the character
    RADCurrent radiation levels of the character
    HUNGERPercent of drained kcal, 0 is 100%, 100 is dead
    MORALECurrent morale levels of the character from all sources
    FOCUSCurrent focus levels ( not effective focus ) of the character
    NONEAlways 0

    Predefined Character Values.

    These are the predefined values which can be used by any mod.

    IdentifierPair
    strengthSTR
    dexterityDEX
    intelligenceINT
    perceptionPER
    healthHEALTH
    health_pointsHP
    manaMANA
    staminaSTAMINA
    bionic_powerBIONIC_POWER
    fatigueFATIGUE
    thirstTHIRST
    painPAIN
    hungerHUNGER
    moraleMORALE
    focusFOCUS

    Effects

    How to give effects in-game?

    Comestibles

    The first way to give a player an effect in-game is through the drug system. To do this your item must have a use_action of type “consume_drug”.

    "use_action" : {
        "type" : "consume_drug",
        "activation_message" : "You take some oxycodone.",
        "effects" : [
            {
                "id": "pkill3",
                "duration": 20
            },
            {
                "id": "pkill2",
                "duration": 200
            }
        ]
    },
    

    Notice the “effects” field. Each effect has four potential fields:

    "id" - Required
    "duration" - Required
    "bp" - This will cause the effect to target this body part specifically
    

    Valid “bp” entries are (no entry means the effect is untargeted):

    "torso"
    "head"
    "eyes"
    "mouth"
    "arm_l"
    "arm_r"
    "hand_l"
    "hand_r"
    "leg_l"
    "leg_r"
    "foot_l"
    "foot_r"
    

    Creature attacks

    Creatures have an effect field similar to the “consume_drug” entry for items. You can make a creature’s attacks apply effects by adding an “attack_effs” entry for the creature.

    "attack_effs": [
        {
            "//": "applying this multiple times makes intensity go up by 3 instead of 1",
            "id": "paralyzepoison",
            "duration": 33
        },
        {
            "id": "paralyzepoison",
            "duration": 33
        },
        {
            "id": "paralyzepoison",
            "duration": 33
        }
    ],
    

    The fields for “attack_effs” function identically to the ones for “consume_drug”. However, creatures have an additional field:

    "chance" - The percentage chance of the effect being applied on a good hit, defaults to 100%
    

    If a creature successfully damages the player and their chance roll succeeds they will apply all of the listed effects to the player. The effects are added one after another.

    Mutations

    Mutations can give effects with the field “enchantments”, the following mutation grants a special attack. The enchant provided after the ink gland mutation permanently affects armor values on the player.

    {
        "type": "mutation",
        "id": "INK_GLANDS",
        "name": { "str": "Ink glands" },
        "points": 1,
        "visibility": 1,
        "ugliness": 1,
        "description": "Several ink glands have grown onto your torso.  They can be used to spray defensive ink and blind an attacker in an emergency, as long as the torso isn't covered.",
        "enchantments": [ "MEP_INK_GLAND_SPRAY" ],
        "category": [ "CEPHALOPOD" ]
      },
      {
        "type": "enchantment",
        "id": "ENCH_BIO_CARBON",
        "condition": "ALWAYS",
        "values": [
          { "value": "ARMOR_BASH", "multiply": -0.05 },
          { "value": "ARMOR_CUT", "multiply": -0.1 },
          { "value": "ARMOR_STAB", "multiply": -0.08 },
          { "value": "ARMOR_BULLET", "multiply": -0.15 }
        ]
      }
    

    Required fields

    "type": "effect_type",      - Required
    "id": "xxxx"                - Must be unique
    

    Optional fields

    Max intensity

    "max_intensity": 3          - Used for many later fields, defaults to 1
    "max_effective_intensity"   - How many intensity levels will apply effects.
                                  Other intensity levels will only increase duration.
    

    Name

    "name": ["XYZ"]
    or
    "name": [
        "ABC",
        "XYZ",
        "123"
    ]
    

    If "max_intensity" > 1 and the number of entries in "name" >= "max_intensity" then it will attempt to use the proper intensity name. In this case that means an intensity of 1 would give the name “ABC”, 2 would give “XYZ”, and 3 would give “123”. If "max_intensity" == 1 or the number of entries in “name” is less than “max_intensity”, it will use the first entry followed by the intensity in brackets if the current intensity > 1, i.e."ABC", "ABC [2]", "ABC [3]". If the desired entry of “name” is the empty string (“”) or “name” is missing then the effect will not display to the player in the status screen.

    Each entry in “name” can also have an optional context:

    "name": [ { "ctxt": "ECIG", "str": "Smoke" } ]
    

    In this case, the game will translate the name with the given context “ECIG”, which makes it possible to distinguish the verb “Smoke” from the noun “Smoke” in other languages.

    "speed_name" : "XYZ"        - Defaults to the first name value
    

    This is the value used in the list of modifiers on a player’s speed. It will default to the first entry in “name” if it doesn’t exist, and if neither one exists or if “speed_name” is the empty string (“”), then it will not appear in the list of modifiers on the players speed (though the effect might still have an effect).

    Descriptions

    "desc": ["XYZ"]
    or
    "desc": [
        "ABC",
        "XYZ",
        "123"
    ]
    

    Descriptions operate identically to the name field when picking which one to use. In general, descriptions should be only 1 line. Stats and effects do not need to be included, and will be automatically generated from the other effect data. Should a description line be the empty string (“”) it will only display the stat changes in the effect description.

    Descriptions also have a second field that can act as a modifier:

    "part_descs": true      - Defaults to false if not present
    

    If “part_descs” == true then descriptions are preceded by “Your X”, where X is the body part name, meaning the prior descriptions would appear as “Your left arm ABC”.

    Descriptions can also have a reduced form:

    "reduced_desc": ["XYZ"]
    or
    "reduced_desc": [
        "ABC",
        "XYZ",
        "123"
    ]
    

    This is the description that will be used if an effect is reduced. By default this will use the normal description if it doesn’t exist.

    Rating

    "rating": "good"        - Defaults to "neutral" if missing
    

    This is used for how the messages when the effect is applied and removed are displayed. Also this affects “blood_analysis_description” (see below) field: effects with “good” rating will be colored green, effects with any other rating will be colored red when character conducts a blood analysis through some means. Valid entries are:

    "good"
    "neutral"
    "bad"
    "mixed"
    

    Looks_like

    "looks_like": "drunk"
    

    If the “looks_like” field exists, the effect will visually resemble the specified tag (for example, “drunk”). This only affects the appearance of the effect over a NPC or character, not its mechanical behavior.

    Messages

    "apply_message": "message",
    "remove_message": "message"
    

    If the “apply_message” or “remove_message” fields exist, the respective message will be displayed upon the addition or removal of the effect. Note: “apply_message” will only display if the effect is being added, not if it is simply incrementing a current effect (so only new bites, etc.).

    Memorial Log

    "apply_memorial_log": "log",
    "remove_memorial_log": "log"
    

    If the “apply_memorial_log” or “remove_memorial_log” fields exist, the game will add the respective message to the memorial log on addition or removal of the effect. Similar to the message fields the “apply_memorial_log” will only be added to the log for new effect additions.

    Resistances

    "resist_trait": "NOPAIN",
    "resist_effect": "flumed"
    

    These fields are used to determine if an effect is being resisted or not. If the player has the matching trait or effect then they are “resisting” the effect, which changes its effects and description. Effects can only have one “resist_trait” and one “resist_effect” at a time.

    Removes effects

    "removes_effects": ["bite", "flu"]
    

    This field will cause an effect to automatically remove any other copies of the listed effects if they are present. In the example above the placed effect would automatically cure any bite wounds or flu the player had. Any values here automatically count for “blocks_effects” as well, no need to duplicate them there.

    Blocks effects

    "blocks_effects": ["cold", "flu"]
    

    This field will cause an effect to prevent the placement of the listed effects. In the example above the effect would prevent the player from catching the cold or the flu (BUT WOULD NOT CURE ANY ONGOING COLDS OR FLUS). Any effects present in “removes_effects” are automatically added to “blocks_effects”, no need for manual duplication.

    Effect limiters

    "max_duration": 100,
    "dur_add_perc": 150     - Defaults to 100%
    

    These are utilized when adding to currently existing effects. “max_duration” limits the overall duration of the effect. “dur_add_perc” is the percentage value of the normal duration for adding to an existing. An example:

    1. I add effect A to the player for 100 ticks.
    2. I add effect A to the player again for 100 ticks. Because the “dur_add_perc” = 150 in the example above, the second addition adds a total of 100 * 150% = 150 ticks, for a total value of 250 ticks from the two. This can also be below 100%, and should be able to even be negative, leading to future applications decreasing the overall time left.

    Intensities

    Intensities are used to control effect effects, names, and descriptions. They are defined with:

    "int_add_val": 2        - Defaults to 0! This means future applications will not increase intensity unless changed!
    and/or
    "int_decay_step": -2,    - Defaults to -1
    "int_decay_tick": 10
    or
    "int_dur_factor": 700
    

    The first value is the amount an intensity will be incremented if adding to an already existing effect. As an example:

    1. I add effect A to the player
    2. I add effect A to the player again Because “int_add_val” = 2, the second addition will change the effect intensity from 1 to 1 + 2 = 3. NOTE: You must have at least one of the 3 intensity data sets for intensity to do anything!

    “int_decay_step” and “int_decay_tick” require one another to do anything. If both exist then the game will automatically increment the current effect intensities by “int_decay_step” every “int_decay_tick” ticks, capping the result at [1, "max_intensity"]. This can be used to make effects automatically increase or decrease in intensity over time.

    “int_dur_factor” overrides the other three intensities fields, and forces the intensity to be a number defined as intensity = duration / “int_dur_factor” rounded up (so from 0 to “int_dur_factor” is intensity 1).

    Permanence

    An effect that is permanent does not lose duration with time. That is, even if its duration is 1 turn, it will last until removed.

    "permanent": true
    

    Miss messages

    "miss_messages": [["Your blisters distract you", 1]]
    or
    "miss_messages": [
        ["Your blisters distract you", 1],
        ["Your blisters don't like you", 10],
    ]
    

    This will add the following miss messages at the given chances while the effect is in effect.

    Decay messages

    "decay_messages": [["The jet injector's chemicals wear off.  You feel AWFUL!", "bad"]]
    or
    "decay_messages": [
        ["The jet injector's chemicals wear off.  You feel AWFUL!", "bad"],
        ["OOGA-BOOGA.  You feel AWFUL!", "bad"],
    ]
    

    The messages are matched to intensities, so the first message is for intensity 1, the second for intensity 2, and so on. The messages will print whenever the intensity decreases to their matching intensity from a higher intensity, whether through decay ticks or through “int_dur_factor”. So if it decayed to intensity 2 from 3+ it would display “OOGA-BOOGA. You feel AWFUL!” as a bad message to the player.

    Targeting modifiers

    "main_parts_only": true     - Defaults to false
    

    This automatically retargets any effect on a non-main part (hands, eyes, feet, etc.) to the matching main part (arms, head, legs, etc.).

    Effect modifiers

    "pkill_addict_reduces": true,   - Defaults to false
    "pain_sizing": true,            - Defaults to false
    "hurt_sizing": true,            - Defaults to false
    "harmful_cough": true           - Defaults to false
    

    “pkill_addict_reduces” makes a player’s addiction to painkillers reduce the chance of the effect giving them more pkill. “pain_sizing” and “hurt_sizing” cause large/huge mutations to affect the chance of pain and hurt effects triggering. “harmful_cough” means that the coughs caused by this effect can hurt the player.

    Morale

    "morale": "morale_high"
    

    Type of morale effect provided. Mandatory if there is a morale effect, must not be specified otherwise.

    Enchantments

    "base_enchantments": [ { "values": [ { "value": "SKILL_LEVEL_COMPUTER", "add": 100 } ] } ],
    "scaling_enchantments": [ { "values": [ { "value": "SKILL_LEVEL_COMPUTER", "add": 100 } ] } ]
    

    Either an inline effect or a enchantment string id Must be an array Scaling is added once for each intensity above 1 Base is added once when effect is applied

    Other effects on removal

    "effects_on_remove": [
        {
            "intensity_requirement": 0, - Defaults to 0
            "effect_type": "cold",      - (Mandatory) Effect that will be applied
            "allow_on_decay": false,    - Defaults to true
            "allow_on_remove" true,     - Defaults to false
            "intensity": 5,             - Defaults to 0
            "inherit_intensity": false, - Defaults to false
            "duration": "10 s",         - Defaults to 0
            "inherit_duration": true,   - Defaults to true
            "body_part": "hand_r,       - Defaults to null
            "inherit_body_part": false  - Defaults to true
        }
    ]
    

    “intensity_requirement” will prevent adding the new effect if current effect has lower intensity. “allow_on_decay” enables adding the effect if parent decayed (was removed due to 0 duration). “allow_on_remove” enables adding the effect if parent was removed before 0 duration. “inherit_duration”, “inherit_intensity” and “inherit_body_part” cause the relevant variable to be copied from parent effect.

    Effect effects

    "base_mods" : {
        arguments
    },
    "scaling_mods": {
        arguments
    }
    

    This is where the real meat of the effect JSON definition lies. Each one can take a variety of arguments. Decimals are valid but must be formatted as “0.X” or “-0.X”. The game will round towards zero at the end when calculating actually applied values

    Basic definitions:

    "X_amount"      - Amount applied of X when effect is placed. Like apply messages it will only trigger on new effects
    "X_min"         - Minimum amount of X applied when roll triggers
    "X_max"         - Maximum amount of X applied when roll triggers (no entry means it will give exactly X_min each time instead of rng(min, max)
    "X_min_val"     - Minimum value the effect will push you to, 0 means uncapped! Doesn't exist for some X's!
    "X_max_val"     - Maximum value the effect will push you to, 0 means uncapped! Doesn't exist for some X's!
    "X_chance"      - Basic chance of X triggering each time, depends on "X_chance_bot" for exact formula
    "X_chance_bot"  - If this doesn't exist then the trigger chance is (1 in "X_chance"). If this does exist then the chance is ("X_chance" in "X_chance_bot")
    "X_tick"        - Effect rolls for X triggering every Y ticks
    

    Valid arguments:

    "str_mod"           - Positive values raises stat, negative values lowers stat
    "dex_mod"           - Positive values raises stat, negative values lowers stat
    "per_mod"           - Positive values raises stat, negative values lowers stat
    "int_mod"           - Positive values raises stat, negative values lowers stat
    "speed_mod"         - Positive values raises stat, negative values lowers stat
    
    "pain_amount"       - Positives raise pain, negatives don't make anything. Don't make it too high.
    "pain_min"          - Minimal amount of pain, certain effect will give/take
    "pain_max"          - if 0 or missing value will be exactly "pain_min"
    "pain_max_val"      - Defaults to 0, which means uncapped
    "pain_chance"       - Chance to get more pain
    "pain_chance_bot"
    "pain_tick"         - Defaults to every tick.
    
    "hurt_amount"       - Positives will give damage, negatives will heal instead. Don't make it too high.
    "hurt_min"          - Minimal amount of damage, certain effect will give/take
    "hurt_max"          - if 0 or missing value will be exactly "hurt_min"
    "hurt_chance"       - Chance to cause damage
    "hurt_chance_bot"
    "hurt_tick"         - Defaults to every tick
    
    "sleep_amount"      - Amount of turns spent sleeping.
    "sleep_min"         - Minimal amount of sleep in turns, certain effect can give
    "sleep_max"         - if 0 or missing value will be exactly "sleep_min"
    "sleep_chance"      - Chance to fall asleep
    "sleep_chance_bot"
    "sleep_tick"        - Defaults to every tick
    
    "pkill_amount"      - Amount of painkiller effect. Don't go too high with it.
    "pkill_min"         - Minimal amount of painkiller, certain effect will give
    "pkill_max"         - if 0 or missing value will be exactly "pkill_min"
    "pkill_max_val"     - Defaults to 0, which means uncapped
    "pkill_chance"      - Chance to cause painkiller effect(lowers pain)
    "pkill_chance_bot"
    "pkill_tick"        - Defaults to every tick
    
    "stim_amount"       - Negatives cause depressants effect and positives cause stimulants effect.
    "stim_min"          - Minimal amount of stimulant, certain effect will give.
    "stim_max"          - if 0 or missing value will be exactly "stim_min"
    "stim_min_val"      - Defaults to 0, which means uncapped
    "stim_max_val"      - Defaults to 0, which means uncapped
    "stim_chance"       - Chance to cause one of two stimulant effects
    "stim_chance_bot"
    "stim_tick"         - Defaults to every tick
    
    "health_amount"     - Negatives decrease health and positives increase it. It's semi-hidden stat, which affects healing.
    "health_min"        - Minimal amount of health, certain effect will give/take.
    "health_max"        - if 0 or missing value will be exactly "health_min"
    "health_min_val"    - Defaults to 0, which means uncapped
    "health_max_val"    - Defaults to 0, which means uncapped
    "health_chance"     - Chance to change health
    "health_chance_bot"
    "health_tick"       - Defaults to every tick
    
    "h_mod_amount"      - Affects health stat growth, positives increase it and negatives decrease it
    "h_mod_min"         - Minimal amount of health_modifier, certain effect will give/take
    "h_mod_max"         - if 0 or missing value will be exactly "h_mod_min"
    "h_mod_min_val"     - Defaults to 0, which means uncapped
    "h_mod_max_val"     - Defaults to 0, which means uncapped
    "h_mod_chance"      - Chance to change health_modifier
    "h_mod_chance_bot"
    "h_mod_tick"        - Defaults to every tick
    
    "rad_amount"        - Amount of radiation it can give/take. Just be aware that anything above [50] is fatal.
    "rad_min"           - Minimal amount of radiation, certain effect will give/take
    "rad_max"           - if 0 or missing value will be exactly "rad_min"
    "rad_max_val"       - Defaults to 0, which means uncapped
    "rad_chance"        - Chance to get more radiation
    "rad_chance_bot"
    "rad_tick"          - Defaults to every tick
    
    "hunger_amount"     - Amount of hunger it can give/take.
    "hunger_min"        - Minimal amount of hunger, certain effect will give/take
    "hunger_max"        - if 0 or missing value will be exactly "hunger_min"
    "hunger_min_val"    - Defaults to 0, which means uncapped
    "hunger_max_val"    - Defaults to 0, which means uncapped
    "hunger_chance"     - Chance to become more hungry
    "hunger_chance_bot"
    "hunger_tick"       - Defaults to every tick
    
    "thirst_amount"     - Amount of thirst it can give/take.
    "thirst_min"        - Minimal amount of thirst, certain effect will give/take
    "thirst_max"        - if 0 or missing value will be exactly "thirst_min"
    "thirst_min_val"    - Defaults to 0, which means uncapped
    "thirst_max_val"    - Defaults to 0, which means uncapped
    "thirst_chance"     - Chance to become more thirsty
    "thirst_chance_bot"
    "thirst_tick"       - Defaults to every tick
    
    "sleepdebt_amount"     - Amount of sleep debt it can give/take.
    "sleepdebt_min"        - Minimal amount of sleep, certain effect will give/take
    "sleepdebt_max"        - if 0 or missing value will be exactly "sleepdebt_min"
    "sleepdebt_min_val"    - Defaults to 0, which means uncapped
    "sleepdebt_max_val"    - Defaults to 0, which means uncapped
    "sleepdebt_chance"     - Chance to give more sleep
    "sleepdebt_chance_bot" - Min chance, unsure, needs auditing
    "sleepdebt_tick"       - Defaults to every tick
    
    "fatigue_amount"    - Amount of fatigue it can give/take. After certain amount character will need to sleep.
    "fatigue_min"       - Minimal amount of fatigue, certain effect will give/take
    "fatigue_max"       - if 0 or missing value will be exactly "fatigue_min"
    "fatigue_min_val"   - Defaults to 0, which means uncapped
    "fatigue_max_val"   - Defaults to 0, which means uncapped
    "fatigue_chance"    - Chance to get more tired
    "fatigue_chance_bot"
    "fatigue_tick"      - Defaults to every tick
    
    "stamina_amount"    - Amount of stamina it can give/take.
    "stamina_min"       - Minimal amount of stamina, certain effect will give/take
    "stamina_max"       - if 0 or missing value will be exactly "stamina_min"
    "stamina_min_val"   - Defaults to 0, which means uncapped
    "stamina_max_val"   - Defaults to 0, which means uncapped
    "stamina_chance"    - Chance to get stamina changes
    "stamina_chance_bot"
    "stamina_tick"      - Defaults to every tick
    
    "cough_chance"      - Chance to cause cough
    "cough_chance_bot"
    "cough_tick"        - Defaults to every tick
    
    "vomit_chance"      - Chance to cause vomiting
    "vomit_chance_bot"
    "vomit_tick"        - Defaults to every tick
    
    "healing_rate"      - Healed rate per day
    "healing_head"      - Percentage of healing value for head
    "healing_torso"     - Percentage of healing value for torso
    
    "morale"            - Amount of morale provided. Must be a single number (resistance not supported).
    
    This following effects only apply to monsters:
    
    "hit_mod"           - Raises or lowers monster melee_skill
    "dodge_mod"         - Raises or lowers monster dodge rating
    "bash_mod"          - Raises or lowers bashing damage dealt by basic attacks and melee special attacks, lowering it to zero will make it deal no damage
    "cut_mod"           - Raises or lowers cutting damage dealt by basic attacks and melee special attacks, lowering it to zero will make it deal no damage
    "size_mod"          - Shrinks or grows a monster's size, can't make a monster smaller than tiny or larger than huge
    

    Each argument can also take either one or two values.

    "thirst_min": [1]
    or
    "thirst_min": [1, 2]
    

    If an effect is “resisted” (either through “resist_effect” or “resist_trait”) then it will use the second value. If there is only one value given it will always use that amount.

    Base mods and Scaling mods: While on intensity = 1 an effect will only have the basic effects of its “base_mods”. However for each additional intensity it gains it adds the value of each of its “scaling_mods” to the calculations. So:

    Intensity 1 values = base_mods values
    Intensity 2 values = base_mods values + scaling_mods values
    Intensity 3 values = base_mods values + 2 * scaling_mods values
    Intensity 4 values = base_mods values + 3 * scaling_mods values
    

    and so on.

    Special case: The only special case is if base_mods’ “X_chance_bot” + intensity * scaling_mods’ “X_chance_bot” = 0 then it treats it as if it were equal to 1 (i.e. trigger every time)

    Example Effect

    "type": "effect_type",
    "id": "drunk",
    "name": [
        "Tipsy",
        "Drunk",
        "Trashed",
        "Wasted"
    ],
    "looks_like": "drunk",
    "max_intensity": 4,
    "apply_message": "You feel lightheaded.",
    "int_dur_factor": 1000,
    "miss_messages": [["You feel woozy.", 1]],
    "morale": "morale_drunk",
    "base_mods": {
        "str_mod": [1],
        "vomit_chance": [-43],
        "sleep_chance": [-1003],
        "sleep_min": [2500],
        "sleep_max": [3500],
        "morale": [ 5 ]
    },
    "scaling_mods": {
        "str_mod": [-0.67],
        "per_mod": [-1],
        "dex_mod": [-1],
        "int_mod": [-1.42],
        "vomit_chance": [21],
        "sleep_chance": [501],
        "morale": [ 10 ]
    }
    

    First when “drunk” is applied to the player if they aren’t already drunk it prints the message, “You feel lightheaded”. It also adds the “You feel woozy” miss message for as long as it is applied. It has “int_dur_factor”: 1000, meaning that its intensity will always be equal to its duration / 1000 rounded up, and it has “max_intensity”: 4 meaning the highest its intensity will go is 4 at a duration of 3000 or higher. As it moves up through the different intensities, its name will change. Its description will simply display the stat changes, with no additional description added.

    As it moves up through the intensity levels its effects will be:

    Intensity 1
        +1 STR
        +5 morale
        No other effects (since both "X_chance"s are negative)
    Intensity 2
        1 - .67 = .33 =         0 STR (Round towards zero)
        0 - 1 =                 -1 PER
        0 - 1 =                 -1 DEX
        0 -1.42 =               -1 INT
        -43 + 21 =              still negative, so no vomiting
        -1003 + 501 =           still negative, so no passing out
        5 + 10 =                15 morale
    Intensity 3
        1 - 2 * .67 = -.34 =    0 STR (round towards zero)
        0 - 2 * 1 =             -2 PER
        0 - 2 * 1 =             -2 DEX
        0 - 2 * 1.43 =          -2 INT
        -43 + 2 * 21 = -1       still negative, no vomiting
        -1003 + 2 * 501 = -1    still negative, no passing out
        5 + 2 * 10 =            25 morale
    Intensity 4
        1 - 3 * .67 = - 1.01 =  -1 STR
        0 - 3 * 1 =             -3 PER
        0 - 3 * 1 =             -3 DEX
        0 - 3 * 1.43 =          -4 INT
        -43 + 3 * 21 = 20       "vomit_chance_bot" doesn't exist, so a 1 in 20 chance of vomiting. "vomit_tick" doesn't exist, so it rolls every turn.
        -1003 + 3 * 501 = 500   "sleep_chance_bot" doesn't exist, so a 1 in 500 chance of passing out for rng(2500, 3500) turns. "sleep_tick" doesn't exist, so it rolls every turn.
        5 + 3 * 10 =            35 morale
    

    Blood analysis description

    "blood_analysis_description": "Minor Painkiller"
    

    This description will be displayed for every effect which has this field when character conducts a blood analysis (for example, through Blood Analysis CBM).

    NPC factions

    An NPC faction looks like this:

    {
      "type": "faction",
      "id": "free_merchants",
      "name": "The Free Merchants",
      "likes_u": 30,
      "respects_u": 30,
      "known_by_u": false,
      "size": 100,
      "power": 100,
      "food_supply": 115200,
      "lone_wolf_faction": true,
      "wealth": 75000000,
      "currency": "FMCNote",
      "relations": {
        "free_merchants": {
          "kill on sight": false,
          "watch your back": true,
          "share my stuff": true,
          "guard your stuff": true,
          "lets you in": true,
          "defends your space": true,
          "knows your voice": true
        },
        "old_guard": {
          "kill on sight": false,
          "watch your back": true,
          "share my stuff": false,
          "guard your stuff": true,
          "lets you in": true,
          "defends your space": true,
          "knows your voice": true
        },
        "hells_raiders": {
          "kill on sight": true
        }
      },    
      "description": "A conglomeration of entrepreneurs and businessmen that stand together to hammer-out an existence through trade and industry."
    },
    
    FieldMeaning
    "type"string, must be "faction"
    "id"string, unique faction id
    "name"string, the faction’s common name
    "likes_u"integer, the faction’s starting opinion of the player. "likes_u" can be increased or decreased in play. If it goes below -10, members of the faction will be hostile.
    "respects_u"integer, the faction’s starting opinionof the player. Has no meaningful effect in game and may be removed in the future.
    "known_by_u"boolean, whether the player has met members of the faction. Can be changed in play. Unknown factions will not be displayed in the faction menu.
    "size"integer, an approximate count of the members of the faction. Has no effect in play currently.
    "power"integer, an approximation of the faction’s power. Has no effect in play currently.
    "food_supply"integer, the number of calories available to the faction. Has no effect in play currently.
    "wealth"integer, number of post-apocalyptic currency in cents that that faction has to purchase stuff.
    "currency"string, the item "id" of the faction’s preferred currency. Faction shopkeeps will trade faction current at 100% value, for both selling and buying.
    "relations"dictionary, a description of how the faction sees other factions. See below
    "mon_faction"string, optional. The monster faction "name" of the monster faction that this faction counts as. Defaults to “human” if unspecified.
    "lone_wolf_faction"bool, optional. This is a proto/micro faction template that is used to generate 1-person factions for dynamically spawned NPCs, defaults to “false” if unspecified.

    Faction relations

    Factions can have relations with each other that apply to each member of the faction. Faction relationships are not reciprocal: members of the Free Merchants will defend members of the Lobby Beggars, but members of the Lobby Beggars will not defend members of the Free Merchants.

    Faction relationships are stored in a dictionary, with the dictionary keys being the name of the faction and the values being a second dictionary of boolean flags. All flags are optional and default to false. The faction with the dictionary is the acting faction and the other faction is the object faction.

    The flags have the following meanings:

    FlagMeaning
    "kill on sight"Members of the acting faction are always hostile to members of the object faction.
    "watch your back"Members of the acting faction will treat attacks on members of the object faction as attacks on themselves.
    "share my stuff"Members of the acting faction will not object if members of the object faction take items owned by the acting faction.
    "guard your stuff"Members of the acting faction will object if someone takes items owned by the object faction.
    "lets you in"Members of the acting faction will not object if a member of the object faction enters territory controlled by the acting faction.
    "defends your space"Members of the acting faction will become hostile if someone enters territory controlled by the object faction.
    "knows your voice"Members of the acting faction will not comment on speech by members of the object faction.

    So far, only "kill on sight", "knows your voice", and "watch your back" have been implemented.

    Spells

    In data/json/debug_spells.json there is a template spell, copied here for your perusal:

    {
      // This spell exists in json as a template for contributors to see the possible values of the spell
      "id": "example_template", // id of the spell, used internally. not translated
      "type": "SPELL",
      "name": "Template Spell", // name of the spell that shows in game
      "description": "This is a template to show off all the available values",
      "blocker_mutations": ["THRESH_RAT"], // list of mutations that will not allow you to cast the spell
      "valid_targets": ["hostile", "ground", "self", "ally"], // if a valid target is not included, you cannot cast the spell on that target.
      "effect": "shallow_pit", // effects are coded in C++. A list will be provided below of possible effects that have been coded.
      "effect_str": "template", // special. see below
      "extra_effects": [{ "id": "fireball", "hit_self": false, "max_level": 3 }], // this allows you to cast multiple spells with only one spell
      "melee_dam": ["cut", "elemental"], // the melee damage of these listed types will be added to spell damage. Supports standard damage type strings and also the categories of 'physical' and 'elemental' for convenience
      "affected_body_parts": [
        "HEAD",
        "TORSO",
        "MOUTH",
        "EYES",
        "ARM_L",
        "ARM_R",
        "HAND_R",
        "HAND_L",
        "LEG_L",
        "FOOT_L",
        "FOOT_R"
      ], // body parts affected by effects
      "spell_class": "NONE", //
      "scale_str": true, // The spell will scale off of strength. Also valid: scale_dex, scale_per, scale_int
      "base_casting_time": 100, // this is the casting time (in moves)
      "base_energy_cost": 10, // the amount of energy (of the requisite type) to cast the spell
      "energy_source": "MANA", // the type of energy used to cast the spell. types are: MANA, BIONIC, HP, STAMINA, FATIGUE, NONE (none will not use mana)
      "components": [requirement_id],                            // an id from a requirement, like the ones you use for crafting. spell components require to cast.
      "difficulty": 12, // the difficulty to learn/cast the spell
      "max_level": 10, // maximum level you can achieve in the spell
      "min_damage": 0, // minimum damage (or "starting" damage)
      "max_damage": 100, // maximum damage the spell can achieve
      "damage_increment": 2.5, // to get damage (and any of the other below stats) multiply this by spell's level and add to minimum damage
      "min_aoe": 0, // area of effect (currently not implemented)
      "max_aoe": 5,
      "aoe_increment": 0.1,
      "min_range": 1, // range of the spell
      "max_range": 10,
      "range_increment": 2,
      "min_accuracy": 50, // percentage "accuracy" of the spell. used for determining which body part was hit
      "max_accuracy": 70,
      "accuracy_increment": 2,
      "min_dot": 0, // damage over time (currently not implemented)
      "max_dot": 2,
      "dot_increment": 0.1,
      "min_duration": 0, // duration of spell effect (if the spell has a special effect)
      "max_duration": 1000,
      "duration_increment": 4,
      "min_pierce": 0, // how much of the spell pierces armor (currently not implemented)
      "max_pierce": 1,
      "pierce_increment": 0.1,
      "field_id": "fd_blood", // the string id of the field (currently hardcoded)
      "field_chance": 100, // one_in( field_chance ) chance of spawning a field per tile in aoe
      "min_field_intensity": 10, // field intensity of fields generated
      "max_field_intensity": 10,
      "field_intensity_increment": 1,
      "field_intensity_variance": 0.1, // the field can range in intensity from -variance as a percent to +variance as a percent i.e. this spell would be 9-11
      "volume": 90, // The volume of noise that the spell produces. This is a flat value that doesn't differ depending on level. Measured in decibels.
      "sound_type": "combat", // the type of sound. possible types are: background, weather, music, movement, speech, activity, destructive_activity, alarm, combat, alert, order
      "sound_description": "a whoosh", // the sound description. in the form of "You hear %s" by default it is "an explosion"
      "sound_ambient": true, // whether or not this is treated as an ambient sound or not
      "sound_id": "misc", // the sound id
      "sound_variant": "shockwave", // the sound variant
      "sprite": "fd_electricity", // This changes the spell sprite to any valid field ID. Do not use with NO_EXPLOSION_VFX
      "learn_spells": { "acid_resistance_greater": 15 } // You learn the specified spell once your level in this spell is greater than or equal to the number shown.
    }
    

    Most of the default values for the above are either 0 or “NONE”, so you may leave out most of the values if they do not pertain to your spell.

    When deciding values for some of these, it is important to note that some of the formulae are not linear. For example, this is the formula for spell failure chance:

    ( ( ( ( spell_level - spell_difficulty ) * 2 + intelligence + spellcraft_skill ) - 30 ) / 30 ) ^ 2

    Meaning a spell with difficulty 0 cast by a player with 8 intelligence, 0 spellcraft, and level 0 in the spell will have a 53% spell failure chance. On the other hand, a player with 12 intelligence, 6 spellcraft, and level 6 in the same spell will have a 0% spell failure chance.

    However, experience gain is a little more complicated to calculate. The formula for how much experience you need to get to a level is below:

    e ^ ( ( level + 62.5 ) * 0.146661 ) ) - 6200

    Currently Implemented Spell Flags

    • PERMANENT - items or creatures spawned with this spell do not disappear and die as normal

    • IGNORE_WALLS - spell’s aoe goes through walls

    • SWAP_POS - teleports the caster to the target location when used by a ranged spell, switching places with any creature that might be in the way

    • HOSTILE_SUMMON - summon spell always spawns a hostile monster

    • HOSTILE_50 - summoned monster spawns friendly 50% of the time

    • SILENT - spell makes no noise at target

    • NO_EXPLOSION_VFX - spell has no visual explosion

    • LOUD - spell makes extra noise at target

    • VERBAL - spell makes noise at caster location, mouth encumbrance affects fail %

    • SOMATIC - arm encumbrance affects fail % and casting time (slightly)

    • NO_HANDS - hands do not affect spell energy cost

    • UNSAFE_TELEPORT - teleport spell risks killing the caster or others

    • NO_LEGS - legs do not affect casting time

    • CONCENTRATE - focus affects spell fail %

    • RANDOM_AOE - picks random number between min+increment*level and max instead of normal behavior

    • RANDOM_DAMAGE - picks random number between min+increment*level and max instead of normal behavior

    • DIVIDE_DAMAGE - divides the spell’s damage among all the creatures it hits evenly

    • RANDOM_DURATION - picks random number between min+increment*level and max instead of normal behavior

    • RANDOM_TARGET - picks a random valid target within your range instead of normal behavior.

    • MUTATE_THRESH - mutate spell_effect will check for if it can grant the victim that the associated threshold, does nothing if MUTATE_TRAIT is also present and requires a category to be specified. If accuracy is defined, this will determine how many tiers of that category’s thresholds it will try to cross, with a default of tier 1.

    • MUTATE_TRAIT - overrides the mutate spell_effect to use a specific trait_id instead of a category

    • WONDER - instead of casting each of the extra_spells, it picks N of them and casts them (where N is std::min( damage(), number_of_spells ))

    • PAIN_NORESIST - pain altering spells can’t be resisted (like with the deadened trait)

    • BRAWL - Allows characters with the Brawler trait to cast the spell (otherwise they cannot)

    • DUPE_SOUND - Allows a spell to play multiple of the same sound (i.e. a sound for each target affected)

    • ADD_MELEE_DAM - Adds the highest category of melee damage for your currently wielded item to the spell’s damage (LEGACY, only handles Bash Stab and Cut. Please instead use melee_dam field)

    • PHYSICAL - Implies BRAWL and also means that Brawlers get a bonus when using the spell. Mostly for “Physical Techniques”

    • MOD_MELEE_MOVES - The melee move cost of your weapon is added to the “spell”’s cast cost. Special behavior: If the base_casting_time is negative with this flag, the “increment” is instead a multiplier on the melee cost (useful for replicating rapid strike in spell form)

    • MOD_MEELE_STAM - Like MOD_MELEE_MOVES but for the casting cost of the spell and the stamina cost of your weapon. Primarily meant for stamina techniques. Has the same special behavior involving negative base costs and the increment field.

    • DAMAGE_TERRAIN - This allows a damaging spell to also hit the terrain for a percentage of its damage based on its damage type.

    • NO_FAIL - this spell cannot fail when you cast it

    Currently Implemented Effects and special rules

    • pain_split - makes all of your limbs’ damage even out.

    • move_earth - “digs” at the target location. some terrain is not diggable this way.

    • target_attack - deals damage to a target (ignores walls). Negative damage heals the target. If “effect_str” is included, it will add that effect (defined elsewhere in json) to the targets if able, to the body parts defined in affected_body_parts. Any aoe will manifest as a circular area centered on the target, and will only deal damage to valid_targets. (aoe does not ignore walls)

    • projectile_attack - similar to target_attack, except the projectile you shoot will stop short at impassable terrain. If “effect_str” is included, it will add that effect (defined elsewhere in json) to the targets if able, to the body parts defined in affected_body_parts.

    • cone_attack - fires a cone toward the target up to your range. The arc of the cone in degrees is aoe. Stops at walls. If “effect_str” is included, it will add that effect (defined elsewhere in json) to the targets if able, to the body parts defined in affected_body_parts.

    • line_attack - fires a line with width aoe toward the target, being blocked by walls on the way. If “effect_str” is included, it will add that effect (defined elsewhere in json) to the targets if able, to the body parts defined in affected_body_parts.

    • spawn_item - spawns an item that will disappear at the end of its duration. Default duration is 0. Damage determines quantity.

    • summon_vehicle - spawns a specified vehicle that should disappear after its duration

    • summon - spawns a monster that will disappear at the end of its duration. By default friendly to the player. Damage determines quantity.

    • translocate - teleports the player between registered ‘translocators’, such as the gates in Magical Nights

    • teleport_random - teleports the player randomly range spaces with aoe variation

    • recover_energy - recovers an energy source (defined in the effect_str, shown below) equal to damage of the spell

    • “MANA”
    • “STAMINA”
    • “FATIGUE”
    • “PAIN”
    • “BIONIC”
    • ter_transform - transform the terrain and furniture in an area centered at the target. The chance of any one of the points in the area of effect changing is one_in( damage ). The effect_str is the id of a ter_furn_transform.

    • vomit - any creature within its area of effect will instantly vomit, if it’s able to do so.

    • timed_event - adds a timed event to the player only. valid timed events: “help”, “wanted”, “robot_attack”, “spawn_wyrms”, “amigara”, “roots_die”, “temple_open”, “temple_flood”, “temple_spawn”, “dim”, “artifact_light” NOTE: This was added only for artifact active effects. support is limited, use at your own risk.

    • explosion - an explosion is centered on the target, with power damage() and factor aoe()/10

    • flashbang - a flashbang effect is centered on the target, with poewr damage() and factor aoe()/10

    • mod_moves - adds damage() moves to the target. can be negative to “freeze” the target for that amount of time

    • map - maps the overmap centered on the player out to a radius of aoe()

    • morale - gives a morale effect to all npcs or avatar within aoe, with value damage(). decay_start is duration() / 10.

    • charm_monster - charms a monster that has less hp than damage() for approximately duration()

    • mutate - mutates the target(s). if effect_str is defined, mutates toward that category instead of picking at random. the “MUTATE_TRAIT” flag allows effect_str to be a specific trait instead of a category. damage() / 100 is the percent chance the mutation will be successful (a value of 10000 represents 100.00%)

    • bash - bashes the terrain at the target. uses damage() as the strength of the bash.

    • dash - moves the player to the target tile, can leave behind fields.

    • area_push - pushes things outwards from a single point

    • directed_push pushes things in a single direction away from you.

    • noise makes noise at a loudness equal to the spell’s damage.

    • WONDER - Unlike the above, this is not an “effect” but a “flag”. This alters the behavior of the parent spell drastically: The spell itself doesn’t cast, but its damage and range information is used in order to cast the extra_effects. N of the extra_effects will be chosen at random to be cast, where N is the current damage of the spell (stacks with RANDOM_DAMAGE flag) and the message of the spell cast by this spell will also be displayed. If this spell’s message is not wanted to be displayed, make sure the message is an empty string.

    • RANDOM_TARGET - A special spell flag (like wonder) that forces the spell to choose a random valid target within range instead of the caster choosing the target. This also affects extra_effects.

    For Spells that have an attack type, these are the available damage types (case-insensitive):
    • fire
    • acid
    • bash
    • bullet
    • bio - internal damage such as poison
    • cold
    • cut
    • electric
    • light - used both for actual light, as well as ‘holy’
    • dark
    • psi - psychic
    • stab
    • true - this damage type goes through armor altogether, and thus is very powerful. It is the default damage type when unspecified.

    Spells that level up

    Spells that change effects as they level up must have a min and max effect and an increment. The min effect is what the spell will do at level 0, and the max effect is where it stops growing. The increment is how much it changes per level. For example:

    "min_range": 1,
    "max_range": 25,
    "range_increment": 5,
    

    Min and max values must always have the same sign, but it can be negative eg. in the case of spells that use a negative ‘recover’ effect to cause pain or stamina damage. For example:

    {
      "id": "stamina_damage",
      "type": "SPELL",
      "name": "Tired",
      "description": "decreases stamina",
      "valid_targets": ["hostile"],
      "min_damage": -2000,
      "max_damage": -10000,
      "damage_increment": -3000,
      "max_level": 10,
      "effect": "recover_energy",
      "effect_str": "STAMINA"
    }
    

    Learning Spells

    There are three ways of granting spells that are implemented: Mutating can grant a spell with the “spells_learned” field which also lets you specify the level granted. Certain spells can also teach you spells once they reach an appropriate level via the “learn_spells” variable. Finally, You can learn a spell from an item through a use_action, which is also the only way to train a spell other than using it. Examples of all three are shown below:

    {
      "id": "DEBUG_spellbook",
      "type": "GENERIC",
      "name": "A Technomancer's Guide to Debugging C:BN",
      "description": "static std::string description( spell sp ) const;",
      "weight": 1,
      "volume": "1 ml",
      "symbol": "?",
      "color": "magenta",
      "use_action": {
        "type": "learn_spell",
        "spells": [ "debug_hp", "debug_stamina", "example_template", "debug_bionic", "pain_split", "fireball" ] // this is a list of spells you can learn from the item
      }
    },
    

    For the below example you will learn the spell Greater Acid Resistance once Acid Resistance reaches level 15

    {
        "id": "acid_resistance",
        "type": "SPELL",
        "name": { "str": "Acid Resistance" },
        "description": "Protects the user from acid.",
        ...
        "learn_spells": { "acid_resistance_greater": 15 }
    }
    

    You can study this spellbook for a rate of ~1 experience per turn depending on intelligence, spellcraft, and focus.

    "spells_learned": [ [ "debug_hp", 1 ], [ "debug_stamina", 1 ], [ "example_template", 1 ], [ "pain_split", 1 ] ],
    

    Spells in professions and NPC classes

    You can add a “spell” member to professions or an NPC class definition like so:

    "spells": [ { "id": "summon_zombie", "level": 0 }, { "id": "magic_missile", "level": 10 } ]
    

    NOTE: This makes it possible to learn spells that conflict with a class. It also does not give the prompt to gain the class. Be judicious upon adding this to a profession!

    Spells in monsters

    You can assign a spell as a special attack for a monster.

    { "type": "spell", "spell_id": "burning_hands", "spell_level": 10, "cooldown": 10 }
    
    • spell_id: the id for the spell being cast.
    • spell_level: the level at which the spell is cast. Spells cast by monsters do not gain levels like player spells.
    • cooldown: how often the monster can cast this spell

    Martial arts & techniques

    Martial arts

    "type" : "martial_art",
    "id" : "style_debug",       // Unique ID. Must be one continuous word,
                                // use underscores if necessary.
    "name" : "Debug Mastery",   // In-game name displayed
    "description": "A secret martial art used only by developers and cheaters.",    // In-game description
    "initiate": [ "You stand ready.", "%s stands ready." ],     // Message shown when player or NPC chooses this art
    "autolearn": [ [ "unarmed", "2" ] ],     // A list of skill requirements that if met, automatically teach the player the martial art
    "learn_difficulty": 5,      // Difficulty to learn a style from book based on "primary skill"
                                // Total chance to learn a style from a single read of the book is equal to one in (10 + learn_difficulty - primary_skill)
    "arm_block" : 99,           // Unarmed skill level at which arm blocking is unlocked
    "leg_block" : 99,           // Unarmed skill level at which arm blocking is unlocked
    "static_buffs" : [          // List of buffs that are automatically applied every turn
        "id" : "debug_elem_resist",
        "heat_arm_per" : 1.0
    ],
    "ondodge_buffs" : [],        // List of buffs that are automatically applied on successful dodge
    "onattack_buffs" : [],       // List of buffs that are automatically applied after any attack, hit or miss
    "onhit_buffs" : [],          // List of buffs that are automatically applied on successful hit
    "onmove_buffs" : [],         // List of buffs that are automatically applied on movement
    "onmiss_buffs" : [],         // List of buffs that are automatically applied on a miss
    "oncrit_buffs" : [],         // List of buffs that are automatically applied on a crit
    "onkill_buffs" : [],         // List of buffs that are automatically applied upon killing an enemy
    "techniques" : [            // List of techniques available when this martial art is used
        "tec_debug_slow",
        "tec_debug_arpen"
    ],
    "weapons": [ "tonfa" ],      // List of weapons usable with this art
    "weapon_category": [ "WEAPON_CAT1" ], // Weapons that have one of the categories in here are usable with this art.
    "mutation": [ "UNSTYLISH" ] // A list of mutations, at least 1 of which is needed to use this art
    

    Techniques

    "id" : "tec_debug_arpen",   // Unique ID. Must be one continuous word
    "name" : "phasing strike",  // In-game name displayed
    "unarmed_allowed" : true,   // Can an unarmed character use this technique
    "unarmed_weapons_allowed" : true,    // Does this technique require the character to be actually unarmed or does it allow unarmed weapons
    "force_unarmed" : true,   // Techniques with this will not take weapon damage into account, e.g. kicks/throws
    "weapon_categories_allowed" : [ "BLADES", "KNIVES" ], // Restrict technique to only these categories of weapons. If omitted, all weapon categories are allowed. Empty hands are always allowed if unarmed_allowed is true.
    "melee_allowed" : true,     // Means that ANY melee weapon can be used, NOT just the martial art's weapons
    "skill_requirements": [ { "name": "melee", "level": 3 } ],     // Skills and their minimum levels required to use this technique. Can be any skill.
    "weapon_damage_requirements": [ { "type": "bash", "min": 5 } ],     // Minimum weapon damage required to use this technique. Can be any damage type.
    "req_buffs": [ "eskrima_hit_buff" ],    // This technique requires a named buff to be active
    "crit_tec" : true,          // This technique only works on a critical hit
    "crit_ok" : true,           // This technique works on both normal and critical hits
    "downed_target": true,      // Technique only works on a downed target
    "stunned_target": true,     // Technique only works on a stunned target
    "human_target": true,       // Technique only works on a human-like target
    "knockback_dist": 1,        // Distance target is knocked back
    "knockback_spread": 1,      // The knockback may not send the target straight back
    "knockback_follow": 1,      // Attacker will follow target if they are knocked back
    "stun_dur": 2,              // Duration that target is stunned for
    "down_dur": 2,              // Duration that target is downed for
    "side_switch": true,        // Technique moves the target behind user
    "disarms": true,            // This technique can disarm the opponent
    "take_weapon": true,        // Technique will disarm and equip target's weapon if hands are free
    "grab_break": true,         // This technique may break a grab against the user
    "aoe": "spin",              // This technique has an area-of-effect; doesn't work against solo targets
    "block_counter": true,      // This technique may automatically counterattack on a successful block
    "dodge_counter": true,      // This technique may automatically counterattack on a successful dodge
    "weighting": 2,             // Affects likelihood this technique will be seleted when many are available
    "defensive": true,          // Game won't try to select this technique when attacking
    "wall_adjacent": true,      // You must be adjacent to a wall
    "miss_recovery": true,      // Misses while attacking will use fewer moves
    "messages" : [              // What is printed when this technique is used by the player and by an npc
        "You phase-strike %s",
        "<npcname> phase-strikes %s"
    ]
    "movecost_mult" : 0.3,       // Any bonuses, as described below
    "mutations_required": [ "MASOCHIST" ] // List of mutations, at least 1 of which is required to use the technique
    

    Buffs

    "id" : "debug_elem_resist",         // Unique ID. Must be one continuous word
    "name" : "Elemental resistance",    // In-game name displayed
    "description" : "+Strength bash armor, +Dexterity acid armor, +Intelligence electricity armor, +Perception fire armor.",    // In-game description
    "buff_duration": 2,                 // Duration in turns that this buff lasts
    "unarmed_allowed" : true,           // Can this buff be applied to an unarmed character
    "melee_allowed" : false,          // Can this buff be applied to an armed character
    "weapon_categories_allowed" : [ "BLADES", "KNIVES" ], // Restrict buff to only these categories of weapons. If omitted, all weapon categories are allowed. Empty hands are always allowed if unarmed_allowed is true.
    "unarmed_weapons_allowed" : true,          // Does this buff require the character to be actually unarmed. If true, allows unarmed weapons (brass knuckles, punch daggers)
    "max_stacks" : 8,                   // Maximum number of stacks on the buff. Buff bonuses are multiplied by current buff intensity
    "bonus_blocks": 1       // Extra blocks per turn
    "bonus_dodges": 1       // Extra dodges per turn
    "flat_bonuses" : [                  // Flat bonuses, see below
    ],
    "mult_bonuses" : [                  // Multiplicative bonuses, see below
    ]
    

    Bonuses

    The bonuses arrays contain any number of bonus entries like this:

    {
      "stat": "damage",
      "type": "bash",
      "scaling-stat": "per",
      "scale": 0.15
    }
    
    • "stat": affected statistic, any of: “hit”, “dodge”, “block”, “speed”, “movecost”, “damage”, “armor”, “arpen”, “target_armor_multiplier”.
    • "type": damage type for the affected statistic (“bash”, “cut”, “heat”, etc.), only needed if the affected statistic is “damage”, “armor”, “arpen”, or “target_armor_multiplier”.
    • "scale": the value of the bonus itself.
    • "scaling-stat": scaling stat, any of: “str”, “dex”, “int”, “per”. Optional. If the scaling stat is specified, the value of the bonus is multiplied by the corresponding user stat.

    Bonuses must be written in the correct order.

    Tokens of useless type will not cause an error, but will not have any effect. For example, speed in a technique will have no effect (movecost should be used for techniques).

    Currently extra elemental damage is not applied, but extra elemental armor is (after regular armor).

    Examples: Incoming bashing damage is decreased by 30% of strength value. Only useful on buffs:

    • flat_bonuses : [ { "stat": "armor", "type": "bash", "scaling-stat": "str", "scale": 0.3 } ]

    All cutting damage dealt is multiplied by (10% of dexterity)*(damage):

    • mult_bonuses : [ { "stat": "damage", "type": "cut", "scaling-stat": "dex", "scale": 0.1 } ]

    Move cost is decreased by 100% of strength value

    • flat_bonuses : [ { "stat": "movecost", "scaling-stat": "str", "scale": -1.0 } ]

    Additional fields usable in static_bonuses

    "stealthy": true, // All movement will make less noise "quiet": true, // Your attacks will be completely silent
    "wall_adjacent": true, // You must be adjacent to a wall
    "throw_immune": true, // You're immune to being thrown
    

    Place relevant items in the world and chargen

    Starting trait selection of your martial art goes in mutations.json. Place your art in the right category (self-defense, Shaolin animal form, melee style, etc)

    Use json/itemgroups/ to place your martial art book and any martial weapons you’ve made for the art into spawns in various locations in the world. If you don’t place your weapons in there, only recipes to craft them will be an option.

    Creating missions

    NPCs can assign missions to the player. There is a fairly regular structure for this:

    {
      "id": "MISSION_GET_BLACK_BOX_TRANSCRIPT",
      "type": "mission_definition",
      "name": "Retrieve Black Box Transcript",
      "description": "Decrypt the contents of the black box using a terminal from a nearby lab.",
      "goal": "MGOAL_FIND_ITEM",
      "difficulty": 2,
      "value": 150000,
      "item": "black_box_transcript",
      "start": {
        "effect": { "u_buy_item": "black_box" },
        "assign_mission_target": { "om_terrain": "lab", "reveal_radius": 3 }
      },
      "origins": ["ORIGIN_SECONDARY"],
      "followup": "MISSION_EXPLORE_SARCOPHAGUS",
      "dialogue": {
        "describe": "With the black box in hand, we need to find a lab.",
        "offer": "Thanks to your searching we've got the black box but now we need to have a look'n-side her.  Now, most buildings don't have power anymore but there are a few that might be of use.  Have you ever seen one of those science labs that have popped up in the middle of nowhere?  Them suckers have a glowing terminal out front so I know they have power somewhere inside'em.  If you can get inside and find a computer lab that still works you ought to be able to find out what's in the black box.",
        "accepted": "Fuck ya, America!",
        "rejected": "Do you have any better ideas?",
        "advice": "When I was play'n with the terminal for the one I ran into it kept asking for an ID card.  Finding one would be the first order of business.",
        "inquire": "How 'bout that black box?",
        "success": "America, fuck ya!  I was in the guard a few years back so I'm confident I can make heads-or-tails of these transmissions.",
        "success_lie": "What?!  I out'ta whip you're ass.",
        "failure": "Damn, I maybe we can find an egg-head to crack the terminal."
      }
    }
    

    type

    Must always be there and must always be “mission_definition”.

    id

    The mission id is required, but for new missions, it can be arbitrary. Convention is to start it with “MISSION” and to use a fairly descriptive name.

    name

    The name is also required, and is displayed to the user in the ’m’issions menu.

    description

    Not required, but it’s strongly recommended that you summarize all relevant info for the mission. You may refer to mission end effects of the “u_buy_item” type, as long as they do not come at a cost to the player. See the example below:

    "id": "MISSION_EXAMPLE_TOKENS",
    "type": "mission_definition",
    "name": "Murder Money",
    "description": "Whack the target in exchange for <reward_item:FMCNote> c-notes and <reward_item:cig> cigarettes.",
    "goal": "MGOAL_ASSASSINATE",
    "end": {
      "effect": [
        { "u_buy_item": "FMCNote", "count": 999 },
        { "u_buy_item": "cig", "count": 666 } ]
    }
    

    This system may be expanded in the future to allow referring to other mission parameters and effects.

    goal

    Must be included, and must be one of these strings:

    goal stringGoal conditions
    MGOAL_GO_TOReach a specific overmap tile
    MGOAL_GO_TO_TYPEReach any instance of a specified overmap tile type
    MGOAL_COMPUTER_TOGGLEActivating the correct terminal will complete the mission
    MGOAL_FIND_ITEMFind 1 or more items of a given type
    MGOAL_FIND_ITEM_GROUPFind 1 or more items of a given item_group.
    MGOAL_FIND_ANY_ITEMFind 1 or more items of a given type, tagged for this mission
    MGOAL_FIND_MONSTERFind and retrieve a friendly monster
    MGOAL_FIND_NPCFind a specific NPC
    MGOAL_TALK_TO_NPCTalk to a specific NPC
    MGOAL_RECRUIT_NPCRecruit a specific NPC
    MGOAL_RECRUIT_NPC_CLASSRecruit an NPC of a specific class
    MGOAL_ASSASSINATEKill a specific NPC
    MGOAL_KILL_MONSTERKill a specific hostile monster
    MGOAL_KILL_MONSTER_TYPEKill some number of a specific monster type
    MGOAL_KILL_MONSTER_SPECKill some number of monsters from a specific species
    MGOAL_KILL_MONSTERSKill specific mission-tagged monsters spawned at mission start
    MGOAL_CONDITIONSatisfy the dynamically created condition and talk to the mission giver

    monster_species

    For “MGOAL_KILL_MONSTER_SPEC”, sets the target monster species.

    monster_type

    For “MGOAL_KILL_MONSTER_TYPE”, sets the target monster type.

    monster_kill_goal

    For “MGOAL_KILL_MONSTER_SPEC” and “MGOAL_KILL_MONSTER_TYPE”, sets the number of monsters above the player’s current kill count that must be killed to complete the mission.

    goal_condition

    For “MGOAL_CONDITION”, defines the condition that must be satisified for the mission to be considered complete. Conditions are explained in more detail in NPCs.md, and are used here in exactly the same way.

    dialogue

    This is a dictionary of strings. The NPC says these exact strings in response to the player inquiring about the mission or reporting its completion. All these strings are required, even if they may not be used in the mission.

    string IDUsage
    describeThe NPC’s overall description of the mission
    offerThe specifics of the mission given when the player selects that mission for consideration
    acceptedThe NPC’s response if the player accepts the mission
    rejectedThe NPC’s response if the player refuses the mission
    adviceIf the player asks for advice on how to complete the mission, they hear this
    inquireThis is used if the NPC asks the player how the mission is going
    successThe NPC’s response to a report that the mission was successful
    success_lieThe NPC’s response if they catch the player lying about a mission’s success
    failureThe NPC’s response if the player reports a failed mission

    start

    Optional field. If it is present and a string, it must be name of a function in mission_start:: that takes a mission * and performs the start code for the mission. This allows missions other than the standard mission types to be run. A hardcoded function is currently necessary to set up missions with “MGOAL_COMPUTER_TOGGLE”.

    Alternately, if present, it can be an object as described below.

    start / end / fail effects

    If any of these optional fields are present they can be objects with the following fields contained:

    effect

    This is an effects array, exactly as defined in NPCs.md, and can use any of the values from effects. In all cases, the NPC involved is the quest giver.

    reveal_om_ter

    This can be a string or a list of strings, all of which must be overmap terrain ids. A randomly selected overmap terrain tile with that id - or one of the ids from list, randomly selected - will be revealed, and there is a 1 in 3 chance that the road route to the map tile will also be revealed.

    assign_mission_target

    The assign_mission_target object specifies the criteria for finding (or creating if necessary) a particular overmap terrain and designating it as the mission target. Its parameters allow control over how it is picked and how some effects (such as revealing the surrounding area) are applied afterwards. The om_terrain is the only required field.

    IdentifierDescription
    om_terrainID of overmap terrain which will be selected as the target. Mandatory.
    om_terrain_match_typeMatching rule to use with om_terrain. Defaults to TYPE. Details below.
    om_specialID of overmap special containing the overmap terrain.
    om_terrain_replaceID of overmap terrain to be found and replaced if om_terrain cannot be found.
    reveal_radiusRadius in overmap terrain coordinates to reveal.
    must_seeIf true, the om_terrain must have been seen already.
    cant_seeIf true, the om_terrain must not have been seen already.
    randomIf true, a random matching om_terrain is used. If false, the closest is used.
    search_rangeRange in overmap terrain coordinates to look for a matching om_terrain.
    min_distanceRange in overmap terrain coordinates. Instances of om_terrain in this range will be ignored.
    origin_npcStart the search at the NPC’s, rather than the player’s, current position.
    zIf specified, will be used rather than the player or NPC’s z when searching.
    offset_x,<br>offset_y,<br>offset_zAfter finding or creating om_terrain, offset the mission target terrain by the offsets in overmap terrain coordinates.

    example

    {
      "assign_mission_target": {
        "om_terrain": "necropolis_c_44",
        "om_special": "Necropolis",
        "reveal_radius": 1,
        "must_see": false,
        "random": true,
        "search_range": 180,
        "z": -2
      }
    }
    

    If the om_terrain is part of an overmap special, it’s essential to specify the om_special value as well–otherwise, the game will not know how to spawn the entire special.

    om_terrain_match_type defaults to TYPE if unspecified, and has the following possible values:

    • EXACT - The provided string must completely match the overmap terrain id, including linear direction suffixes for linear terrain types or rotation suffixes for rotated terrain types.

    • TYPE - The provided string must completely match the base type id of the overmap terrain id, which means that suffixes for rotation and linear terrain types are ignored.

    • PREFIX - The provided string must be a complete prefix (with additional parts delimited by an underscore) of the overmap terrain id. For example, “forest” will match “forest” or “forest_thick” but not “forestcabin”.

    • CONTAINS - The provided string must be contained within the overmap terrain id, but may occur at the beginning, end, or middle and does not have any rules about underscore delimiting.

    If an om_special must be placed, it will follow the same placement rules as defined in its overmap special definition, respecting allowed terrains, distance from cities, road connections, and so on. Consequently, the more restrictive the rules, the less likely this placement will succeed (as it is competing for space with already-spawned specials).

    om_terrain_replace is only relevent if the om_terrain is not part of an overmap special. This value is used if the om_terrain cannot be found, and will be used as an alternative target which will then be replaced with the om_terrain value.

    If must_see is set to true, the game will not create the terrain if it can’t be found. It tries to avoid having new terrains magically appear in areas where the player has already been, and this is a consequence.

    reveal_radius, min_distance, and search_range are all in overmap terrain coordinates (an overmap is currently 180 x 180 OMT units). The search is centered on the player unless origin_npc is set, in which case it centered on the NPC. Currently, there is rarely a difference between the two, but it is possible to assign missions over a radio. The search gives preference to existing overmaps (and will only spawn new overmaps if the terrain can’t be found on existing overmaps), and only executes on the player’s current z-level. The z attribute can be used to override this and search on a different z-level than the player–this is an absolute value rather than relative.

    offset_x, offset_y, and offset_z change the final location of the mission target by their values. This can change the mission target’s overmap terrain type away from om_terrain.

    update_mapgen

    The update_mapgen object or array provides a way to modify existing overmap tiles (including the ones created by “assign_mission_target”) to add mission specific monsters, NPCs, computers, or items.

    As an array, update_mapgen consists of two or more update_mapgen objects.

    As an object, update_mapgen contains any valid JSON mapgen objects. The objects are placed on the mission target terrain from “assign_mission_target” or optionally the closest overmap terrain specified by the om_terrain and om_special fields. If “mapgen_update_id” is specified, the “mapge_update” object with the matching “mapgen_update_id” will be executed.

    See doc/MAPGEN.md for more details on JSON mapgen and update_mapgen.

    An NPC, monster, or computer placed using update_mapgen will be the target of a mission if it has the target boolean set to true in its place object in update_mapgen.

    Adding new missions to NPC dialogue

    In order to assign missions to NPCs, the first step is to find that NPC’s definition. For unique NPCs this is usually at the top of the npc’s JSON file and looks something like this:

    {
      "type": "npc",
      "id": "refugee_beggar2",
      "//": "Schizophrenic beggar in the refugee center.",
      "name_unique": "Dino Dave",
      "gender": "male",
      "name_suffix": "beggar",
      "class": "NC_BEGGAR_2",
      "attitude": 0,
      "mission": 7,
      "chat": "TALK_REFUGEE_BEGGAR_2",
      "faction": "lobby_beggars"
    },
    

    Add a new line that defines the NPC’s starting mission, eg:

    "mission_offered": "MISSION_BEGGAR_2_BOX_SMALL"
    

    Any NPC that has missions needs to have a dialogue option that leads to TALK_MISSION_LIST, to get the player started on their first mission for the NPC, and either:

    • Add one of their talk_topic IDs to the list of generic mission reponse IDs in the first talk_topic of data/json/npcs/TALK_COMMON_MISSION.json, or
    • Have a similar talk_topic with responses that lead to TALK_MISSION_INQUIRE and TALK_MISSION_LIST_ASSIGNED.

    Either of these options will allow the player to do normal mission management dialogue with the NPC.

    This is an example of how a custom mission inquiry might appear. This will only appear in the NPC’s dialogue options if the player has already been assigned a mission.

    {
        "type": "talk_topic",
        "//": "Generic responses for Old Guard Necropolis NPCs that can have missions",
        "id": [ "TALK_OLD_GUARD_NEC_CPT", "TALK_OLD_GUARD_NEC_COMMO" ],
        "responses": [
          {
            "text": "About the mission...",
            "topic": "TALK_MISSION_INQUIRE",
            "condition": { "and": [ "has_assigned_mission", { "u_is_wearing": "badge_marshal" } ] }
          },
          {
            "text": "About one of those missions...",
            "topic": "TALK_MISSION_LIST_ASSIGNED",
            "condition": { "and": [ "has_many_assigned_missions", { "u_is_wearing": "badge_marshal" } ] }
          }
        ]
    },
    

    Monster Factions

    Note

    This article was recently split off from JSON INFO and likely could use additional work

    Monster Factions

    IdentifierDescription
    nameUnique ID. Must be one continuous word, use underscores when necessary.
    base_factionOptional base faction. Relations to other factions are inherited from it and relations of other factions to this one check this.
    by_moodBe hostile towards this faction when angry, neutral otherwise. Default attitude to all other factions.
    neutralAlways be neutral towards this faction.
    friendlyAlways be friendly towards this faction. By default a faction is friendly towards itself.
    hateAlways be hostile towards this faction. Will change target to monsters of this faction if available.
    {
      "name": "cult",
      "base_faction": "zombie",
      "by_mood": ["blob"],
      "neutral": ["nether"],
      "friendly": ["blob"],
      "hate": ["fungus"]
    }
    

    Monster Spawning System

    Note

    This article was recently split off from JSON INFO and likely could use additional work

    Monster Groups

    Group definition

    IdentifierDescription
    nameUnique ID. Must be one continuous word, use underscores if necessary.
    defaultDefault monster, automatically fills in any remaining spawn chances.
    monstersTo choose a monster for spawning, the game creates 1000 entries and picks one. Each monster will have a number of entries equal to it’s “freq” and the default monster will fill in the remaining. See the table below for how to build the single monster definitions.
    is_safe(bool) Check to not trigger safe-mode warning.
    is_animal(bool) Check if that group has only normal animals.
    evolve_repeat(int) Number of attempts for extra default evolutions. 0 means off
    evolve_chance(int) Chance for extra evolutions from 0-100
    replacement_time(time_duration) Time until it upgrades to new_monster_group_id
    new_monster_group_id(mongroup_id) What group this upgrades to over time
    auto_total(bool) Force freq_total to be the sum of all frequencies, no matter how it was defined

    Monster definition

    IdentifierDescription
    monsterThe monster’s unique ID, eg. "mon_zombie". Either this or monster_group is required
    monster_groupThe monster groups unique ID to pull from, eg. "GROUP_NETHER"
    freqChance of occurrence, x/freq_total.
    weightChance of occurrence, weighted. If used without freq_total being defined ( I.E. freq_total == 1000 ), their sum is freq_total, otherwise it adds to freq total.
    cost_multiplierHow many monsters each monster in this definition should count as, if spawning a limited number of monsters.
    pack_size(optional) The minimum and maximum number of monsters in this group that should spawn together. (default: [1,1])
    conditionsConditions limit when monsters spawn. Valid options: SUMMER, WINTER, AUTUMN, SPRING, DAY, NIGHT, DUSK, DAWN. Multiple Time-of-day conditions (DAY, NIGHT, DUSK, DAWN) will be combined together so that any of those conditions makes the spawn valid. Multiple Season conditions (SUMMER, WINTER, AUTUMN, SPRING) will be combined together so that any of those conditions makes the spawn valid.
    starts(optional) This entry becomes active after this time. (Measured in hours)
    ends(optional) This entry becomes inactive after this time. (Measured in hours)
    {
      "name": "GROUP_ANT",
      "default": "mon_ant",
      "monsters": [
        { "monster": "mon_ant_larva", "freq": 40, "multiplier": 0 },
        { "monster": "mon_ant_soldier", "freq": 90, "multiplier": 5 },
        { "monster": "mon_ant_queen", "freq": 0, "multiplier": 0 },
        {
          "monster": "mon_thing",
          "freq": 100,
          "multiplier": 0,
          "pack_size": [3, 5],
          "conditions": ["DUSK", "DAWN", "SUMMER"]
        }
      ]
    }
    

    Monsters

    Monster types

    Monster types are specified as JSON object with “type” member set to “MONSTER”:

    {
        "type": "MONSTER",
        "id": "mon_foo",
        ...
    }
    

    The id member should be the unique id of the type. It can be any string, by convention it has the prefix “mon_”. This id can be referred to in various places, like monster groups or in mapgen to spawn specific monsters.

    For quantity strings (ie. volume, weight) use the largest unit you can keep full precision with.

    Monster types support the following properties (mandatory, except if noted otherwise):

    “name”

    (string or object)

    "name": "cow"
    
    "name": { "ctxt": "fish", "str": "pike", "str_pl": "pikes" }
    

    or, if the singular and plural forms are the same:

    "name": { "ctxt": "fish", "str_sp": "bass" }
    

    Name displayed in-game, and optionally the plural name and a translation context (ctxt).

    If the plural name is not specified, it defaults to singular name + “s”.

    Ctxt is used to help translators in case of homonyms (two different things with the same name). For example, pike the fish and pike the weapon.

    “description”

    (string)

    In-game description for the monster.

    “categories”

    (array of strings, optional)

    Monster categories. Can be NULL, CLASSIC (only mobs found in classic zombie movies) or WILDLIFE (natural animals). If they are not CLASSIC or WILDLIFE, they will not spawn in classic mode. One can add or remove entries in mods via “add:flags” and “remove:flags”.

    “species”

    (array of strings, optional)

    A list of species ids. One can add or remove entries in mods via “add:species” and “remove:species”, see Modding below. Properties (currently only triggers) from species are added to the properties of each monster that belong to the species.

    In mainline game it can be HUMAN, ROBOT, ZOMBIE, MAMMAL, BIRD, FISH, REPTILE, WORM, MOLLUSK, AMPHIBIAN, INSECT, SPIDER, FUNGUS, PLANT, NETHER, MUTANT, BLOB, HORROR, ABERRATION, HALLUCINATION and UNKNOWN.

    “volume”

    (string)

    "volume": "40 L"
    

    The numeric part of the string must be an integer. Accepts L, and ml as units. Note that l and mL are not currently accepted.

    “weight”

    (string)

    "weight": "3 kg"
    

    The numeric part of the string must be an integer. Use the largest unit you can keep full precision with. For example: 3 kg, not 3000 g. Accepts g and kg as units.

    “scent_tracked”

    (array of strings, optional)

    List of scenttype_id tracked by this monster. scent_types are defined in scent_types.json

    “scent_ignored”

    (array of strings, optional)

    List of scenttype_id ignored by this monster. scent_types are defined in scent_types.json

    “symbol”, “color”

    (string)

    Symbol and color representing monster in-game. The symbol must be a UTF-8 string, that is exactly one console cell width (may be several Unicode characters). See COLOR.md for details.

    “size”

    (string, optional)

    Size flag, see json_flags.md.

    “material”

    (array of strings, optional)

    The materials the monster is primarily composed of. Must contain valid material ids. An empty array (which is the default) is also allowed, the monster is made of no specific material. One can add or remove entries in mods via “add:material” and “remove:material”.

    “diet”

    (array of strings, optional)

    Material ids of the comestibles this monster eats. A comestible matches when any of its materials is in this list, e.g. [ "flesh", "bone" ] lets a canine be lured by meat or bones. Monsters walk to matching food they can see, eat it while standing on its tile, and become well fed afterwards. Eating from the ground never tames a monster. Mods can add or remove entries via "extend" and "delete".

    “phase”

    (string, optional)

    It describes monster’s body state of matter. However, it doesn’t seem to have any gameplay purpose, right now. It can be SOLID, LIQUID, GAS, PLASMA or NULL.

    “default_faction”

    (string)

    The id of the faction the monster belongs to, this affects what other monsters it will fight. See Monster factions.

    “bodytype”

    (string)

    The id of the monster’s bodytype, which is a general description of the layout of the monster’s body.

    Value should be one of:

    valuedescription
    angela winged human
    beara four legged animal that can stand on its hind legs
    birda two legged animal with two wings
    bloba blob of material
    craba multilegged animal with two large arms
    quadrupeda four legged animal
    elephanta very large quadruped animal with a large head and torso with equal sized limbs
    fishan aquatic animal with a streamlined body and fins
    flying insecta six legged animal with a head and two body segments and wings
    froga four legged animal with a neck and with very large rear legs and small forelegs
    gatora four legged animal with a very long body and short legs
    humana bipedal animal with two arms
    insecta six legged animal with a head and two body segments
    kangarooa pentapedal animal that utilizes a large tail for stability with very large rear legs and smaller forearms
    lizarda smaller form of ‘gator’
    migowhatever form migos have
    piga four legged animal with the head in the same line as the body
    spideran eight legged animal with a small head on a large abdomen
    snakean animal with a long body and no limbs

    “attack_cost”

    (integer, optional)

    Number of moves per regular attack.

    “diff”

    (integer, optional)

    Monster baseline difficulty. Impacts the shade used to label the monster, and if it is above 30 a kill will be recorded in the memorial log. Monster difficult is calculated based on expected melee damage, dodge, armor, hit points, speed, morale, aggression, and vision ranges. The calculation does not handle ranged special attacks or unique special attacks very well, and baseline difficulty can be used to account for that. Suggested values:

    valuedescription
    2a limited defensive ability such as a skitterbot’s taser, or a weak special like a shrieker zombie’s special ability to alert nearby monsters, or a minor bonus to attack like poison or venom.
    5a limited ranged attack weaker than spitter zombie’s spit, or a powerful defensive ability like a shocker zombie’s zapback or an acid zombie’s acid spray.
    10a powerful ranged attack, like a spitters zombie’s spit or an turret’s 9mm SMG.
    15a powerful ranged attack with additional hazards, like a corrosize zombie’s spit
    20a very powerful ranged attack, like a laser turret or military turret’s 5.56mm rifle, or a powerful special ability, like a zombie necromancer’s ability to raise other zombies.
    30a ranged attack that is deadly even for armored characters, like an anti-material turret’s .50 BMG rifle.

    Most monsters should have difficulty 0 - even dangerous monsters like a zombie hulk or razorclaw alpha. Difficulty should only be used for exceptional, ranged, special attacks.

    “aggression”

    (integer, optional)

    Defines how aggressive the monster is. Ranges from -99 (totally passive) to 100 (guaranteed hostility on detection)

    “morale”

    (integer, optional)

    Monster morale. Defines how low monster HP can get before it retreats. This number is treated as % of their max HP.

    “tracking_distance”

    (integer, optional, default 8)

    Distance in tiles that the monster keeps between itself and its current target when it has the KEEP_DISTANCE flag. This also controls how close following monsters approach their goal.

    “aggro_character”

    (bool, optional, default true)

    If the monster will differentiate between monsters and characters (NPC, Player) when deciding on targets - if false the monster will ignore characters regardless of current anger/morale until a character trips and anger trigger. Resets randomly when the monster is at its base anger level.

    “lua_attitude”

    (string, optional)

    If set, uses a Lua function from game.monster_attitude_functions to determine the monster’s attitude instead of the default C++ logic. The Lua function is called with (monster, target), where target can be nil, and should return a MonsterAttitude value. Returning nil falls back to the default behavior.

    "lua_attitude": "my_attitude"
    
    game.monster_attitude_functions["my_attitude"] = function(mon, target)
      if target ~= nil and target:is_avatar() then
        return MonsterAttitude.MATT_ATTACK
      end
      return nil
    end
    

    “lua_ai”

    (string, optional)

    If set, runs a Lua function from game.monster_ai_functions each monster turn. The function is called with (monster) and should return a boolean: true means Lua handled the turn and the default C++ AI is skipped, false or nil falls back to the default AI.

    "lua_ai": "my_ai"
    
    game.monster_ai_functions["my_ai"] = function(mon)
      local avatar = gapi.get_avatar()
      if avatar ~= nil then
        local function sign(val)
          if val > 0 then
            return 1
          end
          if val < 0 then
            return -1
          end
          return 0
        end
        local pos = mon:get_pos_ms()
        local tgt = avatar:get_pos_ms()
        local step = Tripoint.new(pos.x + sign(tgt.x - pos.x), pos.y + sign(tgt.y - pos.y), pos.z)
        mon:set_target(avatar)
        mon:move_to(step, false, true, 1.0)
      end
      return true
    end
    

    “speed”

    (integer)

    Monster speed. 100 is the normal speed for a human being - higher values are faster and lower values are slower.

    “mountable_weight_ratio”

    (float, optional)

    Used as the acceptable rider vs. mount weight percentage ratio. Defaults to “0.3”, which means the mount is capable of carrying riders weighing <= 30% of the mount’s weight.

    “mountable_pixels_up”

    (int, optional) Used as the number of pixels upward to place the player when the mount is mounted

    “melee_skill”

    (integer, optional)

    Monster melee skill, ranges from 0 - 10 in base game generally, with 4 being an average mob. Past 10 is likely magic or anomalous See GAME_BALANCE.txt for more examples

    “dodge”

    (integer, optional)

    Monster dodge skill. 0 to 10 in base game. See GAME_BALANCE.txt for an explanation of dodge mechanics.

    “melee_damage”

    (array of objects, optional)

    PropertyDescription
    damage_typeType of damage. See damage types
    amountAmount of damage dealt.
    armor_penetrationAmount of armor ignored by this damage instance.
    armor_multiplierMultiplier applied to armor_penetration.
    damage_multiplierMultiplier applied to amount.
    "melee_damage": [ { "damage_type": "electric", "amount": 4.0, "armor_penetration": 1, "armor_multiplier": 1.2, "damage_multiplier": 1.4 } ],
    

    “melee_dice”, “melee_dice_sides”

    (integer, optional)

    Number of dices and their sides that are rolled on monster melee attack. This defines the amount of bash damage.

    “grab_strength”

    (integer, optional)

    Intensity of the grab effect applied by this monster. Defaults to 1, is only useful for monster with a GRAB special attack and the GRABS flag. A monster with grab_strength = n applies a grab as if it was n zombies. A player with max(Str,Dex)<=n has no chance of breaking that grab.

    “uncanny_dodge_cost”

    (integer, optional)

    How many moves it costs this monster to uncanny dodge. Defaults to 100, is only useful for monster with the UNCANNY_DODGE flag.

    “melee_cut”

    (integer, optional)

    Amount of cutting damage added to die roll on monster melee attack.

    “armor_bash”, “armor_cut”, “armor_stab”, “armor_acid”, “armor_fire”, “armor_cold”, “armor_electric”

    (integer, optional)

    Monster protection from bashing, cutting, stabbing, acid, fire, cold and electric damage.

    “vision_day”, “vision_night”

    (integer, optional)

    Vision range in full daylight and in total darkness.

    “clairvoyance”

    (integer, optional)

    Clairvoyance vision range

    “luminance”

    (integer, optional)

    Amount of light passively output by monster. Ranges from 0 to 10.

    “hp”

    (integer)

    Monster hit points.

    “monster_weapon”

    (item group, optional)

    An item group that is used to spawn items assumed to be the monster’s wielded weapon. Having this defined will make said monster vulnerable to disarming techniques. If disarmed, a monster will have their bashing damage roll greatly reduced and any special melee damage (cut, electric, etc) reduced to zero, and they’ll be unable to use certain special attacks (notably attacks of "type": "gun", but also some such as TAZER, SHOCKSTORM, FLAMETHROWER, etc).

    Can freely be a collection to imply two weapons wielded in both hands, as items will be dropped on the ground instead of wielded by the attacker, even if the technique has take_weapon set. Itemgroup will also spawn on death as with death_drops if the monster was killed without being disarmed.

    “death_drops”

    (string or item group, optional)

    An item group that is used to spawn items when the monster dies. This can be an inlined item group, see ITEM_SPAWN.md. The default subtype is “distribution”.

    Use "extend": { "death_drops": ... } in an inherited or overridden monster to add another drop group without replacing existing death drops. A top-level "death_drops" member replaces inherited death drops.

    “death_function”

    (array of strings, optional)

    How the monster behaves on death. See json_flags.md for a list of possible functions. One can add or remove entries in mods via “add:death_function” and “remove:death_function”.

    “on_death”

    (dictionary, optional)

    A collection of behaviors to apply on death. Can embed “death_function” within. If this field is present the field “death_function” will be skipped.

    "on_death": {
      "death_function": [ "THING" ]
    }
    

    Also supports

    “spawn_mon”

    (string, optional) Spawns a single monster at the location of the dying monster

    "on_death": {
      "spawn_mon": "mon_thing"
    }
    

    “spawn_mon_near”

    (dictionary, optional)

    Made up of two values:

    • “distance”: (integer, required) maximum distance from death location to allow a monster to spawn
    • “ids”: (string or array of strings, optional) ids of monsters to try to spawn within set distance

    Can spawn a single monster

    "on_death": {
      "spawn_mon_near": {
        "distance": 5,
        "ids": "mon_thing"
      }
    }
    

    or multiple monsters

    "on_death": {
      "spawn_mon_near": {
        "distance": 3,
        "ids": [ "mon_thing", "mon_zombie", "mon_zombie_anklebiter" ]
      }
    }
    

    “harvest”

    (string, optional)

    If this monster’s death function leaves a corpse behind, this defines what items will be produced when butchering or dissecting its corpse. If none is specified, it will default to human. Harvest entries, their yields, and mass ratios, are defined in harvest.json

    “emit_field”

    (array of objects of emit_id and time_duration, optional) “emit_fields”: [ { “emit_id”: “emit_gum_web”, “delay”: “30 m” } ],

    What field the monster emits and how often it does so. Time duration can use strings: “1 h”, “60 m”, “3600 s” etc…

    “regenerates”

    (integer, optional)

    Number of hitpoints regenerated per turn.

    “regeneration_modifiers”

    ( array of objects consisting of effect, base_mod (float) and scaling_mod (float), optional ) “regeneration_modifiers”: [ { “effect”: “on_fire”, “base_mod”: -0.3, “scaling_mod”: -0.15 } ],

    What effects (if any) affect the monster’s regeneration positively/negatively. The mods stack additively (Intensity 2 on_fire produces a multiplier of 0.45) but are applied multiplicatively.

    “regenerates_in_dark”

    (boolean, optional)

    Monster regenerates very quickly in poorly lit tiles.

    “regen_morale”

    (boolean, optional)

    Will stop fleeing if at max hp, and regen anger and morale.

    “special_attacks”

    (array of special attack definitions, optional)

    Monster’s special attacks. This should be an array, each element of it should be an object (new style) or an array (old style).

    The old style array should contain 2 elements: the id of the attack (see json_flags.md for a list) and the cooldown for that attack. Example (grab attack every 10 turns):

    "special_attacks": [ [ "GRAB", 10 ] ]
    

    The new style object should contain at least a “type” member (string) and “cooldown” member (integer). It may contain additional members as required by the specific type. Possible types are listed below. Example:

    "special_attacks": [
        { "type": "leap", "cooldown": 10, "max_range": 4 }
    ]
    

    “special_attacks” may contain any mixture of old and new style entries:

    "special_attacks": [
        [ "GRAB", 10 ],
        { "type": "leap", "cooldown": 10, "max_range": 4 }
    ]
    

    One can add entries (when doing inheritance) via the "extend" field.

    "extend": { "special_attacks": [ [ "PARROT", 50 ] ] }
    

    Entries can be removed via the "delete" field. However, unlike adding a special attack (manually or via extends), the syntax is slightly different. There is no need for a second set of brackets, and you should not include the cooldown.

    "delete": { "special_attacks": [ "FUNGUS" ] },
    

    “flags”

    (array of strings, optional)

    Monster flags. See json_flags.md for a full list. One can add or remove entries in mods via “add:flags” and “remove:flags”.

    “fear_triggers”, “anger_triggers”, “placate_triggers”

    (array of strings, optional)

    What makes the monster afraid / angry / what calms it. See json_flags.md for a full list

    “revert_to_itype”

    (string, optional)

    If not empty and a valid item id, the monster can be converted into this item by the player, when it’s friendly. This is usually used for turrets and similar to revert the turret monster back into the turret item, which can be picked up and placed elsewhere.

    “starting_ammo”

    (object, optional)

    An object containing ammo that newly spawned monsters start with. This is useful for a monster that has a special attack that consumes ammo. Example:

    "starting_ammo": { "9mm": 100, "40mm_frag": 100 }
    

    “upgrades”

    (boolean or object, optional)

    Controls how this monster is upgraded over time. It can either be the single value false (which is the default and disables upgrading) or an object describing the upgrades.

    Example:

    "upgrades": {
        "into_group": "GROUP_ZOMBIE_UPGRADE",
        "half_life": 28
    }
    

    The upgrades object may have the following members:

    “half_life”

    (int) Time in which half of the monsters upgrade according to an approximated exponential progression. It is scaled with the evolution scaling factor which defaults to 4 days.

    “into_group”

    (string, optional) The upgraded monster’s type is taken from the specified group. The cost in these groups is for an upgrade in the spawn process (related to the rare “replace_monster_group” and “new_monster_group_id” attributes of spawning groups).

    “into”

    (string, optional) The upgraded monster’s type.

    “age_grow”

    (int, optional) Number of days needed for monster to change into another monster.

    “reproduction”

    (dictionary, optional) The monster’s reproduction cycle, if any. Supports:

    “baby_monster”

    (string, optional) the id of the monster spawned on reproduction for monsters who give live births. You must declare either this or baby_egg for reproduction to work.

    “baby_egg”

    (string, optional) The id of the egg type to spawn for egg-laying monsters. You must declare either this or “baby_monster” for reproduction to work.

    “baby_count”

    (int) Number of new creatures or eggs to spawn on reproduction.

    “baby_timer”

    (int) Number of days between reproduction events.

    “baby_flags”

    (Array, optional) Designate seasons during which this monster is capable of reproduction. ie: [ "SPRING", "SUMMER" ]

    “special_when_hit”

    (array, optional)

    A special defense attack, triggered when the monster is attacked. It should contain an array with the id of the defense (see Monster defense attacks in json_flags.md) and the chance for that defense to be actually triggered. Example:

    "special_when_hit": [ "ZAPBACK", 100 ]
    

    “attack_effs”

    (array of objects, optional)

    A set of effects that may get applied to the attacked creature when the monster successfully attacks. Example:

    "attack_effs": [
        {
            "id": "paralyzepoison",
            "duration": 33,
            "chance": 50
        }
    ]
    

    Each element of the array should be an object containing the following members:

    “id”

    (string)

    The id of the effect that is to be applied.

    “duration”

    (integer, optional)

    How long (in turns) the effect should last.

    “affect_hit_bp”

    (boolean, optional)

    Whether the effect should be applied to the hit body part instead of the one set below.

    “bp”

    (string, optional)

    The body part that where the effect is applied. The default is to apply the effect to the whole body. Note that some effects may require a specific body part (e.g. “hot”) and others may require the whole body (e.g. “meth”).

    “chance”

    (integer, optional)

    The chance of the effect getting applied.

    Modding

    Monster types can be overridden or modified in mods. To do so, one has to add an “edit-mode” member, which can contain either:

    • “create” (the default if the member does not exist), an error will be shown if a type with the given id already exists.
    • “override”, an existing type (if any) with the given id will be removed and the new data will be loaded as a completely new type.
    • “modify”, an existing type will be modified. If there is no type with the given id, an error will be shown.

    Mandatory properties (all that are not marked as optional) are only required if edit mode is “create” or “override”.

    Example (rename the zombie monster, leaves all other properties untouched):

    {
      "type": "MONSTER",
      "edit-mode": "modify",
      "id": "mon_zombie",
      "name": "clown"
    }
    

    The default edit mode (“create”) is suitable for new types, if their id conflicts with the types from other mods or from the core data, an error will be shown. The edit mode “override” is suitable for re-defining a type from scratch, it ensures that all mandatory members are listed and leaves no traces of the previous definitions. Edit mode “modify” is for small changes, like adding a flag or removing a special attack.

    Modifying a type overrides the properties with the new values, this example sets the special attacks to contain only the “SHRIEK” attack:

    {
      "type": "MONSTER",
      "edit-mode": "modify",
      "id": "mon_zombie",
      "special_attacks": [["SHRIEK", 20]]
    }
    

    Some properties allow adding and removing entries, as documented above, usually via members with the “add:”/“remove:” prefix.

    Monster special attack types

    The listed attack types can be as monster special attacks (see “special_attacks”).

    “melee”

    Makes a general melee special attack

    “damage_max_instance”

    Max damage it can deal on one attack.

    “move_cost”

    Turns needed to complete special attack. 100 move_cost with 100 speed is equal to 1 second/turn.

    “accuracy”

    (Integer) How accurate it is. Not many monsters use it though.

    “requires_grab”

    Whether the attack requires the target to be grabbed first. Useful for multi-stage attacks or “finisher” attacks.

    “max_range”

    The maximum range of the attack. Monsters will not use this special attack against enemies outside of max range.

    “min_range”

    The minimum range of the attack. Monsters will not use this special attack against enemies inside of minimum range.

    “leap”

    Makes the monster leap a few tiles. It supports the following additional properties:

    “max_range”

    (Required) Maximal range of attack.

    “min_range”

    (Required) Minimal range needed for attack.

    “allow_no_target”

    This prevents monster from using the ability on empty space.

    “move_cost”

    Turns needed to complete special attack. 100 move_cost with 100 speed is equal to 1 second/turn.

    “min_consider_range”, “max_consider_range”

    Minimal range and maximal range to consider for using specific attack.

    “throw_strength”

    Whether and how much the attack throws its target.

    “bite”

    Makes monster use teeth to bite opponent. Some monsters can give infection by doing so.

    “damage_max_instance”

    Max damage it can deal on one bite.

    “min_mul”, “max_mul”

    How hard is to get free of bite without killing attacker.

    “move_cost”

    Turns needed to complete special attack. 100 move_cost with 100 speed is equal to 1 second/turn.

    “accuracy”

    (Integer) How accurate it is. Not many monsters use it though.

    “no_infection_chance”

    Chance to not give infection.

    “gun”

    Fires a gun at a target. If friendly, will avoid harming the player.

    “gun_type”

    (Required) Valid item id of a gun that will be used to perform the attack.

    “ammo_type”

    (Required) Valid item id of the ammo the gun will be loaded with. Monster should also have a “starting_ammo” field with this ammo. For example

    "ammo_type" : "50bmg",
    "starting_ammo" : {"50bmg":100}
    

    “max_ammo”

    Cap on ammo. If ammo goes above this value for any reason, a debug message will be printed.

    “fake_str”

    Strength stat of the fake NPC that will execute the attack. 8 if not specified.

    “fake_dex”

    Dexterity stat of the fake NPC that will execute the attack. 8 if not specified.

    “fake_int”

    Intelligence stat of the fake NPC that will execute the attack. 8 if not specified.

    “fake_per”

    Perception stat of the fake NPC that will execute the attack. 8 if not specified.

    “fake_skills”

    Array of 2 element arrays of skill id and skill level pairs.

    “move_cost”

    Move cost of executing the attack

    // If true, gives “grace period” to player

    “require_targeting_player”

    If true, the monster will need to “target” the player, wasting targeting_cost moves, putting the attack on cooldown and making warning sounds, unless it attacked something that needs to be targeted recently.

    “require_targeting_npc”

    As above, but with npcs.

    “require_targeting_monster”

    As above, but with monsters.

    “targeting_timeout”

    Targeting status will be applied for this many turns. Note that targeting applies to turret, not targets.

    “targeting_timeout_extend”

    Successfully attacking will extend the targeting for this many turns. Can be negative.

    “targeting_cost”

    Move cost of targeting the player. Only applied if attacking the player and didn’t target player within last 5 turns.

    “no_crits”

    If true then attacking create will be unable to score ranged critical hit on target, also good hits no longer has high change to go to the head, instead there is high change to score hit to the body and limbs. If false then default behavior used - critical hits are allowed and good hit has high chance to reach head.

    “laser_lock”

    If true and attacking a creature that isn’t laser-locked but needs to be targeted, the monster will act as if it had no targeting status (and waste time targeting), the target will become laser-locked, and if the target is the player, it will cause a warning.

    Laser-locking affects the target, but isn’t tied to specific attacker.

    “range”

    Maximum range at which targets will be acquired.

    “range_no_burst”

    Maximum range at which targets will be attacked with a burst (if applicable).

    “burst_limit”

    Limit on burst size.

    “description”

    Description of the attack being executed if seen by the player.

    “targeting_sound”

    Description of the sound made when targeting.

    “targeting_volume”

    OBSOLETE

    Volume of the sound made when targeting. ( in tiles of volume )

    “targeting_volume_dB”

    Volume of the sound made when targeting in dB

    “no_ammo_sound”

    Description of the sound made when out of ammo.

    “deployer”

    {
      "type": "deployer",
      "deployables": {
        "bot_c4_hack": { // Item Id of ammo to deploy
          "message": "The elite zombie grenadier deploys a c4 hack", // Message to display when deploying
          "chance": 1, // Spawn weight, randomly selected based on total weight of available deployables
          "ammo_percentage": 0.6, // Threshold for when it will add this deployable to the pool for random selection, e.g. won't start deploying this until 40% of total deployables have already been used up.
          "range": 10 // Spawn radius when deploying
        }
      },
      "cooldown": 3 // Turns between deployments
    }
    

    Mutations & Traits

    Note

    This page is currently under-construction and was recently split off from JSON INFO

    Traits/Mutations fields

    "id": "LIGHTEATER",  // Unique ID
    "name": "Optimist",  // In-game name displayed
    "points": 2,         // Point cost of the trait. Positive values cost points and negative values give points
    "visibility": 0,     // Visibility of the trait for purposes of NPC interaction (default: 0)
    "ugliness": 0,       // Ugliness of the trait for purposes of NPC interaction (default: 0)
    "cut_dmg_bonus": 3, // Bonus to unarmed cut damage (default: 0)
    "pierce_dmg_bonus": 3, // Bonus to unarmed pierce damage (default: 0.0)
    "bash_dmg_bonus": 3, // Bonus to unarmed bash damage (default: 0)
    "butchering_quality": 4, // Butchering quality of this mutations (default: 0)
    "rand_cut_bonus": { "min": 2, "max": 3 }, // Random bonus to unarmed cut damage between min and max.
    "rand_bash_bonus": { "min": 2, "max": 3 }, // Random bonus to unarmed bash damage between min and max.
    "bodytemp_modifiers" : [100, 150], // Range of additional bodytemp units (these units are described in 'weather.h'. First value is used if the person is already overheated, second one if it's not.
    "bodytemp_sleep" : 50, // Additional units of bodytemp which are applied when sleeping
    "initial_ma_styles": [ "style_crane" ], // (optional) A list of ids of martial art styles of which the player can choose one when starting a game.
    "mixed_effect": false, // Whether the trait has both positive and negative effects. This is purely declarative and is only used for the user interface. (default: false)
    "description": "Nothing gets you down!" // In-game description
    "apperance_description": "mowhawk" //only used for describing apperance mutations (i.e hair_color, hair_style, eye_color, skin_tone) in photos and extended descriptions 
    "starting_trait": true, // Can be selected at character creation (default: false)
    "random_starting_trait": true, // Will be randomly selected at character creation (default: starting_trait)
    "valid": false,      // Can be mutated ingame (default: true)
    "purifiable": false, //Sets if the mutation be purified (default: true)
    "profession": true, //Trait is a starting profession special trait. (default: false)
    "debug": false,     //Trait is for debug purposes (default: false)
    "player_display": true, //Trait is displayed in the `@` player display menu
    "category": ["BIRD", "INSECT"], // Categories containing this mutation
    "prereqs": ["SKIN_ROUGH"], // Needs these mutations before you can mutate toward this mutation
    "prereqs2": ["LEAVES"], //Also need these mutations before you can mutate towards this mutation. When both set creates 2 different mutation paths, random from one is picked. Only use together with "prereqs"
    "threshold_tier": 1, //Required tier of one of the categories' thresholds to mutate
    "cancels": ["ROT1", "ROT2", "ROT3"], // Cancels these mutations when mutating
    "prevents": ["ROT1", "ROT2", "ROT3"], // Prevents you from recieving these mutations when mutating
    "changes_to": ["FASTHEALER2"], // Can change into these mutations when mutating further
    "leads_to": [], // Mutations that add to this one
    "passive_mods" : { //increases stats with the listed value. Negative means a stat reduction
                "per_mod" : 1, //Possible values per_mod, str_mod, dex_mod, int_mod
                "str_mod" : 2
    },
    "wet_protection":[{ "part": "HEAD", // Wet Protection on specific bodyparts
                        "good": 1 } ] // "neutral/good/ignored" // Good increases pos and cancels neg, neut cancels neg, ignored cancels both
    "vitamin_rates": [ [ "vitC", -1200 ] ], // How much extra vitamins do you consume per minute. Negative values mean production
    "vitamins_absorb_multi": [ [ "flesh", [ [ "vitA", 0 ], [ "vitB", 0 ], [ "vitC", 0 ], [ "calcium", 0 ], [ "iron", 0 ] ], [ "all", [ [ "vitA", 2 ], [ "vitB", 2 ], [ "vitC", 2 ], [ "calcium", 2 ], [ "iron", 2 ] ] ] ], // multiplier of vitamin absorption based on material. "all" is every material. supports multiple materials.
    "craft_skill_bonus": [ [ "electronics", -2 ], [ "tailor", -2 ], [ "mechanics", -2 ] ], // Skill affected by the mutation and their bonuses. Bonuses can be negative, a bonus of 4 is worth 1 full skill level.
    "restricts_gear" : [ "TORSO" ], //list of bodyparts that get restricted by this mutation
    "allowed_items" : [ "TORSO" ], //Items with these flags can be worn regardless of restrictions.
    "allowed_items_only" : true, //If true and this mutation restricts gear, then only `allowed_items` can be worn with this, excluding even OVERSIZE items that would otherwise be wearable. (default: false)
    "allow_soft_gear" : true, //If there is a list of 'restricts_gear' this sets if the location still allows items made out of soft materials (Only one of the types need to be soft for it to be considered soft). (default: false)
    "destroys_gear" : true, //If true, destroys the gear in the 'restricts_gear' location when mutated into. (default: false)
    "encumbrance_always" : [ // Adds this much encumbrance to selected body parts
        [ "ARM_L", 20 ],
        [ "ARM_R", 20 ]
    ],
    "encumbrance_covered" : [ // Adds this much encumbrance to selected body parts, but only if the part is covered by not-OVERSIZE worn equipment
        [ "HAND_L", 50 ],
        [ "HAND_R", 50 ]
    ],
    "armor" : [ // Protects selected body parts this much. Resistances use syntax like `PART RESISTANCE` below.
        [
            [ "ALL" ], // Shorthand that applies the selected resistance to the entire body
            { "bash" : 2 } // The resistance provided to the body part(s) selected above
        ],
        [   // NOTE: Resistances are applies in order and ZEROED between applications!
            [ "ARM_L", "ARM_R" ], // Overrides the above settings for those body parts
            { "bash" : 1 }        // ...and gives them those resistances instead
        ]
    ],
    "dodge_modifier" : 1, // Bonus granted to your effective change to dodge. Negative values inflict a penalty instead.
    "speed_modifier" : 2.0, // Multiplies your current speed by this amount.  Higher means more speed, with 1.0 being no change.
    "movecost_modifier" : 0.5, // Multiplies the amount of moves it takes to perform most actions, with lower meaning faster actions. 
    "movecost_flatground_modifier" : 0.5, // Multiplies the movecost of terrain/furniture that is easy to move over. Lower means faster movement.
    "movecost_obstacle_modifier" : 0.5, // Multipliers the movecost across rough terrain, lower means faster movement
    "movecost_swim_modifier" : 0.5, // Multiplies the movecost needed to swim. Lower is faster.
    "falling_damage_multiplier" : 0.5, // Multiplier on how much damage you take when falling into pits, falling off ledges, or being tossed by a hulk. Zero grants immunity.
    "attackcost_modifier" : 0.5, // Multiplier on the movecost of attacks. Lower is better.
    "weight_capacity_modifier" : 0.5, // Multiplies how much weight you can carry before being penalized.
    "hearing_modifier" : 0.5, // Multiplier for how good your hearing is, higher values mean detecting sounds from farther away. A value of zero renders you completely deaf.
    "noise_modifier" : 0.5, // Multiplier for how much noise you make while moving, with zero making your footsteps silent.
    "packmule_modifier" : 1.0, // Multiplies the storage space granted by backpacks and similar worn containers.
    "crafting_speed_modifier" : 1.0, // Multiplies the crafting speed of the player.
    "construction_speed_modifier" : 1.0, // Multiplies the construction speed of the player.
    "stealth_modifier" : 0, // Percentage to be subtracted from player's visibility range, capped to 60. Negative values work, but are not very effective due to the way vision ranges are capped
    "night_vision_range" : 0.0, // Night range vision. Only the best and the worst value out of all mutations are added. A value of 8 or higher will allow reading in complete darkness as though the player were in dim lighting. (default: 0.0)
    "active" : true, //When set the mutation is an active mutation that the player needs to activate (default: false)
    "starts_active" : true, //When true, this 'active' mutation starts active (default: false, requires 'active')
    "cost" : 8, // Cost to activate this mutation. Needs one of the hunger, thirst, or fatigue values set to true. (default: 0)
    "time" : 100, //Sets the amount of (turns * current player speed ) time units that need to pass before the cost is to be paid again. Needs to be higher than one to have any effect. (default: 0)
    "hunger" : true, //If true, activated mutation increases hunger by cost. (default: false)
    "thirst" : true, //If true, activated mutation increases thirst by cost. (default: false)
    "fatigue" : true, //If true, activated mutation increases fatigue by cost. (default: false)
    "stamina" : true, //If true, activated mutation decreases stamina by cost. (default: false)
    "mana" : true, //If true, activated mutation decreases mana by cost. (default: false)
    "bionic" : true, //If true, activated mutation decreases bionic power by cost. (default: false)
    "pain" : true, //If true, activated mutation increases pain by cost. (default: false)
    "health" : true, //If true, activated mutation decreases health by cost. (default: false)
    "scent_modifier": 0.0,// float affecting the intensity of your smell. (default: 1.0)
    "scent_intensity": 800,// int affecting the target scent toward which you current smell gravitates. (default: 500)
    "scent_mask": -200,// int added to your target scent value. (default: 0)
    "scent_type": "sc_flower",// scent_typeid, defined in scent_types.json, The type scent you emit. (default: empty)
    "bleed_resist": 1000, // Int quantifiying your resistance to bleed effect, if its > to the intensity of the effect you don't get any bleeding. (default: 0)
    "fat_to_max_hp": 1.0, // Amount of hp_max gained for each unit of bmi above character_weight_category::normal. (default: 0.0)
    "healthy_rate": 0.0, // How fast your health can change. If set to 0 it never changes. (default: 1.0)
    "weakness_to_water": 5, // How much damage water does to you, negative values heal you. (default: 0)
    "ignored_by": [ "ZOMBIE" ], // List of species ignoring you. (default: empty)
    "anger_relations": [ [ "MARSHMALLOW", 20 ], [ "GUMMY", 5 ], [ "CHEWGUM", 20 ] ], // List of species angered by you and by how much, can use negative value to calm.  (default: empty)
    "can_only_eat": [ "junk" ], // List of materiel required for food to be comestible for you. (default: empty)
    "can_only_heal_with": [ "bandage" ], // List of med you are restricted to, this includes mutagen,serum,aspirin,bandages etc... (default: empty)
    "can_heal_with": [ "caramel_ointement" ], // List of med that will work for you but not for anyone. See `CANT_HEAL_EVERYONE` flag for items. (default: empty)
    "allowed_category": [ "ALPHA" ], // List of category you can mutate into. (default: empty)
    "no_cbm_on_bp": [ "TORSO", "HEAD", "EYES", "MOUTH", "ARM_L" ], // List of body parts that can't receive cbms. (default: empty)
    "body_size": "LARGE", // Increase or decrease size, only one size mutation at a time will be valid. Allowed values are: `TINY`, `SMALL`, `LARGE`, `HUGE`. `MEDIUM` can be specified but has no effect, as this is the default size for players and NPCs.
    "lumination": [ [ "HEAD", 20 ], [ "ARM_L", 10 ] ], // List of glowing bodypart and the intensity of the glow as a float. (default: empty)
    "kcal_scale" : 0.5, //Scales maximum kcal storage. 1.0 doubles, -0.5 halves.
    "metabolism_modifier": 0.333, // Extra metabolism rate multiplier. 1.0 doubles usage, -0.5 halves.
    "fatigue_modifier": 0.5, // Extra fatigue rate multiplier. 1.0 doubles usage, -0.5 halves.
    "fatigue_regen_modifier": 0.333, // Modifier for the rate at which fatigue and sleep deprivation drops when resting.
    "healing_awake": 1.0, //  Affects healing while awake. This and resting is affected by healthiness awake_rate = heal_rate * healing_awake
    "healing_resting": 0.5, // Affects healing while asleep. asleep_rate = at_rest_quality * heal_rate * ( 1.0f + healing_resting)
    "mending_modifier": 1.2 // Multiplier on how fast your limbs mend - This value would make your limbs mend 20% faster
    "stamina_regen_modifier": 0.5 // Extra stamina regeneration rate multiplier. 1.0 doubles regen, -0.5 halves.
    "max_stamina_modifier": 1.5 // Multiplier on maximum stamina.  Stamina regeneration is proportionally modified by the same rate, so this includes stamina_regen_modifier implicitly. See Character::update_stamina in Character.cpp.
    "transform": { "target": "BIOLUM1", // Trait_id of the mutation this one will transfomr into
                   "msg_transform": "You turn your photophore OFF.", // message displayed upon transformation
                   "active": false , // Will the target mutation start powered ( turn ON ).
                   "moves": 100 // how many moves this costs. (default: 0)
    "enchantments": [ "MEP_INK_GLAND_SPRAY" ], // Applies this enchantment to the player. See magic.md and effects_json.md
    "mutagen_target_modifier": 5,        // Increases or decreases how mutations prefer to balance out when mutating from mutant toxins, negative values push the target value lower (default: 0)
    "flags": [ "LIMB_SCORE_DODGE_AFFECTED" ], // List of mutation flags applied to this mutation. See Mutation Flags below. (default: empty)
    "types": [ "CLAWS" ]                 // List of mutation type IDs this mutation belongs to. Used for conflict detection and mandatory appearance logic. See Mutation Types below. (default: empty)
    }
    

    Mutation Flags

    Mutation flags are defined in data/json/flags_mutation.json and referenced in the flags field of a mutation.

    Gender Flags

    These flags control how a mutation is assigned during character creation and NPC generation. They apply to cosmetic appearance traits and are checked during randomization and character creation trait selection.

    FlagEffect
    MALE_EXCLUSIVEMutation cannot be assigned to female characters. Hidden from female characters in character creation.
    FEMALE_EXCLUSIVEMutation cannot be assigned to male characters. Hidden from male characters in character creation.
    MALE_PREFERREDMutation is never auto-assigned to female characters, but female players may still manually select it.
    FEMALE_PREFERREDMutation is never auto-assigned to male characters, but male players may still manually select it.

    EXCLUSIVE flags take precedence over mandatory_one — if no gender-valid trait exists for a mandatory type, the type is silently skipped rather than assigning an invalid trait.

    Mutation Types

    Mutation types group related mutations together. They are defined as separate JSON objects and referenced via a mutation’s types field.

    {
      "type": "mutation_type",
      "id": "hair_color", // Unique string ID for this type
      "mandatory_one": true, // If true, characters must always have at least one mutation of this type. Implies swap_on_conflict. (default: false)
      "default_trait": "SKIN_LIGHTER", // Optional mutation added to loaded characters that lack this mandatory type. (default: none)
      "swap_on_conflict": true, // If true, selecting a new mutation of this type in character creation automatically removes the previously held mutation of the same type instead of showing a conflict error. (default: false)
      "random_chance": 50 // Percent chance (0–100) that a mutation of this type is randomly assigned during cosmetic randomization. Only used if mandatory_one is false. (default: 0)
    }
    

    Notes

    • mandatory_one guarantees every new character receives exactly one mutation of that type during creation and rerolls.
    • default_trait lets old saves or templates that predate a mandatory appearance type receive a fallback trait when loaded.
    • swap_on_conflict alone (without mandatory_one) is useful for optional appearance types where only one option makes sense at a time (e.g. facial hair style).
    • random_chance and mandatory_one are mutually exclusive in intent: a type should use one or the other, not both.

    new mutation system

    At the moment the system only covers untargeted mutations. The targeted ones (alpha mutagen etc.) still use the old one, with the only difference being that it doesn’t force negative mutations 33% of the time and doesn’t support Robust Genetics, which would turn those 33% forced negative mutations into forced positive ones.

    You can use the old system by adding the “Old mutations” mod to a world. This can be safely done to already generated worlds. Same for removal of this mod.

    Accumulated mutagen

    The character passively accumulates inactive “mutagenic potential” over time, which is all turned into new mutations the moment character mutates uncontrollably for any reason. The potential is then cleared.

    This potential caps at 7.333 potential mutations, which takes 22 days (1 mutation per 3 days).

    Mutagenic flesh

    Flesh of mutants contains mutagenic toxins, which will cause uncontrollable mutations over a period of time if allowed to accumulate sufficiently.

    The character loses about 630 kcal of mutant flesh of mutagen per day. If a starved character gorged on mutant flesh, it would take a little more than 5000 kcal to start mutating.

    Uncontrollable mutations

    Once the character starts mutating, all the mutagenic potential is immediately turned into new mutations and the character will continue mutating for at least 4 days.

    The character will gain mutagenic potential at a faster rate and will gain about 2 new mutations by the end of it, assuming no more mutagenic toxins. Mutagenic toxins will extend the process and may even speed it up to up to over 1 mutation per day.

    Mutation selection

    Overall the mutations picked will trend towards positive, until the character has a set of traits that is “more good than bad”.

    Picked mutations trend towards a character with +6 trait score overall. For example, a character with just Quick (+4) and Fleet Footed (+2) traits will receive positive and negative traits about equally, while a character with no positive traits and -12 worth of negative ones will be more likely to get Quick over Fleet Footed and very unlikely to get Junkfood Intolerance.

    NPCs

    Writing Dialogues

    TODO: document the “npc” structure, used to load NPC template

    Dialogues work like state machines. They start with a certain topic (the NPC says something), the player character can respond (choosing one of several responses), and that response sets the new talk topic. This goes on until the dialogue is finished, or the NPC turns hostile.

    Note that it is perfectly fine to have a response that switches the topic back to itself.

    NPC missions are controlled by a separate but related JSON structure and are documented in the missions docs.

    NPC classes

    NPC classes are defined as "type": "npc_class" entries (see data/json/npcs/classes.json).

    “lua_ai”

    (string, optional)

    If set, runs a Lua function from game.npc_ai_functions each NPC turn. The function is called with (npc) and should return a boolean: true means Lua handled the turn and the default C++ AI is skipped, false or nil falls back to the default AI.

    "lua_ai": "my_npc_ai"
    
    game.npc_ai_functions["my_npc_ai"] = function(npc)
      npc:set_moves(0)
      return true
    end
    

    Two topics are special:

    • TALK_DONE ends the dialogue immediately.
    • TALK_NONE goes to the previously talked about topic.

    Validating Dialogues

    Keeping track of talk topics and making sure that all the topics referenced in responses are defined, and all defined topics are referenced in a response or an NPC’s chat, is very tricky. There is a python script in tools/dialogue_validator.py that will map all topics to responses and vice versa. Invoke it with

    python tools/dialogue_validator.py data/json/npcs/* data/json/npcs/Backgrounds/* data/json/npcs/refugee_center/*
    

    If you are writing a mod with dialogue, you can add the paths to the mod’s dialogue files.

    Talk topics

    Each topic consists of:

    1. a topic id (e.g. TALK_ARSONIST)
    2. a dynamic line, spoken by the NPC.
    3. an optional list of effects that occur when the NPC speaks the dynamic line
    4. a list of responses that can be spoken by the player character.
    5. a list of repeated responses that can be spoken by the player character, automatically generated if the player or NPC has items in a list of items.

    One can specify new topics in json. It is currently not possible to define the starting topic, so you have to add a response to some of the default topics (e.g. TALK_STRANGER_FRIENDLY or TALK_STRANGER_NEUTRAL) or to topics that can be reached somehow.

    Format:

    {
      "type": "talk_topic",
      "id": "TALK_ARSONIST",
      "dynamic_line": "What now?",
      "responses": [
        {
          "text": "I don't know either",
          "topic": "TALK_DONE"
        }
      ],
      "replace_built_in_responses": true
    }
    

    type

    Must always be there and must always be "talk_topic".

    id

    The topic id can be one of the built-in topics or a new id. However, if several talk topics in json have the same id, the last topic definition will override the previous ones.

    The topic id can also be an array of strings. This is loaded as if several topics with the exact same content have been given in json, each associated with an id from the id, array. Note that loading from json will append responses and, if defined in json, override the dynamic_line and the replace_built_in_responses setting. This allows adding responses to several topics at once.

    This example adds the “I’m going now!” response to all the listed topics.

    {
        "type": "talk_topic",
        "id": [ "TALK_ARSONIST", "TALK_STRANGER_FRIENDLY", "TALK_STRANGER_NEUTRAL" ],
        "dynamic_line": "What now?",
        "responses": [
            {
                "text": "I'm going now.",
                "topic": "TALK_DONE"
            }
        ]
    }
    

    dynamic_line

    The dynamic_line is the line spoken by the NPC. It is optional. If it is not defined and the topic has the same id as a built-in topic, the dynamic_line from that built-in topic will be used. Otherwise the NPC will say nothing. See the chapter about dynamic_line below for more details.

    speaker_effect

    The speaker_effect is an object or array of effects that will occur after the NPC speaks the dynamic_line, no matter which response the player chooses. See the chapter about Speaker Effects below for more details.

    response

    The responses entry is an array with possible responses. It must not be empty. Each entry must be a response object. See the chapter about Responses below for more details.

    replace_built_in_responses

    replace_built_in_responses is an optional boolean that defines whether to dismiss the built-in responses for that topic (default is false). If there are no built-in responses, this won’t do anything. If true, the built-in responses are ignored and only those from this definition in the current json are used. If false, the responses from the current json are used along with the built-in responses (if any).


    dynamic_line

    A dynamic line can either be a simple string, or an complex object, or an array with dynamic_line entries. If it’s an array, an entry will be chosen randomly every time the NPC needs it. Each entry has the same probability.

    Example:

    "dynamic_line": [
        "generic text",
        {
            "npc_female": [ "text1", "text2", "text3" ],
            "npc_male": { "u_female": "text a", "u_male": "text b" }
        }
    ]
    

    A complex dynamic_line usually contains several dynamic_line entry and some condition that determines which is used. If dynamic lines are not nested, they are processed in the order of the entries below. The possible types of lines follow.

    In all cases, npc_ refers to the NPC, and u_ refers to the player. Optional lines do not have to be defined, but the NPC should always have something to say. Entries are always parsed as dynamic_line and can be nested.

    Several lines joined together

    The dynamic line is a list of dynamic lines, all of which are displayed. The dynamic lines in the list are processed normally.

    {
      "and": [
        {
          "npc_male": true,
          "yes": "I'm a man.",
          "no": "I'm a woman."
        },
        "  ",
        {
          "u_female": true,
          "no": "You're a man.",
          "yes": "You're a woman."
        }
      ]
    }
    

    A line to be translated with gender context

    The line is to be given a gender context for the NPC, player, or both, to aid translation in languages where that matters. For example:

    {
      "gendered_line": "Thank you.",
      "relevant_genders": ["npc"]
    }
    

    (“Thank you” is different for male and female speakers in e.g. Portuguese).

    Valid choices for entries in the "relevant_genders" list are "npc" and "u".

    A randomly selected hint

    The dynamic line will be randomly chosen from the hints snippets.

    {
      "give_hint": true
    }
    

    Based on a previously generated reason

    The dynamic line will be chosen from a reason generated by an earlier effect. The reason will be cleared. Use of it should be gated on the "has_reason" condition.

    {
      "has_reason": { "use_reason": true },
      "no": "What is it, boss?"
    }
    

    Based on any Dialogue condition

    The dynamic line will be chosen based on whether a single dialogue condition is true or false. Dialogue conditions cannot be chained via "and", "or", or "not". If the condition is true, the "yes" response will be chosen and otherwise the "no" response will be chosen. Both the '"yes" and "no" reponses are optional. Simple string conditions may be followed by "true" to make them fields in the dynamic line dictionary, or they can be followed by the response that will be chosen if the condition is true and the "yes" response can be omitted.

    {
        "npc_need": "fatigue",
        "level": "TIRED",
        "no": "Just few minutes more...",
        "yes": "Make it quick, I want to go back to sleep."
    }
    {
        "npc_aim_rule": "AIM_PRECISE",
        "no": "*will not bother to aim at all.",
        "yes": "*will take time and aim carefully."
    }
    {
        "u_has_item": "india_pale_ale",
        "yes": "<noticedbooze>",
        "no": "<neutralchitchat>"
    }
    {
        "days_since_cataclysm": 30,
        "yes": "Now, we've got a moment, I was just thinking it's been a month or so since... since all this, how are you coping with it all?",
        "no": "<neutralchitchat>"
    }
    {
        "is_day": "Sure is bright out.",
        "no": {
            "u_male": true,
            "yes": "Want a beer?",
            "no": "Want a cocktail?"
        }
    }
    

    Speaker Effects

    The speaker_effect entry contains dialogue effects that occur after the NPC speaks the dynamic_line but before the player responds and regardless of the player response. Each effect can have an optional condition, and will only be applied if the condition is true. Each speaker_effect can also have an optional sentinel, which guarantees the effect will only run once.

    Format:

    "speaker_effect": {
      "sentinel": "...",
      "condition": "...",
      "effect": "..."
    }
    

    or:

    "speaker_effect": [
      {
        "sentinel": "...",
        "condition": "...",
        "effect": "..."
      },
      {
        "sentinel": "...",
        "condition": "...",
        "effect": "..."
      }
    ]
    

    The sentinel can be any string, but sentinels are unique to each TALK_TOPIC. If there are multiple speaker_effects within the TALK_TOPIC, they should have different sentinels. Sentinels are not required, but since the speaker_effect will run every time the dialogue returns to the TALK_TOPIC, they are highly encouraged to avoid inadvertently repeating the same effects.

    The effect can be any legal effect, as described below. The effect can be a simple string, object, or an array of strings and objects, as normal for objects.

    The optional condition can be any legal condition, as described below. If a condition is present, the effect will only occur if the condition is true.

    Speaker effects are useful for setting status variables to indicate that player has talked to the NPC without complicating the responses with multiple effect variables. They can also be used, with a sentinel, to run a mapgen_update effect the first time the player hears some dialogue from the NPC.


    Responses

    A response contains at least a text, which is display to the user and “spoken” by the player character (its content has no meaning for the game) and a topic to which the dialogue will switch to. It can also have a trial object which can be used to either lie, persuade or intimidate the NPC, see below for details. There can be different results, used either when the trial succeeds and when it fails.

    Format:

    {
      "text": "I, the player, say to you...",
      "condition": "...something...",
      "trial": {
        "type": "PERSUADE",
        "difficulty": 10
      },
      "success": {
        "topic": "TALK_DONE",
        "effect": "...",
        "opinion": {
          "trust": 0,
          "fear": 0,
          "value": 0,
          "anger": 0,
          "owed": 0,
          "favors": 0
        }
      },
      "failure": {
        "topic": "TALK_DONE"
      }
    }
    

    Alternatively a short format:

    {
      "text": "I, the player, say to you...",
      "effect": "...",
      "topic": "TALK_WHATEVER"
    }
    

    The short format is equivalent to (an unconditional switching of the topic, effect is optional):

    {
      "text": "I, the player, say to you...",
      "trial": {
        "type": "NONE"
      },
      "success": {
        "effect": "...",
        "topic": "TALK_WHATEVER"
      }
    }
    

    The optional boolean keys “switch” and “default” are false by default. Only the first response with "switch": true, "default": false, and a valid condition will be displayed, and no other responses with "switch": true will be displayed. If no responses with "switch": true and "default": false are displayed, then any and all responses with "switch": true and "default": true will be displayed. In either case, all responses that have "switch": false (whether or not they have "default": true is set) will be displayed as long their conditions are satisfied.

    switch and default Example

    "responses": [
      { "text": "You know what, never mind.", "topic": "TALK_NONE" },
      { "text": "How does 5 Ben Franklins sound?",
        "topic": "TALK_BIG_BRIBE", "condition": { "u_has_items": { "item": "100_usd", "count": 5 } }, "switch": true },
       { "text": "I could give you a big Grant.",
        "topic": "TALK_BRIBE", "condition": { "u_has_item": "50_usd" }, "switch": true },
      { "text": "Lincoln liberated the slaves, what can he do for me?",
        "topic": "TALK_TINY_BRIBE", "condition": { "u_has_item": "5_usd" }, "switch": true, "default": true },
      { "text": "Maybe we can work something else out?", "topic": "TALK_BRIBE_OTHER",
        "switch": true, "default": true },
      { "text": "Gotta go!", "topic": "TALK_DONE" }
    ]
    

    The player will always have the option to return to a previous topic or end the conversation, and will otherwise have the option to give a $500, $50, or $5 bribe if they have the funds. If they don’t have at least $50, they will also have the option to provide some other bribe.

    truefalsetext

    The player will have one response text if a condition is true, and another if it is false, but the same trial for either line. condition, true, and false are all mandatory.

    {
      "truefalsetext": {
        "condition": { "u_has_item": "FMCNote" },
        "true": "I may have the money, I'm not giving you any.",
        "false": "I don't have that money."
      },
      "topic": "TALK_WONT_PAY"
    }
    

    text

    Will be shown to the user, no further meaning.

    trial

    Optional, if not defined, "NONE" is used. Otherwise one of "NONE", "LIE", "PERSUADE", "INTIMIDATE", or "CONDITION". If "NONE" is used, the failure object is not read, otherwise it’s mandatory.

    The difficulty is only required if type is not "NONE" or "CONDITION" and specifies the success chance in percent (it is however modified by various things like mutations). Higher difficulties are easier to pass.

    An optional mod array takes any of the following modifiers and increases the difficulty by the NPC’s opinion of your character or personality trait for that modifier multiplied by the value: "ANGER", "FEAR", "TRUST", "VALUE", "AGRESSION", "ALTRUISM", "BRAVERY", "COLLECTOR". The special "POS_FEAR" modifier treats NPC’s fear of your character below 0 as though it were 0. The special "TOTAL" modifier sums all previous modifiers and then multiplies the result by its value and is used when setting the owed value.

    "CONDITION" trials take a mandatory condition instead of difficulty. The success object is chosen if the condition is true and the failure is chosen otherwise.

    success and failure

    Both objects have the same structure. topic defines which topic the dialogue will switch to. opinion is optional, if given it defines how the opinion of the NPC will change. The given values are added to the opinion of the NPC, they are all optional and default to 0. effect is a function that is executed after choosing the response, see below.

    The opinion of the NPC affects several aspects of the interaction with NPCs:

    • Higher trust makes it easier to lie and persuade, and it usually a good thing.
    • Higher fear makes it easier to intimidate, but the NPC may flee from you (and will not talk to you).
    • Higher value makes it easier to persuade them and to give them orders, it’s a kind of a friendship indicator.
    • High anger value (about 20 points more than fear, but this also depends on the NPCs personality) makes the NPC hostile and is usually a bad thing. The combination of fear and trust decide together with the personality of the NPC the initial talk topic ("TALK_MUG", "TALK_STRANGER_AGGRESSIVE", "TALK_STRANGER_SCARED", "TALK_STRANGER_WARY", "TALK_STRANGER_FRIENDLY", or "TALK_STRANGER_NEUTRAL").

    For the actual usage of that data, search the source code for "op_of_u".

    The failure object is used if the trial fails, the success object is used otherwise.

    Sample trials

    "trial": { "type": "PERSUADE", "difficulty": 0, "mod": [ [ "TRUST", 3 ], [ "VALUE", 3 ], [ "ANGER", -3 ] ] }
    "trial": { "type": "INTIMIDATE", "difficulty": 20, "mod": [ [ "FEAR", 8 ], [ "VALUE", 2 ], [ "TRUST", 2 ], [ "BRAVERY", -2 ] ] }
    "trial": { "type": "CONDITION", "condition": { "npc_has_trait": "FARMER" } }
    

    topic can also be a single topic object (the type member is not required here):

    "success": {
        "topic": {
            "id": "TALK_NEXT",
            "dynamic_line": "...",
            "responses": [
            ]
        }
    }
    

    condition

    This is an optional condition which can be used to prevent the response under certain circumstances. If not defined, it defaults to always true. If the condition is not met, the response is not included in the list of possible responses. For possible content see Dialogue Conditions below.


    Talk Tags

    Talk tags are special strings held between ‘<’ and ‘>’ characters that get dynamically replaced. There are three kinds:

    Special

    These are hard-coded to be dynamically filled in.

    | |––––––––––––––––––––––––––––––––| –––––––––––––––––––––––––––––––––––––––––––––––––––––––– | | ‘’ | Name of your primary weapon, with ‘none’ as default if none found. | | ‘’ | Name of the npcs’ primary weapon, with ‘fists’ as default if none found. | | ‘’ | Name of your primary weapons’ ammo, with ‘BADAMMO’ as default if not a gun. | | ‘<current_activity>’ | Npcs’ current activity as a verb, with ‘doing this and that’ if not doing anything. | | ‘’ | Npcs’ pronoun, uppercase. eg. ‘He’ / ‘She’ | | ‘<topic_item>’ | Item from a repeat response. | | ‘<topic_item_price>’ | Price of item from a repeat response. | | ‘<topic_item_my_total_price>’ | Price of all items of this type from a repeat response, using the npcs’ inventory. | | ‘<topic_item_your_total_price>’ | Price of all items of this type from a repeat response, using the players’ inventory. | | ‘’ | The time until this npc restocks their item shop |

    Snippets

    These are lists of phrases that can be chosen at random. Examples of these are in talk_tags.json

    Here’s an example taken from that file:

    {
    	"type": "snippet",
    	"category": "<lets_talk>",
    	"//": "NPCs shout these things while approaching the avatar for the first time",
    	"text": [
    		"Wait up, let's talk!",
    		"Hey, I <really> want to talk to you!",
    		"Come on, talk to me!",
    		"Hey <name_g>, let's talk!",
    		"<name_g>, we <really> need to talk!",
    		"Hey, we should talk, <okay>?",
    		"Hey, can we talk for a bit?",
    		"<name_g>!  Wait up!",
    		"Wait up, <okay>?",
    		"Let's talk, <name_g>!",
    		"Look, <name_g><punc> let's talk!",
    		"Hey, what's the rush?  Let's chat a tad."
    	]
    },
    

    As can be seen, it can even reverence other talk tags, since the function loops over the string until no tags remain. Ensure you do not create loops!

    Talk Variables

    These are defined either by using lua, or by setting variables via the dialogue system itself. Remember that for the purposes of lua, you’ll need to have ‘npctalk_var_’ prepend the key for compatibility. In dialogue, all one must do is call the set_var functions as applicable.

    Here’s an example:

    {
    	"effect": [
    		{ "u_add_var": "player_val", "value": "testing string" },
    		{ "npc_add_var": "npc_test_var", "value": "npc testing string" },
    	],
    },
    

    You could display those later using ‘<utalk_var_player_val>’ and ‘<npctalk_var_npc_test_var>’, displaying ‘testing string’ and ‘npc testing string’ respectively.


    Repeat Responses

    Repeat responses are responses that should be added to the response list multiple times, once for each instance of an item.

    A repeat response has the following format:

    {
      "for_item": [
        "jerky",
        "meat_smoked",
        "fish_smoked",
        "cooking_oil",
        "cooking_oil2",
        "cornmeal",
        "flour",
        "fruit_wine",
        "beer",
        "sugar"
      ],
      "response": { "text": "Delivering <topic_item>.", "topic": "TALK_DELIVER_ASK" }
    }
    

    "response" is mandatory and must be a standard dialogue response, as described above. "switch" is allowed in repeat responses and works normally.

    One of "for_item" or "for_category", and each can either be a single string or list of items or item categories. The response is generated for each item in the list in the player or NPC’s inventory.

    "is_npc" is an optional bool value, and if it is present, the NPC’s inventory list is checked. By default, the player’s inventory list is checked.

    "include_containers" is an optional bool value, and if it is present, items containing an item will generate separate responses from the item itself.


    Dialogue Effects

    The effect field of speaker_effect or a response can be any of the following effects. Multiple effects should be arranged in a list and are processed in the order listed.

    Missions

    EffectDescription
    assign_missionAssigns a previously selected mission to your character.
    mission_successResolves the current mission successfully.
    mission_failureResolves the current mission as a failure.
    clear_missionClears the mission from the your character’s assigned missions.
    mission_rewardGives the player the mission’s reward.
    assign_mission: mission_type_id stringWill assign mission mission_type_id to the player.
    finish_mission: mission_type_id string,success: success_boolWill complete mission mission_type_id to the player as a success if success is true, as a failure otherwise.

    Stats / Morale

    EffectDescription
    give_aidRemoves all bites, infection, and bleeding from your character’s body and heals 10-25 HP of injury on each of your character’s body parts. Takes 30 minutes. NPC receives 30 minutes of currently_busy effect on start.
    give_all_aidPerforms give_aid on your character and each of your character’s NPC allies in crafting range. Takes 1 hour. NPC receives 1 hour of currently_busy effect on start.
    buy_haircutGives your character a haircut morale boost for 12 hours.
    buy_shaveGives your character a shave morale boost for 6 hours.
    morale_chatGives your character a pleasant conversation morale boost for 6 hours.
    player_weapon_awayMakes your character put away (unwield) their weapon.
    player_weapon_dropMakes your character drop their weapon.

    Character effects / Mutations

    EffectDescription
    u_add_effect: effect_string, (one of duration: duration_string, duration: duration_int)
    npc_add_effect: effect_string, (one of duration: duration_string, duration: duration_int)
    Your character or the NPC will gain the effect for duration_string or duration_int turns. If duration_string is "PERMANENT", the effect will be added permanently.
    u_add_trait: trait_string
    npc_add_trait: trait_string
    Your character or the NPC will gain the trait.
    u_lose_effect: effect_string
    npc_lose_effect: effect_string
    Your character or the NPC will lose the effect if they have it.
    u_lose_trait: trait_string
    npc_lose_trait: trait_string
    Your character or the NPC will lose the trait.
    u_add_var, npc_add_var: var_name, type: type_str, context: context_str, value: value_strYour character or the NPC will store value_str as a variable that can be later retrieved by u_has_var or npc_has_var. npc_add_var can be used to store arbitrary local variables, and u_add_var can be used to store arbitrary “global” variables, and should be used in preference to setting effects.
    u_lose_var, npc_lose_var: var_name, type: type_str, context: context_strYour character or the NPC will clear any stored variable that has the same var_name, type_str, and context_str.
    u_adjust_var, npc_adjust_var: var_name, type: type_str, context: context_str, adjustment: adjustment_numYour character or the NPC will adjust the stored variable by adjustment_num.
    barber_hairOpens a menu allowing the player to choose a new hair style.
    barber_beardOpens a menu allowing the player to choose a new beard style.
    u_learn_recipe: recipe_stringYour character will learn and memorize the recipe recipe_string.
    npc_first_topic: topic_stringNPC permanently changes first dialogue topic to topic_string.

    Trade / Items

    EffectDescription
    start_tradeOpens the trade screen and allows trading with the NPC.
    buy_10_logsPlaces 10 logs in the ranch garage, and makes the NPC unavailable for 1 day.
    buy_100_logsPlaces 100 logs in the ranch garage, and makes the NPC unavailable for 7 days.
    give_equipmentAllows your character to select items from the NPC’s inventory and transfer them to your inventory.
    npc_gets_itemAllows your character to select an item from your character’s inventory and transfer it to the NPC’s inventory. The NPC will not accept it if they do not have space or weight to carry it, and will set a reason that can be referenced in a future dynamic line with "use_reason".
    npc_gets_item_to_useAllow your character to select an item from your character’s inventory and transfer it to the NPC’s inventory. The NPC will attempt to wield it and will not accept it if it is too heavy or is an inferior weapon to what they are currently using, and will set a reason that can be referenced in a future dynamic line with "use_reason".
    u_buy_item: item_string, (optional cost: cost_num, optional count: count_num, optional container: container_string)The NPC will give your character the item or count_num copies of the item, contained in container, and will subtract cost_num from op_of_u.owed if specified. If the op_o_u.owed is less than cost_num, the trade window will open and the player will have to trade to make up the difference; the NPC will not give the player the item unless cost_num is satisfied.
    If cost isn’t present, the NPC gives your character the item at no charge.
    u_sell_item: item_string, (optional cost: cost_num, optional count: count_num)Your character will give the NPC the item or count_num copies of the item, and will add cost_num to the NPC’s op_of_u.owed if specified.
    If cost isn’t present, the your character gives the NPC the item at no charge.
    This effect will fail if you do not have at least count_num copies of the item, so it should be checked with u_has_items.
    u_bulk_trade_accept
    npc_bulk_trade_accept
    Only valid after a repeat_response. The player trades all instances of the item from the repeat_response with the NPC. For u_bulk_trade_accept, the player loses the items from their inventory and gains the same value of the NPC’s faction currecy; for npc_bulk_trade_accept, the player gains the items from the NPC’s inventory and loses the same value of the NPC’s faction currency. If there is remaining value, or the NPC doesn’t have a faction currency, the remainder goes into the NPC’s op_of_u.owed.
    u_bulk_donate
    npc_bulk_donate
    Only valid after a repeat_response. The player or NPC transfers all instances of the item from the repeat_response. For u_bulk_donate, the player loses the items from their inventory and the NPC gains them; for npc_bulk_donate, the player gains the items from the NPC’s inventory and the NPC loses them.
    u_spend_ecash: amountRemove amount from your character’s pre-cataclysm bank account. Negative values means your character gains e-cash. NPCs should not deal in e-cash, only personal debts and items (including faction currency).
    add_debt: mod_listIncreases the NPC’s debt to the player by the values in the mod_list.
    The following would increase the NPC’s debt to the player by 1500x the NPC’s altruism and 1000x the NPC’s opinion of the player’s value: { "effect": { "add_debt": [ [ "ALTRUISM", 3 ], [ "VALUE", 2 ], [ "TOTAL", 500 ] ] } }
    u_consume_item, npc_consume_item: item_string, (optional count: count_num)You or the NPC will delete the item or count_num copies of the item from their inventory.
    This effect will fail if the you or NPC does not have at least count_num copies of the item, so it should be checked with u_has_items or npc_has_items.
    u_remove_item_with, npc_remove_item_with: item_stringYou or the NPC will delete any instances of item in inventory.
    This is an unconditional remove and will not fail if you or the NPC does not have the item.
    u_buy_monster: monster_type_string, (optional cost: cost_num, optional count: count_num, optional name: name_string, optional pacified: pacified_bool)The NPC will give your character count_num (default 1) instances of the monster as pets and will subtract cost_num from op_of_u.owed if specified. If the op_o_u.owed is less than cost_num, the trade window will open and the player will have to trade to make up the difference; the NPC will not give the player the item unless cost_num is satisfied.
    If cost isn’t present, the NPC gives your character the item at no charge.
    If name_string is specified the monster(s) will have the specified name. If pacified_bool is set to true, the monster will have the pacified effect applied.

    Behavior / AI

    EffectDescription
    assign_guardMakes the NPC into a guard. If allied and at a camp, they will be assigned to that camp.
    stop_guardReleases the NPC from their guard duty (also see assign_guard). Friendly NPCs will return to following.
    wake_upWakes up sleeping, but not sedated, NPCs.
    reveal_statsReveals the NPC’s stats, based on the player’s skill at assessing them.
    end_conversationEnds the conversation and makes the NPC ignore you from now on.
    insult_combatEnds the conversation and makes the NPC hostile, adds a message that character starts a fight with the NPC.
    hostileMakes the NPC hostile and ends the conversation.
    fleeMakes the NPC flee from your character.
    followMakes the NPC follow your character, joining the “Your Followers” faction.
    leaveMakes the NPC leave the “Your Followers” faction and stop following your character.
    follow_onlyMakes the NPC follow your character without changing factions.
    stop_followingMakes the NPC stop following your character without changing factions.
    npc_thankfulMakes the NPC positively inclined toward your character.
    drop_weaponMakes the NPC drop their weapon.
    stranger_neutralChanges the NPC’s attitude to neutral.
    start_muggingThe NPC will approach your character and steal from your character, attacking if your character resists.
    lead_to_safetyThe NPC will gain the LEAD attitude and give your character the mission of reaching safety.
    start_trainingThe NPC will train your character in a skill or martial art.
    companion_mission: role_stringThe NPC will offer you a list of missions for your allied NPCs, depending on the NPC’s role.
    basecamp_missionThe NPC will offer you a list of missions for your allied NPCs, depending on the local basecamp.
    bionic_installThe NPC installs a bionic from your character’s inventory onto your character, using very high skill, and charging you according to the operation’s difficulty.
    bionic_removeThe NPC removes a bionic from your character, using very high skill, and charging you according to the operation’s difficulty.
    npc_class_change: class_stringChange the NPC’s faction to class_string.
    npc_faction_change: faction_stringChange the NPC’s faction membership to faction_string.
    u_faction_rep: rep_numIncreases your reputation with the NPC’s current faction, or decreases it if rep_num is negative.
    toggle_npc_rule: rule_stringToggles the value of a boolean NPC follower AI rule such as "use_silent" or "allow_bash"
    set_npc_rule: rule_stringSets the value of a boolean NPC follower AI rule such as "use_silent" or "allow_bash"
    clear_npc_rule: rule_stringClears the value of a boolean NPC follower AI rule such as "use_silent" or "allow_bash"
    set_npc_engagement_rule: rule_stringSets the NPC follower AI rule for engagement distance to the value of rule_string.
    set_npc_aim_rule: rule_stringSets the NPC follower AI rule for aiming speed to the value of rule_string.
    npc_dieThe NPC will die at the end of the conversation.

    Map Updates

    mapgen_update: mapgen_update_id_string
    mapgen_update: list of mapgen_update_id_strings, (optional assign_mission_target parameters) | With no other parameters, updates the overmap tile at the player’s current location with the changes described in mapgen_update_id (or for each mapgen_update_id in the list). The assign_mission_target parameters can be used to change the location of the overmap tile that gets updated. See the missions docs for assign_mission_target parameters and the mapgen docs for mapgen_update.

    Deprecated

    EffectDescription
    deny_follow
    deny_lead
    deny_train
    deny_personal_info
    Sets the appropriate effect on the NPC for a few hours.
    These are deprecated in favor of the more flexible npc_add_effect described above.

    Sample effects

    { "topic": "TALK_EVAC_GUARD3_HOSTILE", "effect": [ { "u_faction_rep": -15 }, { "npc_change_faction": "hells_raiders" } ] }
    { "text": "Let's trade then.", "effect": "start_trade", "topic": "TALK_EVAC_MERCHANT" },
    { "text": "What needs to be done?", "topic": "TALK_CAMP_OVERSEER", "effect": { "companion_mission": "FACTION_CAMP" } }
    { "text": "Do you like it?", "topic": "TALK_CAMP_OVERSEER", "effect": [ { "u_add_effect": "concerned", "duration": 600 }, { "npc_add_effect": "touched", "duration": "3600" }, { "u_add_effect": "empathetic", "duration": "PERMANENT" } ] }
    

    opinion changes

    As a special effect, an NPC’s opinion of your character can change. Use the following:

    opinion:

    trust, value, fear, and anger are optional keywords inside the opinion object. Each keyword must be followed by a numeric value. The NPC’s opinion is modified by the value.

    Sample opinions

    { "effect": "follow", "opinion": { "trust": 1, "value": 1 }, "topic": "TALK_DONE" }
    { "topic": "TALK_DENY_FOLLOW", "effect": "deny_follow", "opinion": { "fear": -1, "value": -1, "anger": 1 } }
    

    mission_opinion:

    trust, value, fear, and anger are optional keywords inside the mission_opinion object. Each keyword must be followed by a numeric value. The NPC’s opinion is modified by the value.


    Dialogue conditions

    Conditions can be a simple string with no other values, a key and an int, a key and a string, a key and an array, or a key and an object. Arrays and objects can nest with each other and can contain any other condition.

    The following keys and simple strings are available:

    Boolean logic

    ConditionTypeDescription
    "and"arraytrue if every condition in the array is true. Can be used to create complex condition tests, like "[INTELLIGENCE 10+][PERCEPTION 12+] Your jacket is torn. Did you leave that scrap of fabric behind?"
    "or"arraytrue if any condition in the array is true. Can be used to create complex condition tests, like "[STRENGTH 9+] or [DEXTERITY 9+] I'm sure I can handle one zombie."
    "not"objecttrue if the condition in the object or string is false. Can be used to create complex conditions test by negating other conditions, for text such as
    "[INTELLIGENCE 7-] Hitting the reactor with a hammer should shut it off safely, right?"

    Player or NPC conditions

    These conditions can be tested for the player using the "u_" form, and for the NPC using the "npc_" form.

    ConditionTypeDescription
    "u_male"
    "npc_male"
    simple stringtrue if the player character or NPC is male.
    "u_female"
    "npc_female"
    simple stringtrue if the player character or NPC is female.
    "u_at_om_location"
    "npc_at_om_location"
    stringtrue if the player character or NPC is standing on an overmap tile with u_at_om_location’s id. The special string "FACTION_CAMP_ANY" changes it to return true if the player or NPC is standing on a faction camp overmap tile. The special string "FACTION_CAMP_START" changes it to return true if the overmap tile that the player or NPC is standing on can be turned into a faction camp overmap tile.
    "u_has_trait"
    "npc_has_trait"
    stringtrue if the player character or NPC has a specific trait. Simpler versions of u_has_any_trait and npc_has_any_trait that only checks for one trait.
    "u_has_trait_flag"
    "npc_has_trait_flag"
    stringtrue if the player character or NPC has any traits with the specific trait flag. More robust versions of u_has_any_trait and npc_has_any_trait. The special trait flag "MUTATION_THRESHOLD" checks to see if the player or NPC has crossed a mutation threshold.
    "u_has_any_trait"
    "npc_has_any_trait"
    arraytrue if the player character or NPC has any trait or mutation in the array. Used to check multiple specific traits.
    "u_has_var", "npc_has_var"string"type": type_str, "context": context_str, and "value": value_str are required fields in the same dictionary as "u_has_var" or "npc_has_var".
    true is the player character or NPC has a variable set by "u_add_var" or "npc_add_var" with the string, type_str, context_str, and value_str.
    "u_compare_var", "npc_compare_var"dictionary"type": type_str, "context": context_str, "op": op_str, "value": value_num are required fields, referencing a var as in "u_add_var" or "npc_add_var".
    true if the player character or NPC has a stored variable that is true for the provided operator op_str (one of ==, !=, <, >, <=, >=) and value.
    "u_has_strength"
    "npc_has_strength"
    inttrue if the player character’s or NPC’s strength is at least the value of u_has_strength or npc_has_strength.
    "u_has_dexterity"
    "npc_has_dexterity"
    inttrue if the player character’s or NPC’s dexterity is at least the value of u_has_dexterity or npc_has_dexterity.
    "u_has_intelligence"
    "npc_has_intelligence"
    inttrue if the player character’s or NPC’s intelligence is at least the value of u_has_intelligence or npc_has_intelligence.
    "u_has_perception"
    "npc_has_perception"
    inttrue if the player character’s or NPC’s perception is at least the value of u_has_perception or npc_has_perception.
    "u_has_item"
    "npc_has_item"
    stringtrue if the player character or NPC has something with u_has_item’s or npc_has_item’s item_id in their inventory.
    "u_has_items"
    "npc_has_item"
    dictionaryu_has_items or npc_has_items must be a dictionary with an item string and a count int.
    true if the player character or NPC has at least count charges or counts of item in their inventory.
    "u_has_item_category"
    "npc_has_item_category"
    string"count": item_count is an optional field that must be in the same dictionary and defaults to 1 if not specified. true if the player or NPC has item_count items with the same category as u_has_item_category or npc_has_item_category.
    "u_has_bionics"
    "npc_has_bionics"
    stringtrue if the player or NPC has an installed bionic with an bionic_id matching "u_has_bionics" or "npc_has_bionics". The special string “ANY” returns true if the player or NPC has any installed bionics.
    "u_has_effect"
    "npc_has_effect"
    stringtrue if the player character or NPC is under the effect with u_has_effect or npc_has_effect’s effect_id.
    "u_can_stow_weapon"
    "npc_can_stow_weapon"
    simple stringtrue if the player character or NPC is wielding a weapon and has enough space to put it away.
    "u_has_weapon"
    "npc_has_weapon"
    simple stringtrue if the player character or NPC is wielding a weapon.
    "u_driving"
    "npc_driving"
    simple stringtrue if the player character or NPC is operating a vehicle. Note NPCs cannot currently operate vehicles.
    "u_has_skill"
    "npc_has_skill"
    dictionaryu_has_skill or npc_has_skill must be a dictionary with a skill string and a level int.
    true if the player character or NPC has at least the value of level in skill.
    "u_know_recipe"stringtrue if the player character knows the recipe specified in u_know_recipe. It only counts as known if it is actually memorized–holding a book with the recipe in it will not count.

    Player Only conditions

    "u_has_mission" | string | true if the mission is assigned to the player character. "u_has_ecash" | int | true if the player character has at least u_has_ecash ecash available in his pre-cataclysm bank account. NPCs should not deal in e-cash, only personal debts and items (including faction currency). "u_are_owed" | int | true if the NPC’s op_of_u.owed is at least u_are_owed. Can be used to check if the player can buy something from the NPC without needing to barter anything. "u_has_camp" | simple string | true is the player has one or more active base camps.

    Player and NPC interaction conditions

    ConditionTypeDescription
    "at_safe_space"simple stringtrue if the NPC’s current overmap location passes the is_safe() test.
    "has_assigned_mission"simple stringtrue if the player character has exactly one mission from the NPC. Can be used for texts like “About that job…”.
    "has_many_assigned_missions"simple stringtrue if the player character has several mission from the NPC (more than one). Can be used for texts like “About one of those jobs…” and to switch to the "TALK_MISSION_LIST_ASSIGNED" topic.
    "has_no_available_mission"simple stringtrue if the NPC has no jobs available for the player character.
    "has_available_mission"simple stringtrue if the NPC has one job available for the player character.
    "has_many_available_missions"simple stringtrue if the NPC has several jobs available for the player character.
    "mission_goal"stringtrue if the NPC’s current mission has the same goal as mission_goal.
    "mission_complete"simple stringtrue if the player has completed the NPC’s current mission.
    "mission_incomplete"simple stringtrue if the player hasn’t completed the NPC’s current mission.
    "mission_has_generic_rewards"simple stringtrue if the NPC’s current mission is flagged as having generic rewards.
    "npc_service"simple stringtrue if the NPC does not have the "currently_busy" effect. Useful to check if the player character can hire an NPC to perform a task that would take time to complete. Functionally, this is identical to not": { "npc_has_effect": "currently_busy" }. Same as npc_available.
    "npc_allies"inttrue if the player character has at least npc_allies number of NPC allies.
    "npc_following"simple stringtrue if the NPC is following the player character.
    "is_by_radio"simple stringtrue if the player is talking to the NPC over a radio.

    NPC only conditions

    ConditionTypeDescription
    "npc_available"simple stringtrue if the NPC does not have effect "currently_busy".
    "npc_following"simple stringtrue if the NPC is following the player character.
    "npc_friend"simple stringtrue if the NPC is friendly to the player character.
    "npc_hostile"simple stringtrue if the NPC is an enemy of the player character.
    "npc_train_skills"simple stringtrue if the NPC has one or more skills with more levels than the player.
    "npc_train_styles"simple stringtrue if the NPC knows one or more martial arts styles that the player does not know.
    "npc_has_class"arraytrue if the NPC is a member of an NPC class.
    "npc_role_nearby"stringtrue if there is an NPC with the same companion mission role as npc_role_nearby within 100 tiles.
    "has_reason"simple stringtrue if a previous effect set a reason for why an effect could not be completed.

    NPC Follower AI rules

    ConditionTypeDescription
    "npc_aim_rule"stringtrue if the NPC follower AI rule for aiming matches the string.
    "npc_engagement_rule"stringtrue if the NPC follower AI rule for engagement matches the string.
    "npc_rule"stringtrue if the NPC follower AI rule for that matches string is set.

    Environment

    ConditionTypeDescription
    "days_since_cataclysm"inttrue if at least days_since_cataclysm days have passed since the Cataclysm.
    "is_season"stringtrue if the current season matches is_season, which must be one of “spring", "summer", "autumn", or "winter".
    "is_day"simple stringtrue if it is currently daytime.
    "is_outside"simple stringtrue if the NPC is on a tile without a roof.

    Sample responses with conditions and effects

    {
      "text": "Understood.  I'll get those antibiotics.",
      "topic": "TALK_NONE",
      "condition": { "npc_has_effect": "infected" }
    },
    {
      "text": "I'm sorry for offending you.  I predict you will feel better in exactly one hour.",
      "topic": "TALK_NONE",
      "effect": { "npc_add_effect": "deeply_offended", "duration": 600 }
    },
    {
      "text": "Nice to meet you too.",
      "topic": "TALK_NONE",
      "effect": { "u_add_effect": "has_met_example_NPC", "duration": "PERMANENT" }
    },
    {
      "text": "Nice to meet you too.",
      "topic": "TALK_NONE",
      "condition": {
        "not": {
          "npc_has_var": "has_met_PC", "type": "general", "context": "examples", "value": "yes"
        }
      },
      "effect": {
        "npc_add_var": "has_met_PC", "type": "general", "context": "examples", "value": "yes" }
      }
    },
    {
      "text": "[INT 11] I'm sure I can organize salvage operations to increase the bounty scavengers bring in!",
      "topic": "TALK_EVAC_MERCHANT_NO",
      "condition": { "u_has_intelligence": 11 }
    },
    {
      "text": "[STR 11] I punch things in face real good!",
      "topic": "TALK_EVAC_MERCHANT_NO",
      "condition": { "and": [ { "not": { "u_has_intelligence": 7 } }, { "u_has_strength": 11 } ] }
    },
    { "text": "[100 Merch, 1d] 10 logs", "topic": "TALK_DONE", "effect": "buy_10_logs", "condition":
    { "and": [ "npc_service", { "u_has_items": { "item": "FMCNote", "count": 100 } } ] } },
    { "text": "Maybe later.", "topic": "TALK_RANCH_WOODCUTTER", "condition": "npc_available" },
    {
      "text": "[1 Merch] I'll take a beer",
      "topic": "TALK_DONE",
      "condition": { "u_has_item": "FMCNote" },
      "effect": [{ "u_sell_item": "FMCNote" }, { "u_buy_item": "beer", "container": "bottle_glass", "count": 2 }]
    },
    {
      "text": "Okay.  Lead the way.",
      "topic": "TALK_DONE",
      "condition": { "not": "at_safe_space" },
      "effect": "lead_to_safety"
    },
    {
      "text": "About one of those missions...",
      "topic": "TALK_MISSION_LIST_ASSIGNED",
      "condition": { "and": [ "has_many_assigned_missions", { "u_is_wearing": "badge_marshal" } ] }
    },
    {
      "text": "[MISSION] The captain sent me to get a frequency list from you.",
      "topic": "TALK_OLD_GUARD_NEC_COMMO_FREQ",
      "condition": {
        "and": [
          { "u_is_wearing": "badge_marshal" },
          { "u_has_mission": "MISSION_OLD_GUARD_NEC_1" },
          { "not": { "u_has_effect": "has_og_comm_freq" } }
        ]
      }
    },
    {
        "text": "I killed them.  All of them.",
        "topic": "TALK_MISSION_SUCCESS",
        "condition": {
            "and": [ { "or": [ { "mission_goal": "KILL_MONSTER_SPEC" }, { "mission_goal": "KILL_MONSTER_TYPE" } ] }, "mission_complete" ]
        },
        "switch": true
    },
    {
        "text": "Glad to help.  I need no payment.",
        "topic": "TALK_NONE",
        "effect": "clear_mission",
        "mission_opinion": { "trust": 4, "value": 3 },
        "opinion": { "fear": -1, "anger": -1 }
    },
    {
        "text": "Maybe you can teach me something as payment?",
        "topic": "TALK_TRAIN",
        "condition": { "or": [ "npc_train_skills", "npc_train_styles" ] },
        "effect": "mission_reward"
    },
    {
        "truefalsetext": {
            "true": "I killed him.",
            "false": "I killed it.",
            "condition": { "mission_goal": "ASSASSINATE" }
        },
        "condition": {
            "and": [
                "mission_incomplete",
                {
                    "or": [
                        { "mission_goal": "ASSASSINATE" },
                        { "mission_goal": "KILL_MONSTER" },
                        { "mission_goal": "KILL_MONSTER_SPEC" },
                        { "mission_goal": "KILL_MONSTER_TYPE" }
                    ]
                }
            ]
        },
        "trial": { "type": "LIE", "difficulty": 10, "mod": [ [ "TRUST", 3 ] ] },
        "success": { "topic": "TALK_NONE" },
        "failure": { "topic": "TALK_MISSION_FAILURE" }
    },
    {
      "text": "Didn't you say you knew where the Vault was?",
      "topic": "TALK_VAULT_INFO",
      "condition": { "not": { "u_has_var": "asked_about_vault", "value": "yes", "type": "sentinel", "context": "old_guard_rep" } },
      "effect": [
          { "u_add_var": "asked_about_vault", "value": "yes", "type": "sentinel", "context": "old_guard" },
          { "mapgen_update": "hulk_hairstyling", "om_terrain": "necropolis_a_13", "om_special": "Necropolis", "om_terrain_replace": "field", "z": 0 }
      ]
    },
    {
      "text": "Why do zombies keep attacking every time I talk to you?",
      "topic": "TALK_RUN_AWAY_MORE_ZOMBIES",
      "condition": { "u_has_var": "even_more_zombies", "value": "yes", "type": "trigger", "context": "learning_experience" },
      "effect": [
        { "mapgen_update": [ "even_more_zombies", "more zombies" ], "origin_npc": true },
        { "mapgen_update": "more zombies", "origin_npc": true, "offset_x": 1 },
        { "mapgen_update": "more zombies", "origin_npc": true, "offset_x": -1 },
        { "mapgen_update": "more zombies", "origin_npc": true, "offset_y": 1 },
        { "mapgen_update": "more zombies", "origin_npc": true, "offset_y": -1 }
      ]
    }
    

    Perks

    Perks are categorized bonuses given to the player. Their only affects are either given via enchantments or lua based id hardcode

    Fields

    IdentifierDescription
    id(mandatory) Unique string id
    name(mandatory) In game name of the perk
    description(mandatory) In game description of the perk
    category(mandatory) Category of the enchantment, used as the in game perk menu name and for matching with other perks.
    hidden(optional) Weather the enchantment is hidden in the perk menu, default false
    enchantments(optional) Array of enchantments defined in either of the inline methods, what enchantments this perk provides

    Example

    {
      "type": "perk",
      "id": "duck_perk_eagle_eyes",
      "name": "Eagle Eyes",
      "description": "Your sharp gazes misses little. +25% to unenhanced sight range",
      "category": "Perk",
      "hidden": false,
      "enchantments": [
        { "values": [ { "value": "SIGHT_RANGE", "multiply": 0.25 } ] },
        { "id": "ENCH_INVISIBILITY" }
      ],
    },
    

    Activities

    Activities are long term actions, that can be interrupted and (optionally) continued. This allows the avatar or an npc to react to events (like monsters appearing, getting hurt) while doing something that takes more than just one turn.

    Adding new activities

    1. player_activities.json Define properties that apply to all instances of the activity in question.

    2. activity_actor.h Create a new subclass of activity_actor (e.g. move_items_activity_actor) to store state and handle turns of the new activity.

    3. activity_actor.cpp Define the start, do_turn, and finish functions needed for the new actor as well as the required serialization functions. Don’t forget to add the deserialization function of your new activity actor to the deserialize_functions map towards the bottom of activity_actor.cpp. Define canceled function if activity modifies some complex state that should be restored upon cancellation / interruption.

    4. If this activity is resumable, override activity_actor::can_resume_with_internal

    5. Construct your activity actor and then pass it to the constructor for player_activity. The newly constructed activity can then be assigned to the character and started using Character::assign_activity.

    Lua-backed activities

    Lua scripts can assign any activity with Lua callbacks in game.activity_functions[id]:

    game.activity_functions["MY_ACTIVITY_FINISH"] = function(params)
      -- params.user, params.activity, params.name, params.pos, params.data
    end
    
    who:assign_lua_activity({
      type = ActivityTypeId.new("ACT_WASH_SELF"),
      duration = TimeDuration.from_minutes(5),
      on_finish = "MY_ACTIVITY_FINISH",
      on_turn = "MY_ACTIVITY_TURN", -- optional
      pos = target_pos,
      data = { mode = "example" },
    })
    

    Use data for serializable Lua state. pos is supplied in bubble coordinates when assigning and is reported to callbacks as absolute map-square coordinates.

    JSON Properties

    • verb: A descriptive term to describe the activity to be used in the query to stop the activity, and strings that describe it, for example: "verb": "mining" or "verb": { "ctxt": "instrument", "str": "playing" }.

    • suspendable (true): If true, the activity can be continued without starting from scratch again. This is only possible if can_resume_with() returns true.

    • rooted (false): If true, then during the activity, recoil is reduced, and plant mutants sink their roots into the ground. Should be true if the activity lasts longer than a few minutes, and can always be accomplished without moving your feet.

    • special (false): activity is considered special and expects to have unconventional logic, compared to other activities

    • complex_moves(false):

      • if false - activity expects to have no speed calculations and do 100 moves per turn, in JSON it’s specified by absence of complex_moves block;

      • if true - activity expects to have complex speed/moves calculations, based on several factors:

        • max_assistants(0): activity can be assisted by provided maximum of other creatures(range is 0-32);
        • bench(false): activity can be done using workbench;
        • light(false): activity speed is affected by current light level;
        • speed(false): activity speed is affected by creature’s speed;
        • skills: activity speed is affected by skills provided in by pairs skill_name: modifier or "skills": true if you want to explicitely show that activity expects to have modifications based on skills, but those will have to be determine on go (like crafting or constructing):
          • "skills": true
          • "skills": ["fabrication", 5]
        • stats: activity speed is affected by skills provided in by pairs stat_name: modifier or "stats": true if you want to explicitely show that activity expects to have modifications based on stats, but those will have to be determine on go (like crafting or constructing):
          • "stats": true
          • "stats": ["DEX", 5]
        • qualities: activity speed is affected by qualities provided in by pairs q_name: modifier or "qualities": true if you want to explicitely show that activity expects to have modifications based on qualities, but those will have to be determine on go (like crafting or constructing):
          • "qualities": true
          • "qualities": ["CUT_FINE", 5]
        • morale(false): activity speed is affected by creature’s current morale level.

        Example for whole block: “complex_moves”: { “max_assistants”: 2, “bench”: true, “light”: true, “speed”: true, “stats”: true, “skills”: [ ], - //same as "skills": true “qualities”: [ [“CUT_FINE”, “5”] ], “morale”: true }

    • morale_blocked(false): activity won’t be performed if creature’s morale level is below certain level.

    • verbose_tooltip(true): activity will have an expanded progress window, showing a lot of information

    • no_resume (false): Rather than resuming, you must always restart the activity from scratch.

    • multi_activity(false): This activity will repeat until it cannot do any more work, used for NPC and avatar zone activities.

    • bubble_size_effect( none ): The size of the reality bubble during this activity: none for the normal size, mobile for the “Mobile Activity Bubble Size” option (zone activities, travelling), or idle for the “Idle Activity Bubble Size” option (sleeping, reading, waiting). With idle, time_skip is true by default.

    • time_skip( true if bubble_size_effect is idle ): If true, the game can run this activity in skip windows. In a skip window, the game runs the activity, stamina recovery, monsters, NPCs and fires every turn, but processes hunger, thirst, fatigue, healing and item aging once, at the end of the window. If false, the game runs this activity one turn at a time.

    • refuel_fires( false ): If true, the character will automatically refuel fires during the long activity.

    • auto_needs( false ) : If true, the character will automatically eat and drink from specific auto_consume zones during long activities.

    • rest_amount( 0.0 ) : How restful the activity is with respects to HP recovery. A rest_amount of 0.2 gives 20% of the HP recovery sleeping would give while the activity is being performed.

    • suppress_comfort_lines( false ) : If false, lines regarding how comfortable the player is will display while performing an activity with rest_amount greater than zero. True will suppress these lines.

    Termination

    There are several ways an activity can be ended:

    1. Call player_activity::set_to_null()

      This can be called if it finished early or something went wrong, such as corrupt data, disappearing items, etc. The activity will not be put into the backlog.

    2. moves_left <= 0

      Once this condition is true, the finish function, if there is one, is called. The finish function should call set_to_null(). If there isn’t a finish function, set_to_null() will be called for you (from activity_actor::do_turn).

    3. progress.complete()

      Basically the same as moves_left <= 0, but with extra checks and using a progress system.

    4. Character::cancel_activity

      Canceling an activity prevents the activity_actor::finish function from running, and the activity does therefore not yield a result. Instead, activity_actor::canceled is called. If activity is suspendable, a copy of it is written to Character::backlog.

    Progress

    progress_counter - class specialize on tracking progress of and activity

    • targets: queue of targets that are expected to be processed, stores target name, moves_total and moves_left for the target;

    • moves_total (0): Total number of moves required to complete the activity aka all the tasks;

    • moves_left (): The number of moves remaining in this activity before it is complete aka all the tasks;

    • idx (1): 1-based index of currently prcessing task;

    • total_tasks (0): Counts total amount of tasks - done and in queue.

    Notes

    While the character performs the activity, activity_actor::do_turn is called on each turn. Depending on the JSON properties, this will do some stuff. It will also call the do_turn function, and if moves_left is non-positive, the finish function.

    Some activities (like playing music on a mp3 player) don’t have an end result but instead do something each turn (playing music on the mp3 player decreases its batteries and gives a morale bonus).

    If the activity needs any information during its execution or when it’s finished (like where to do something, which item to use to do something, …), simply add data members to your activity actor as well as serialization functions for the data so that the activity can persist across save/load cycles.

    Be careful when storing coordinates as the activity may be carried out by NPCS. If its, the coordinates must be absolute not local as local coordinates are based on the avatars position.

    activity_actor::start

    This function is called exactly once when the activity is assigned to a character. It is useful for setting player_activity::moves_left/player_activity::moves_total in the case of an activity based on time or speed.

    activity_actor::do_turn

    To prevent an infinite loop, ensure that one of the following is satisfied:

    • The player_activity::progress.moves_left is decreased in do_turn

    • The the activity is stopped in do_turn (see ‘Termination’ above)

    For example, move_items_activity_actor::do_turn will either move as many items as possible given the character’s current moves or, if there are no target items remaining, terminate the activity.

    activity_actor::finish

    This function is called when the activity has been completed (moves_left <= 0). It must call player_activity::set_to_null() or assign a new activity. One should not call Character::cancel_activity for the finished activity, as this could make a copy of the activity in Character::backlog, which allows resuming an already finished activity.

    Colors

    BN is a colorful game. You can use several foreground and background colors in various places:

    • map data (terrain and furniture);
    • item data;
    • text data;
    • etc.

    Note: Map data objects can only have one color-related node defined (either color or bgcolor).

    Color string format

    Whenever color is defined in JSON it should be defined in following format: Prefix_Foreground_Background.

    Prefix can take one of following values:

    • c_ - default color prefix (can be omitted);
    • i_ - optional prefix which indicates that foreground color should be inverted (special rules will be applied to foreground and background colors);
    • h_ - optional prefix which indicates that foreground color should be highlighted (special rules will be applied to foreground and background colors).

    Foreground - defines mandatory color of foreground/ink/font.

    Background - defines optional color of background/paper.

    Note: Not all foreground + background pairs are defined by their full name. Use in-game Color manager to see all color names.

    Note: If color was not found by its name, then c_unset is used for Foreground and i_white for Background.

    Examples of color strings

    • c_white - white color (with default prefix c_);
    • black - black color (default prefix c_ is omitted);
    • i_red - inverted red color;
    • dark_gray_white - dark_gray foreground color with white background color;
    • light_gray_light_red - light_gray foreground color with light_red background color;
    • dkgray_red - dark_gray foreground color with red background color (deprecated prefix dk instead of dark_);
    • ltblue_red - light_blue foreground color with red background color (deprecated prefix lt instead of light_).

    Color code

    Color code is short string which defines color and can be used, for example, in maps notes.

    Possible colors

    Color (image)Color name (cataclysm)Color name (curses)Default R,G,B valuesColor codeNotes
    blackBLACK0,0,0
    redRED255,0,0R
    greenGREEN0,110,0G
    brownBROWN92,51,23br
    blueBLUE0,0,200B
    magenta or pinkMAGENTA139,58,98P
    cyanCYAN0,150,180C
    light_grayGRAY150,150,150lgdeprecated lt prefix can be used instead of light_
    dark_grayDGRAY99,99,99dgdeprecated dk prefix can be used instead of dark_
    light_redLRED255,150,150deprecated lt prefix can be used instead of light_
    light_greenLGREEN0,255,0gdeprecated lt prefix can be used instead of light_
    light_yellowYELLOW255,255,0deprecated lt prefix can be used instead of light_
    light_blueLBLUE100,100,255bdeprecated lt prefix can be used instead of light_
    light_magentaLMAGENTA254,0,254lmdeprecated lt prefix can be used instead of light_
    light_cyanLCYAN0,240,255cdeprecated lt prefix can be used instead of light_
    whiteWHITE255,255,255W

    Note: Default RGB values are taken from file \data\raw\colors.json. Note: RGB values can be redefined in file \config\base_colors.json.

    Color rules

    There are two types of special color transformation which can affect both foreground and background color:

    • inversion;
    • highlight.

    Note: Color rules can be redefined (for example, \data\raw\color_templates\no_bright_background.json).

    External Tilesets

    data/json/external_tileset is used for content specific to Bright Nights which are not presently in primary tilesets such as UDP or Ultica, for which looks_like is inadequate to depict the content to a satisfactory degree. It functions using the mod_tileset feature, applying any desired new sprites or overriding sprites to the specified tileset.

    The primary advantage of this method is to set aside sprites so they won’t interfere with updating the tilesets themselves (as their sources are in the repositories of the tileset authors), and likewise ensuring anything specific to BN won’t be accidentally erased, like it would if a tileset update was submitted to BN after these editing these sprites our versions of the tilesets. It also covers divergences in content were, by nessecity, a different sprite is a better fit.

    Links to relevant pull requests, for content covered below:

    • Patchwork Skin port from DDA: #1298
    • Bullet animations: #1861
    • Steam turbine: #2815
    • Wooden shields, riot shields, and ballistic shields: #2851
    • Lead sling bullet: #2709
    • Leather and banded shields: #2856
    • Edits to blueberry bushes, strawberry bushes, and cherry trees: #2861
    • De-obsoleted wooden greatbow, reflavored compound/composite greatbow: #2862
    • Katar and sai: #2715
    • Utility light can be switched off: #1003
    • Mi-go nerve cluster: #1962
    • Scaled bear: #1371
    • Buckler and welded shield: #2878
    • Battle masks and bronze arm guards: #3221
    • Rewired street lights: #3273
    • Alternative ear/tail mutation: #3340
    • Iron ore from bog iron: #3506
    • New trees: #3626
    • Alternative sign sprite: #3670
    • M1874 Gatling gun: #3815
    • New traps: #3939
    • New monster: #4182
    • Furniture form of utility light: #4780
    • Knocked-down version of steel target: #5361
    • Flagpoles: #5363
    • Vehicle-mounted Flags: #5372
    • Pirate Flag: #5375
    • Makeshift cannons and canister shot: #5398
    • Harvested cattails: #5445
    • Niter beds: #5446
    • Scaleskin armor, tooth and bone weapons: #5466
    • Reimplemented bone armor: #5646
    • More tooth and bone weapons, triffid weapons: #5712
    • Treetops ported from DDA: #5167
    • Skateboards ported from DDA: #5849
    • Ability to weld shut doors: #6182
    • Scouting visor: #6687
    • Skeletal lich and master ported from DDA: #6831
    • New elite zombies: #6854
    • Flipping tables/benches for cover: #6857
    • Arrow slits/fortifications: #6864
    • Adobe flooring: #6864
    • Lakebed content: #6903

    Undead People

    The following is a current list of sprites this folder adds to the UDP tileset, in which files and for what purpose. This is currently the only tileset with external_tileset coverage, but sprites for Ultica are planned for the future.

    External_Tileset_DP_Normal.png

    • Furniture form of steam turbines, to be deconstructed for advanced steam engine. Content specific to BN.
    • Animation effects for bullets in flight. Feature specific to BN.
    • Wooden shield, including worn and wielded. Item specific to BN.
    • Riot shield, including worn and wielded. Item specific to BN.
    • Ballistic shield, including worn and wielded. Item specific to BN.
    • Lead sling bullet. Item specific to BN, looks_like of rock did not seem fitting
    • Leather-reinforced shield, including worn and wielded. Item specific to BN.
    • Large leather-reinforced shield, including worn and wielded. Item specific to BN.
    • Banded shield, including worn and wielded. Item specific to BN.
    • Large banded shield, including worn and wielded. Item specific to BN.
    • Fixed worn sprite for woodgreatbow, as it had a sprite error in its UDP version. Note: this can be removed once UDP is updated in BN, as the fix has been published in the source repository.
    • Overriding sprite for compgreatbow, as its version in BN is modeled after a composite bow instead of a compound bow.
    • New worn sprite for compgreatbow, as compound greatbow in DDA can’t be worn thus UDP lacks a worn sprite for it (which we’d liklely need to edit to resemble composite bow anyway).
    • Katar, including sprite for wielded state. Item specific to BN.
    • Sai (weapon, not to be confused with telecoms location), including sprite for wielded state. Item specific to BN.
    • Welded shield, including worn and wielded. Item specific to BN.
    • Buckler, including worn and wielded. Item specific to BN.
    • Battle masks, iron and bronze, including worn sprites. Items specific to BN.
    • Bronze arm guards, including worn sprites. Item specific to BN.
    • Cacao pods. Item specific to BN.
    • Override for sign sprite. Removes lettering on the front specific to DDA.
    • Makeshift perimeter alarm. Trap specific to BN.
    • Lepidopterid. New monster specific to BN.
    • Furniture version of utility light. Furniture specific to BN.
    • Knocked-down steel target. Furniture specific to BN.
    • Jolly Roger, item and worn sprite. Item specific to BN.
    • Makeshift cannon, item and vehiclepart sprite. Item specific to BN.
    • Explosive cannonshells and sprites for readied cannon ammo. Items specific to BN.
    • Harvested state for cattails, including winter variation. Furniture specific to BN.
    • Armor made from reptile scutes, weapons made from heavy bones, teeth, and insect stingers. Items specific to BN.
    • Sprites for bone cuirass and greaves. Reimplementation of previously-obsoleted bone armor specific to BN.
    • Additional tooth and stinger weapons, including triffid stinger weapons. Items specific to BN.
    • Scouting visors, item specific to BN.
    • Cadaver assembler, zombie supply sergeant, banshee, stormbringer, shroud weaver, and shock vortex. Monsters specific to BN.
    • Flipped variants of benches and tables. Furniture specific to BN.
    • Iron ore, item ported from DDA we lacked a suitable sprite for.
    • M1874 Gatling gun, including wielded sprite and vehicle turret. Item specific to BN.
    • Patchwork Skin, ported from DDA but our version of UDP lacked a sprite for it.
    • Skateboard, item and vehicleparts. Port from DDA lacking sprites in UDP.
    • Sea scooter, item and vehiclepart. Item unique to BN.
    • Skeletal lich and skeletal master. Port from DDA that UDP lacked a sprite for.
    • AR-10.

    External_Tileset_DP_terrain_normal.png

    • Rice paddies. Terrain specific to BN.
    • Niter beds. Terrain specific to BN.
    • Swapped spring and summer sprites (the latter not depicting young berries) for blueberry bush, as harvest season has been moved in BN.
    • Welded-shut metal doors including peephole, bulkhead, lab door, and bar doors. Terrain specific to BN.
    • Fortifcations carved into wood, log, stone, and brick walls. Terrain specific to BN.
    • Adobe floors, terrain specific to BN.
    • Moss and tree trunks on lake bed surface. Terrain specific to BN.

    External_Tileset_DP_Tall.png

    • Off state for utility light. Ability to switch on and off specific to BN.
    • Alien nerve cluster, furniture added to mi-go locations in BN. Note: this can be removed once UDP is updated in BN, as the sprite for this has been published in the source repository.
    • Scaled bear, including corpse. Monster specific to BN.
    • Cherry tree uses summer sprite (plus cherry blossom coloration), summer sprite depicted without berries, due to harvest season being moved in BN.
    • Rewired street light, including active state. Furniture specific to BN.
    • Cocoa tree. Terrain specific to BN.
    • Coca plant. Terrain specific to BN.
    • Grid floodlights, furniture based off now-deconstructabble utility lights, furniture added to BN.
    • Metal and wooden flagpoles (including with flag raised), furniture added to BN.
    • American flag displayed as a vehiclepart, specific to BN.
    • Flagpole furniture and vehiclepart for Jolly Roger, content specific to BN.
    • Treetops. Terrain ported from DDA, but which had no sprites available in UDP at present.

    alternative_mutation_tileset.png

    Before

    After

    contains alternative sprites for:

    • FELINE_EARS
    • LUPINE_EARS
    • MOUSE_EARS
    • CANINE_EARS
    • TAIL_FLUFFY
    • TAIL_STUB

    Mod Tileset

    MOD tileset defines additional sprite sheets. It is specified as JSON object with type member set to mod_tileset.

    Example:

    [
      {
        "type": "mod_tileset",
        "compatibility": ["MshockXottoplus"],
        "tiles-new": [
          {
            "file": "test_tile.png",
            "tiles": [
              {
                "id": "player_female",
                "fg": 1,
                "bg": 0
              },
              {
                "id": "player_male",
                "fg": 2,
                "bg": 0
              }
            ]
          }
        ]
      }
    ]
    

    compatibility

    (string)

    The internal ID of the compatible tilesets. MOD tileset is only applied when base tileset’s ID exists in this field.

    tiles-new

    Setting of sprite sheets. Same as tiles-new field in tile_config. Sprite files are loaded from the same folder json file exists.

    state-modifiers

    State modifiers allow mod tilesets to define or override UV-based sprite modifications for character states. When a mod tileset defines a state modifier group with the same id as the base tileset, the mod’s definition replaces the base tileset’s.

    {
      "type": "mod_tileset",
      "compatibility": ["UndeadPeopleTileset"],
      "tiles-new": [
        {
          "file": "uv-tiles.png",
          "tiles": [],
          "state-modifiers": [
            {
              "id": "movement_mode",
              "override": false,
              "use_offset": false,
              "tiles": [
                { "id": "walk", "fg": null },
                { "id": "crouch", "fg": 1 },
                { "id": "run", "fg": 2 }
              ]
            }
          ]
        }
      ]
    }
    

    The state-modifiers array goes inside a tiles-new entry alongside tiles. Each modifier group requires:

    FieldTypeDescription
    idstringGroup identifier (movement_mode, downed, lying_down).
    overrideboolSkip lower-priority groups when this state is active.
    use_offsetbooltrue for offset mode, false for normalized UV mode.
    tilesarrayState-to-sprite mappings.

    See the State Modifiers section in Tilesets for full documentation on UV mapping modes and creating modifier sprites.

    Mutation overlay ordering

    The file mutation_ordering.json defines the order that visual mutation and bionic overlays are rendered on a character ingame. The layering value from 0 (bottom) - 9999 (top) sets the order.

    Example:

    [
      {
        "type": "overlay_order",
        "overlay_ordering": [
          {
            "id": [
              "BEAUTIFUL",
              "BEAUTIFUL2",
              "BEAUTIFUL3",
              "LARGE",
              "PRETTY",
              "RADIOACTIVE1",
              "RADIOACTIVE2",
              "RADIOACTIVE3",
              "REGEN"
            ],
            "order": 1000
          },
          {
            "id": ["HOOVES", "ROOTS1", "ROOTS2", "ROOTS3", "TALONS"],
            "order": 4500
          },
          {
            "id": "FLOWERS",
            "order": 5000
          },
          {
            "id": [
              "PROF_CYBERCOP",
              "PROF_FED",
              "PROF_PD_DET",
              "PROF_POLICE",
              "PROF_SWAT",
              "PHEROMONE_INSECT"
            ],
            "order": 8500
          },
          {
            "id": [
              "bio_armor_arms",
              "bio_armor_legs",
              "bio_armor_torso",
              "bio_armor_head",
              "bio_armor_eyes"
            ],
            "order": 500
          }
        ]
      }
    ]
    

    id

    (string)

    The internal ID of the mutation. Can be provided as a single string, or an array of strings. The order value provided will be applied to all items in the array.

    order

    (integer)

    The ordering value of the mutation overlay. Values range from 0 - 9999, 9999 being the topmost drawn layer. Mutations that are not in any list will default to 9999.

    Tilesets

    A tileset provides graphic images for the game. Each tileset has one or more tilesheets of image sprites and a tile_config.json file that describes how to map the contents of the sprite sheets to various entities in the game. It also has a tileset.txt file that provides metadata.

    Compositing Tilesets

    Prior October 2019, tilesets had to be submitted to the repo with each tilesheet fully composited and the sprite indices in tile_config.json calculated by hand. Since then, tilesets can be submitted as directories of individual sprite files and tile_entry JSON files that use sprite file names. The TypeScript tileset tool merges those files into tilesheets, converts sprite file names to sprite indices, and writes tile_config.json.

    For the rest of this document, tilesets that are submitted as fully composited tilesheets are called legacy tilesets, and tilesets that are submitted as individual sprite image files are compositing tilesets.

    TypeScript tileset tool

    Use scripts/tileset.ts for normal compose/decompose work. It replaced the old Python compose workflow in PR #8151.

    # Compose individual sprite files and tile entries into tile_config.json and tilesheet PNGs.
    deno run -A scripts/tileset.ts --pack gfx/Retrodays
    
    # Write the composed output to another directory.
    deno run -A scripts/tileset.ts --pack gfx/Retrodays /tmp/Retrodays-composed
    
    # Decompose a legacy tileset into individual sprite files and tile entries.
    deno run -A scripts/tileset.ts --unpack gfx/ChestHole16Tileset
    

    Useful options:

    • --format-json: pretty-print the generated tile_config.json.
    • --only-json: regenerate tile_config.json without writing tilesheet PNGs.
    • --use-all: include otherwise unused PNG files with ids based on their filenames.
    • --palette and --palette-copies: generate 8-bit palette output.

    The old tools/gfx_tools/compose.py and tools/gfx_tools/decompose.py scripts are deprecated for documentation and daily tileset work. They remain in the repository for compatibility and parity tests.

    The original sprite files and tile_entry JSON files are preserved when composing.

    For small examples or quick browser-only checks, see the tileset web tool.

    directory structure

    Each compositing tileset has one or more directories in it with a name that starts with pngs_, such as pngs_tree_32x40 or pngs_overlay. These are the image directories. All of the sprites in an image directory must have the same height and width and will be merged into a single tilesheet.

    It is recommended that tileset developers include the sprite dimensions in the image directory name, but this is not required. pngs_overlay_24x24 is preferred over pngs_overlay but both are allowed. As each image directory creates its own tilesheet, and tilesheets should be as large as possible for performance reasons, tileset developers are strongly encouraged to minimize the number of image directories.

    Each image directory contains a hierarchy of subdirectories, tile_entry JSON files, and sprite files. There is no restriction on the arrangement or names of these files, except for tile_entry JSON files for expansion tilesheets must be at the top level of the image directory. Subdirectories are not required but are recommended to keep things manageable.

    tile_entry JSON

    Each tile_entry JSON is a dictionary that describes how to map one or more game entities to one or more sprites. The simplest version has a single game entity, a single foreground sprite, an optional background sprite, and a rotation value. For instance:

    {                                           // this is an object and doesn't require a list
        "id": "mon_cat",                        // the game entity represented by this sprite
        "fg": "mon_cat_black",                  // some sprite name
        "bg": "shadow_bg_1",                    // some sprite name; always a single value
        "rotates": false                        // true for things that rotate like vehicle parts
    }
    

    The values in "id", "fg", and "bg" can be repeated within an image directory or in different image directories. "fg" and "bg" sprite images can be referenced across image directories, but the sprites must be stored in an image directory with other sprites of the same height and width.

    "id" can also be a list of multiple game entities sharing the same sprite, like "id": ["vp_door"], ["vp_hddoor"]. "id" can be any vehicle part, terrain, furniture, item, or monster in the game. The special ids "player_female", "player_male", "npc_female", "npc_male" are used to identify the sprites for the player avatar and NPCs. The special id "unknown" provides a sprite that is displayed when an entity has no other sprite.

    The special suffixes _season_spring, _season_summer, _season_autumn, and _season_winter can be applied to any entity id to create a seasonal variant for that entity that will be displayed in the appropriate season like this "id": "mon_wolf_season_winter".

    The special prefixes overlay_mutation_, overlay_female_mutation_, overlay_male_mutation_ can prefix any trait or bionic in the game to specify an overlay image that will be laid over the player and NPC sprites to indicate they have that mutation or bionic.

    The special prefixes overlay_worn_, overlay_female_worn_, overlay_male_worn_ can prefix any item in the game to specify an overlay image that will be laid over the player and NPC sprites to indicate they are wearing that item.

    The special prefixes overlay_wielded_, overlay_female_wielded_, overlay_male_wielded_ can prefix any item in the game to specify an overlay image that will be laid over the player and NPC sprites to indicate they are holding that item.

    "fg" and "bg" can also be a list of 2 or 4 pre-rotated rotational variants, like "bg": ["t_wall_n", "t_wall_e", "t_wall_s", "t_wall_w"] or "fg": ["mon_dog_left", "mon_dog_right"].

    "fg" and "bg" can also be a list of dictionaries of weighted, randomly chosen options, any of which can also be a rotated list:

    "fg": [
        { "weight": 50, "sprite": "t_dirt_brown"},       // appears in 50 of 53 tiles
        { "weight": 1, "sprite": "t_dirt_black_specks"}, // appears 1 in 53 tiles
        { "weight": 1, "sprite": "t_dirt_specks_gray"},
        { "weight": 1, "sprite": "t_patchy_grass"}       // file names are arbitrary
    ],
    

    "multitle" is an optional field. If it is present and true, there must be an additional_tiles list with 1 or more dictionaries for entities and sprites associated with this tile, such as broken versions of an item or wall connections. Each dictionary in the list has an "id“ field, as above, and a "fg" field, which can be a single filename, a list of filenames, or a list of dictionaries as above.

    Each tile_entry.json file can have a single object in it, or a list of 1 or more objects like so:

    [
        { "id": "mon_zombie", "fg": "mon_zombie", "bg": "mon_zombie_bg", "rotates": false },
        { "id": "corpse_mon_zombie", "fg": "mon_zombie_corpse", "bg": "mon_zombie_bg", "rotates": false },
        { "id": "overlay_wielding_corse_mon_zombie", "fg": "wielded_mon_zombie_corpse", "bg": [], "rotates": false }
    ]
    

    Having a list of tile entries in a file may be useful for organization, but completely unrelated entries may all exist in the same file without any complications.

    expansion tile_entry JSON

    Tilesheets can have expansion tilesheets, which are tilesheets from mods. Each expansion tilesheet is a single "id" value, "rotates": false", and "fg": 0. Expansion tile_entry JSON are the only tile_entry JSONs that use an integer value for "fg" and that value must be 0. Expansion tile_entry JSONs must be located at the top layer of each image directory.

    Sprite Images

    Every sprite inside an image directory must have the same height and width as every other sprite in the image directory.

    Sprites can be organized into subdirectories within the image directory however the tileset developer prefers. Sprite filenames are completely arbitrary and should be chosen using a scheme that makes sense to the tileset developer.

    After loading a tileset, config/debug.log will contain a space separated list of every entity missing a sprite in the tileset. Entities that have sprites because of a "looks_like" definition will not show up in the list.

    tile_info.json

    Each compositing tileset must have a tile_info.json, laid out like so:

    [
      {
        "width": 32,
        "pixelscale": 1,
        "height": 32
      },
      {
        "1_tiles_32x32_0-5199.png": {}
      },
      {
        "2_expan_32x32_5200-5391.png": {}
      },
      {
        "3_tree_64x80_5392-5471.png": {
          "sprite_offset_x": -16,
          "sprite_offset_y": -48,
          "sprite_height": 80,
          "sprite_width": 64
        }
      },
      {
        "4_fallback_5472-9567.png": { "fallback": true }
      }
    ]
    

    The first dictionary is mandatory, and gives the default sprite width and sprite height for all tilesheets in the tileset. Each of the image directories must have a separate dictionary, containing the tilesheet png name as its key. If the tilesheet has the default sprite dimensions and no special offsets, it can have an empty dictionary as the value for the tilesheet name key. Otherwise, it should have a dictionary of the sprite offsets, height, and width.

    A special key is "fallback" which should be true if present. If a tilesheet is designated as fallback, it will be treated as a tilesheet of fallback ASCII characters. scripts/tileset.ts will also compose the fallback tilesheet to the end of the tileset, and will add a “fallback.png” to tile_config.json if there is no "fallback" entry in tile_info.json.

    A special is "filler" which should be true if present. If a tilesheet is designated as filler, entries from its directory will be ignored if an entry from a non-filler directory has already defined the same id. Entries will also be ignored if the id was already defined by in the filler directory. Also, pngs from a filler directory will be ignored if they share a name with a png from a non-filler directory. A filler tilesheet is useful when upgrading the art in a tileset: old, low-quality art can be placed on filler tilesheet and will be automatically replaced as better images are added to the non-filler tilesheets.

    Legacy tilesets

    tilesheets

    Each tilesheet contains 1 or more sprites with the same width and height. Each tilesheet contains one or more rows of exactly 16 sprites. Sprite index 0 is special and the first sprite of the first tilesheet in a tileset should be blank. Indices run sequentially through each sheet and continue incrementing for each new sheet without reseting, so index 32 is the first sprite in the third row of the first sheet. If the first sheet has 320 sprites in it, index 352 would be the first sprite of the third row of the second sheet.

    tile_config

    Each legacy tileset has a tile_config.json describing how to map the contents of a sprite sheet to various tile identifiers, different orientations, etc. The ordering of the overlays used for displaying mutations can be controlled as well. The ordering can be used to override the default ordering provided in mutation_ordering.json. Example:

    { // whole file is a single object
      "tile_info": [ // tile_info is mandatory
        {
          "height": 32,
          "width": 32,
          "iso": true, //  Optional. Indicates an isometric tileset. Defaults to false.
          "pixelscale": 2 //  Optional. Sets a multiplier for resizing a tileset. Defaults to 1.
        }
      ],
      "tiles-new": [ // tiles-new is an array of sprite sheets
        { //   alternately, just one "tiles" array
          "file": "tiles.png", // file containing sprites in a grid
          "tiles": [ // array with one entry per tile
            {
              "id": "10mm", // id is how the game maps things to sprites
              "fg": 1, //   lack of prefix mostly indicates items
              "bg": 632, // fg and bg can be sprite indexes in the image
              "rotates": false
            },
            {
              "id": "t_wall", // "t_" indicates terrain
              "fg": [2918, 2919, 2918, 2919], // 2 or 4 sprite numbers indicates pre-rotated
              "bg": 633,
              "rotates": true,
              "multitile": true,
              "additional_tiles": [ // connected/combined versions of sprite
                { //   or variations, see below
                  "id": "center",
                  "fg": [2919, 2918, 2919, 2918]
                },
                {
                  "id": "corner",
                  "fg": [2924, 2922, 2922, 2923]
                },
                {
                  "id": "end_piece",
                  "fg": [2918, 2919, 2918, 2919]
                },
                {
                  "id": "t_connection",
                  "fg": [2919, 2918, 2919, 2918]
                },
                {
                  "id": "unconnected",
                  "fg": 2235
                }
              ]
            },
            {
              "id": "vp_atomic_lamp", // "vp_" vehicle part
              "fg": 3019,
              "bg": 632,
              "rotates": false,
              "multitile": true,
              "additional_tiles": [
                {
                  "id": "broken", // variant sprite
                  "fg": 3021
                }
              ]
            },
            {
              "id": "t_dirt",
              "rotates": false,
              "fg": [
                { "weight": 50, "sprite": 640 }, // weighted random variants
                { "weight": 1, "sprite": 3620 },
                { "weight": 1, "sprite": 3621 },
                { "weight": 1, "sprite": 3622 }
              ]
            },
            {
              "id": [
                "overlay_mutation_GOURMAND", // character overlay for mutation
                "overlay_mutation_male_GOURMAND", // overlay for specified gender
                "overlay_mutation_active_GOURMAND" // overlay for activated mutation
              ],
              "fg": 4040
            }
          ]
        },
        { // second entry in tiles-new
          "file": "moretiles.png", // another sprite sheet
          "tiles": [
            {
              "id": ["xxx", "yyy"], // define two ids at once
              "fg": 1,
              "bg": 234
            }
          ]
        }
      ],
      "overlay_ordering": [
        {
          "id": "WINGS_BAT", // mutation name, in a string or array of strings
          "order": 1000 // range from 0 - 9999, 9999 being the topmost layer
        },
        {
          "id": ["PLANTSKIN", "BARK"], // mutation name, in a string or array of strings
          "order": 3500 // order is applied to all items in the array
        },
        {
          "id": "bio_armor_torso", // Overlay order of bionics is controlled in the same way
          "order": 500
        }
      ]
    }
    

    Tinting

    Tilesets can support tinting, and tinting pairs.

    Tint pairs

    Tint pairs are used to have 1 “type” control the tinting of another tile base on it’s “type”. For example, hair_color controlling hair_style.

    "tint_pairs": [
      { "source_type": "hair_color", "target_type": "hair_style", "override": true },
      { "source_type": "hair_color", "target_type": "facial_hair", "override": true }
    ],
    "tints": [
    			{ "id": "hair_blond", "fg": "#91631f", "contrast": 1.1, "blend_mode": "multiply" },
    			{ "id": "hair_white", "fg": "#ffffff", "blend_mode": "multiply" },
          //...
    ],
    "tiles-new": [//...
    

    “override” is false by default, and enforces bypassing the legacy tile specification. This is more useful for mod_tilesets, which cannot remove entries from the main tileset. The “source_type” controls the “target_type” depending on what kind of overlay it is. Currently, this only effects mutations, and so it can handle “mutation_type” as input. Alternatively, target_type can match a tag instead. This allows things like tinting fur based on hair color.

    Tints

    Tints can be used for modifying the color of a tile, preventing the need to create an entirely seperate sprite for simple color variations. A tint entry can accept an “id”, which can refer to a tile, or a tint pair source. Example:

    "tint_pairs": [//...
    "tints": [
      { "id": "eye_pink", "fg": "#ff00bb", "saturation": 1.5 },
      { "id": "eye_black", "fg": "c_black", "blend_mode": "multiply" },
      { "id": "eye_white", "fg": { "color": "#ffffff", "saturation": 0.0, "brightness": 1.2 } },
    ],
    "tiles-new": [//...
    

    Tints are rather flexible. You can handle fg and bg seperately. They can accept either a color input, or an entry containing the color and modifiers. You must pick which kind you’ll use. You cannot utilize modifiers that apply to both, and use the entry method. The modifiers are “saturation”, “brightness”, and “contrast”. These are also mostly useful for mod_tilesets, but not exclusive. Additionally, you can set “blend_mode” to one of the following:

    • tint (default)
    • overlay
    • softlight
    • hardlight
    • multiply
    • additive
    • subtract
    • normal
    • screen
    • divide

    References can be seen here: https://en.wikipedia.org/wiki/Blend_modes Of note: tint is bespoke. It changes the color of the texture in such a way that even black and white completely converts the resulting tile, while still preserving decent contrast. It’s useful for a “painted” effect. normal uses the alpha of the tile at the moment, since the alpha of the tint would result in an awkward square halo for any effect.

    Colors can be hex codes, or curses color names. There’s fallback logic to aquire the color from the id using curses colors, but don’t rely on it. Tints can currently be applied to mutations, items, bionics, and effects. You can tint by id or by tag, though effect flags are unsupported.

    Projectile Sprites

    Custom sprites can be defined for projectiles (bullets and thrown items) using specific naming conventions:

    Note

    included sprite must face upwards (0 degrees) for correct orientation.

    Bullets (fired from guns)

    Use animation_bullet_{ammo_type} where {ammo_type} is the ammo’s item ID:

    { "id": "animation_bullet_9mm", "fg": 123, "rotates": true }
    { "id": "animation_bullet_556", "fg": 124, "rotates": true }
    { "id": "animation_bullet_762", "fg": 125, "rotates": true }
    

    The system follows the ammo’s looks_like chain. If animation_bullet_556 doesn’t exist but the 556 ammo has looks_like: "223", it will automatically use animation_bullet_223 if available.

    Thrown Items

    Use animation_bullet_{item_type} where {item_type} is the thrown item’s ID:

    { "id": "animation_bullet_javelin", "fg": 126, "rotates": true }
    { "id": "animation_bullet_throwing_axe", "fg": 127, "rotates": true }
    { "id": "animation_bullet_throwing_knife", "fg": 128, "rotates": true }
    

    The system also follows the item’s looks_like chain for thrown items.

    Fallback Behavior

    If no custom projectile sprite is found:

    1. Thrown items: Falls back to the item’s own sprite (e.g., javelin)
    2. Bullets: Falls back to animation_bullet_normal_0deg

    Rotation

    • Items with the FLY_STRAIGHT flag (like javelins and spears) maintain their orientation during flight
    • Other thrown items (axes, knives, etc.) will rotate during flight
    • Set "rotates": true in the tile definition to enable directional sprite support

    State Modifiers

    State modifiers allow tilesets to dynamically adjust character sprites based on game state (crouching, downed, etc.) without requiring separate artwork for each state. This is achieved through UV mapping, where a modifier image controls how pixels are displaced.

    How UV Mapping Works

    UV mapping is a technique from 3D graphics where a 2D image controls how another image is sampled. In this context:

    • Each pixel in a UV modifier image encodes a displacement using its red (X) and green (Y) channels
    • When rendering, instead of drawing pixel (x, y) directly, the system reads the modifier at (x, y) to determine where to sample from the source sprite
    • This allows effects like squishing, stretching, or shifting parts of a sprite

    Offset Mode vs Normalized Mode

    State modifiers support two interpretation modes for the UV data:

    Offset Mode ("use_offset": true, default):

    • Red/Green values encode displacement relative to neutral (127, 127)
    • Value 127 = no movement, 0 = -127 pixels, 255 = +128 pixels
    • Easy to understand: paint gray (127,127) where no change is needed
    • Displacements from multiple modifiers stack additively

    Normalized Mode ("use_offset": false):

    • Red/Green values encode absolute UV coordinates normalized to tile dimensions
    • (0,0) samples bottom-left, (255,255) samples top-right
    • More precise for complex remapping but harder to intuit
    • Easier to modify quickly: rotating the uv results in a rotated result
    • Modifiers chain by re-sampling through each other
    • Marginally more computationally expensive

    JSON Structure

    State modifiers are defined in the "state-modifiers" array within a tileset’s tile configuration:

    "state-modifiers": [
      {
        "id": "movement_mode",
        "override": false,
        "use_offset": true,
        "tiles": [
          { "id": "walk", "fg": null },
          { "id": "crouch", "fg": 100 },
          { "id": "run", "fg": 101 }
        ]
      },
      {
        "id": "downed",
        "override": true,
        "use_offset": true,
        "tiles": [
          { "id": "normal", "fg": null },
          { "id": "downed", "fg": 102 }
        ]
      }
    ]
    

    Fields

    FieldTypeDescription
    idstringModifier group identifier. Must match a supported group (see below).
    overrideboolIf true, when this state is active, lower-priority groups are skipped.
    use_offsetbooltrue for offset mode, false for normalized mode. Default: true.
    tilesarrayState-to-sprite mappings for this group.
    whitelistarrayOptional. Only apply to overlays matching these prefixes.
    blacklistarrayOptional. Never apply to overlays matching these prefixes.

    Each entry in tiles:

    FieldTypeDescription
    idstringState identifier within the group.
    fgint/nullSprite index for the UV modifier image. null means identity (no modification).
    offsetobjectOptional {"x": n, "y": n} for oversized modifier sprites.

    Supported Modifier Groups

    Group IDStatesDescription
    movement_modewalk, run, crouchCharacter movement stance
    downednormal, downedWhether character is knocked down
    lying_downnormal, lyingWhether character is lying down (sleeping, etc.)
    activitynone, activity IDsCurrent activity (e.g., ACT_CRAFT, ACT_READ)
    body_sizetiny, small, medium, large, hugeSize of character (changed by mutations)

    Priority and Overrides

    Modifier groups are processed in array order (index 0 = highest priority). When "override": true is set on a group and its state has an active modifier (non-null fg), all lower-priority groups are skipped. This allows, for example, a “downed” state to completely replace movement-based modifications.

    Overlay Filtering

    Per-group whitelist and blacklist arrays control which overlays a modifier affects. Overlays are matched by prefix (e.g., "wielded_" matches "wielded_katana"). If a group specifies either filter, it overrides global filters. Common prefixes include wielded_, worn_, mutation_, effect_, and bionic_.

    {
      "id": "movement_mode",
      "blacklist": ["wielded_"],
      "tiles": [...]
    }
    

    Multiple groups can share the same id if they have different filters, allowing different UV modifiers for different overlay types. When doing this, filters must be mutually exclusive—each overlay should match at most one group per ID. Overlapping filters cause duplicate rendering artifacts.

    {
      "id": "movement_mode",
      "blacklist": ["wielded_"],
      "tiles": [...]
    },
    {
      "id": "movement_mode",
      "whitelist": ["wielded_"],
      "tiles": [...]
    }
    

    Base sprite behavior: The base character sprite (skin, eyes, hair, etc.) is not an overlay and has no prefix. Groups with a whitelist never apply to the base sprite since it cannot match any prefix. Groups with only a blacklist (or no filters) apply to the base sprite normally. To apply different modifiers to the base sprite vs specific overlays, use a blacklist group for the base and a whitelist group for the overlays.

    Creating UV Modifier Sprites

    Method 1; use_offset = true

    1. Start with a neutral gray image (RGBA 127, 127, 0, 255)
    2. Paint red channel to shift pixels horizontally (< 127 = left, > 127 = right)
    3. Paint green channel to shift pixels vertically (< 127 = up, > 127 = down)

    For a crouch effect, you might paint the lower portion of the modifier with green values < 127 to pull pixels downward, compressing the sprite vertically.


    Method 2; use_offset = false

    1. Start with a base UV Identity image:
    1. Shift pixels around based on translation, rotation, scale, etc. to cause that effect to the result
    2. Paint green channel to shift pixels vertically (< 127 = up, > 127 = down)

    As this method may be harder to intuit, here’s some examples:

    Standing As you can see, "standing" is the normal state, so the UV image is not edited.
    Crouching It may be hard to notice, but the pixels just below the character have been adjusted, and the topmost pixels are missing. Most of the UVs have been lowered.
    Lying Down This is dead simple. There are some small adjustements to the back to lie flatter, but this largely boils down to rotating the entire UV image and moving it down slightly.

    The blue channel is ignored, and alpha 0 makes the pixel transparent.

    Sprite Size

    When defining the tileset, you specify sprite_width and sprite_height, alongside sprite_offset_x and sprite_offset_y. For UVs, this defines the area they effect. Pixels outside these bounds remain unaffected. If everything were the same resolution, this wouldn’t be of note. But overlays can also be offset / different sizes. This feature assumes consistent pixel scaling, but otherwise supports different sized sprites. It’s recommended for state-modifiers to be authored in 64x64 with an offset of (-16,-16) in order to account for overlays that extend past the avatar, such as weapons and status indicators. In theory, you could reduce memory footprint for a state-modifier. As an example, if one were to implement facial expressions as a new modifier group, you could limit the modifier to just the facial region, using extremely small UVs. You would likely want to use offset mode in that case to avoid issues with rounding.

    Sprite Bounds

    Pixels moved outside the original sprite bounds are supported, but there is a rendering limitation: tiles are drawn row by row from top to bottom, so if a warped sprite extends downward into the row below, that portion will be overwritten when the next row’s terrain is drawn. Sprites extending upward, left, or right render correctly. This is a fundamental limitation of the tile rendering order.

    Performance

    State modifiers are processed at render time and cached per unique state combination. The feature can be disabled in graphics options via the “State Modifiers” toggle if performance is a concern.

    allergies

    Basic Info

    Allergies are based on the vitamins system for the purpose of inheritability and avoiding a need to create several variants of items / make tough calls as to the material of foods.

    As an initial measure, these vitamins were applied based on materials to prevent regression and having to add the vitamins all by hand. However, unless an item has NUTRIENT_OVERRIDE, cooking should correctly reflect what actually went into it. Naturally spawned items will have whatever their materials would indicate.

    If a food item has veggy allergens in it, a carnivore will be unable to eat it. Vice versa for an herbivore and something with meat allergens.

    Current ‘allergens’:

    • "egg_allergen"
    • "fruit_allergen"
    • "human_flesh_vitamin" (This one is a special case, as it’s instead used for morale maluses / boons due to Cannibalism)
    • "junk_allergen"
    • "meat_allergen"
    • "milk_allergen"
    • "nut_allergen"
    • "veggy_allergen"
    • "wheat_allergen" (Actually just general bread / baked goods)

    Current dietary restrictions:

    Full bans:

    • Carnivore: veggy_allergen, fruit_allergen, wheat_allergen, nut_allergen
    • Herbivore / Ruminant: meat_allergen, egg_allergen Dislikes:
    • Vegetarian
    • Anti-plant
    • Lactose intolerance
    • Fruit intolerance
    • Junkfood intolerance
    • Grain intolerance

    Ammo Effects

    There are two types of ammo_effects. Hardcoded ammo effects and jsonized ammo effects.

    Hardcoded Ammo Effects

    IdentifierDescription
    THROWNUsed to check if it was thrown or not
    NO_PENETRATE_OBSTACLESCannot obstacles; such as penetrate fences or reinforced glass
    HEAVY_HITWill trigger traps and make a louder sound on hitting walls
    NO_ITEM_DAMAGEItems and traps the projectile hits will not be damaged
    NOGIBAmmo will not overkill and explode corpses
    COOKOFFAmmo will explode in fires
    INCENDIARYCauses fire in terrain / targets
    NEVER_MISFIRESWill not misfire
    ACT_ON_RANGED_HITThe item will trigger it’s use action on hit
    APPLY_SAPApplies the sap effect for turns scaling off damage
    BEANBAGApplies the stun effect for a short duration
    BLINDS_EYESApplies blind if hits eyes
    BOUNCEBounces and hits other targets in a nearby area also gives the WIDE effect
    BURSTDrops contents on impact, but is also destroyed
    CUSTOM_EXPLOSIONUses the explosion data of the item
    DRAW_AS_LINEDrawn instantly without animation
    IGNITEIgnites all hit creatures
    JETDraws the whole effect even if damage becomes 0
    LARGE_BEANBAGApplies the BEANBAG stun effect for a longer duration
    MUZZLE_SMOKEProduces a small smoke plume on firing
    NO_CRITCannot critically hit, can still graze
    NO_DAMAGEDoes not apply any damage
    NO_DAMAGE_SCALINGCannot critically hit, cannot graze
    NO_EMBEDCannot embed in creatures
    NO_OVERSHOOTTrajectory cannot extend pass target, even when missing
    NULL_SOURCEUsed internally, origin is not a real critter
    POISONApplies poison on hit, worse poison on crit
    PARALYZEPOISONApplies paralyzing poison on hit
    SHATTER_SELFThrown destoryed on hit, drops contents, produces noise
    TANGLEApplies tied effect to creature can be recovered
    NET_TANGLEApplies tied effect to a group, irrecoverable
    WHIPScares wildlife hit by it, will also apply disarm sometimes on reach attacks
    BLACKPOWDERWill cause build up of damaging gunk
    RECYCLEDCauses a 1 in 256 chance to fail to fire
    RECOVER_XHas a (X-1/X) chance to recover one charge of used ammo at the impact
    WIDENegates the effect of the HARDTOSHOOT monster flag.
    SHOTMultiplies point-blank damage to terrain, also gives the WIDE effect

    Fields

    IdentifierDescription
    id(mandatory) Unique ID.
    aoe(optional) Object, see aoe for fields
    trail(optional) Object, see trail for fields
    explosion(optional) Object, see explosions for fields
    do_flashbang(optional) Do flashbang effect
    do_emp_blast(optional) Do Emp effect

    Aoe

    An effect centered on the target

    IdentifierDescription
    field_type(optional) Id of field to use in the effect
    intensity_min(optional) Minimum intensity of field
    intensity_max(optional) Maximum intensity of field
    radius(optional) Radius of effect
    radius_z(optional) Z axis radius of effect
    chance(optional) Percent chance for added field
    size(optional) Rough size of the aoe
    check_sees(optional) Source has to see location for effect, effects below condition
    check_sees_radius(optional) Source has to see any spot in the radius
    check_passable(optional) Target must have to be on a passable tile

    Trail

    All effects are applied in a trail following the projectile’s path

    IdentifierDescription
    field_type(optional) Id of field to use in the effect
    intensity_min(optional) Minimum intensity of field
    intensity_max(optional) Maximum intensity of field
    chance(optional) Percent chance for added field

    Example

    {
      "id": "MININUKE_MOD",
      "type": "ammo_effect",
      "aoe": {
        "field_type": "fd_nuke_gas",
        "intensity_min": 3,
        "intensity_max": 3,
        "chance": 100,
        "radius": 24,
        "radius_z": 0,
        "size": 1,
        "check_passable": true,
        "check_sees": true,
        "check_sees_radius": 3
      },
      "trail": { "field_type": "fd_acid", "intensity_min": 1, "intensity_max": 3, "chance": 66 },
      "explosion": {
        "damage": 3000,
        "radius": 20,
        "fragment": {
          "impact": { "damage_type": "heat", "amount": 3000, "armor_multiplier": 2 },
          "range": 24
        }
      }
    }
    

    Clothing Modifications

    clothing_mod

    "type": "clothing_mod",
    "id": "leather_padded",   // Unique ID.
    "flag": "leather_padded", // flag to add to clothing.
    "item": "leather",        // item to consume.
    "implement_prompt": "Pad with leather",      // prompt to show when implement mod.
    "destroy_prompt": "Destroy leather padding", // prompt to show when destroy mod.
    "restricted": true,       // (optional) If true, clothing must list this mod's flag in "valid_mods" list to use it. Defaults to false.
    "use_base_material": true,       // (optional) If true, Clothing mod uses one of the base materials of the clothing to apply instead of whatever is within the item field. Defaults to false.
    "mod_value": [            // List of mod effect.
        {
            "type": "bash",   // "bash", "cut", "bullet", "fire", "acid", "warmth", "storage", and "encumbrance" is available.
            "value": 1,       // value of effect.
            "round_up": false // (optional) round up value of effect. defaults to false.
            "proportion": [   // (optional) value of effect propotions to clothing's parameter.
                "thickness",  //            Add value for every layer of "material_thickness" the item has.
                "volume",     //            Add value for every liter of baseline volume the item has.
                "coverage"    //            Reduce value by percentage of average coverage the item has.
            ]
        }
    ]
    

    Digital media

    Digital files are items stored inside USB drives, SD cards, hard drives, or a reader. The e-ink tablet loads books and saved text from SD cards. Laptops, wrist computers, and smartphones provide a Download data from storage media action that copies files into internal storage. Browse digital files offers information, study, and item actions for installed files. Only options supported by the selected file are shown. Each use action appears under its configured name; cooldown and availability details appear in the menu description area.

    Copy files to storage media copies all installed files onto an unencrypted USB drive, SD card, or hard drive. For a single file, choose Browse digital files → file → Copy to storage media. The reader must be powered. Existing destination files are retained, and the original files stay on the reader. Copies preserve their entry counts, metadata, and file identities, including shared cooldowns. The media can then be imported onto another reader. Encrypted media are excluded from the destination picker.

    Wipe storage media deletes every file and legacy data record on a selected USB drive, SD card, or hard drive, and removes its encryption. The reader must support that media’s port. The action asks for confirmation and leaves the device itself intact. Wiped media remain empty when accessed again. Wipe this device’s storage deletes the reader’s installed files, saved photos, recipe records, and monster collection. It also asks for confirmation; the device keeps its battery charge and storage ports. Digital cameras offer the same wipe action for their local photo storage.

    Readers connect to removable storage through digital_reader_ports, a comma-separated list matched against the storage’s digital_storage_ports. USB drives use USB, SD cards use SD, and hard drives use HARD_DRIVE. Laptops support USB and hard drives, smartphones support SD cards, and wrist computers support all three. Storage without a port requirement remains compatible with any reader.

    Files and readers

    Choose Scan book on a reader to digitize a physical book in your inventory. Scanning takes one minute per 50 ml of book volume, with a minimum of one minute, and consumes one device use per minute. Losing the book, reader, power, or enough light to see fine details interrupts the scan without producing a file. The physical book is preserved.

    The resulting digital copy retains the original book’s type, skills, recipes, morale effects, and manual actions. Its instance flags mark it as DIGITAL, IRREMOVABLE, and NO_DROP, and its volume is 1 ml. It can be studied, copied, exported, and deleted like other installed files. Scanning the same title again is unnecessary while a copy is installed on the reader.

    • DIGITAL: the item is a file. It can only be placed in digital storage, and requires installation on a powered reader to study or activate it.
    • DIGITAL_STORAGE: the item accepts digital contents and rejects physical contents. Dropping the media does not spill its files.
    • DIGITAL_READER: installed files can supply recipe references and be used while the device has sufficient power for one use. Readers should also have DIGITAL_STORAGE and a tool battery configuration.
    • DIGITAL_MUSIC: the file contains music tracks for the reader’s playlist.

    Derive instructional files from digital_instruction, a BOOK abstract with zero mass, a minimum volume of 1 ml, and the DIGITAL, IRREMOVABLE, and NO_DROP flags:

    {
      "id": "my_cooking_lesson",
      "copy-from": "digital_instruction",
      "type": "BOOK",
      "name": { "str": "cooking tutorial" },
      "description": "A saved lesson in basic kitchen techniques.",
      "skill": "cooking",
      "required_level": 0,
      "max_level": 3,
      "time": "20 m",
      "fun": 1
    }
    

    Associate recipes through their existing book_learn field, using the digital item ID as the book ID. Installed instructional files supply recipe references from a powered reader without permanently teaching them. Studying uses the normal book activity, including skill limits and the recipe-learning option, and consumes one device use per minute. Losing the device or its power stops the activity.

    Non-book files can derive from software. Override container to "null" when defining files intended for a media contents group; otherwise the software base wraps spawned files in a USB drive. Existing JSON or Lua use_actions are listed individually under their configured action names, including menu_text overrides. Actions receive the file as their item and retain their normal cost and behavior. The tablet additionally charges one device use for its browse operation. Destructive actions can therefore remove their file; actions intended to be repeatable should not consume it.

    digital_hello_world (hello_world.exe) is a minimal executable example found on personal SD cards. Copy it to a powered reader and choose Browse digital files → hello_world.exe → Print greeting to print Hello, world!. Its JSON manualnoise action uses noise: 0 to display a message silently. The file is preserved and can be run repeatedly.

    All digital settings below are per-instance item_vars. JSON values must be strings, including numeric settings. They are copied with the file and saved with it. Lua can edit them through the existing item variable methods:

    file:set_var_num("digital_music_morale_cap", 40)
    file:set_var_str("digital_recipes", '[{"id":"3d_printer_basic","skill_level":7}]')
    

    Recipe selections and media loot are generated once. Changing the settings does not replace an already resolved selection or reroll initialized media. To explicitly regenerate a recipe file, erase DIGITAL_RECIPES and reinstall it on a reader. Older saves receive missing default digital settings while retaining saved overrides and recipe selections.

    Recipe reference files

    Reference files are GENERIC items, separate from instructional BOOK files. They supply crafting recipes through a powered reader without teaching a skill or memorizing a recipe. The 3D printing infographic archive is one example. Choose View recipes in its file menu to inspect the available recipes.

    Recipe definitions live directly on each item. digital_recipes is a JSON-encoded array of recipe IDs and optional required skill levels:

    "item_vars": {
      "digital_recipes": "[{\"id\":\"3d_printer_basic\",\"skill_level\":7}]"
    }
    

    Omitting skill_level uses the recipe’s difficulty. digital_random_recipes contains JSON-encoded selection options and can include recipes added by mods:

    "item_vars": {
      "digital_random_recipes": "{\"count\":1,\"category\":\"CC_FOOD\",\"min_difficulty\":0,\"max_difficulty\":3,\"difficulty_chance_offset\":0}"
    }
    

    Both variables can be present on the same file. No separate recipe-file JSON object type or registry is needed. An empty string disables a definition.

    category is optional. Difficulty defaults to an unrestricted nonnegative range, and count defaults to one. An optional candidates array restricts the pool to specific recipe IDs. Recipes marked never_learn are excluded unless include_unlearnable is true. Random selections do not repeat fixed entries or other selections on the same file.

    When difficulty_chance_offset is present, each matching recipe has a one-in-max(1, difficulty + offset) chance to enter the pool before selection. Omit this field to include every matching candidate. The standard cooking archive uses food recipes of difficulty 0–3 with offset 0; the scientific archive uses difficulty 3 and above with offset 1, matching the old random recipe filters. Item-group entries control how often these files appear.

    Selections are generated once when the file enters storage and are saved in the file. Downloading, exporting, and loading the file retain that selection. An empty result is retained too, rather than rerolled on every access.

    Digital maps

    digital_urbex_map is a saved urban exploration forum guide, found among personal files, encrypted card contents, and salvaged terminal files. Copy it onto a powered reader, then select Browse digital files → saved urbex forum guide → Read. It inherits the paper urban explorer’s map’s reveal action, including its coverage and location filters. A reveal_map_center_omt item variable, when present, travels with the file when it is copied or saved.

    digital_evacuation_map is a saved emergency evacuation guide found on personal SD cards, encrypted cards, and salvaged hard drives. Open it on a powered reader to mark refugee centers, evac shelters, and roads within 180 overmap tiles of the map’s saved center or your current location. It covers both refugee center layouts and the standard, expanded, and vandalized evac shelters.

    Salvaged hard drives

    Disassembling intact or broken computer terminals, including the furniture versions, recovers a hard_drive. Each drive generates three to seven random files from digital_content_terminal when first accessed. The pool includes photos, music, instructional files, executables, and recipe archives. Files are rolled once and retained when copied or saved.

    Hard drives use the same removable-storage support as USB drives and SD cards: download their files onto a powered reader, copy additional files back, or encrypt them through the reader’s storage menu. Genome workstations can also store sample files on unencrypted hard drives.

    Generating content

    Media can name an ordinary item group using the digital_content item variable:

    "item_vars": { "digital_content": "my_digital_content" }
    

    The reader rolls this group on the first access to the media, then stores the result as real item contents. Use collection probabilities, distributions, and nested groups as usual. Generated items must be DIGITAL. A file packaged in a single-file storage device, such as software’s default USB drive, is extracted from that wrapper. Already initialized legacy SD cards keep their original contents rather than receiving another loot roll.

    Saved text files reuse the newspaper, flier, character-sheet, radio-archive, and lab-note snippet categories. Choose Read saved text in the file browser to open a scrolling view. The selected text is retained when copied or saved. Saved lab emails appear in scientific storage; personal files also include fliers, character sheets, and radio transcripts. Ordinary software can appear in the random file pools, with technical programs more common in scientific storage.

    digital_encryption_chance is a one-in-N chance to set MC_ENCRYPTED when initializing a media content group. Encryption is an instance flag and does not change the device’s item type. Item groups can also set MC_ENCRYPTED through custom-flags, including on USB drives.

    The sd_memory_card_personal, sd_memory_card_encrypted, and sd_memory_card_science loot groups all spawn sd_memory_card items. Their flags select personal, encrypted, or science content, preserving the different loot profiles without separate card item types. Personal cards have a one-in-eight chance of encryption. Plain sd_memory_card items start empty.

    For predetermined contents, use existing item-group modifiers instead:

    { "item": "sd_memory_card", "contents-item": "digital_cooking_show" }
    

    Files are copied without consuming the source. Identical copies are skipped; file identity and item variables are preserved, so copying a photo album again does not reset the viewer’s cooldown. Encryption prevents downloading until the SD card is decrypted. Formatting or triggering a card’s data-erasure protection deletes its files.

    USB drives and SD cards keep the same item type whether empty, populated, or encrypted. Encrypted media display an (encrypted) suffix and hide their contents. Encrypt storage media encrypts either kind of media, and Decrypt storage media uses the existing computer-skill check to unlock it. Encrypted media cannot be copied to or downloaded from until unlocked. Copying files preserves existing data on both media and readers. Old SD-card variants migrate to sd_memory_card, preserving files and encryption.

    Music and photos

    The digital_collection abstract supplies CAN_HAVE_CHARGES, which preserves track and photo counts during saving and loading.

    These collections are ordinary GENERIC digital items. Their item-group charges field specifies the number of tracks, including random ranges:

    {
      "id": "my_media_files",
      "type": "item_group",
      "subtype": "collection",
      "entries": [
        { "item": "digital_music_collection", "prob": 35, "charges": [5, 15] }
      ]
    }
    

    Music collections set digital_music_morale_cap in their item_vars. The playing collection’s morale cap is limited by its own track count. The digital_builtin_music group defines the preloaded collection on existing reader devices. The digital_content_reader group combines it with random personal files, including photos, lessons, executables, and recipe archives. Readers retain these files and their menu when switched to music or light modes. Music flavor text is in the existing <music_description> snippet category, including its genre and instrument templates. digital_music_cooldown_seconds sets the pause between listening sessions (five minutes for the standard collection). Stopping playback preserves every track, and the reader menu remains available during playback. Each collection has its own cooldown for each listener. Listening to one does not block another or reduce its morale reward. Use Browse digital files → Listen to choose a collection. The general music action automatically picks an available collection. Copies of the same file share a cooldown, even on another reader.

    Camera photographs and monster collection entries are viewed through the camera or their saved camera photo collection. Viewing either kind of photo can improve morale, with a shared ten-minute cooldown per character. Synthetic digital photo albums and their morale action have been removed. Genome sample files copied from USB drives or SD cards onto a reader also reveal their specimens in the reader’s monster collection. If a photo of the same creature is available, the collection shows its photo quality. Collecting a genome sample or opening its file on a reader also records that creature in the character’s Creatures tab, as taking a photo does.

    First-pass limits

    Media capacity is not measured in bytes. The tablet imports USB drives, SD cards, and hard drives directly; format compatibility is not modeled yet. Other media, such as DVDs, can later use the same flags and content groups without adding media-specific file types. Files must be copied into a reader before use; an adjacent USB or SD card alone supplies no recipe references.

    Old MC_MUSIC and EIPC_MUSIC counters are converted into music collection items once, preserving their counts. Synthetic MC_PHOTOS and EIPC_PHOTOS counters are discarded. Legacy recipe tokens (MC_RECIPE) become cooking or scientific reference files using the item-variable definitions above. Existing tablet recipe references remain readable for save compatibility. Camera captures are stored in a digital_camera_photo_collection file on the camera or phone. Camera photos and Browse digital files → Browse captured photos reopen the individual photographs with their original descriptions and quality. The computer’s monster collection includes creatures recorded in these files, including photographs taken with the same device. Camera exports copy the collection onto an unencrypted USB drive or SD card. Newer captures can be exported again without changing previously copied files. Legacy camera photos migrate into a collection when the device is used. Older tablet and SD-card photo metadata remains readable through its existing import path. Existing mission-terminal downloads retain their original behavior, including overwriting the chosen USB drive.

    Genome samples

    USB drives and SD cards store digital_genome_sample files. These preserve the specimen ID, name, and scan progress when downloaded to a reader or copied to an SD card. The genome sampler and workstation can use samples carried inside digital storage, including USB drives, SD cards, and readers. Scanning more specimens updates a partial file without requiring another storage device; workstation research updates the selected file. The workstation can copy a sample onto another USB drive or unencrypted SD card without erasing existing files. Updated samples can be copied again.

    Old genome drives, including prefilled rat and dire wolf drives, migrate their stored specimen variables into a sample file when loaded or accessed, and become ordinary USB drives. Migration preserves partial progress and other drive data.

    Item Categories

    Item Category

    When you sort your inventory by category, these are the categories that are displayed.

    IdentifierDescription
    idUnique ID. Must be one continuous word, use underscores if necessary
    nameThe name of the category. This is what shows up in-game when you open the inventory.
    zoneThe corresponding loot_zone (see loot_zones.json)
    sort_rankUsed to sort categories when displaying. Lower values are shown first
    priority_zonesWhen set, items in this category will be sorted to the priority zone if the conditions are met. If the user does not have the priority zone in the zone manager, the items get sorted into zone set in the ‘zone’ property. It is a list of objects. Each object has 3 properties: ID: The id of a LOOT_ZONE (see LOOT_ZONES.json), flags: array of flags
    {
      "id": "armor",
      "name": "ARMOR",
      "zone": "LOOT_ARMOR",
      "sort_rank": -21,
      "priority_zones": [{ "id": "LOOT_FARMOR", "flags": ["RAINPROOF"] }]
    }
    

    Item Creation / Types

    Note

    This page is currently under-construction and was recently split off from JSON INFO

    Generic Items

    "type": "GENERIC",                // Defines this as some generic item
    "id": "socks",                    // Unique ID. Must be one continuous word, use underscores if necessary
    "name": {
        "ctxt": "clothing",           // Optional translation context. Useful when a string has multiple meanings that need to be translated differently in other languages.
        "str": "pair of socks",       // The name appearing in the examine box.  Can be more than one word separated by spaces
        "str_pl": "pairs of socks"    // Optional. If a name has an irregular plural form (i.e. cannot be formed by simply appending "s" to the singular form), then this should be specified. "str_sp" can be used if the singular and plural forms are the same
    },
    "conditional_names": [ {          // Optional list of names that will be applied in specified conditions (see Conditional Naming section for more details).
        "type": "COMPONENT_ID",       // The condition type.
        "condition": "leather",       // The condition to check for.
        "name": { "str": "pair of leather socks", "str_pl": "pairs of leather socks" } // Name field, same rules as above.
    } ],
    "container": "null",             // What container (if any) this item should spawn within
    "repairs_like": "scarf",          // If this item does not have recipe, what item to look for a recipe for when repairing it.
    "color": "blue",                 // Color of the item symbol.
    "symbol": "[",                   // The item symbol as it appears on the map. Must be a Unicode string exactly 1 console cell width.
    "looks_like": "rag",              // hint to tilesets if this item has no tile, use the looks_like tile
    "description": "Socks. Put 'em on your feet.", // Description of the item
    "ascii_picture": "ascii_socks", // Id of the asci_art used for this item
    "phase": "solid",                            // (Optional, default = "solid") What phase it is
    "spill_field": "fd_water",                   // (Optional) For liquids dropped onto ordinary ground, create this field before any drop_action runs.
    "weight": "350 g",                           // Weight, weight in grams, mg and kg can be used - "50 mg", "5 g" or "5 kg". For stackable items (ammo, comestibles) this is the weight per charge.
    "volume": "250 ml",                          // Volume, volume in ml and L can be used - "50 ml" or "2 L". For stackable items (ammo, comestibles) this is the volume of stack_size charges.
    "integral_volume": 0,                        // Volume added to base item when item is integrated into another (eg. a gunmod integrated to a gun). Volume in ml and L can be used - "50 ml" or "2 L". Can be negative to reduce parent volume. Clamped at 1% of parent base volume.
    "integral_weight": 0,                        // Weight added to base item when item is integrated into another (eg. a gunmod integrated to a gun). Can be negative to reduce parent weight. Clamped at 1% of parent base weight.
    "rigid": false,                              // For non-rigid items volume (and for worn items encumbrance) increases proportional to contents
    "insulation": 1,                             // (Optional, default = 1) If container or vehicle part, how much insulation should it provide to the contents
    "price": 100,                                // Used when bartering with NPCs. For stackable items (ammo, comestibles) this is the price for stack_size charges. Can use string "cent" "USD" or "kUSD".
    "price_postapoc": "1 USD",                   // Same as price but represent value post cataclysm. Can use string "cent" "USD" or "kUSD".
    "material": ["COTTON"],                      // Material types, can be as many as you want.  See materials.json for possible options
    "weapon_category": [ "WEAPON_CAT1" ],        // (Optional) Weapon categories this item is in for martial arts.
    "cutting": 0,                                // (Optional, default = 0) Cutting damage caused by using it as a melee weapon.  This value cannot be negative.
    "bashing": 0,                                // (Optional, default = 0) Bashing damage caused by using it as a melee weapon.  This value cannot be negative.
    "to_hit": 0,                                 // (Optional, default = 0) To-hit bonus if using it as a melee weapon (whatever for?)
    "attacks": [                                 // (Optional) New attack statblock, WIP feature
      { "id": "BASH",                            // ID of the attack.  Attack with ID "DEFAULT" will be replaced by calculated data (this can be used to remove custom attacks on "copy-from" item)
        "to_hit": 1,                             // To-hit bonus of this attack
        "damage": { "values": [ { "damage_type": "bash", "amount": 50 } ] } }, // Damage of this attack, using `damage_instance` syntax (see below)
      { "id": "THRUST", "damage": { "values": [ { "damage_type": "stab", "amount": 45 } ] } }
    ],
    "flags": ["VARSIZE"],                        // Indicates special effects, see json_flags.md
    "environmental_protection_with_filter": 6,   // the resistance to environmental effects if an item (for example a gas mask) requires a filter to operate and this filter is installed. Used in combination with use_action 'GASMASK' and 'DIVE_TANK'
    "magazine_well": 0,                          // Volume above which the magazine starts to protrude from the item and add extra volume
    "magazines": [                               // Magazines types for each ammo type (if any) which can be used to reload this item
        [ "9mm", [ "glockmag" ] ]                // The first magazine specified for each ammo type is the default
        [ "45", [ "m1911mag", "m1911bigmag" ] ],
    ],
    "crafting_speed_modifier": 1.0,              // Optional (default = 1.0). Multiplier applied to crafting speed when this item satisfies a tool or quality requirement.
    "milling": {                                 // Optional. If given, the item can be milled in a water/wind mill.
      "into": "flour",                           // The item id of the product. Product MUST be something that uses charges.
      "conversion_rate": 4                       // Number of products per item consumed. At a conversion_rate of 4, 1 item is milled into 4 product. Only accepts integers.
    },
    "item_vars": {                               // Prepopulate Item Vars; Currently used by nothing other then mods and in game logic
      "test": "test"                             // Predominately lua mods will find this useful
    }
    "explode_in_fire": true,                     // Should the item explode if set on fire
    "explosion": {                               // Physical explosion data
      "damage": 10,                              // Damage the explosion deals to player at epicenter. Damage is halved above 50% radius.
      "radius": 8,                               // Radius of the explosion. 0 means only the epicenter is affected.
      "fire": true,                              // Should the explosion leave fire
      "fragment_effect": [ {                     // Effects data of "shrapnel"
          "effect": "onfire",                    // Effect to apply (note that onfire has special hardcoded behaviour to check the target is flamable)
          "odds": 2,                             // One in x chance to apply this effect
          "min_turns": 4,                        // Min turn duration for effect
          "max_turns": 8                         // Max turn duration for effect
        }
      ],
      "fragment": {                              // Projectile data of "shrapnel". This projectile will hit every target in its range and field of view exactly once.
        "damage": {                              // Damage data of the shrapnel projectile.  Uses damage_instance syntax (see below)
          "damage_type": "acid",                 // Type of damage dealt.
          "amount": 10                           // Amount of damage dealt.
          "armor_penetration": 4                 // Amount of armor ignored. Applied per armor piece, not in total.
          "armor_multiplier": 2.5                // Multiplies remaining damage reduction from armor, applied after armor penetration (if present). Higher numbers make armor stop fragments from this explosion more effectively, lower numbers act as a percentage reduction in remaining armor.
        }
      }
    },
    "repair_difficulty": 2                       // Overrites recipe difficulty being used for repair difficulty
    

    spill_field is intended for liquids. If a liquid item with a spill_field is dropped onto ordinary ground, the game marks the liquid dirty when appropriate, creates the specified field, and then still runs any drop_action the item defines. The liquid item is consumed: its charges and item state are not stored in the field, and the puddle cannot be collected as liquid again. Tiles with the LIQUIDCONT flag do not convert liquids to spill fields.

    Spill visuals are volume-based rather than charge-count-based. The current implementation treats each liter of liquid as one unit of visible spill intensity, with a minimum of one unit for any non-zero spill. When additional liquid is poured into an existing connected spill of the same field type, the spill deepens existing tiles first by raising field intensity, then expands outward into adjacent passable tiles. The visible footprint is capped, so very large spills stop growing visually while still consuming the poured liquid.

    In practice, spill_field is usually many-to-one. Multiple related liquids can intentionally map to the same visible field to avoid JSON bloat and unnecessary field type proliferation. For example, tea, coca_tea, and sweet_tea can all spill as fd_tea, producing the same visible puddle of tea field. A separate field type is only needed when the puddle has different effects or appearance. See Field Types for field properties.

    damage_instance

    {
      "damage_type": "acid", // Type of damage dealt.
      "amount": 10, // Amount of damage dealt.
      "armor_penetration": 4, // Amount of armor ignored. Applied per armor piece, not in total.
      "armor_multiplier": 2.5 // Multiplies remaining damage reduction from armor, applied after armor penetration (if present). Higher numbers make armor more effective at protecting from this attack, lower numbers act as a percentage reduction in remaining armor.
    }
    

    Ammo

    "type" : "AMMO",            // Defines this as ammo
    ...                         // same entries as above for the generic item.
                                // additional some ammo specific entries:
    "ammo_type" : "shot",       // Determines what it can be loaded in
    "damage" : 18,              // Ranged damage when fired
    "prop_damage": 2,           // Multiplies the damage of weapon by amount (overrides damage field)
    "pierce" : 0,               // Armor piercing ability when fired
    "range" : 5,                // Range when fired
    "dispersion" : 0,           // Inaccuracy of ammo, measured in quarter-degrees
    "recoil" : 18,              // Recoil caused when firing
    "count" : 25,               // Number of rounds that spawn together
    "stack_size" : 50,          // (Optional) How many rounds are in the above-defined volume. If omitted, is the same as 'count'
    "show_stats" : true,        // (Optional) Force stat display for combat ammo. (for projectiles lacking both damage and prop_damage)
    "dont_recover_one_in": 1    // (Optional) 1 in x chance of not recovering the ammo (100 means you have a 99% chance of getting it back)
    "drop": "nail",             // (Optional) Defines an object that drops at the projectile location at a 100% chance.
    "drop_active": false        // (Optional) Whether the object starts active. Default is true.
    "drop_count": 1,            // (Optional) Number of items to drop. For tools, this sets their charges. 
                                 // If omitted, the drop amount defaults to the 'count' defined in its itype.
    "shot": {                   // (Optional) Shot-pattern data for pellet-style ammo.
      "count": 12,             // Number of projectile attacks spawned by one round.
      "half_angle": 3          // Half-angle in degrees used for the pellet spread preview and pattern.
    },
    "effects" : ["COOKOFF", "SHOT"]
    

    Magazine

    "type": "MAGAZINE",              // Defines this as a MAGAZINE
    ...                              // same entries as above for the generic item.
                                     // additional some magazine specific entries:
    "ammo_type": [ "40", "357sig" ], // What types of ammo this magazine can be loaded with
    "capacity" : 15,                 // Capacity of magazine (in equivalent units to ammo charges)
    "count" : 0,                     // Default amount of ammo contained by a magazine (set this for ammo belts)
    "default_ammo": "556",           // If specified override the default ammo (optionally set this for ammo belts)
    "reliability" : 8,               // How reliable this this magazine on a range of 0 to 10? (see GAME_BALANCE.md)
    "reload_time" : 100,             // How long it takes to load each unit of ammo into the magazine
    "linkage" : "ammolink"           // If set one linkage (of given type) is dropped for each unit of ammo consumed (set for disintegrating ammo belts)
    "reloads_like": "light_minus_battery_cell" // If set, anything that takes that itype as a magazine will also take this itype
    

    Armor

    Armor can be defined like this:

    "type" : "ARMOR",     // Defines this as armor
    ...                   // same entries as above for the generic item.
                          // additional some armor specific entries:
    "covers" : ["FEET"],  // Where it covers.  Possible options are TORSO, HEAD, EYES, MOUTH, ARMS, HANDS, LEGS, FEET
    "storage" : 0,        //  (Optional, default = 0) How many volume storage slots it adds
    "warmth" : 10,        //  (Optional, default = 0) How much warmth clothing provides
    "environmental_protection" : 0,  //  (Optional, default = 0) How much environmental protection it affords
    "encumbrance" : 0,    // Base encumbrance (unfitted value)
    "max_encumbrance" : 0,    // When a character is completely full of volume, the encumbrance of a non-rigid storage container will be set to this. Otherwise it'll be between the encumbrance and max_encumbrance following the equation: encumbrance + (max_encumbrance - encumbrance) * character volume.
    "weight_capacity_bonus": "20 kg",    // (Optional, default = 0) Bonus to weight carrying capacity, can be negative. Strings must be used - "5000 g" or "5 kg"
    "weight_capacity_modifier": 1.5, // (Optional, default = 1) Factor modifying base weight carrying capacity.
    "coverage" : 80,      // What percentage of body part
    "material_thickness" : 1,  // Thickness of material, in millimeter units (approximately).  Generally ranges between 1 - 5, more unusual armor types go up to 10 or more
    "power_armor" : false, // If this is a power armor item (those are special).
    "valid_mods" : ["steel_padded"], // List of valid clothing mods. Note that if the clothing mod doesn't have "restricted" listed, this isn't needed.
    "resistance": { "cut": 0, "bullet": 1000 }, // If set, overrides usual resistance calculation. Values are for undamaged item, thickness affects scaling with damage - 1 thickness means no reduction from damage, 2 means it's halved on first damage, 10 means each level of damage decreases armor by 10%
    "hearing_protection": 0,    // How much does this armor dampen sound hear by the wearer, in dB spl. 0 - 191. This will make all sounds harder to hear for the wearer, including deafening sounds. At a hearing_ability multiplier of one, heard sounds of 120dB+ can deafen the player, with guaranteed temporary deafness at 140dB+. Use this instead of the "DEAF" or "PARTIAL_DEAF" flags. ~40 dB spl total protection will protect against most gunfire, 80 will protect against almost any sound. Cumulative with other items with this quality.
    "adv_hearing_protection": 0 // How much does this armor dampen deafening sounds heard by the wearer, in dB spl. 0 - 191. This will reduce the damaging volume of deafening sounds by its given amount without dampening other sounds.  Cumulative with other items with this quality.
    "provided_slots": [ { "id": "INSERT_FLAG_ID_HERE", "amount": 1 } ] // Flag id to provide for wearing requirements
    "consumed_slots": [ { "id": "INSERT_FLAG_ID_HERE", "amount": 1 } ] // Flag id to require for wearing requirements, automatically is this with 1 if there is one such instance.
    

    Alternately, every item (book, tool, gun, even food) can be used as armor if it has armor_data:

    "type" : "TOOL",      // Or any other item type
    ...                   // same entries as for the type (e.g. same entries as for any tool),
    "armor_data" : {      // additionally the same armor data like above
        "covers" : ["FEET"],
        "storage" : 0,
        "warmth" : 10,
        "environmental_protection" : 0,
        "encumbrance" : 0,
        "coverage" : 80,
        "material_thickness" : 1,
        "power_armor" : false
    }
    

    Armor Portion Data

    For items that cover multiple body parts with different coverage or encumbrance values, use armor_portion_data. This allows defining separate values for each body part or group of body parts:

    "armor_portion_data": [
        { 
            "covers": [ "torso" ], 
            "coverage": 95, 
            "encumbrance": 15 
        },
        { 
            "covers": [ "arms", "legs" ], 
            "coverage": 80, 
            "encumbrance": 10,
            "max_encumbrance": 20
        }
    ]
    

    Fields for each entry in armor_portion_data:

    • covers: Array of body part IDs this entry applies to (e.g., “torso”, “head”, “eyes”, “mouth”, “arms”, “hands”, “legs”, “feet”)
    • coverage: Percentage of body part area covered (0-100). Higher values mean better protection.
    • encumbrance: How much the item encumbers the body part. Default is 0.
    • max_encumbrance: Encumbrance when the character is at full storage volume. Default equals encumbrance.

    When armor_portion_data is used, the top-level covers, coverage, encumbrance, and max_encumbrance fields should not be used as they are replaced by the portion data.

    Pet Armor

    Pet armor can be defined like this:

    "type" : "PET_ARMOR",     // Defines this as armor
    ...                   // same entries as above for the generic item.
                          // additional some armor specific entries:
    "storage" : 0,        //  (Optional, default = 0) How many volume storage slots it adds
    "environmental_protection" : 0,  //  (Optional, default = 0) How much environmental protection it affords
    "material_thickness" : 1,  // Thickness of material, in millimeter units (approximately).  Generally ranges between 1 - 5, more unusual armor types go up to 10 or more
    "pet_bodytype": "dog",       // the body type of the pet that this monster will fit.  See MONSTERS.md
    "max_pet_vol": "50 ml",   // the maximum volume of the pet that will fit into this armor. Volume in ml and L can be used - "50 ml" or "2 L".
    "min_pet_vol": "50 ml",   // the minimum volume of the pet that will fit into this armor. Volume in ml and L can be used - "50 ml" or "2 L".
    "power_armor" : false, // If this is a power armor item (those are special).
    

    Alternately, every item (book, tool, gun, even food) can be used as armor if it has armor_data:

    "type" : "TOOL",      // Or any other item type
    ...                   // same entries as for the type (e.g. same entries as for any tool),
    "pet_armor_data" : {      // additionally the same armor data like above
        "storage" : 0,
        "environmental_protection" : 0,
        "pet_bodytype": "dog",
        "max_pet_vol": "35000 ml",
        "min_pet_vol": "25000 ml",
        "material_thickness" : 1,
        "power_armor" : false
    }
    

    Books

    Books can be defined like this:

    "type" : "BOOK",      // Defines this as a BOOK
    ...                   // same entries as above for the generic item.
                          // additional some book specific entries:
    "max_level" : 5,      // Maximum skill level this book will train to
    "intelligence" : 11,  // Intelligence required to read this book without penalty
    "time" : "35 m",          // Time a single read session takes. An integer will be read in minutes or a time string can be used.
    "fun" : -2,           // Morale bonus/penalty for reading
    "skill" : "computer", // Skill raised
    "chapters" : 4,       // Number of chapters (for fun only books), each reading "consumes" a chapter. Books with no chapters left are less fun (because the content is already known to the character).
    "required_level" : 2  // Minimum skill level required to learn
    

    Alternately, every item (tool, gun, even food) can be used as book if it has book_data:

    "type" : "TOOL",      // Or any other item type
    ...                   // same entries as for the type (e.g. same entries as for any tool),
    "book_data" : {       // additionally the same book data like above
        "max_level" : 5,
        "intelligence" : 11,
        "time" : "35 m",
        "fun" : -2,
        "skill" : "computer",
        "chapters" : 4,
        "use_action" : "MA_MANUAL", // The book_data can have use functions (see USE ACTIONS) that are triggered when the books has been read. These functions are not triggered by simply activating the item (like tools would).
        "required_level" : 2
    }
    

    Since many book names are proper names, it’s often necessary to explicitly specify the plural forms. The following is the game’s convention on plural names of books:

    1. For non-periodical books (textbooks, manuals, spellbooks, etc.),
      1. If the book’s singular name is a proper name, then the plural name is copies of (singular name). For example, the plural name of Lessons for the Novice Bowhunter is copies of Lessons for the Novice Bowhunter.
      2. Otherwise, the plural name is the usual plural of the singular name. For example, the plural name of tactical baton defense manual is tactical baton defense manuals
    2. For periodicals (magazines and journals),
      1. If the periodical’s singular name is a proper name, and doesn’t end with “Magazine”, “Weekly”, “Monthly”, etc., the plural name is issues of (singular name). For example, the plural name of Archery for Kids is issues of Archery for Kids.
      2. Otherwise, the periodical’s plural name is the usual plural of the singular name. For example, the plural name of Crafty Crafter's Quarterly is Crafty Crafter's Quarterlies.
    3. For board games (represented internally as book items),
      1. If the board game’s singular name is a proper name, the plural is sets of (singular name). For example, the plural name of Picturesque is sets of Picturesque.
      2. Otherwise the plural name is the usual plural. For example, the plural of deck of cards is decks of cards.

    Conditional Naming

    The conditional_names field allows defining alternate names for items that will be displayed instead of (or in addition to) the default name, when specific conditions are met. Take the following (incomplete) definition for sausage as an example of the syntax:

    {
      "name": "sausage",
      "conditional_names": [
        {
          "type": "FLAG",
          "condition": "CANNIBALISM",
          "name": "Mannwurst"
        },
        {
          "type": "COMPONENT_ID",
          "condition": "mutant",
          "name": { "str_sp": "sinister %s" }
        }
      ]
    }
    

    You can list as many conditional names for a given item as you want. Each conditional name must consist of 3 elements:

    1. The condition type:
      • COMPONENT_ID searches all the components of the item (and all of their components, and so on) for an item with the condition string in their ID. The ID only needs to contain the condition, not match it perfectly (though it is case sensitive). For example, supplying a condition mutant would match mutant_meat.
      • FLAG which checks if an item has the specified flag (exact match).
    2. The condition you want to look for.
    3. The name to use if a match is found. Follows all the rules of a standard name field, with valid keys being str, str_pl, and ctxt. You may use %s here, which will be replaced by the name of the item. Conditional names defined prior to this one are taken into account.

    So, in the above example, if the sausage is made from mutant humanoid meat, and therefore both has the CANNIBALISM flag, and has a component with mutant in its ID:

    1. First, the item name is entirely replaced with “Mannwurst” if singular, or “Mannwursts” if plural.
    2. Next, it is replaced by “sinister %s”, but %s is replaced with the name as it was before this step, resulting in “sinister Mannwurst” or “sinister Mannwursts”.

    NB: If "str": "sinister %s" was specified instead of "str_sp": "sinister %s", the plural form would be automatically created as “sinister %ss”, which would become “sinister Mannwurstss” which is of course one S too far. Rule of thumb: If you are using %s in the name, always specify an identical plural form unless you know exactly what you’re doing!

    Color Key

    When adding a new book, please use this color key:

    • Magazines: pink
    • “Paperbacks” Short enjoyment books (including novels): light_cyan
    • “Hardbacks” Long enjoyment books (including novels): light_blue
    • “Small textbook” Beginner level textbooks, guides and martial arts books: green
    • “Large textbook” Advanced level textbooks and advanced guides: blue
    • Religious books: dark_gray
    • “Printouts” (including spiral-bound, binders, and similar) Technical documents, (technical?) protocols, (lab) journals, personal diaries: light_green
    • Other reading material/non-books (use only if every other category does not apply): light_gray

    A few exceptions to this color key may apply, for example for books that don’t are what they seem to be. Never use yellow and red, those colors are reserved for sounds and infrared vision.

    CBMs

    CBMs can be defined like this:

    "type" : "BIONIC_ITEM",         // Defines this as a CBM
    ...                             // same entries as above for the generic item.
                                    // additional some CBM specific entries:
    "bionic_id" : "bio_advreactor", // ID of the installed bionic if not equivalent to "id"
    "difficulty" : 11,              // Difficulty of installing CBM
    "is_upgrade" : true             // Whether the CBM is an upgrade of another bionic.
    "installation_data" : "AID_bio_advreactor" // ID of the item which allows for almost guaranteed installation of corresponding bionic.
    

    Comestibles

    "type" : "COMESTIBLE",      // Defines this as a COMESTIBLE
    ...                         // same entries as above for the generic item.
                                // additional some comestible specific entries:
    "addiction_type" : "crack", // Addiction type
    "spoils_in" : 0,            // A time duration: how long a comestible is good for. 0 = no spoilage.
    "use_action" : "CRACK",     // What effects a comestible has when used, see special definitions below
    "stim" : 40,                // Stimulant effect
    "fatigue_mod": 3,           // How much fatigue this comestible removes. (Negative values add fatigue)
    "radiation": 8,             // How much radiation you get from this comestible.
    "comestible_type" : "MED",  // Comestible type, used for inventory sorting
    "quench" : 0,               // Thirst quenched
    "heal" : -2,                // Health effects (used for sickness chances)
    "addiction_potential" : 80, // Ability to cause addictions
    "monotony_penalty" : 0,     // (Optional, default: 2) Fun is reduced by this number for each one you've consumed in the last 48 hours.
                                // Can't drop fun below 0, unless the comestible also has the "NEGATIVE_MONOTONY_OK" flag.
    "calories" : 0,             // Hunger satisfied (in kcal)
    "nutrition" : 0,            // Hunger satisfied (OBSOLETE)
    "tool" : "apparatus",       // Tool required to be eaten/drank
    "charges" : 4,              // Number of uses when spawned
    "stack_size" : 8,           // (Optional) How many uses are in the above-defined volume. If omitted, is the same as 'charges'
    "fun" : 50                  // Morale effects when used
    "cooks_like": "meat_cooked" // (Optional) If the item is used in a recipe, replaces it with its cooks_like
    "parasites": 10,            // (Optional) Probability of becoming parasitised when eating
    "contamination": [ { "disease": "bad_food", "probability": 5 } ],         // (Optional) List of diseases carried by this comestible and their associated probability. Values must be in the [0, 100] range.
    

    Containers

    "type": "CONTAINER",  // Defines this as a container
    ...                   // same data as for the generic item (see above).
    "contains": 200,      // How much volume this container can hold
    "seals": false,       // Can be resealed, this is a required for it to be used for liquids. (optional, default: false)
    "watertight": false,  // Can hold liquids, this is a required for it to be used for liquids. (optional, default: false)
    "preserves": false,   // Contents do not spoil. (optional, default: false)
    

    Alternately, every item can be used as container:

    "type": "ARMOR",      // Any type is allowed here
    ...                   // same data as for the type
    "container_data" : {  // The container specific data goes here.
        "contains": 200,
    }
    

    This defines a armor (you need to add all the armor specific entries), but makes it usable as container. It could also be written as a generic item (“type”: “GENERIC”) with “armor_data” and “container_data” entries.

    Melee

    "id": "hatchet",       // Unique ID. Must be one continuous word, use underscores if necessary
    "symbol": ";",         // ASCII character used in-game
    "color": "light_gray", // ASCII character color
    "name": "hatchet",     // In-game name displayed
    "description": "A one-handed hatchet. Makes a great melee weapon, and is useful both for cutting wood, and for use as a hammer.", // In-game description
    "price": 95,           // Used when bartering with NPCs.  Can use string "cent" "USD" or "kUSD".
    "material": ["iron", "wood"], // Material types.  See materials.json for possible options
    "weight": 907,         // Weight, measured in grams
    "volume": "1500 ml",   // Volume, volume in ml and L can be used - "50 ml" or "2 L"
    "bashing": 12,         // Bashing damage caused by using it as a melee weapon
    "cutting": 12,         // Cutting damage caused by using it as a melee weapon
    "flags" : ["CHOP"],    // Indicates special effects
    "to_hit": 1            // To-hit bonus if using it as a melee weapon
    

    Melee Weapon_category

    Weapon CategoryDescription
    FIST_WEAPONSHandheld weapons used to supplement fists in martial arts.
    ——
    STILETTOSShort, tapering ‘blade’ fixed onto a handle, has no cutting edge
    KNIVESShort blade fixed onto a handle, for cutting or as weapon.
    SHORT_SWORDSOne handed sword of length between a large knife and a ‘proper’ sword.
    1H_SWORDSSword meant to be wielded with one hand.
    2H_SWORDSSword meant to be wielded with both hands.
    DUELING_SWORDSSwords with thin profiles typically meant for stabbing.
    BIONIC_SWORDSSwords integrated into the body via bionics.
    ——
    SAPSVery short length of typically flexible material, with a weighted tip.
    BATONSThin, balanced rod of strong material.
    TONFASUnique looking T-shaped baton believed to originate from China.
    CLUBSRod with a thicker striking head. May be one or two-handed.
    QUARTERSTAVESLong pole wielded with both hands.
    MACESShort one-handed weapon with a striking head firmly attached to a short handle.
    MORNINGSTARSTypically two-handed weapon with a striking head firmly attached to a long handle.
    FLAILSStriking head attached to handle by flexible rope/chain.
    1H_HAMMERSHammers meant to be wielded with a single hand.
    2H_HAMMERSHammers meant to be wielded with both hands.
    ——
    HAND_AXESAxe with a short handle, typically wielded in one hand, ocassionally thrown.
    1H_AXESAxes meant to be wielded with one hand, typically with a handle longer than the handaxe.
    2H_AXESAxes meant to be wielded with two hands.
    ——
    WHIPSFlexible tool used to strike at range.
    ——
    1H_HOOKEDOne handed weapon with hooking capability. (and isn’t an axe or hammer)
    ——
    HOOKED_POLESPolearm with hooked end (Like a shepherd’s crook)
    SPEARSPolearm with a long shaft and a sharp tip made of hard material.
    PIKESVery long spear that can only be wielded in two hands, very unwieldy.
    GLAIVESPolearm with a single-edged blade mounted on the end.
    Weapon StylesDescription
    MEDIEVAL_SWORDSSwords associated with European culture.
    JAPANESE_SWORDSSwords associated with Japanese culture.
    BIONIC_WEAPONRYWeapons integrated into the body via bionics.

    Gun

    Guns can be defined like this:

    "type": "GUN",             // Defines this as a GUN
    ...                        // same entries as above for the generic item.
                               // additional some gun specific entries:
    "skill": "pistol",         // Skill used for firing
    "ammo": [ "357", "38" ],   // Ammo types accepted for reloading
    "ranged_damage": 0,        // Ranged damage when fired
    "range": 0,                // Range when fired
    "dispersion": 32,          // Inaccuracy of gun, measured in quarter-degrees
    // When sight_dispersion and aim_speed are present in a gun mod, the aiming system picks the "best"
    // sight to use for each aim action, which is the fastest sight with a dispersion under the current
    // aim threshold.
    "sight_dispersion": 10,    // Inaccuracy of gun derived from the sight mechanism, also in quarter-degrees
    "aim_speed": 3,            // A measure of how quickly the player can aim, in moves per point of dispersion.
    "recoil": 0,               // Recoil caused when firing, in quarter-degrees of dispersion.
    "durability": 8,           // Resistance to damage/rusting, also determines misfire chance
    "blackpowder_tolerance": 8,// One in X chance to get clogged up (per shot) when firing blackpowder ammunition (higher is better). Optional, default is 8.
    "min_cycle_recoil": 0,     // Minimum ammo recoil for gun to be able to fire more than once per attack.
    "burst": 5,                // Number of shots fired in burst mode
    "handling": 15,            // Modifier in how quick the gun recovers from recoil. 20 is baseline, below that is worse and above is better. Scales with '2 - 2.0 => 0' by default, for example 15 handling would be '2 - 1.5 => 0.5' increase to recoil and 30 would be '2 - 3.0 => -1' reduction to recoil
    "clip_size": 100,          // Maximum amount of ammo that can be loaded
    "ups_charges": 0,          // Additionally to the normal ammo (if any), a gun can require some charges from an UPS. This also works on mods. Attaching a mod with ups_charges will add/increase ups drain on the weapon.
    "ammo_to_fire" 1,          // Amount of ammo used per shot, separate from any UPS cost that may be given to the weapon.
    // The legacy item flags `FIRE_20`, `FIRE_50`, and `FIRE_100` are still permitted and will override `ammo_to_fire` if present.
    "reload": 450,             // Amount of time to reload, 100 = 1 second = 1 "turn". Default 100.
    "reload_noise_volume": 6   // [DEPRECIATED] How loud is reloading the gun, in tile distance. This is depreciated, use reload_noise_volume_dB instead. This value will be converted to an appropiate dB volume if provided.
    "reload_noise_volume_dB": 40, // How loud is reloading the gun, in dB spl @1 meter reference. Default 40dB. Normal conversation is ~60dB, deafening sounds are 120dB+
    "built_in_mods": ["m203"], // An array of mods that will be integrated in the weapon using the IRREMOVABLE tag.
    "default_mods": ["m203"]   // An array of mods that will be added to a weapon on spawn.
    "barrel_volume": "30 mL",  // Amount of volume lost when the barrel is sawn. Approximately 250 ml per IRL inch is a decent approximation.
    "barrel_length": "30 mL",  // Depreciated alias of barrel_volume, which should be used instead for clarity.
    "valid_mod_locations": [ [ "accessories", 4 ], [ "grip", 1 ] ],  // The valid locations for gunmods and the mount of slots for that location.
    "loudness_modifier": 4,    // Optional field increasing or decreasing base ammo loudness, measured in dB spl.
    "speed": 100               // Optional field increasing or decreasing base ammo speed in meters per second. Speed of sound is taken at 343 meters per second.
    

    Alternately, every item (book, tool, armor, even food) can be used as gun if it has gun_data:

    "type": "TOOL",      // Or any other item type
    ...                   // same entries as for the type (e.g. same entries as for any tool),
    "gun_data" : {        // additionally the same gun data like above
        "skill": ...,
        "recoil": ...,
        ...
    }
    

    Ranged Weapon_category

    Weapon CategoryDescription
    BOWSElastic launching device for long-shafted projectiles.
    S_XBOWSElastic launching device mounted on a frame to be triggered, pistol sized.
    M_XBOWSElastic launching device mounted on a frame to be triggered.
    SLINGSHOTSElastic, handheld launching device typically used for small round projectiles.
    SLINGSProjectile weapon using a cradle connected to two retention cords, used to fling blunt projectiles.
    ——
    PISTOLSHandgun with a chamber integral to the gun barrel. In-game, any handgun that isn’t a revolver goes here.
    REVOLVERSRepeating handgun with a revolving cylinder containing multiple chambers.
    SUBMACHINE_GUNSMagazine fed automatic carbine designed to fire handgun cartridges.
    RIFLESLong barrelled firearms designed for more accurate shooting.
    MACHINE_GUNSFully automatic autoloading firearm designed for sustained fire.
    GATLING_GUNSRapid firing multi barrel firearm.
    SHOTGUNSLong barreled firearm generally designed to fire shotshells.
    ——
    GRENADE_LAUNCHERSFirearm designed to propel large caliber projectile typically loaded with warhead of some kind (smoke, gas, explosive, etc)
    ROCKET_LAUNCHERSFirearm that propels unguided, rocket-propelled projectile.
    ——
    FLAMETHROWERSRanged incendiary device designed to propel a controllable jet of fire.
    WATER_CANNONSIt fires water at your enemies.
    SPRAY_GUNSIt spews chemicals at your enemies.
    Action categoryDescription
    1SHOTRanged weapon with at least one barrel but no loading system/magazine.
    AUTOLOADINGRanged weapon with autoloading mechanisms like blowback, gas-operated, or recoil operated systems.
    MANUAL_ACTIONRanged weapon using manual actions like bolt/pump/lever.
    ENERGY_WEAPONSWeapon designed to utilize focused energy (sonic, electromagnetic waves, particle beams, etc). Both Ranged/Melee.
    MAGNETICWeapon that propels payload via electromagnetism.
    PNEUMATICRanged weapon that propels payload via compressed air.
    ELASTICRanged weapon that propels payload via elastic band.

    Gunmod

    Gun mods can be defined like this:

    "type": "GUNMOD",              // Defines this as a GUNMOD
    ...                            // Same entries as above for the generic item.
                                   // Additionally some gunmod specific entries:
    "location": "stock",           // Mandatory. Where is this gunmod is installed?
    "mod_targets": [ "crossbow" ], // Optional. What specific weapons can this gunmod be used with?
    "mod_target_category": [ [ "BOWS" ] ], // Optional. Weapon category requirements. Inner arrays are AND, outer array is OR. E.g. [["RIFLES","AUTOLOADING"]] = RIFLE AND AUTOLOADING; [["PISTOLS"],["REVOLVERS"]] = PISTOL OR REVOLVER.
    "mod_exclusions": [ "laser_rifle" ], // Optional. What specific weapons can't this gunmod be used with?
    "mod_exclusion_category": [ [ "ENERGY_WEAPONS" ] ], // Optional. Excluded weapon categories. Same logic as mod_target_category - matching any inner array prevents installation.
    "acceptable_ammo": [ "9mm" ],  // Optional filter restricting mod to guns with those base (before modifiers) ammo types
    "install_time": "30 s",        // Optional time installation takes. Installation is instantaneous if unspecified. An integer will be read as moves or a time string can be used.
    "ammo_modifier": [ "57" ],     // Optional field which if specified modifies parent gun to use these ammo types
    "magazine_adaptor": [ [ "223", [ "stanag30" ] ] ], // Optional. Array of [ammotype, [...magazines]] pairs. Overrides the weapon's compatible magazines for that ammo type.
    "mode_modifier": [ [ "AUTO", "auto", 5 ] ],       // Optional. Array of [mode_id, mode_name, burst_size, [...flags]?] arrays. Adds firing modes to the weapon. Optional flags array can include "MELEE", "REACH_ATTACK", etc.
    "damage_modifier": -1,         // Optional field increasing or decreasing base gun damage
    "dispersion_modifier": 15,     // Optional field increasing or decreasing base gun dispersion
    "loudness_modifier": 4,        // Optional field increasing or decreasing base ammo loudness, measured in dB spl.
    "speed": 100,                  // Optional field increasing or decreasing base ammo speed in meters per second. Speed of sound is taken at 343 meters per second.
    "speed": 100,                  // Optional field increasing or decreasing base ammo speed in meters per second. Speed of sound is taken at 343 meters per second.
    "range_modifier": 2,           // Optional field increasing or decreasing base gun range
    "recoil_modifier": -100,       // Optional field increasing or decreasing base gun recoil
    "ups_charges_modifier": 200,   // Optional field increasing or decreasing base gun UPS consumption (per shot) by adding given value
    "ups_charges_multiplier": 2.5, // Optional field increasing or decreasing base gun UPS consumption (per shot) by multiplying by given value
    "ammo_to_fire_modifier": 200,   // Optional field increasing or decreasing amount of main ammo consumed per shot by adding given value
    "ammo_to_fire_multiplier": 2.5, // Optional field increasing or decreasing main ammo consumed per shot by multiplying by given value
    "reload_modifier": -10,        // Optional field increasing or decreasing base gun reload time in percent
    "min_str_required_mod": 14,    // Optional field increasing or decreasing minimum strength required to use gun
    "weight_multiplier": 0.75,     // Optional field increasing or decreasing the weight of the parent gun by multiplying. 1.0 means no change, 0.75 means 25% lighter.
    "volume_multiplier": 0.67,     // Optional field increasing or decreasing the volume of the parent gun by multiplying. 1.0 means no change, 0.67 means ~33% reduction. Replaces the deprecated COLLAPSIBLE_STOCK flag.
    

    Alternately, every item (book, tool, armor, even food) can be used as a gunmod if it has gunmod_data:

    "type": "TOOL",       // Or any other item type
    ...                   // same entries as for the type (e.g. same entries as for any tool),
    "gunmod_data" : {
        "location": ...,
        "mod_targets": ...,
        ...
    }
    

    Batteries

    "type": "BATTERY",    // Defines this as a BATTERY
    ...                   // Same entries as above for the generic item
                          // Additionally some battery specific entries:
    "max_energy": "30 kJ" // Mandatory. Maximum energy quantity the battery can hold
    

    Tools

    "id": "torch_lit",    // Unique ID. Must be one continuous word, use underscores if necessary
    "type": "TOOL",       // Defines this as a TOOL
    "symbol": "/",        // ASCII character used in-game
    "color": "brown",     // ASCII character color
    "name": "torch (lit)", // In-game name displayed
    "description": "A large stick, wrapped in gasoline soaked rags. This is burning, producing plenty of light", // In-game description
    "price": 0,           // Used when bartering with NPCs.  Can use string "cent" "USD" or "kUSD".
    "material": "wood",   // Material types.  See materials.json for possible options
    "techniques": [ "FLAMING" ], // Combat techniques used by this tool
    "flags": "FIRE",      // Indicates special effects
    "weight": 831,        // Weight, measured in grams
    "volume": "1500 ml",  // Volume, volume in ml and L can be used - "50 ml" or "2 L"
    "bashing": 12,        // Bashing damage caused by using it as a melee weapon
    "cutting": 0,         // Cutting damage caused by using it as a melee weapon
    "to_hit": 3,          // To-hit bonus if using it as a melee weapon
    "max_charges": 75,    // Maximum charges tool can hold
    "initial_charges": 75, // Charges when spawned
    "rand_charges": [10, 15, 25], // Randomize the charges when spawned. This example has a 50% chance of rng(10, 15) charges and a 50% chance of rng(15, 25) (The endpoints are included)
    "sub": "hotplate",    // optional; this tool has the same functions as another tool
    "charge_factor": 5,   // this tool uses charge_factor charges for every charge required in a recipe; intended for tools that have a "sub" field but use a different ammo that the original tool
    "charges_per_use": 1, // Charges consumed per tool use
    "turns_per_charge": 20, // Charges consumed over time, deprecated in favor of power_draw
    "power_draw": 50,       // Energy consumption rate in mW
    "ups_eff_mult": 2,       // Multiplier for UPS efficiency
    "ups_recharge_rate": 10,       // The power output for UPS recharging of items
    "ammo": [ "NULL" ],       // Ammo types used for reloading
    "revert_to": "torch_done", // Transforms into item when charges are expended
    "use_action": "firestarter" // Action performed when tool is used, see special definition below
    

    Seed Data

    Every item type can have optional seed data, if the item has seed data, it’s considered a seed and can be planted:

    "seed_data" : {
        "fruit": "weed", // The item id of the fruits that this seed will produce.
        "seeds": false, // (optional, default is true). If true, harvesting the plant will spawn seeds (the same type as the item used to plant). If false only the fruits are spawned, no seeds.
        "fruit_div": 2, // (optional, default is 1). Final amount of fruit charges produced is divided by this number. Works only if fruit item is counted by charges.
        "byproducts": ["withered", "straw_pile"], // A list of further items that should spawn upon harvest.
        "harvest_inherit_flags": ["HIDDEN_POISON", "HIDDEN_HALLU"], // Optional, default: []. Flags present on the planted item to copy to harvested fruits and seeds, excluding byproducts. Works with any required_terrain_flag.
        "harvest_action": "lua:my_harvest", // Optional. Calls game.harvest_functions["my_harvest"] instead of the built-in harvest; the callback must replace the grown plant furniture. Must start with "lua:".
        "harvest_inherit_poison": true, // Optional, default: false. Copy the planted item's poison value to harvested fruits and seeds, excluding byproducts. Independent of flag inheritance.
        "plant_name": "sunflower", // The name of the plant that grows from this seed. This is only used as information displayed to the user.
        "grow" : 91 // A time duration: how long it takes for a plant to fully mature. Based around a 91 day season length (roughly a real world season) to give better accuracy for longer season lengths
                    // Note that growing time is later converted based upon the season_length option, basing it around 91 is just for accuracy purposes
                    // A value 91 means 3 full seasons, a value of 30 would mean 1 season.
        "required_terrain_flag": "PLANTABLE" // A tag that terrain and furniture would need to have in order for the seed to be plantable there.
    					 // Default is "PLANTABLE", and using this will cause any terain the plant is wrown on to turn into dirt once the plant is planted, unless furniture is used.
    					 // Using any other tag will not turn the terrain into dirt.
    }
    

    Brewing Data

    Every item type can have optional brewing data, if the item has brewing data, it can be placed in a vat and will ferment into a different item type.

    Currently only vats can only accept and produce liquid items.

    "brewable" : {
        "time": 3600, // A time duration: how long the fermentation will take.
        "result": "beer" // The id of the result of the fermentation.
    }
    

    Relic Data

    Defines various (semi-)magical properties of items. See RELICS.md for

    Artifact Data

    Artifacts are getting deprecated in favor of relic, avoid using them.

    Effects_carried

    (optional, default: empty list)

    Effects of the artifact when it’s in the inventory (main inventory, wielded, or worn) of the player.

    Possible values (see src/enums.h for an up-to-date list):

    • AEP_STR_UP Strength + 4
    • AEP_DEX_UP Dexterity + 4
    • AEP_PER_UP Perception + 4
    • AEP_INT_UP Intelligence + 4
    • AEP_ALL_UP All stats + 2
    • AEP_SPEED_UP +20 speed
    • AEP_IODINE Reduces radiation
    • AEP_SNAKES Summons friendly snakes when you’re hit
    • AEP_INVISIBLE Makes you invisible
    • AEP_CLAIRVOYANCE See through walls
    • AEP_SUPER_CLAIRVOYANCE See through walls to a great distance
    • AEP_STEALTH Your steps are quieted
    • AEP_EXTINGUISH May extinguish nearby flames
    • AEP_GLOW Four-tile light source
    • AEP_PSYSHIELD Protection from fear paralyze attack
    • AEP_RESIST_ELECTRICITY Protection from electricity
    • AEP_CARRY_MORE Increases carrying capacity by 200
    • AEP_SAP_LIFE Killing non-zombie monsters may heal you
    • AEP_HUNGER Increases hunger
    • AEP_THIRST Increases thirst
    • AEP_SMOKE Emits smoke occasionally
    • AEP_EVIL Addiction to the power
    • AEP_SCHIZO Mimicks schizophrenia
    • AEP_RADIOACTIVE Increases your radiation
    • AEP_MUTAGENIC Mutates you slowly
    • AEP_ATTENTION Draws netherworld attention slowly
    • AEP_STR_DOWN Strength - 3
    • AEP_DEX_DOWN Dex - 3
    • AEP_PER_DOWN Per - 3
    • AEP_INT_DOWN Int - 3
    • AEP_ALL_DOWN All stats - 2
    • AEP_SPEED_DOWN -20 speed
    • AEP_FORCE_TELEPORT Occasionally force a teleport
    • AEP_MOVEMENT_NOISE Makes noise when you move
    • AEP_BAD_WEATHER More likely to experience bad weather
    • AEP_SICK Decreases health over time

    effects_worn

    (optional, default: empty list)

    Effects of the artifact when it’s worn (it must be an armor item to be worn).

    Possible values are the same as for effects_carried.

    effects_wielded

    (optional, default: empty list)

    Effects of the artifact when it’s wielded.

    Possible values are the same as for effects_carried.

    effects_activated

    (optional, default: empty list)

    Effects of the artifact when it’s activated (which require it to have a "use_action": "ARTIFACT" and it must have a non-zero max_charges value).

    Possible values (see src/artifact.h for an up-to-date list):

    • AEA_STORM Emits shock fields
    • AEA_FIREBALL Targeted
    • AEA_ADRENALINE Adrenaline rush
    • AEA_MAP Maps the area around you
    • AEA_BLOOD Shoots blood all over
    • AEA_FATIGUE Creates interdimensional fatigue
    • AEA_ACIDBALL Targeted acid
    • AEA_PULSE Destroys adjacent terrain
    • AEA_HEAL Heals minor damage
    • AEA_CONFUSED Confuses all monsters in view
    • AEA_ENTRANCE Chance to make nearby monsters friendly
    • AEA_BUGS Chance to summon friendly insects
    • AEA_TELEPORT Teleports you
    • AEA_LIGHT Temporary light source
    • AEA_GROWTH Grow plants, a la triffid queen
    • AEA_HURTALL Hurts all monsters!
    • AEA_FUN Temporary morale bonus
    • AEA_SPLIT Split between good and bad
    • AEA_RADIATION Spew radioactive gas
    • AEA_PAIN Increases player pain
    • AEA_MUTATE Chance of mutation
    • AEA_PARALYZE You lose several turns
    • AEA_FIRESTORM Spreads minor fire all around you
    • AEA_ATTENTION Attention from sub-prime denizens
    • AEA_TELEGLOW Teleglow disease
    • AEA_NOISE Loud noise
    • AEA_SCREAM Noise & morale penalty
    • AEA_DIM Darkens the sky slowly
    • AEA_FLASH Flashbang
    • AEA_VOMIT User vomits
    • AEA_SHADOWS Summon shadow creatures
    • AEA_STAMINA_EMPTY Empties most of the player’s stamina gauge

    Software Data

    Every item type can have software data, it does not have any behavior:

    "software_data" : {
        "type": "USELESS", // unused
        "power" : 91 // unused
    }
    

    Fuel data

    Every item type can have fuel data that determines how much horse power it produces per unit consumed. Currently, gasses and plasmas cannot really be fuels.

    If a fuel has the PERPETUAL flag, engines powered by it never use any fuel. This is primarily intended for the muscle pseudo-fuel, but mods may take advantage of it to make perpetual motion machines.

    "fuel" : {
        "energy": 34.2,               // battery charges per mL of fuel. batteries have energy 1
                                     // is also MJ/L from https://en.wikipedia.org/wiki/Energy_density
                                     // assumes stacksize 250 per volume 1 (250mL). Multiply
                                     // by 250 / stacksize * volume for other stack sizes and
                                     // volumes
       "pump_terrain": "t_gas_pump", // optional. terrain id for the fuel's pump, if any.
       "explosion_data": {           // optional for fuels that can cause explosions
            "chance_hot": 2,         // 1 in chance_hot of explosion when attacked by HEAT weapons
            "chance_cold": 5,        // 1 in chance_cold of explosion when attacked by other weapons
            "factor": 1.0,           // explosion factor - larger numbers create more powerful explosions
            "fiery": true,           // true for fiery explosions
            "size_factor": 0.1       // size factor - larger numbers make the remaining fuel increase explosion power more
        }
    }
    

    Use Actions

    The contents of use_action fields can either be a string indicating a built-in function to call when the item is activated (defined in iuse.cpp), or one of several special definitions that invoke a more structured function.

    All object defined use actions support the following two types.

    "use_action": {
      "menu_text": "xyz", // Text shown in the activate menu; also accepts { "str": "xyz", "ctxt": "item action" }
      // Unique key for the iuse, defaults to the `type`
      // Note: This should only be used on repeated type definitions
      // WARN: This does not work on `repair_item` iuse actors -> they have their own special `item_action_type`
      "internal_name": "test"
    }
    
    "use_action": {
        "type": "transform",  // The type of method, in this case one that transforms the item.
        "target": "gasoline_lantern_on", // The item to transform to.
        "active": true,       // Whether the item is active once transformed.
        "msg": "You turn the lamp on.", // Message to display when activated.
        "need_fire": 1,                 // Whether fire is needed to activate.
        "need_fire_msg": "You need a lighter!", // Message to display if there is no fire.
        "transform_charges": 1,         // Number of charges used by item when it transforms.
        "need_charges": 1,                      // Number of charges the item needs to transform. Just a check, nothing is consumed.
        "need_charges_msg": "The lamp is empty.", // Message to display if there aren't enough charges.
        "need_worn": true,                        // Whether the item needs to be worn to be transformed, is false by default.
        "need_wielding": false,             // Whether the item needs to be wielded to be transformed, false by default.
        "need_dry": false,                  // Whether the item cannot transform while submerged in water, false by default.
        "target_charges" : 3, // Number of charges the transformed item has.
        "rand_target_charges": [10, 15, 25], // Randomize the charges the transformed item has. This example has a 50% chance of rng(10, 15) charges and a 50% chance of rng(15, 25) (The endpoints are included)
        "set_timer": false,   // Query the player on activation how many charges the transformed item should have, e.g. C-4. False by default.
        "container" : "jar",  // Container holding the target item.
        "moves" : 500         // Moves required to transform the item in excess of a normal action.
    },
    "use_action": {
        "type": "explosion", // An item that explodes when it runs out of charges.
        "sound_volume": 0, // Volume of a sound the item makes every turn.
        "sound_msg": "Tick.", // Message describing sound the item makes every turn.
        "no_deactivate_msg": "You've already pulled the %s's pin, try throwing it instead.", // Message to display if the player tries to activate the item, prevents activation from succeeding if defined.
        "explosion": { // Optional: physical explosion data
            // Specified like `"explosion"` field in generic items
        },
        "draw_explosion_radius" : 5, // How large to draw the radius of the explosion.
        "draw_explosion_color" : "ltblue", // The color to use when drawing the explosion.
        "do_flashbang" : true, // Whether to do the flashbang effect.
        "flashbang_player_immune" : true, // Whether the player is immune to the flashbang effect.
        "fields_radius": 3, // The radius of spread for fields produced.
        "fields_type": "fd_tear_gas", // The type of fields produced.
        "fields_min_density": 3,
        "fields_max_density": 3,
        "emp_blast_radius": 4,
        "scrambler_blast_radius": 4
    },
    "use_action": {
        "type": "change_scent", // Change the scent type of the user.
        "scent_typeid": "sc_fetid", // The scenttype_id of the new scent.
        "charges_to_use": 2, // Charges consumed when the item is used.  (Default: 1)
        "scent_mod": 150, // Modifier added to the scent intensity.  (Default: 0)
        "duration": "6 m", // How long does the effect last.
        "effects": [ { "id": "fetid_goop", "duration": 360, "bp": "TORSO" } ], // List of effects with their id, duration, and bodyparts
        "waterproof": true, // Is the effect waterproof.  (Default: false)
        "moves": 500 // Number of moves required in the process.
    },
    "use_action": {
        "type": "unfold_vehicle", // Transforms the item into a vehicle.
        "vehicle_name": "bicycle", // Vehicle name to create.
        "unfold_msg": "You painstakingly unfold the bicycle and make it ready to ride.", // Message to display when transforming.
        "full_battery": true, // If set to true, vehicle will be created with full fuel and batteries. It's recommended you only use this if the vehicle being deployed is made entirely from foldable parts, as those will convert into a generic folded vehicle item that tracks its status when taken down.  (Default: false)
        "moves": 500 // Number of moves required in the process.
    },
    "use_action" : {
        "type" : "consume_drug", // A drug the player can consume.
        "activation_message" : "You smoke your crack rocks.  Mother would be proud.", // Message, ayup.
        "effects" : { "high": 15 }, // Effects and their duration.
        "stat_adjustments": {"hunger" : -10}, // Adjustment to make to player stats.
        "fields_produced" : {"cracksmoke" : 2}, // Fields to produce, mostly used for smoke.
        "charges_needed" : { "fire" : 1 }, // Charges to use in the process of consuming the drug.
        "tools_needed" : { "apparatus" : -1 }, // Tool needed to use the drug.
        "fake_item" : "fake_ecig", // Item used to fake addiction and copy other consumption effects from.
        "lightweight_mod" : 1.2, // Drug duration modifier if the user has LIGHTWEIGHT trait.
        "tolerance_mod" : .8, // Drug duration modifier if the user has a tolerance.
        "tolerance_lightweight_effected": true, // Should this drugs time duration be effected by tolerance/lightweight?
        "too_much_threshold": 10, // Number of minutes to use for the too much calculation.
        "addiction_type_too_much": [["cig", "nicotine"]], // Link an effect to an addiction. Used for 'you feel gross... too much' message
        "lit_item": "cigar_lit", // Defines an item to turn into for smoking_duration minutes.
        "smoking_duration": 12, // Number of minutes the lit_item will remain lit, afterwards it will turn into the extinguished item.
        "used_up_item": "", // Item to give once used, alternative to lit_item which should be used in tandem with smoking_duration.
        "do_weed_msg": false, // Should weed_msg(player) be called after using the item?
        "snippet_category": "killer_withdrawal", // Chance (1 in 5) to say a random snippet from this category upon use. Like do_weed_msg, but unhardcoded.
        "snippet_chance": 5, // Chance (1 in snippet_chance) to make the player think a snippet.
        "moves": 50 // Number of moves required in the process, default value is 100.
    },
    "use_action": {
        "type": "place_monster", // place a turret / manhack / whatever monster on the map
        "monster_id": "mon_manhack", // monster id, see monsters.json
        "difficulty": 4, // difficulty for programming it (manhacks have 4, turrets 6, ...)
        "hostile_msg": "It's hostile!", // (optional) message when programming the monster failed and it's hostile.
        "friendly_msg": "Good!", // (optional) message when the monster is programmed properly and it's friendly.
        "place_randomly": true, // if true: places the monster randomly around the player, if false: let the player decide where to put it (default: false)
        "skill1": "throw", // Id of a skill, higher skill level means more likely to place a friendly monster.
        "skill2": "unarmed", // Another id, just like the skill1. Both entries are optional.
        "moves": 60 // how many move points the action takes.
    },
    "use_action": {
        "type": "place_npc", // place npc of specific class on the map
        "npc_class_id": "true_foodperson", // npc class id, see npcs/classes.json
        "summon_msg": "You summon a food hero!", // (optional) message when summoning the npc.
        "place_randomly": true, // if true: places npc randomly around the player, if false: let the player decide where to put it (default: false)
        "moves": 50 // how many move points the action takes.
    },
    "use_action": {
        "type": "ups_based_armor", // Armor that can be activated and uses power from an UPS, needs additional json code to work
        "activate_msg": "You activate your foo.", // Message when the player activates the item.
        "deactive_msg": "You deactivate your foo.", // Message when the player deactivates the item.
        "out_of_power_msg": "Your foo runs out of power and deactivates itself." // Message when the UPS runs out of power and the item is deactivated automatically.
    }
    "use_action" : {
        "type" : "delayed_transform", // Like transform, but it will only transform when the item has a certain age
        "transform_age" : 600, // The minimal age of the item. Items that are younger wont transform. In turns (60 turns = 1 minute)
        "not_ready_msg" : "The yeast has not been done The yeast isn't done culturing yet." // A message, shown when the item is not old enough
    },
    "use_action": {
        "type": "firestarter", // Start a fire, like with a lighter.
        "moves_cost": 15 // Number of moves it takes to start the fire.
    },
    "use_action": {
        "type": "unpack", // unpack this item
        "group": "gobag_contents", // itemgroup this unpacks into
        "items_fit": true, // Do the armor items in this fit? Defaults to false.
    },
    "use_action": {
        "type": "extended_firestarter", // Start a fire (like with magnifying glasses or a fire drill). This action can take many turns, not just some moves like firestarter, it can also be canceled (firestarter can't).
        "need_sunlight": true // Whether the character needs to be in direct sunlight, e.g. to use magnifying glasses.
    },
    "use_action": {
        "type": "inscribe", // Inscribe a message on an item or on the ground.
        "on_items": true, // Whether the item can inscribe on an item.
        "on_terrain": false, // Whether the item can inscribe on the ground.
        "material_restricted": true, // Whether the item can only inscribe on certain item materials. Not used when inscribing on the ground.
        "material_whitelist": [ // List of material ids (not item ids!) that can be inscribed on.
            "wood",             // Only used when inscribing on an item, and only when material_restricted is true.
            "plastic",          // The list here is the default that is used when no explicit list is given.
            "glass",
            "chitin",
            "iron",
            "steel",
            "silver"
        ]
    },
    "use_action": {
        "type": "cauterize", // Cauterize the character.
        "flame": true // If true, the character needs 4 charges of fire (e.g. from a lighter) to do this action, if false, the charges of the item itself are used.
    },
    "use_action": {
        "type": "enzlave" // Make a zlave.
    },
    "use_action": {
        "type": "fireweapon_off", // Activate a fire based weapon.
        "target_id": "firemachete_on", // The item type to transform this item into.
        "success_message": "Your No. 9 glows!", // A message that is shows if the action succeeds.
        "failure_message": "", // A message that is shown if the action fails, for whatever reason. (Optional, if not given, no message will be printed.)
        "lacks_fuel_message": "Out of fuel", // Message that is shown if the item has no charges.
        "noise": 0, // The noise it makes to active the item, Optional, 0 means no sound at all.
        "moves": 0, // The number of moves it takes the character to even try this action (independent of the result).
        "success_chance": 0 // How likely it is to succeed the action. Default is to always succeed. Try numbers in the range of 0-10.
    },
    "use_action": {
        "type": "fireweapon_on", // Function for active (burning) fire based weapons.
        "noise_chance": 1, // The chance (one in X) that the item will make a noise, rolled on each turn.
        "noise": 0, // The sound volume it makes, if it makes a noise at all. If 0, no sound is made, but the noise message is still printed.
        "held_message": "Your No. 9 hisses.", // The message / sound description (if noise is > 0), that appears when the item makes a sound and player is wielding it.
        "noise_message": "hsss.", // Sound description when heard from another tile, e.g. wielded by an NPC.
        "voluntary_extinguish_message": "Your No. 9 goes dark.", // Message that appears when the item is turned of by player.
        "charges_extinguish_message": "Out of ammo!", // Message that appears when the item runs out of charges.
        "water_extinguish_message": "Your No. 9 hisses in the water and goes out.", // Message that appears if the character walks into water and the fire of the item is extinguished.
        "auto_extinguish_chance": 0, // If > 0, this is the (one in X) chance that the item goes out on its own.
        "auto_extinguish_message": "Your No. 9 cuts out!" // Message that appears if the item goes out on its own (only required if auto_extinguish_chance is > 0).
        "noise_variant": "fireweapon_lit" // sound variant for soundpacks, pair with id `tool`
    },
    "use_action": {
        "type": "musical_instrument", // The character plays an instrument (this item) while walking around.
        "speed_penalty": 10, // This is subtracted from the characters speed.
        "volume": 12, // Volume of the sound of the instrument.
        "fun": -5, // Together with fun_bonus, this defines how much morale the character gets from playing the instrument. They get `fun + fun_bonus * <character-perception>` morale points out of it. Both values and the result may be negative.
        "fun_bonus": 2,
        "description_frequency": 20, // Once every Nth turn, a randomly chosen description (from the that array) is displayed.
        "player_descriptions": [
            "You play a little tune on your flute.",
            "You play a beautiful piece on your flute.",
            "You play a piece on your flute that sounds harmonious with nature."
        ]
    },
    "use_action": {
        "type": "holster", // Holster or draw a weapon
        "holster_prompt": "Holster item", // Prompt to use when selecting an item
        "holster_msg": "You holster your %s", // Message to show when holstering an item
        "max_volume": "1500 ml", // Maximum volume of each item that can be holstered. Volume in ml and L can be used - "50 ml" or "2 L".
        "min_volume": "750 ml",  // Minimum volume of each item that can be holstered or 1/3 max_volume if unspecified. volume in ml and L can be used - "50 ml" or "2 L".
        "max_weight": 2000, // Maximum weight of each item. If unspecified no weight limit is imposed
        "multi": 1, // Total number of items that holster can contain
        "draw_cost": 10, // Base move cost per unit volume when wielding the contained item
        "skills": ["pistol", "shotgun"], // Guns using any of these skills can be holstered
        "flags": ["SHEATH_KNIFE", "SHEATH_SWORD"] // Items with any of these flags set can be holstered
    },
    "use_action": {
        "type": "bandolier", // Store ammo and later reload using it
        "capacity": 10, // Total number of rounds that can be stored
        "ammo": [ "shot", "9mm" ], // What types of ammo can be stored?
    },
    "use_action": {
        "type": "reveal_map", // reveal specific terrains on the overmap
        "radius": 180, // radius around the player where things are revealed. A single overmap is 180x180 tiles.
        "terrain": ["s_gun", "hiway", "road"], // ids of overmap terrain types that should be revealed (as many as you want).
        "terrain_view": ["s_gun"], // (optional) ids of overmap terrain types that should be shown on a prompt after using the map (as many as you want, ideally a subset of terrain).
        "terrain_view_exclude": ["hiway", "road"], // (optional) ids of overmap terrain types that should NOT be shown on the prompt after using the map (as many as you want, ideally a subset of terrain_view).
        "message": "You add roads and tourist attractions to your map." // Displayed after the revelation.
    },
    "use_action": {
        "type" : "heal",        // Heal damage, possibly some statuses
        "limb_power" : 10,      // How much hp to restore when healing limbs? Mandatory value
        "head_power" : 7,       // How much hp to restore when healing head? If unset, defaults to 0.8 * limb_power.
        "torso_power" : 15,     // How much hp to restore when healing torso? If unset, defaults to 1.5 * limb_power.
        "bleed" : 0.4,          // Chance to remove bleed effect.
        "bite" : 0.95,          // Chance to remove bite effect.
        "infect" : 0.1,         // Chance to remove infected effect.
        "move_cost" : 250,      // Cost in moves to use the item.
        "long_action" : true,   // Is using this item a long action. Setting this to true will divide move cost by (first aid skill + 1).
        "limb_scaling" : 1.2,   // How much extra limb hp should be healed per first aid level. Defaults to 0.25 * limb_power.
        "head_scaling" : 1.0,   // How much extra limb hp should be healed per first aid level. Defaults to (limb_scaling / limb_power) * head_power.
        "torso_scaling" : 2.0,  // How much extra limb hp should be healed per first aid level. Defaults to (limb_scaling / limb_power) * torso_power.
        "effects" : [           // Effects to apply to patient on finished healing. Same syntax as in consume_drug effects.
            { "id" : "pkill1", "duration" : 120 }
        ],
        "used_up_item" : "rag_bloody" // Item produced on successful healing. If the healing item is a tool, it is turned into the new type. Otherwise a new item is produced.
    },
    "use_action": {
        "type": "place_trap", // places a trap
        "allow_underwater": false, // (optional) allow placing this trap when the player character is underwater
        "allow_under_player": false, // (optional) allow placing the trap on the same square as the player character (e.g. for benign traps)
        "needs_solid_neighbor": false, // (optional) trap must be placed between two solid tiles (e.g. for tripwire).
        "needs_neighbor_terrain": "t_tree", // (optional, default is empty) if non-empty: a terrain id, the trap must be placed adjacent to that terrain.
        "outer_layer_trap": "tr_blade", // (optional, default is empty) if non-empty: a trap id, makes the game place a 3x3 field of traps. The center trap is the one defined by "trap", the 8 surrounding traps are defined by this (e.g. tr_blade for blade traps).
        "bury_question": "", // (optional) if non-empty: a question that will be asked if the player character has a shoveling tool and the target location is diggable. It allows to place a buried trap. If the player answers the question (e.g. "Bury the X-trap?") with yes, the data from the "bury" object will be used.
        "bury": { // If the bury_question was answered with yes, data from this entry will be used instead of outer data.
             // This json object should contain "trap", "done_message", "practice" and (optional) "moves", with the same meaning as below.
        },
        "trap": "tr_engine", // The trap to place.
        "done_message": "Place the beartrap on the %s.", // The message that appears after the trap has been placed. %s is replaced with the terrain name of the place where the trap has been put.
        "practice": 4, // How much practice to the "traps" skill placing the trap gives.
        "moves": 10 // (optional, default is 100): the move points that are used by placing the trap.
    },
    "use_action": {
      {
        "type": "repair_item",                // Repair items. Skill, tool quality, and dexterity is checked against how hard that item is to craft/dissemble (which may be modified with repairs_like).
        "item_action_type": "repair_fabric",  // Points to an item_action JSON entry that determines the action's name in the use menu. Vanilla examples include repair_fabric and repair_metal.
        "materials": [                        // What materials can be repaired by this item. Materials.json defines what item is consumed when repairing items of that material.
          "cotton",
          "leather",
          "nylon",
          "wool",
          "fur",
          "faux_fur",
          "nomex",
          "kevlar",
          "neoprene",
          "gutskin"
        ],
        "skill": "tailor",    // What skill determines chance of success vs. risk of damaging the item further.
        "tool_quality": 3,    // Bonus from tool, 1.<X> times multiplier on skill.  With 8 Dex, 10 skill plus 2 or more tool_quality allows any item in the game to be fully reinforced.
        "cost_scaling": 0.1,  // Reduces or increases how much raw material is needed per successful repair action, also affected by the item's volume.
        "move_cost": 800      // How long between each roll for success or failure, 100 moves is 1 turn.
      }
    },
    "use_action": {
        "type": "sew_advanced",  // Modify clothing
        "materials": [           // materials to deal with. Power armor can be targeted when its material matches.
            "cotton",
            "leather"
        ],
        "skill": "tailor",       // Skill used.
        "clothing_mods": [       // Clothing mods to deal with.
            "leather_padded",
            "kevlar_padded"
        ]
    },
    "use_action": {
        "type": "multicooker",  // Crafts an item over time without requiring the player to sit there and watch
        "do_hallu": false, //Enables multicooker hallucinations and spawning of the evil multicooker when interacting
        "charges_to_start": 50, // Static cost per item crafted
        "charges_per_minute": 1, // Cost per minute of craft time
        "time_mult": 1, //Multiplier for craft time, 2 is twice as long, 0.5 is half as long, 0 is instant
        "recipes": [ "water_clean" ], //Any recipie ident (crafted item + its suffix, e.g water_clean_using_water_purifier) in this list can be crafted
        "subcategories": [ "CSC_FOOD_MEAT", "CSC_FOOD_VEGGI", "CSC_FOOD_PASTA" ], //Any item in these subcategories can be crafted
        "temporary_tools": [ "hotplate", "tongs", "toolset", "pot" ] //Temporary items spawned when crafting to allow for innate qualities
    },
    "use_action": { 
        "type": "cast_spell",       // Casts a spell based on ID using item charges or, if the flag USE_PLAYER_ENERGY is on the item, the energy source defined in the spell
        "spell_id": "magus_escape", // The ID of the spell to be casted
        "no_fail": true,            // Whether you can fail the cast
        "level": 10,                // The level its cast at
        "need_worn": true,          // if you need to wear it to cast the spell
        "need_wielding": true       // if you need to wield it to cast the spell
    },
    "use_action": {
        "type": "paint_stuff",      // Paints terrain or vehicles using ammo
        "charge_cost": 0            // Number of charges to use
    },
    "use_action": {
        "type": "paint_stuff_cfg",  // Configures how it paints using paint stuff
        "color_swap": true          // Allow the color to be swapped to any other named color
    }
    "use_action": {
      "type": "passivenoise", // Emits noise periodically, used mainly with active items such as chainsaws
      "noise": 90, // Noise in decibels
      "noise_chance": 10, // Percent chance to trigger per turn
      "held_message": "The chainsaws rumble." // Message to display if player is holding the item
      "noise_message": "a chainsaw rumbling." // Sound string when heard from another tile
      "noise_variant": "chainsaw" // sound variant for soundpacks, pair with id `tool`
    }
    

    Random Descriptions

    Any item with a “snippet_category” entry will have random descriptions, based on that snippet category:

    "snippet_category": "newspaper",
    

    The item descriptions are taken from snippets, which can be specified like this (the value of category must match the snippet_category in the item definition):

    {
      "type": "snippet",
      "category": "newspaper",
      "id": "snippet-id", // id is optional, it's used when the snippet is referenced in the item list of professions
      "text": "your flavor text"
    }
    

    or several snippets at once:

    {
      "type": "snippet",
      "category": "newspaper",
      "text": [
        "your flavor text",
        "more flavor",
        // entries can also bo of this form to have a id to reference that specific snippet.
        { "id": "snippet-id", "text": "another flavor text" }
      ],
      "text": ["your flavor text", "another flavor text", "more flavor"]
    }
    

    Multiple snippets for the same category are possible and actually recommended. The game will select a random one for each item of that type.

    One can also put the snippets directly in the item definition:

    "snippet_category": [ "text 1", "text 2", "text 3" ],
    

    This will automatically create a snippet category specific to that item and populate that category with the given snippets. The format also support snippet ids like above.

    Item spawn system

    Collection or Distribution

    In a Collection each entry is chosen independently from the other entries. Therefore the probability associated with each entry is absolute, in the range of 0…1. In the json files it is implemented as percentage with values from 0 to 100.

    A probability of 0 (or negative) means the entry is never chosen, a probability of 100% means its always chosen. The default is 100, because it’s the most useful value. Default 0 would mean the entry can be removed anyway.

    A Distribution is a weighted list like the current system. Exactly one entry is chosen from it. The probability of each entry is relative to the probability of the other entries. A probability of 0 (or negative) means it is never chosen.

    An example: Suppose item A has a probability of 30 and item B has a probability of 20. Then the probabilities of the 4 combinations of A and B are:

    CombinationCollectionDistribution
    Neither A nor B56%0%
    Only A24%60%
    Only B14%40%
    Both A and B6%0%

    Format

    The format is this:

    {
        "type": "item_group",
        "subtype": "<subtype>",
        "id": "<some name>",
        "ammo": <some number>,
        "magazine": <some number>,
        "purge": <true/false>,
        "delete": [ ... ],
        "entries": [ ... ]
    }
    

    purge is optional. It is a bool for weather or not all previous things defined in the item group should be purged. subtype is optional. It can be collection or distribution. If unspecified, it defaults to old, which denotes that this item group uses the old format (which is technically a distribution).

    There are some caveats to watch out for when using ammo or magazine.

    Entries array

    The entries list contains entries, each of which can be one of the following:

    1. Item

      { "item": "<item-id>", ... }
      
    2. Group

      { "group": "<group-id>", ... }
      
    3. Distribution

      {
        "distribution": [
          "An array of entries, each of which can match any of these 4 formats"
        ]
      }
      
    4. Collection

      {
        "collection": [
          "An array of entries, each of which can match any of these 4 formats"
        ]
      }
      

    The game decides based on the existence of either the item or the group value if the entry denotes a item or a reference to another item group.

    Each entry can have more values (shown above as ...). They allow further properties of the item(s):

    "damage": <number>|<array>,
    "damage-min": <number>,
    "damage-max": <number>,
    "count": <number>|<array>,
    "count-min": <number>,
    "count-max": <number>,
    "charges": <number>|<array>,
    "charges-min": <number>,
    "charges-max": <number>,
    "active": "<bool>"
    "vars": [ { "name": "<var_name>", "value": "<var_value>" } ] ( dynamically populating item variables )
    "contents-item": "<item-id>" (can be a string or an array of strings),
    "contents-group": "<group-id>" (can be a string or an array of strings),
    "ammo-item": "<ammo-item-id>",
    "ammo-group": "<group-id>",
    "container-item": "<container-item-id>",
    "container-group": "<group-id>",
    

    contents is added as contents of the created item. It is not checked if they can be put into the item. This allows water, that contains a book, that contains a steel frame, that contains a corpse.

    count makes the item spawn repeat to create more items, each time creating a new item.

    charges: Setting only min, not max will make the game calculate the max charges based on container or ammo/magazine capacity. Setting max too high will decrease it to maximum capacity. Not setting min will set it to 0 when max is set.

    active: If true, activates the item on spawn. Note that this does not work for itemgroups, only individual items within itemgroups.

    active Usage example

    [
      {
        "id": "test_grenade",
        "type": "item_group",
        "subtype": "collection",
        "items": [{ "item": "grenade_act", "prob": 100, "active": true }]
      },
      {
        "type": "mapgen",
        "method": "json",
        "om_terrain": "shelter_roof",
        "weight": 100,
        "object": {
          // ...
          "place_items": [{ "item": "test_grenade", "x": 12, "y": 12, "chance": 100, "repeat": 1 }],
          "place_item": [{ "item": "grenade_act", "x": 15, "y": 15, "chance": 100, "active": true }]
        }
      }
    ]
    
    "damage-min": 0,
    "damage-max": 3,
    "count": 4
    "charges": [10, 100]
    

    This will create 4 items, they can have different damage levels as the damage value is rolled separately for each of these items. Each item has charges (AKA ammo) in the range of 10 to 100 (inclusive); if the item needs a magazine before it can have charges, that will be taken care of for you. Using an array (which must have 2 entries) for charges/count/damage is equivalent to writing explicit min and max values. In other words "count": [a,b] is the same as "count-min": a, "count-max": b.

    The container is checked and the item is put inside the container, and the charges of the item are capped/increased to match the size of the container.

    Delete array

    The delete list contains entries, each of which can be one of the followingi:

    1. Item

      { "item": "<item-id>" }
      
    2. Group

      { "group": "<group-id>" }
      

    All previously defined items with these ids will be removed from the list, if they do not exist there is no error emmitted, it just skips along ( as it was most likely already removed by another mod )

    Ammo and Magazines

    Here are some ways to make items spawn with/without ammo/magazines (note that ammo-item can be specified for guns and magazines in the entries array to use a non-default ammo type):

    • Specify an ammo/magazine chance (introduced in Section 2) for the entire item group. ammo specifies the percent chance that the entries will spawn fully loaded (if it needs a magazine, it will be added for you). magazine specifies the percent chance that the entries will spawn with a magazine. Both of these default to 0 if unspecified.

      Note that ammo and magazine only apply to tools, guns, and magazines. Furthermore, they don’t apply to tools whose entry explicitly specifies how much ammo (charges) to spawn with, or to tools whose JSON item definition specifies a random amount or a fixed, nonzero amount of initial charges.

      If any item groups are referenced from your item group, then their ammo/magazine chances are ignored, and yours are used instead.

    • Use charges, charges-min, or charges-max in the entries array. A default magazine will be added for you if needed.

    Shortcuts

    This:

    "items": [ "<id-1>", [ "<id-2>", 10 ] ]
    

    means the same as:

    "entries": [ { "item": "<id-1>" }, { "item": "<id-2>", "prob": 10 } ]
    

    In other words: a single string denotes an item id, an array (which must contain a string and a number) denotes an item id and a probability.

    This is true for groups as well:

    "groups": [ "<id-1>", [ "<id-2>", 10 ] ]
    

    This format does not support further properties of the created items - the probability is only optional for entries of collections!

    The content of “entries”, “items” and “groups” are all added if those members exist. This will have the item <id-1> appear twice in the item group:

    {
      "items": ["<id-1>"],
      "entries": [{ "item": "<id-1>" }]
    }
    

    Another example. The group “milk” spawns a container (taken from milk_containers) that contains milk (maximal amount that fits into the container, because there is no specific charges value defined).

    {
        "type" : "item_group",
        "id": "milk_containers",
        "subtype": "distribution",
        "items": [
        "bottle_plastic", "bottle_glass", "flask_glass",
        "jar_glass", "jar_3l_glass", "flask_hip", "55gal_drum"
        ]
    },
    {
        "type" : "item_group",
        "id": "milk",
        "subtype": "distribution",
        "entries": [
            { "item": "milk", "container-group": "milk_containers" }
        ]
    },
    

    Inlined item groups

    In some places one can define an item group directly instead of giving the id of a group. One can not refer to that group as it has no visible id (it has an unspecific/random id internally). This is most useful when the group is very specific to the place it is used and wont ever appear anywhere else.

    As an example: monster death drops (death_drops entry in the MONSTER object, check here) can do this. If the monster is very specific (e.g. a special robot, a unique endgame monster), the item spawned upon its death won’t (in that form) appear in any other group.

    Therefore, this snippet:

    {
        "type": "item_group",
        "id": "specific_group_id",
        "subtype": "distribution",
        "items": [ "a", "b" ]
    },
    {
        "death_drops": "specific_group_id"
    }
    

    is equivalent to:

    {
      "death_drops": {
        "subtype": "distribution",
        "items": ["a", "b"]
      }
    }
    

    The inline group is read like any other group and one can use all the properties mentioned above. Its type and its id members are always ignored.

    Instead of a full JSON object, one can also write a JSON array. The default subtype is used and the array is read like the “entries” array (see above). Each entry of that array must be a JSON object. Example:

    {
      "death_drops": [
        { "item": "rag", "damage": 2 },
        { "item": "bowling_ball" }
      ]
    }
    

    Notes

    Testing

    You can test your item groups in the game:

    1. Load a game and call the debug menu

      TIP (If a key isn’t bound to the debug menu or you forgot it, use ESC > 1)

    2. Choose “Test Item Group”.

    3. Select the item group you want to debug.

      The game will then spawn items in that group 100 times and count the spawned items. They’ll then be displayed, sorted by their frequency.

      TIP: You can filter anything in the debug menu using /

    You should not add items to the item group EMPTY_GROUP. This group can be used when the game requires a group id, but you don’t want to spawn any items there. The group will never spawn items.

    SUS

    When adding items to item groups, attempt to locate or create SUS item groups. SUS item groups are collections that contain a reasonable realistic distribution of items that might spawn in a given piece of storage furniture. SUS stands for “specific use storage.” One of the aims of organizing item groups into specific use storage is to promote reusable tables that can be maintained and extended.

    You can find SUS item groups at /data/json/itemgroups/SUS

    JSON Inheritance

    To reduce duplication in the JSON data it is possible for some types to inherit from an existing type.

    Properties

    abstract

    Creates an abstract item (an item that does not end up in the game and solely exists in the json to be copied-from). Use this instead of "id".

    copy-from

    The identifier of the item you wish to copy properties from. This allows you to make an exact copy of an item of the same type and only provide entries that should change from the item you copied from.

    Giving the new item the same "id" as the copy-from target replaces the original item.

    extends

    Modders can add an "extends" field to their definition to append entries to a list instead of overriding the entire list.

    delete

    Modders can also add a "delete" field that removes elements from lists instead of overriding the entire list.

    Examples

    In the following condensed example 556 ammo is derived from 223 ammo via copy-from:

    "id": "556",
    "copy-from": "223",
    "type": "AMMO",
    "name": "5.56 NATO M855A1",
    "description": "5.56x45mm ammunition with a 62gr FMJ bullet...",
    "price": 3500,
    "relative": {
        "damage": -2,
        "pierce": 4,
    },
    "extend": { "effects": [ "NEVER_MISFIRES" ] }
    

    The following rules apply to the above example:

    • Missing fields have the same value as the parent

    • Fields explicitly specified replace those of the parent type. The above example replaces name, description and price.

    • Numeric values may be specified relative to the parent. For example 556 has less damage but more pierce than 223 and will maintain this relationship if the definition for 223 is changed.

    • Flags can be added via extend. For example 556 is military ammo and gains the NEVER_MISFIRES ammo effect. Any existing flags specified from 223 are preserved.

    • The entry you copied from must be of the same type as the item you added or changed (not all types are supported, see ‘support’ below)

    Reloaded ammo is derived from the factory equivalent but with a 10% penalty to damage and dispersion and a chance to misfire:

    "id": "reloaded_556",
    "copy-from": "556",
    "type": "AMMO",
    "name": "reloaded 5.56 NATO",
    "proportional": {
        "damage": 0.9,
        "dispersion": 1.1
    },
    "extend": { "effects": [ "RECYCLED" ] },
    "delete": { "effects": [ "NEVER_MISFIRES" ] }
    

    The following additional rules apply to the above example:

    Chained inheritance is possible; for example reloaded_556 inherits from 556 which is itself derived from 223

    Numeric values may be specified proportional to the parent by via a decimal factor where 0.5 is 50% and 2.0 is 200%.

    Flags can be deleted via delete. It is not an error if the deleted flag does not exist in the parent.

    It is possible to define an abstract type that exists only for other types to inherit from and cannot itself be used in game. In the following condensed example magazine_belt provides values common to all implemented ammo belts:

    "abstract": "magazine_belt",
    "type": "MAGAZINE",
    "name": "Ammo belt",
    "description": "An ammo belt consisting of metal linkages which disintegrate upon firing.",
    "rigid": false,
    "armor_data": {
        "covers": [ "TORSO" ],
        ...
    },
    "flags": [ "MAG_BELT", "MAG_DESTROY" ]
    

    The following additional rules apply to the above example:

    Missing mandatory fields do not result in errors as the abstract type is discarded after JSON loading completes

    Missing optional fields are set to the usual defaults for that type

    Support

    The following types currently support inheritance:

    • GENERIC
    • AMMO
    • GUN
    • GUNMOD
    • MAGAZINE
    • TOOL (but not TOOL_ARMOR)
    • COMESTIBLE
    • BOOK
    • ENGINE

    To find out if a types supports copy-from, you need to know if it has implemented generic_factory. To find out if this is the case, do the following:

    • Open init.cpp
    • Find the line that mentions your type, for example add( "gate", &gates::load );
    • Copy the load function, in this case it would be gates::load
    • Use this in the search bar on github to find the file that contains gates::load
    • In the search results you find gates.cpp. open it.
    • In gates.cpp, find the generic_factory line, it looks like this: generic_factory<gate_data> gates_data( "gate type", "handle", "other_handles" );
    • Since the generic_factory line is present, you can now conclude that it supports copy-from.
    • If you don’t find generic_factoy present, it does not support copy-from, as is the case for type vitamin (repeat the above steps and find that vitamin.cpp does not contain generic_factoy)

    Material Definitions

    Note

    This article was recently split off from JSON INFO and likely could use additional work

    Materials

    IdentifierDescription
    idUnique ID. Lowercase snake_case. Must be one continuous word, use underscores if necessary.
    nameIn-game name displayed.
    bash_resistHow well a material resists bashing damage.
    cut_resistHow well a material resists cutting damage.
    bullet_resistHow well a material resists bullet damage.
    acid_resistAbility of a material to resist acid.
    elec_resistAbility of a material to resist electricity.
    fire_resistAbility of a material to resist fire.
    chip_resistReturns resistance to being damaged by attacks against the item itself.
    bash_dmg_verbVerb used when material takes bashing damage.
    cut_dmg_verbVerb used when material takes cutting damage.
    dmg_adjDescription added to damaged item in ascending severity.
    dmg_adjAdjectives used to describe damage states of a material.
    densityDensity of a material.
    vitaminsVitamins in a material. Usually overridden by item specific values.
    wind_resistPercentage 0-100. How effective this material is at stopping wind from getting through. Higher values are better. If none of the materials an item is made of specify a value, a default of 99 is assumed.
    warmth_when_wetPercentage of warmth retained when fully drenched. Default is 0.2.
    specific_heat_liquidSpecific heat of a material when not frozen (J/(g K)). Default 4.186.
    specific_heat_solidSpecific heat of a material when frozen (J/(g K)). Default 2.108.
    latent_heatLatent heat of fusion for a material (J/g). Default 334.
    freeze_pointFreezing point of this material (F). Default 32 F ( 0 C ).
    edibleOptional boolean. Default is false.
    rottingOptional boolean. Default is false.
    softOptional boolean. Default is false.
    reinforcesOptional boolean. Default is false.

    There are six -resist parameters: acid, bash, chip, cut, elec, and fire. These are integer values; the default is 0 and they can be negative to take more damage.

    {
      "type": "material",
      "id": "hflesh",
      "name": "Human Flesh",
      "density": 5,
      "specific_heat_liquid": 3.7,
      "specific_heat_solid": 2.15,
      "latent_heat": 260,
      "edible": true,
      "rotting": true,
      "bash_resist": 1,
      "cut_resist": 1,
      "bullet_resist": 1,
      "acid_resist": 1,
      "fire_resist": 1,
      "elec_resist": 1,
      "chip_resist": 2,
      "dmg_adj": ["bruised", "mutilated", "badly mutilated", "thoroughly mutilated"],
      "bash_dmg_verb": "bruised",
      "cut_dmg_verb": "sliced",
      "vitamins": [["calcium", 0.1], ["vitB", 1], ["iron", 1.3]],
      "burn_data": [
        { "fuel": 1, "smoke": 1, "burn": 1, "volume_per_turn": "2500_ml" },
        { "fuel": 2, "smoke": 3, "burn": 2, "volume_per_turn": "10000_ml" },
        { "fuel": 3, "smoke": 10, "burn": 3 }
      ]
    }
    

    Nested Recipe Categories

    Nested Recipe Categories

    Nested categories let you create hierarchical groupings inside the crafting UI. They are JSON objects with type: "nested_category" that behave like recipes for listing and filtering, but they do not produce items. A nested category appears as a collapsible entry and expands into the recipes (or other nested categories) listed in its nested_category_data.

    Use nested categories when a subcategory has too many entries or you want an extra grouping layer without adding new craft tabs.

    Fields

    IdentifierDescription
    idUnique ID for the nested category.
    typeMust be nested_category.
    nested_nameDisplay name shown in the crafting UI. Recommended because nested categories have no result.
    categoryCrafting category (CC_*) where the entry appears.
    subcategoryCrafting subcategory where the entry appears.
    descriptionOptional description shown in the crafting UI.
    nested_category_dataArray of recipe IDs or nested category IDs to display under this entry.

    Behavior Notes

    • nested_category_data can reference standard recipes (by recipe ID) or other nested categories (by id). Recipe IDs are the recipe’s own ID, which is the result item ID with any id_suffix applied.
    • Nested categories should not define result, components, tools, or time. They are UI-only entries and cannot be crafted.
    • Avoid circular references between nested categories. Cycles are ignored in the UI and can hide entries.

    Example

    [
      {
        "type": "nested_category",
        "id": "hot_drinks",
        "nested_name": "hot drinks",
        "category": "CC_FOOD",
        "subcategory": "CSC_FOOD_DRINKS",
        "description": "Warm beverages and infusions.",
        "nested_category_data": [
          "coffee",
          "tea",
          "herbal_tea"
        ]
      }
    ]
    

    Recipes

    Note

    This article was recently split off from JSON INFO and likely could use additional work

    Recipes

    Recipes represent both craft and uncraft (disassembly) recipes.

    See Nested Recipe Categories for creating hierarchical crafting menu groupings.

    "type": "recipe",            // Recipe type. Possible values: 'recipe' (craft recipe) and 'uncraft' (uncraft recipe).
    "reversible": false,         // Generate an uncraft recipe that is a reverse of this craft recipe.
    "result": "javelin",         // ID of resulting item. By default, also used as the ID of the recipe.
    "id_suffix": "",             // Optional (default: empty string). Some suffix to make the ID of the recipe unique. The ID of the recipe is "<result><id_suffix>".
    "category": "CC_WEAPON",     // Category of crafting recipe. CC_NONCRAFT used for disassembly recipes
    "subcategory": "",           // Subcategory of crafting recipe. 
    "override": false,           // Optional (default: false). If false and the ID of the recipe is already used by another recipe, loading of recipes fails. If true and a recipe with the ID is already defined, the existing recipe is replaced by the new recipe.
    "obsolete": false,           // Optional (default: false). Marks this recipe as obsolete. Use this instead of outright deleting it to preserve save compatibility.
    "delete_flags": [ "CANNIBALISM" ], // Optional (default: empty list). Flags specified here will be removed from the resultant item upon crafting. This will override flag inheritance, but *will not* delete flags that are part of the item type itself.
    "contained": false,          // Optional (default: false). Spawn produced item in a container.
    "container": "can_medium",   // Optional. Override container to spawn item in (by default uses item's default container)
    "charges": 1,                // Optional (default: null). Override default charges for count-by-charges items (ammo, comestibles, etc.)
    "result_mult": 1,            // Optional (default: 1). Produce multiple items (or stacks for count-by-charges items) from single craft
    "skill_used": "fabrication", // Skill trained and used for success checks
    "skills_required": [["survival", 1], ["throw", 2]], // Skills required to unlock recipe
    "book_learn": [              // (optional) Array of books that this recipe can be learned from. Each entry contains the id of the book and the skill level at which it can be learned.
        [ "textbook_anarch", 7, "something" ], // The optional third entry defines a name for the recipe as it should appear in the books description (default is the name of resulting item of the recipe)
        [ "textbook_gaswarfare", 8, "" ] // If the name is empty, the recipe is hidden, it will not be shown in the description of the book.
    ],
    "difficulty": 3,             // Difficulty of success check
    "time": "5 m",               // Time to perform the recipe specified as time string (can use minutes, hours, etc.)
    "time": 5000,                // Legacy time format, in moves. Won't be supported in the future. Here, 1000 ~= 10 turns ~= 10 seconds of game time
    "autolearn": true,           // Automatically learned upon gaining required skills
    "autolearn" : [              // Automatically learned upon gaining listed skills
        [ "survival", 2 ],
        [ "fabrication", 3 ]
    ],
    "decomp_learn" : 4,          // Can be learned by disassembling an item of same type as result at this level of the skill_used
    "decomp_learn" : [           // Can be learned by disassembling an item of same type as result at specified levels of skills
        [ "survival", 1 ],
        [ "fabrication", 2 ]
    ],
    "never_learn": false,        // Optional (default: false). Prevents this recipe from being learned by the player. For debug or NPC purposes.
    "batch_time_factors": [25, 15], // Optional factors for batch crafting time reduction. First number specifies maximum crafting time reduction as percentage, and the second number the minimal batch size to reach that number. In this example given batch size of 20 the last 6 crafts will take only 3750 time units.
    "flags": [                   // A set of strings describing boolean features of the recipe
      "BLIND_EASY",
      "ANOTHERFLAG"
    ],
    "construction_blueprint": "camp", // an optional string containing an update_mapgen_id.  Used by faction camps to upgrade their buildings. If non-empty, the function must exist.
    "on_display": false,         // this is a hidden construction item, used by faction camps to calculate construction times but not available to the player
    "using": [                   // Optional, string or array. Additional external requirements to use.
      "butter_resealable_containers"
    ],
    "qualities": [               // Generic qualities of tools needed to craft
      {"id":"CUT","level":1,"amount":1}
    ],
    "tools": [                   // Specific tools needed to craft
    [
        [ "fire", -1 ]           // Charges consumed when tool is used, -1 means no charges are consumed
    ]],
    "components": [              // Equivalent tools or components are surrounded by a single set of brackets
    [
      [ "spear_wood", 1 ],       // Number of charges/items required
      [ "pointy_stick", 1 ]
    ],
    [
      [ "rag", 1 ],
      [ "leather", 1 ],
      [ "fur", 1 ]
    ],
    [
      [ "plant_fibre", 20, false ], // Optional flag for recoverability, default is true.
      [ "sinew", 20, false ],
      [ "thread", 20, false ],
      [ "duct_tape", 20 ]  // Certain items are flagged as unrecoverable at the item definition level.
    ]
    ]
    

    Overlapping recipe component requirements

    Note

    This section was inherited from DDA, and has not been proven to still apply yet. Take the below with a grain of salt.

    If recipes have requirements which overlap, this makes it more difficult for the game to calculate whether it is possible to craft a recipe at all.

    For example, the survivor telescope recipe has the following requirements (amongst others):

    1 high-quality lens
    AND
    1 high-quality lens OR 1 small high-quality lens
    

    These overlap because both list the high-quality lens.

    A small amount of overlap (such as the above) can be handled, but if you have too many component lists which overlap in too many ways, then you may see an error during recipe finalization that your recipe is too complex. In this case, the game may not be able to corectly predict whether it can be crafted.

    To work around this issue, if you do not wish to simplify the recipe requirements, then you can split your recipe into multiple steps. For example, if we wanted to simplify the above survivor telescope recipe we could introduce an intermediate item “survivor eyepiece”, which requires one of either lens, and then the telescope would require a high-quality lens and an eyepiece. Overall, the requirements are the same, but neither recipe has any overlap.

    Relics

    Relics

    Relics are regular items with special relic data attached to them.

    Relic data is defined in JSON in relic_data field of corresponding item type definition, and whenever the item is spawned a copy of relic data is attached to the item instance.

    Relic data object can contain the following fields:

    {
    "name": "Boots of Haste",       // Overrides default item name
    "moves": 100,                   // (optional) Activation move cost (default 100)
    "charges_per_activation": 1,    // (optional) Charges per activation (default 1)
    "active_effects": [ {}, ... ],  // (optional) Spells executed on activation (identical to `hit_you_effect`, see [MAGIC.md](MAGIC.md/#hit_you_effect))
    "passive_effects": [ {}, ... ], // (optional) List of passive effects (enchantments), see [ENCHANTMENTS.md](ENCHANTMENTS.md)
    "recharge_scheme": [ {}, ... ], // (optional) List of recharge methods, see below
    }
    

    Relic recharge

    Relics can recharge under certain conditions. Recharge method is defined as follows (all fields optional):

    Only works for guns, tools and magazines. Won’t work while an item is loaded into another item.

    {
      "type": "time", // Defines what resource is consumed. Default: time
      "req": "none", // Defines under what conditions recharge works. Default: none (no special requirements)
      "field": "fd_blood", // Field type to be consumed with 'field' recharge type
      "trap": "tr_portal", // Trap type to be consumed with 'trap' recharge type
      "interval": "5 minutes", // Interval at which the recharge check is done. Default: 1 second
      "int_min": 1, // Min intensity of related 'type' effect. Default: 0
      "int_min": 5, // Max intensity of related 'type' effect. Default: 0
      "rate": 2, // Amount of charges restored when recharge operation succeeds. Default: 0
      "message": "Your body decays!" // Optional message to print on success
    }
    

    Recharge type

    IDDescription
    timeNeeds no additional resources
    solarConsumes sunlight (character must be in sunlight)
    painCauses pain to recharge. Intensity controlled by int_min and int_max
    hpCauses damage to all body parts. Intensity controlled by int_min and int_max
    fatigueCauses fatigue and drains stamina. Fatigue drain controlled by int_min and int_max, stamina drain rolled as [ int_min*100, int_max*100 ]
    fieldConsumes adjacent field. Allowed field intensity controlled by int_min and int_max
    trapConsumes adjacent trap.

    Recharge requirements

    IDDescription
    noneNo additional requirements (always works)
    equippedMust be worn if armor, wielded if weapon.
    close_to_skinMust be worn underneath all other clothing, or be wielded with bare hands
    sleepCharacter must be asleep
    radCharacter or map tile must be irradiated
    wetCharacter must be wet, or it’s raining
    skyCharacter must be above z=0

    tool_qualities

    Tool Qualities

    Note

    This article is new and may need more examples and links.

    Tool qualities define named capability tiers used by recipes and other systems. They are loaded from data/json/tool_qualities.json.

    {
      "type": "tool_quality", // Tool quality definition
      "id": "SEW", // Unique quality id
      "name": { "str": "sewing" }, // Display name for the quality
      "crafting_speed_bonus_per_level": 1.1, // Optional per-level multiplier (see below)
      "crafting_speed_level_offset": 2 // Optional per-level offset (see below)
    }
    

    Fields

    • id: Unique quality id.
    • name: Display name for the quality.
    • crafting_speed_bonus_per_level: Optional (default = 0.0). Crafting speed multiplier per quality level above the recipe requirement (e.g., 1.1 for +10% per extra level), applied only when the item does not define its own crafting_speed_modifier.
    • crafting_speed_level_offset: Optional (default = 0). Minimum quality level at which crafting_speed_bonus_per_level starts to apply, even if recipes require lower levels.

    Crafting Usage

    Tool qualities are used in recipes to group many equivalent items under a single capability. Any item that lists a quality in its qualities array can satisfy a recipe qualities requirement at or above the requested level. This lets you avoid listing every acceptable tool explicitly.

    Example recipe requirement:

    "qualities": [ { "id": "SEW", "level": 2 } ]
    

    Example items:

    "qualities": [ [ "SEW", 2 ] ]   // Basic sewing tools
    "qualities": [ [ "SEW", 4 ] ]   // Higher-quality tailoring kit
    

    When a recipe requires SEW 2, any item with SEW 2 or higher can be used. If the quality defines crafting_speed_bonus_per_level, higher levels above the requirement increase crafting speed unless the item provides its own crafting_speed_modifier. If crafting_speed_level_offset is set, the speed bonus starts at the higher of the recipe level and the offset.

    vitamin

    definition

    {
      "id": "iron",
      "type": "vitamin",
      "vit_type": "vitamin",
      "name": "Iron",
      "excess": "hypervitaminosis",
      "deficiency": "anemia",
      "min": -12000,
      "max": 3600,
      "rate": "15 m",
      "flags": [ "FOO" ],
      "disease": [ [ -4800, -5600 ], [ -5601, -6400 ], [ -6401, -12000 ] ],
      "disease_excess": [ [ 10, 19 ], [ 20, 29 ], [ 30, 40 ] ]
    },
    

    id

    Mandatory. The id of the vitamin.

    type

    Mandatory. Must be vitamin.

    vit_type

    The type of the vitamin. Valid values are:

    vitamin

    When simplified nutrition is enabled, this vitamin will not be added to any items and any time the game attempts to retrieve it from the player it will give 0. Only nutritional vitamins should have this type.

    toxin

    This is some toxic chemical or component. This currently has no effect.

    drug

    This is a drug. This currently has no effect.

    counter

    This is a counter for something, that is neither a toxin, vitamin, or drug. This currently has no effect.

    name

    What the vitamin shows up as where vitamins are displayed, such as the vitamins display in the item menu.

    deficiency

    The id of an effect that is triggered by a deficiency of this vitamin.

    excess

    The id of an effect that is triggered by a excess of this vitamin.

    min

    The smallest amount of this vitamin that the player can have.

    max

    The highest amount of this vitamin that the avatar can have.

    rate

    How long it takes to lose one unit of this vitamin.

    flags

    An array of string flags, see the flags section below for valid ones

    disease

    What the thresholds of deficiency of this vitamin are. Each pair in the list determines the start and end points of that tier of deficiency. Each tier of deficiency corresponds to the intensity level of the effect defined in deficiency.

    disease_excess

    What the thresholds of excess of this vitamin are. Each pair in the list determines the start and end points of that tier of excess. Each tier of excess corresponds to the intensity level of the effect defined in excess.

    flags

    • NO_DISPLAY - This vitamin will not be shown when examining a food

    Field Types

    {
      // Required data
      "type": "field_type", // this is a field type
      "id": "fd_gum_web", // id of the field
      // Array of intensities of the field.
      // The first one is intensity 1, they increase by one each time
      "intensity_levels": [
        {
          "name": "shadow", // name of this level of intensity
          "sym": "a", // Symbol for this field intensity level
          "color": "light_red", // Curses color for the field symbol
          // Visibility
          "transparent": false, // Weather the field can be seen through
          "light_override": 3.7, // The amount of light to be used, ignores ambient light. 100 is daylight 0 is 100% dark.
          "light_color": "#ffd08a", // Color of light to emit
          "light_emitted": 20, // Amount of light to emit
          // Movement
          "dangerous": true, // Weather this intensity is dangerous to go through
          "move_cost": 50, // Move cost of moving through the field
          // Radiation
          "extra_radiation_min": 10, // Minimum amount of extra radiation from entering field
          "extra_radiation_max": 100, // Maximum amount of extra radiation from entering field
          "radiation_hurt_damage_min": 1, // Minimum amount of pain to cause to all bodyparts
          "radiation_hurt_damage_max": 3, // Maximum amount of pain to cause to all bodyparts
          "radiation_hurt_message": "The radioactive gas burns!", // Message to print when getting pain from it
          // Intensity manipulation
          "intensity_upgrade_chance": 10, // One in x chance to upgrade intensity every few ticks
          "intensity_upgrade_duration": 1, // Number of ticks to wait before upgrading intensity
          // Monster Group spawning
          "monster_spawn_chance": 10, // Chance to spawn monsters
          "monster_spawn_count": 10, // Number of monsters to spawn
          "monster_spawn_radius": 10, // Radius to spawn monsters in
          "monster_spawn_group": "GROUP_ZOMBIE", // Group to spawn
          // Misc
          "convection_temperature_mod": 10, // Amount of temperature to add
          // Effects
          "effects": [{
            // Basic information
            "effect_id": "sap", // Effect id to apply
            "body_part": "torso", // Bodypart with the stated id
            "intensity": 1, // Intensity of the effect
            // Duration
            "max_duration": "2 seconds", // Maximum duration of the effect
            "min_duration": "2 seconds", // Minimum duration of the effect
            // Immunity and application chances
            "is_environmental": true, // Will environmental protection protect
            "immune_in_vehicle": true, // Immune when on any vehicle part
            "chance_in_vehicle": 10, // One in x chance to get the effect when meeting above condition
            "immune_inside_vehicle": true, // Immune when on a vehicle part that qualifies as inside
            "chance_inside_vehicle": 10, // One in x chance to get the effect when meeting above condition
            "immune_outside_vehicle": true, // Immune when not on a vehicle part that qualifies as inside
            "chance_outside_vehicle": 10, // On in x chance to get the effect when meeting above condition
            // Messages
            "message": "The sap is sticky!", // Message to print when recieving the effect
            "message_npc": "The sap sticks to <npcname>!", // Message to print when NPC gets effect
            "message_type": "bad", // What type of message is this?
          }],
        },
      ],
      // Graphical
      "display_items": true, // Display the items on the files or not?
      "display_field": true, // Display the field or not?
      "priority": 1, // Priority to display the field's symbol / sprite
      "tint": "#123456", // Optional sprite tint: a color name or RGB color. Inherited through copy-from.
      // Immunities
      "immunity_data": {
        "traits": ["M_IMMUNE"], // Array of traits that prevent effects from the field
        "body_part_env_resistance": [["mouth", 15], ["eyes", 15]], // Environemental resistance on bodyparts required to protect from the field
      },
      "immune_mtypes": ["mon_zombie"], // Monster Types immune to the field
      "has_fire": true, // Does fire immunity make you immune to this field
      "has_acid": true, // Does acid immunity?
      "has_elec": true, // What about electricity?
      "has_fume": true, // Shall we change the background color to white on curses?
      // Decaying and spreading
      "underwater_age_speedup": "1 minute", // This many more turns pass on it's age in water
      "outdoor_age_speedup": "1 minute", // This many more turns pass on it's age while in water
      "decay_amount_factor": 5, // Yet another turn increment to the field's age
      "percent_spread": 10, // Percent chance to spread each turn
      "half_life": "10 minutes", // Number of turns til half of it is gone
      "stacking_type": "duration", // Does more field add `intensity` or `duration`
      "wandering_field": "fd_toxic_gas", // Field that this field produces
      "accelerated_decay": true, // Does this field go downward with terrain shifts?
      // Misc
      "conductive": false, // If true, an electrical pulse energizes connected conductive fields, then fades. Defaults to false.
      "flammable": false, // If true, ignition consumes this field to create sustained fire. Defaults to false.
      "moppable": false, // If true, mops and automatic mopping remove this field. Defaults to false.
      "gas_absorbption_factor": 10, // Number of charges to eat from the gas mask
      "dirty_transparency_cache": true, // Weather to forcefully recalc the transparency cache. It is automatically set with transparent being false
      "description_affix": "covered in", // Puts this in front of every intensity level name
      "phase": "solid", // Is it solid liquid gas or plasma? Mainly gas has effect on propagation
      "is_splattering": true, // Does this apply blood to vehicle parts?
      "apply_slime_factor": 2, // Applies scent of factor * intensity
      "scent_neutralization": 2, // Reduces scent by this value
      // NPC Complain
      "npc_complain": {
        "chance": 20, // One out of x chance to complain
        "issue": "crack_smoke", // Talk tag to complain about
        "duration": "30 minutes", // How long will they be complaining
        "speech": "<crack_smoke>", // Once again the talk tag to have spoken
      },
      // Monster spawning
      "monster_spawn_chance": 2, // One in x chance to spawn monster
      "monster_spawn_count": 3, // How many monsters to spawn
      "monster_spawn_group": "GROUP_ZOMBIE", // What monster group to spawn
      "monster_spawn_radius": 5, // Tile radius of monster spawn locations
      // Bash data
      "bash": {
        "str_min": 1, // lower bracket of bashing damage required to bash
        "str_max": 3, // higher bracket
        "sound_vol": 2, // noise made when succesfully bashing the field
        "sound_fail_vol": 2, // noise made when failing to bash the field
        "sound": "shwip", // sound on success
        "sound_fail": "shwomp", // sound on failure
        "msg_success": "You brush the gum web aside.", // message on success
        "move_cost": 120, // how many moves it costs to succesfully bash that field (default: 100)
        "items": [ // item dropped upon succesful bashing
          { "item": "2x4", "count": [5, 8] },
          { "item": "nail", "charges": [6, 8] },
          {
            "item": "splinter",
            "count": [3, 6],
          },
          { "item": "rag", "count": [40, 55] },
          { "item": "scrap", "count": [10, 20] },
        ],
      },
    }
    

    Mapgen

    How buildings and terrain are generated

    Cataclysm creates buildings and terrain on discovery via ‘mapgen’; functions specific to an overmap terrain (the tiles you see in [m]ap are also determined by overmap terrain). Overmap terrains (“oter”) are defined in overmap_terrain.json.

    By default, an oter has a single built-in mapgen function which matches the ‘“id”’ in it’s json entry (examples: “house”, “bank”, etc). Multiple functions also possible. When a player moves into range of an area marked on the map as a house, the game chooses semi-randomly from a list of functions for “house”, picks one, and runs it, laying down walls and adding items, monsters, rubber chickens and whatnot. This is all done in a fraction of a second (something to keep in mind for later).

    All mapgen functions build in a 24x24 tile area - even for large buildings; obtuse but surprisingly effective methods are used to assemble giant 3x3 hotels, etc..

    In order to make a world that’s random and (somewhat) sensical, there are numerous rules and exceptions to them, which are clarified below.

    There are three methods:

    • Adding mapgen entries
    • JSON object definition
    • Using update_mapgen

    Adding mapgen entries

    One doesn’t need to create a new overmap_terrain for a new variation of a building. For a custom gas station, defining a mapgen entry and adding it to the “s_gas” mapgen list will add it to the random variations of gas station in the world.

    If you use an existing overmap_terrain and it has a roof or other z-level linked to its file, the other levels will be generated with the ground floor. To avoid this, or add your own multiple z-levels, create an overmap_terrain with a similar name (s_gas_1).

    Methods

    While adding mapgen as a c++ function is one of the fastest (and the most versatile) ways to generate procedural terrain on the fly, this requires recompiling the game.

    Most of the existing c++ buildings have been moved to json and currently json mapping is the preferred method of adding both content and mods.

    • JSON: A set of json arrays and objects for defining stuff and things. Pros: Fastest to apply, mostly complete. Cons: Not a programming language; no if statements or variables means instances of a particular json mapgen definition will all be similar. Third party map editors are currently out of date.

    • JSON support includes the use of nested mapgen, smaller mapgen chunks which override a portion of the linked mapgen. This allows for greater variety in furniture, terrain and spawns within a single mapgen file. You can also link mapgen files for multiple z-level buildings and multi-tile buildings.

    • Lua: Lua support depends on the use of a lua method defined by the field luamethod, during mod loading one would place the method into game.mapgen_functions[id] where id is what is the string in luamethod This allows for procedual overmap tiles to be made, similar to the hardcoded labs

    Mapgen definition Placement

    Mapgen definitions can be added in 3 places:

    Lua mapgen

    This is how to define a map defined by lua elsewhere

    [
      {
        "type": "mapgen",
        "method": "lua",
        "om_terrain": ["slimepit", "slimepit_down"],
        "luamethod": "slimepit"
      }
    ]
    

    Embedded mapgen

    As "mapgen": { ... } only used in combination with the ‘builtin’ method:

    "mapgen": [ { "method": "builtin", "name": "parking_lot" } ]
    

    Do not use this, use standalone instead.

    Standalone mapgen

    As standalone { "type": "mapgen", ... } objects in a .json inside data/json. Below is the fast food restaurant.

    [
      {
        "type": "mapgen",
        "om_terrain": "s_restaurant_fast",
        "weight": 250,
        "method": "json",
        "object": {
          "//": "(see below)"
        }
      }
    ]
    

    Note how “om_terrain” matches the overmap “id”. om_terrain is required for standalone mapgen entries.

    Format and variables

    The above example only illustrate the mapgen entries, not the actual format for building stuff. However, the following variables impact where and how often stuff gets applied:

    • method
    • om_terrain
    • weight

    Define mapgen “method”

    required Values: json - required

    "object": { (more json here) }
    

    Define overmap terrain with “om_terrain” value, array, or nested array

    required for standalone

    The om_terrain value may be declared in one of three forms: with a single overmap terrain ID, with a list of IDs, or with a nested list (of lists) of IDs.

    With the first form, simply give the ID of an overmap terrain from overmap_terrain.json:

    "om_terrain": "oter_id"
    

    In the second form, provide a list of IDs:

    "om_terrain": [ "house", "house_base" ]
    

    This creates duplicate overmap terrains by applying the same json mapgen to each of the listed overmap terrain IDs.

    The third option is a nested list:

    "om_terrain": [ [ "oter_id_1a", "oter_id_1b", ... ], [ "oter_id_2a", "oter_id_2b", ... ], ... ]
    

    This form allows for multiple overmap terrains to be defined using a single json object, with the “rows” property expanding in blocks of 24x24 characters to accommodate as many overmap terrains as are listed here. The terrain ids are specified using a nested array of strings which represent the rows and columns of overmap terrain ids (found in overmap_terrain.json) that are associated with the “rows” property described in section 2.1 of this document.

    Characters mapped using the “terrain”, “furniture”, or any of the special mappings (“items”, “monsters”, etc) will be applied universally to all of the listed overmap terrains.

    Placing things using x/y coordinates (“place_monsters”, “place_loot”, “place_item”, etc) works using the full extended coordinates beyond 24x24. An important limitation is that ranged random coordinates (such as “x”: [ 10, 18 ]) must not cross the 24x24 terrain boundaries. Ranges such as [ 0, 23 ] and [ 50, 70 ] are valid, but [ 0, 47 ] and [ 15, 35 ] are not because they extend beyond a single 24x24 block.

    Example:

    "om_terrain": [
      [ "apartments_mod_tower_NW", "apartments_mod_tower_NE" ],
      [ "apartments_mod_tower_SW", "apartments_mod_tower_SE" ]
    ]
    

    In this example, the “rows” property should be 48x48, with each quadrant of 24x24 being associated with each of the four apartments_mod_tower overmap terrain ids specified.

    “om_terrain” for linear terrain

    Some overmap terrains are linear. This is used for things like roads, tunnels, etc. where they form lines which can connect in various ways. Such terrains are defined with the LINEAR flag in their overmap_terrain definition (see the OVERMAP docs).

    When defining the JSON mapgen for such terrain, you must define several instances, for each type of connection that might exist. Each gets a suffix added to the overmap_terrain id. The suffixes are: _end, _straight, _curved, _tee, _four_way. For an example, see the definitions for ants in ants.json.

    Define mapgen “weight”

    (optional) When the game randomly picks mapgen functions, each function’s weight value determines how rare it is. 1000 is the default, so adding something with weight ‘500’ will make it appear 1/3 times, unless more functions are added. (An insanely high value like 10000000 is useful for testing)

    Values: number - 0 disables

    Default: 1000

    How “overmap_terrain” variables affect mapgen

    “id” is used to determine the required “om_terrain” id for standalone, except when the following variables are set in “overmap_terrain”:

    • “extras” - applies rare, random scenes after mapgen; helicopter crashes, etc
    • “mondensity” - determines the default ‘density’ value for "place_groups": [ { "monster": ... (json). If this is not set then place_monsters will not work without its own explicitly set density argument.

    Limitations / TODO

    • JSON: adding specific monster spawns are still WIP.
    • The old mapgen.cpp system involved The Biggest “if / else if / else if / ..” Statement Known to Man(tm), and is only halfway converted to the “builtin” mapgen class. This means that while custom mapgen functions are allowed, the game will cheerfully forget the default if one is added.
    • TODO: Add to this list.

    JSON object definition

    The JSON object for a mapgen entry must include either "fill_ter", or "rows" and "terrain". All other fields are optional.

    Fill terrain using “fill_ter”

    required if “rows” is unset Fill with the given terrain.

    Value: "string": Valid terrain id from data/json/terrain.json

    Example: "fill_ter": "t_grass"

    ASCII map using “rows” array

    required if “fill_ter” is unset

    Nested array of 24 (or 48) strings, each 24 (or 48) characters long, where each character is defined by “terrain” and optionally “furniture” or other entries below.

    Usage:

    "rows": [ "row1...", "row2...", ..., "row24..." ]
    

    Other parts can be linked with this map, for example one can place things like a gaspump (with gasoline) or a toilet (with water) or items from an item group or fields at the square given by a character.

    Any character used here must have some definition elsewhere to indicate its purpose. Failing to do so is an error which will be caught by running the tests. The tests will run automatically when you make a pull request for adding new maps to the game. If you have defined fill_ter or you are writing nested mapgen, then there are a couple of exceptions. The space and period characters (`` and .) are permitted to have no definition and be used for ‘background’ in the rows.

    As keys, you can use any Unicode characters which are not double-width. This includes for example most European alphabets but not Chinese characters. If you intend to take advantage of this, ensure that your editor is saving the file with a UTF-8 encoding. Accents are acceptable, even when using combining characters. No normalization is performed; comparison is done at the raw bytes (code unit) level. Therefore, there are literally an infinite number of mapgen key characters available. Please don’t abuse this by using distinct characters that are visually indistinguishable, or which are so rare as to be unlikely to render correctly for other developers.

    Example:

    "rows": [
      ",_____ssssssssssss_____,",
      ",__,__#### ss ####__,__,",
      ",_,,,_#ssssssssss#__,__,",
      ",__,__#hthsssshth#__,__,",
      ",__,__#ssssssssss#_,,,_,",
      ",__,__|-555++555-|__,__,",
      ",_____|.hh....hh.%_____,",
      ",_____%.tt....tt.%_____,",
      ",_____%.tt....tt.%_____,",
      ",_____%.hh....hh.|_____,",
      ",_____|..........%_____,",
      ",,,,,,|..........+_____,",
      ",_____|ccccxcc|..%_____,",
      ",_____w.......+..|_____,",
      ",_____|e.ccl.c|+-|_____,",
      ",_____|O.....S|.S|_____,",
      ",_____||erle.x|T||_____,",
      ",_____#|----w-|-|#_____,",
      ",________,_____________,",
      ",________,_____________,",
      ",________,_____________,",
      " ,_______,____________, ",
      "  ,,,,,,,,,,,,,,,,,,,,  ",
      "   dd                   "
    ],
    

    Row terrains in “terrain”

    required by “rows”

    Defines terrain ids for “rows”, each key is a single character with a terrain id string

    Value: {object}: { "a", "t_identifier", ... }

    Example:

    "terrain": {
      " ": "t_grass",
      "d": "t_floor",
      "5": "t_wall_glass_h",
      "%": "t_wall_glass_v",
      "O": "t_floor",
      ",": "t_pavement_y",
      "_": "t_pavement",
      "r": "t_floor",
      "6": "t_console",
      "x": "t_console_broken",
      "$": "t_shrub",
      "^": "t_floor",
      ".": "t_floor",
      "-": "t_wall_h",
      "|": "t_wall_v",
      "#": "t_shrub",
      "t": "t_floor",
      "+": "t_door_glass_c",
      "=": "t_door_locked_alarm",
      "D": "t_door_locked",
      "w": "t_window_domestic",
      "T": "t_floor",
      "S": "t_floor",
      "e": "t_floor",
      "h": "t_floor",
      "c": "t_floor",
      "l": "t_floor",
      "s": "t_sidewalk"
    },
    

    Furniture symbols in “furniture” array

    optional

    Defines furniture ids for “rows” ( each character in rows is a terrain -or- terrain/furniture combo ). “f_null” means no furniture but the entry can be left out

    Example:

    "furniture": {
      "d": "f_dumpster",
      "5": "f_null",
      "%": "f_null",
      "O": "f_oven",
      "r": "f_rack",
      "^": "f_indoor_plant",
      "t": { "furn": "f_table" "palette": "wooden_furniture_palette" },
      "T": "f_toilet",
      "S": "f_sink",
      "e": "f_fridge",
      "h": "f_chair",
      "c": "f_counter",
      "l": "f_locker"
    },
    

    The palette causes the furniture to be default painted based off the palette The palette randomly chooses a color based of the position on the global overmap

    Can also defined an inline palette as a seperate option

    Set terrain, furniture, or traps with a “set” array

    optional Specific commands to set terrain, furniture, traps, radiation, etc. Array is processed in order.

    Value: [ array of {objects} ]: [ { "point": .. }, { "line": .. }, { "square": .. }, ... ]

    Example:

    "set": [
      { "point": "furniture", "id": "f_chair", "x": 5, "y": 10 },
      { "point": "radiation", "id": "f_chair", "x": 12, "y": 12, "amount": 20 },
      { "point": "trap", "id": "tr_beartrap", "x": [ 0, 23 ], "y": [ 5, 18 ], "chance": 10, "repeat": [ 2, 5 ] }
    ]
    

    All X and Y values may be either a single integer between 0 and 23, or an array of two integers [ n1, n2 ] (each between 0 and 23). If X or Y are set to an array, the result is a random number in that range (inclusive). In the above examples, the furniture "f_chair" is always at coordinates "x": 5, "y": 10, but the trap "tr_beartrap" is randomly repeated in the area "x": [ 0, 23 ], "y": [ 5, 18 ]".

    See terrain.json, furniture.json, and trap.json for “id” strings.

    Set things at a “point”

    • Requires “point” type, and coordinates “x” and “y”
    • For “point” type “radiation”, requires “amount”
    • For other types, requires “id” of terrain, furniture, or trap
    FieldDescription
    pointAllowed values: "terrain", "furniture", "trap", "radiation"
    idTerrain, furniture, or trap ID. Examples: "id": "f_counter", "id": "tr_beartrap". Omit for “radiation”.
    x, yX, Y coordinates. Value from 0-23, or range [ 0-23, 0-23 ] for a random value in that range. Example: "x": 12, "y": [ 5, 15 ]
    amountRadiation amount. Value from 0-100.
    chance(optional) One-in-N chance to apply
    repeat(optional) Value: [ n1, n2 ]. Spawn item randomly between n1 and n2 times. Only makes sense if the coordinates are random. Example: [ 1, 3 ] - repeat 1-3 times.

    Set things in a “line”

    • Requires “line” type, and endpoints “x”, “y” and “x2”, “y2”
    • For “line” type “radiation”, requires “amount”
    • For other types, requires “id” of terrain, furniture, or trap

    Example:

    { "line": "terrain", "id": "t_lava", "x": 5, "y": 5, "x2": 20, "y2": 20 }
    
    FieldDescription
    lineAllowed values: "terrain", "furniture", "trap", "radiation"
    idTerrain, furniture, or trap ID. Examples: "id": "f_counter", "id": "tr_beartrap". Omit for “radiation”.
    x, yStart X, Y coordinates. Value from 0-23, or range [ 0-23, 0-23 ] for a random value in that range. Example: "x": 12, "y": [ 5, 15 ]
    x2, y2End X, Y coordinates. Value from 0-23, or range [ 0-23, 0-23 ] for a random value in that range. Example: "x": 22, "y": [ 15, 20 ]
    amountRadiation amount. Value from 0-100.
    chance(optional) One-in-N chance to apply
    repeat(optional) Value: [ n1, n2 ]. Spawn item randomly between n1 and n2 times. Only makes sense if the coordinates are random. Example: [ 1, 3 ] - repeat 1-3 times.

    Set things in a “square”

    • Requires “square” type, and opposite corners at “x”, “y” and “x2”, “y2”
    • For “square” type “radiation”, requires “amount”
    • For other types, requires “id” of terrain, furniture, or trap

    The “square” arguments are the same as for “line”, but “x”, “y” and “x2”, “y2” define opposite corners.

    Example:

    { "square": "radiation", "amount": 10, "x": [0, 5], "y": [0, 5], "x2": [18, 23], "y2": [18, 23] }
    
    FieldDescription
    squareAllowed values: "terrain", "furniture", "trap", "radiation"
    idTerrain, furniture, or trap ID. Examples: "id": "f_counter", "id": "tr_beartrap". Omit for “radiation”.
    x, yTop-left corner of square.
    x2, y2Bottom-right corner of square.

    Spawn item or monster groups with “place_groups”

    optional Spawn items or monsters from item_groups.json and monster_groups.json

    Value: [ array of {objects} ]: [ { "monster": ... }, { "item": ... }, ... ]

    Spawn monsters from a group with “monster”

    FieldDescription
    monster(required) Value: "MONSTER_GROUP". The monster group id, which picks random critters from a list
    x, y(required) Spawn coordinates. Value from 0-23, or range [ 0-23, 0-23 ] for a random value in that range.
    density(optional) Floating-point multiplier to “chance” (see below).
    chance(optional) One-in-N chance to spawn

    Example:

    { "monster": "GROUP_ZOMBIE", "x": [13, 15], "y": 15, "chance": 10 }
    

    When using a range for "x" or "y", the minimum and maximum values will be used in creating rectangle coordinates to be used by map::place_spawns. Each monster generated from the monster group will be placed in a different random location within the rectangle. The values in the above example will produce a rectangle for map::place_spawns from ( 13, 15 ) to ( 15, 15 ) inclusive.

    The optional “density” is a floating-point multipier to the “chance” value. If the result is bigger than 100% it gurantees one spawn point for every 100% and the rest is evaluated by chance (one added or not). Then the monsters are spawned according to their spawn-point cost “cost_multiplier” defined in the monster groups. Additionally all overmap densities within a square of raduis 3 (7x7 around player - exact value in mapgen.cpp/MON_RADIUS macro) are added to this. The “pack_size” modifier in monstergroups is a random multiplier to the rolled spawn point amount.

    Spawn items from a group with “item”

    FieldDescription
    item(required) Value: “ITEM_GROUP”. The item group id, which picks random stuff from a list.
    x, y(required) Spawn coordinates. Value from 0-23, or range [ 0-23, 0-23 ] for a random value in that range.
    chance(required) Percentage chance to spawn.

    Example:

    { "item": "livingroom", "x": 12, "y": [5, 15], "chance": 50 }
    

    When using a range for "x" or "y", the minimum and maximum values will be used in creating rectangle coordinates to be used by map::place_items. Each item from the item group will be placed in a different random location within the rectangle. These values in the above example will produce a rectangle for map::place_items from ( 12, 5 ) to ( 12, 15 ) inclusive.

    Spawn a single monster with “place_monster”

    optional Spawn single monster. Either specific monster or a random monster from a monster group. Is affected by spawn density game setting.

    Value: [ array of {objects} ]: [ { "monster": ... } ]

    FieldDescription
    monsterID of the monster to spawn.
    groupID of the monster group from which the spawned monster is selected. monster and group should not be used together. group will act over monster.
    x, ySpawn coordinates ( specific or area rectangle ). Value: 0-23 or [ 0-23, 0-23 ] - random value between [ a, b ].
    chancePercentage chance to do spawning. If repeat is used each repeat has separate chance.
    repeatThe spawning is repeated this many times. Can be a number or a range.
    pack_sizeHow many monsters are spawned. Can be single number or range like [1-4]. Is affected by the chance and spawn density. Ignored when spawning from a group.
    one_or_noneDo not allow more than one to spawn due to high spawn density. If repeat is not defined or pack size is defined this defaults to true true, otherwise this defaults to false. Ignored when spawning from a group.
    friendlySet true to make the monster friendly. Default false.
    nameExtra name to display on the monster.
    targetSet to true to make this into mission target. Only works when the monster is spawned from a mission.

    Note that high spawn density game setting can cause extra monsters to spawn when monster is used. When group is used only one monster will spawn.

    When using a range for "x" or "y", the minimum and maximum values will be used in creating rectangle coordinates to be used by map::place_spawns. Each monster generated from the monster group will be placed in a different random location within the rectangle. Example: "x": 12, "y": [ 5, 15 ] - these values will produce a rectangle for map::place_spawns from ( 12, 5 ) to ( 12, 15 ) inclusive.

    Example:

    "place_monster": [
        { "group": "GROUP_REFUGEE_BOSS_ZOMBIE", "name": "Sean McLaughlin", "x": 10, "y": 10, "target": true }
    ]
    

    This places a single random monster from group “GROUP_REFUGEE_BOSS_ZOMBIE”, sets the name to “Sean McLaughlin”, spawns the monster at coordinate (10, 10) and also sets the monster as the target of this mission.

    Example:

    "place_monster": [
        { "monster": "mon_secubot", "x": [ 7, 18 ], "y": [ 7, 18 ], "chance": 30, "repeat": [1, 3] }
    ]
    

    This places “mon_secubot” at random coordinate (7-18, 7-18). The monster is placed with 30% probablity. The placement is repeated by random number of times [1-3].

    Spawn an entire group of monsters with “place_monsters”

    Using place_monsters to spawn a group of monsters works in a similar fashion to place_monster. The key difference is that place_monsters guarantees that each valid entry in the group is spawned. It is strongly advised that you avoid using this flag with larger monster groups, as the total number of spawns is quite difficult to control.

    FieldDescription
    monsterThe ID of the monster group that you wish to spawn
    x, ySpawn coordinates ( specific or area rectangle ). Value: 0-23 or [ 0-23, 0-23 ] - random value between [ a, b ].
    chanceRepresents a 1 in N chance that the entire group will spawn. This is done once for each repeat. If this dice roll fails, the entire group specified will not spawn. Leave blank to guarantee spawns.
    repeatThe spawning is repeated this many times. Can be a number or a range. Again, this represents the number of times the group will be spawned.
    densityThis number is multiplied by the spawn density of the world the player is in and then probabilistically rounded to determine how many times to spawn the group. This is done for each time the spawn is repeated. For instance, if the final multiplier from this calculation ends up being 2, and the repeat value is 6, then the group will be spawned 2 * 6 or 12 times.

    Spawn specific items with a “place_item” array

    optional A list of specific things to add. WIP: Monsters and vehicles will be here too

    Value: [ array of {objects} ]: [ { "item", ... }, ... ]

    Example:

    "place_item": [
        { "item": "weed", "x": 14, "y": 15, "amount": [ 10, 20 ], "repeat": [1, 3], "chance": 20 }
    ]
    
    FieldDescription
    item(required) ID of the item to spawn
    x, y(required) Spawn coordinates. Value from 0-23, or range [ 0-23, 0-23 ] for a random value in that range.
    amount(required) Number of items to spawn. Single integer, or range [ a, b ] for a random value in that range.
    chance(optional) One-in-N chance to spawn item.
    repeat(optional) Value: [ n1, n2 ]. Spawn item randomly between n1 and n2 times. Only makes sense if the coordinates are random. Example: [ 1, 3 ] - repeat 1-3 times.

    Spawn artifacts with a “place_artifact” array

    optional A list of artifacts to spawn. Use natural: true with an optional property to spawn a natural artifact, otherwise a random artifact is created. For mapping-style usage, the special type is artifact (or artifacts).

    Example:

    "place_artifact": [
        { "x": 12, "y": 10 },
        { "x": [ 4, 18 ], "y": [ 4, 18 ], "repeat": [ 1, 2 ], "natural": true, "property": "ARTPROP_GLOWING" }
    ]
    
    FieldDescription
    x, y(required) Spawn coordinates. Value from 0-23, or range [ 0-23, 0-23 ] for a random value in that range.
    repeat(optional) Value: [ n1, n2 ]. Spawn artifacts randomly between n1 and n2 times. Only makes sense if the coordinates are random. Example: [ 1, 3 ] - repeat 1-3 times.
    chance(optional) Percentage chance to spawn the artifact.
    natural(optional) If true, spawn a natural artifact.
    property(optional) ARTPROP_* value for the natural artifact property. If omitted, a random property is chosen.

    Extra map features with specials

    optional Special map features that do more than just placing furniture / terrain.

    Specials can be defined either via a mapping like the terrain / furniture mapping using the “rows” entry above or through their exact location by its coordinates.

    The mapping is defined with a json object like this:

    "<type-of-special>" : {
        "A" : { <data-of-special> },
        "B" : { <data-of-special> },
        "C" : { <data-of-special> },
        ...
    }
    

    "<type-of-special>" is one of the types listed below. <data-of-special> is a json object with content specific to the special type. Some types require no data at all or all their data is optional, an empty object is enough for those specials. You can define as many mapping as you want.

    Each mapping can be an array, for things that can appear several times on the tile (e.g. items, fields) each entry of the array is applied in order. For traps, furniture and terrain, one entry is randomly chosen (all entries have the same chances) and applied.

    Example (places grass at 2/3 of all ‘.’ square and dirt at 1/3 of them):

    "terrain" : {
        ".": [ "t_grass", "t_grass", "t_dirt" ]
    }
    

    It is also possible to specify the number of instances (and consequently their chance) directly, which is particularly useful for rare occurrences (rather than repeating the common value many times):

    "terrain" : {
        ".": [ [ "t_grass", 2 ], "t_dirt" ]
    }
    

    It is also possible to specify a color palette to apply The palette is a mapgen_color_palette

    Can also defined an inline palette as a seperate option

    "terrain": {
      "|": { "ter": "t_wall_paintable", "palette": "plaster_wall_palette" }
    }
    
    Example (places a blood and a bile field on each '.' square):
    
    ```json
    "fields" : {
        ".": [ { "field": "fd_blood" }, { "field": "fd_bile" } ]
    }
    

    Or define the mappings for one character at once:

    "mapping" : {
        ".": {
            "traps": "tr_beartrap",
            "field": { "field": "fd_blood" },
            "item": { "item": "corpse" },
            "terrain": { "t_dirt" }
        }
    }
    

    This might be more useful if you want to put many different type of things on one place.

    Defining specials through their specific location:

    "place_<type-of-special>" : {
        { "x": <x>, "y": <y>, <data-of-special> },
        ...
    }
    

    <x> and <y> define where the special is placed (x is horizontal, y vertical). Valid value are in the range 0..23, min-max values are also supported: "x": [ 0, 23 ], "y": [ 0, 23 ] places the special anyway on the map.

    Example with mapping (the characters "O" and ";" should appear in the rows array where the specials should appear):

    "gaspumps": {
        "O": { "amount": 1000 }
    },
    "toilets": {
        ";": { }
    }
    

    The amount of water to be placed in toilets is optional, an empty entry is therefor completely valid.

    Example with coordinates:

    "place_gaspumps": [
        { "x": 14, "y": 15, "amount": [ 1000, 2000 ] }
    ],
    "place_toilets": [
        { "x": 19, "y": 22 }
    ]
    

    Terrain, furniture and traps can specified as a single string, not a json object:

    "traps" : {
        ".": "tr_beartrap"
    }
    

    Same as

    "traps" : {
        ".": { "trap": "tr_beartrap" }
    }
    

    Place smoke, gas, or blood with “fields”

    FieldDescription
    field(required, string) the field type (e.g. "fd_blood", "fd_smoke")
    density(optional, integer) field density. Defaults to 1. Possible values are 1, 2, or 3.
    intensity(optional, integer) how concentrated the field is, from 1 to 3 or more. See data/json/field_type.json
    age(optional, integer) field age. Defaults to 0.

    Place NPCs with “npcs”

    Example:

    "npcs": { "A": { "class": "NC_REFUGEE", "target": true, "add_trait": "ASTHMA" } }
    
    FieldDescription
    class(required, string) the npc class id, see data/json/npcs/npc.json or define your own npc class.
    target(optional, bool) this NPC is a mission target. Only valid for update_mapgen.
    add_trait(optional, string or string array) this NPC gets these traits, in addition to any from the class definition.

    Place signs with “signs”

    Places a sign (furniture f_sign) with a message written on it. Either “signage” or “snippet” must be defined. The message may include tags like <full_name>, <given_name>, and <family_name> that will insert a randomly generated name, or <city> that will insert the nearest city name.

    Example:

    "signs": { "P": { "signage": "Subway map: <city> stop" } }
    
    FieldDescription
    signage(optional, string) the message that should appear on the sign.
    snippet(optional, string) a category of snippets that can appear on the sign.

    Place a vending machine and items with “vendingmachines”

    Places a vending machine (furniture) and fills it with items from an item group. The machine can sometimes spawn as broken one.

    FieldDescription
    item_group(optional, string) the item group that is used to create items inside the machine. It defaults to either “vending_food” or “vending_drink” (randomly chosen).

    Place a toilet with some amount of water with “toilets”

    Places a toilet (furniture) and adds water to it.

    FieldDescription
    amount(optional, integer or min/max array) the amount of water to be placed in the toilet.

    Place a gas or diesel pump with some fuel with “gaspumps”

    Places a gas pump with gasoline (or sometimes diesel) in it.

    FieldDescription
    amount(optional, integer or min/max array) the amount of fuel to be placed in the pump.
    fuel(optional, string: “gasoline” or “diesel”) the type of fuel to be placed in the pump.

    Place items from an item group with “items”

    FieldDescription
    item(required, string or itemgroup object) the item group / itype_id to use.
    chance(optional, integer or min/max array) x in 100 chance that a loop will continue to spawn items from the group (which itself may spawn multiple items or not depending on its type, see ITEM_SPAWN.md), unless the chance is 100, in which case it will trigger the item group spawn exactly 1 time (see map::place_items).
    repeat(optional, integer or min/max array) the number of times to repeat this placement, default is 1.

    Place monsters from a monster group with “monsters”

    The actual monsters are spawned when the map is loaded. Fields:

    FieldDescription
    monster(required, string) a monster group id, when the map is loaded, a random monsters from that group are spawned.
    density(optional, float) if defined, it overrides the default monster density at the location (monster density is bigger towards the city centers) (see map::place_spawns).
    chance(optional, integer or min/max array) one in x chance of spawn point being created (see map::place_spawns).

    Place a vehicle by type or group with “vehicles”

    FieldDescription
    vehicle(required, string) type of the vehicle or id of a vehicle group.
    chance(optional, integer or min/max array) x in 100 chance of the vehicle spawning at all. The default is 1 (which means 1% probability that the vehicle spawns, you probably want something larger).
    rotation(optional, integer) the direction the vehicle faces.
    fuel(optional, integer) the fuel status. Default is -1 which makes the tanks 1-7% full. Positive values are interpreted as percentage of the vehicles tanks to fill (e.g. 100 means completely full).
    status(optional, integer) default is -1 (light damage), a value of 0 means perfect condition, 1 means heavily damaged.
    place_beyond_bounds(optional, integer) semi-dangerous value that allows for all collisions outside the 24x24 OMT to be ignored, allowing for larger vehicles to spawn

    Place a specific item with “item”

    FieldDescription
    item(required, string) the item type id of the new item.
    chance(optional, integer or min/max array) one in x chance that the item will spawn. Default is 1, meaning it will always spawn.
    amount(optional, integer or min/max array) the number of items to spawn, default is 1.
    repeat(optional, integer or min/max array) the number of times to repeat this placement, default is 1.

    To use this type with explicit coordinates use the name “place_item” (this if for backwards compatibility) like this:

    "item": {
        "x": { "item": "rock" }
    },
    "place_item": [
        { "x": 10, "y": 1, "item": "rock" }
    ]
    

    Place a specific monster with “monster”

    FieldDescription
    monster(required, string) type id of the monster (e.g. mon_zombie).
    friendly(optional, bool) whether the monster is friendly, default is false.
    name(optional, string) a name for that monster, optional, default is to create an unnamed monster.
    target(optional, bool) this monster is a mission target. Only valid for update_mapgen.

    Place a trap with “traps”

    FieldDescription
    trap(required, string) type id of the trap (e.g. tr_beartrap).

    Place furniture with “furniture”

    FieldDescription
    furn(required, string) type id of the furniture (e.g. f_chair).

    Place terrain with “terrain”

    If the terrain has the value “roof” set and is in an enclosed space, it’s indoors.

    FieldDescription
    ter(required, string) type id of the terrain (e.g. t_floor).

    Place rubble and smash existing terrain with “rubble”

    Creates rubble and bashes existing terrain (this step is applied last, after other things like furniture/terrain have been set). Creating rubble invokes the bashing function that can destroy terrain and cause structures to collapse.

    FieldDescription
    rubble_type(optional, furniture id, default: f_rubble) the type of the created rubble.
    items(optional, bool, default: false) place items that result from bashing the structure.
    floor_type(optional, terrain id, default: t_dirt) only used if there is a non-bashable wall at the location or with overwrite = true.
    overwrite(optional, bool, default: false) if true it just writes on top of what currently exists.

    To use this type with explicit coordinates use the name “place_rubble” (no plural) like this:

    "place_rubble": [
        { "x": 10, "y": 1 }
    ]
    

    Place spilled liquids with “place_liquids”

    Creates a liquid item at the specified location. Liquids can’t currently be picked up (except for gasoline in tanks or pumps), but can be used to add flavor to mapgen.

    FieldDescription
    liquid(required, item id) the item (a liquid)
    amount(optional, integer/min-max array) amount of liquid to place (a value of 0 defaults to the item’s default charges)
    chance(optional, integer/min-max array) one in x chance of spawning a liquid, default value is 1 (100%)

    Example for dropping a default amount of gasoline (200 units) on the ground (either by using a character in the rows array or explicit coordinates):

    "liquids": {
        "g": { "liquid": "gasoline" }
    },
    "place_liquids": [
        { "liquid": "gasoline", "x": 3, "y": 5 }
    ],
    

    Place a specific item or an item from a group with “loot”

    Places item(s) from an item group, or an individual item. An important distinction between this and place_item and item/items is that loot can spawn a single item from a distribution group (without looping). It can also spawn a matching magazine and ammo for guns.

    Note: Either group or item must be specified, but not both.

    FieldDescription
    group(string) the item group to use (see ITEM_SPAWN.md for notes on collection vs distribution groups)
    item(string) the type id of the item to spawn
    chance(optional, integer) x in 100 chance of item(s) spawning. Defaults to 100.
    ammo(optional, integer) x in 100 chance of item(s) spawning with the default amount of ammo. Defaults to 0.
    magazine(optional, integer) x in 100 chance of item(s) spawning with the default magazine. Defaults to 0.

    Plant seeds in a planter with “sealed_item”

    Places an item or item group inside furniture that has special handling for items.

    This is intended for furniture such as f_plant_harvest with the PLANT flag, because placing items on such furniture via the other means will not work (since they have the NOITEM FLAG).

    On such furniture, there is supposed to be a single (hidden) seed item which dictates the species of plant. Using sealed_item, you can create such plants by specifying the furniture and a seed item.

    Note: Exactly one of “item” or “items” must be given (but not both).

    FieldDescription
    furniture(string) the id of the chosen furniture.
    itemspawn an item as the “item” special
    itemsspawn an item group as the “items” special.

    Example:

    "sealed_item": {
      "p": {
        "items": { "item": "farming_seeds", "chance": 100 },
        "furniture": "f_plant_harvest"
      }
    },
    

    Place messages with “graffiti”

    Places a graffiti message at the location. Either “text” or “snippet” must be defined. The message may include tags like <full_name>, <given_name>, and <family_name> that will insert a randomly generated name, or <city> that will insert the nearest city name.

    FieldDescription
    text(optional, string) the message that will be placed.
    snippet(optional, string) a category of snippets that the message will be pulled from.

    Place a zone for an NPC faction with “zones”

    NPCs in the faction will use the zone to influence the AI.

    FieldDescription
    type(required, string) Values: "NPC_RETREAT", "NPC_NO_INVESTIGATE", or "NPC_INVESTIGATE_ONLY".
    faction(required, string) the faction id of the NPC faction that will use the zone.
    name(optional, string) the name of the zone.

    The type field values affect NPC behavior. NPCs will:

    • Prefer to retreat towards NPC_RETREAT zones.
    • Not move to the see the source of unseen sounds coming from NPC_NO_INVESTIGATE zones.
    • Not move to the see the source of unseen sounds coming from outside NPC_INVESTIGATE_ONLY zones.

    Translate terrain type with “translate_ter”

    Translates one type of terrain into another type of terrain. There is no reason to do this with normal mapgen, but it is useful for setting a baseline with update_mapgen.

    FieldDescription
    from(required, string) the terrain id of the terrain to be transformed
    to(required, string) the terrain id that the from terrain will transformed into

    Apply mapgen transformation with “ter_furn_transforms”

    Run a ter_furn_transform at the specified location. This is mostly useful for applying transformations as part of an update_mapgen, as normal mapgen can just specify the terrain directly.

    • “transform”: (required, string) the id of the ter_furn_transform to run.

    Spawn nested chunks based on overmap neighbors with “place_nested”

    Place_nested allows for limited conditional spawning of chunks based on the "id"s of their overmap neighbors and the joins that were used in placing a mutable overmap special. This is useful for creating smoother transitions between biome types or to dynamically create walls at the edges of a mutable structure.

    FieldDescription
    chunks/else_chunks(required, string) the nested_mapgen_id of the chunk that will be conditionally placed. Chunks are placed if the specified neighbor matches, and “else_chunks” otherwise.
    x and y(required, int) the cardinal position in which the chunk will be placed.
    neighbors(optional) Any of the neighboring overmaps that should be checked before placing the chunk. Each direction is associated with a list of overmap "id" substrings.
    joins(optional) Any mutable overmap special joins that should be checked before placing the chunk. Each direction is associated with a list of join "id" strings.
    connections(optional) Any connection that should be directed toward this overmap before placing the chunk. Each direction is associated with a list of connection "id" strings.
    rotation(optional) How many turns to rotate the map, 90 degree turns

    The adjacent overmaps which can be checked in this manner are:

    • the direct cardinal neighbors ( "north", "east", "south", "west" ),
    • the inter cardinal neighbors ( "north_east", "north_west", "south_east", "south_west" ),
    • the direct vertical neighbors ( "above", "below" ).

    Joins can be checked only for the cardinal directions, "above", and "below"

    Example:

    "place_nested": [
      { "chunks": [ "concrete_wall_ew" ], "x": 0, "y": 0, "neighbors": { "north": [ "empty_rock", "field" ] }, "rotation": 0  },
      { "chunks": [ "gate_north" ], "x": 0, "y": 0, "joins": { "north": [ "interior_to_exterior" ] } },
      { "else_chunks": [ "concrete_wall_ns" ], "x": 0, "y": 0, "neighbors": { "north_west": [ "field", "microlab" ] } }
    ],
    

    The code excerpt above will place chunks as follows:

    • "concrete_wall_ew" if the north neighbor is either a field or solid rock
    • "gate_north" if the join "interior_to_exterior" was used to the north during mutable overmap placement.
    • "concrete_wall_ns"if the north west neighbor is neither a field nor any of the microlab overmaps.

    Clear an area before placing it

    If it’s the entire nested section

    "flags": [ "ERASE_ALL_BEFORE_PLACING_TERRAIN" ]
    

    Otherwise give xy coordinates with place_remove_all, or use palette with remove_all on a character This always runs before anything else

    Mapgen values

    A mapgen value can be used in various places where a specific id is expected. For example, the default value of a parameter, or a terrain id in the "terrain" object. A mapgen value can take one of three forms:

    • A simple string, which should be a literal id. For example, "t_flat_roof".
    • A JSON object containing the key "distribution", whose corresponding value is a list of lists, each a pair of a string id and an integer weight. For example:
    { "distribution": [ [ "t_flat_roof", 2 ], [ "t_tar_flat_roof", 1 ], [ "t_shingle_flat_roof", 1 ] ] }
    
    • A JSON object containing the key "param", whose corresponding value is the string name of a parameter as discussed in Mapgen parameters. For example, { "param": "roof_type" }.

      You may be required to also supply a fallback value, such as { "param": "roof_type", "fallback": "t_flat_roof" }. The fallback is necessary to allow mapgen definitions to change without breaking an ongoing game. Different parts of the same overmap special can be generated at different times, and if a new parameter is added to the definition part way through the generation then the value of that parameter will be missing and the fallback will be used.

    • A switch statement to select different values depending on the value of some other mapgen value. This would most often be used to switch on the value of a mapgen parameter, so as to allow two parts of the mapgen to be consistent. For example, the following switch would match a fence gate type to a fence type chosen by a mapgen parameter fence_type:

    {
      "switch": { "param": "fence_type", "fallback": "t_splitrail_fence" },
      "cases": {
        "t_splitrail_fence": "t_splitrail_fencegate_c",
        "t_chainfence": "t_chaingate_c",
        "t_fence_barbed": "t_gate_metal_c",
        "t_privacy_fence": "t_privacy_fencegate_c"
      }
    }
    

    Mapgen parameters

    (Note that this feature is under development and functionality may not line up exactly with the documentation.)

    Another entry within a mapgen definition or palette can be a "parameters" key. For example:

    "parameters": {
      "roof_type": {
        "type": "ter_str_id",
        "default": { "distribution": [ [ "t_flat_roof", 2 ], [ "t_tar_flat_roof", 1 ], [ "t_shingle_flat_roof", 1 ] ] }
      }
    },
    

    Each entry in the "parameters" JSON object defines a parameter. The key is the parameter name. Each such key should have an associated JSON object. That object must provide its type (which should be a type string as for a cata_variant) and may optionally provide a default value. The default value should be a mapgen value as defined above.

    At time of writing, the only way for a parameter to get a value is via the "default", so you probably want to always have one.

    The primary application of parameters is that you can use a "distribution" mapgen value to select a value at random, and then apply that value to every use of that parameter. In the above example, a random roof terrain is picked. By using the parameter with some "terrain" key, via a "param" mapgen value, you can use a random but consistent choice of roof terrain across your map. In contrast, placing the "distribution" directly in the "terrain" object would cause mapgen to choose a terrain at random for each roof tile, leading to a mishmash of roof terrains.

    By default, the scope of a parameter is the overmap_special being generated. That is, the parameter will have the same value across the overmap_special. When a default value is needed, it will be chosen when the first chunk of that special is generated, and that value will be saved to be reused for later chunks.

    If you wish, you may specify "scope": "omt" to limit the scope to just a single overmap tile. Then a default value will be chosen independently for each OMT. This has the advantage that you are no longer forced to select a "fallback" value when using that parameter in mapgen.

    The third option for scope is "scope": "nest". This only makes sense when used in nested mapgen (although it is not an error to use it elsewhere, so that the same palette may be used for nested and non-nested mapgen). When the scope is nest, the value of the parameter is chosen for a particular nested chunk. For example, suppose a nest defines a carpet across several tiles, you can use a parameter to ensure that the carpet is the same colour for all the tiles within that nest, but another instance of the same nested_mapgen_id elsewhere in the same OMT might choose a different colour.

    To help you debug mapgen parameters and their effect on mapgen, you can see the chosen values for overmap_special-scoped parameters in the overmap editor (accessible via the debug menu).

    Rotate the map with “rotation”

    Rotates the generated map after all the other mapgen stuff has been done. The value can be a single integer or a range (out of which a value will be randomly chosen). Example: "rotation": [ 0, 3 ]

    Values are 90° steps.

    Pre-load a base mapgen with “predecessor_mapgen”

    Specifying an overmap terrain id here will run the entire mapgen for that overmap terrain type first, before applying the rest of the mapgen defined here. The primary use case for this is when our mapgen for a location takes place in a natural feature like a forest, swamp, or lake shore. Many existing JSON mapgen attempt to emulate the mapgen of the type they’re being placed on (e.g. a cabin in the forest has placed the trees, grass and clutter of a forest to try to make the cabin fit in) which leads to them being out of sync when the generation of that type changes. By specifying the predecessor_mapgen, you can instead focus on the things that are added to the existing location type.

    Example: "predecessor_mapgen": "forest"

    Palettes

    A palette provides a way to use the same symbol definitions for different pieces of mapgen. For example, most of the houses defined in CDDA us the standard_domestic_palette. That palette, for example, defines h as meaning f_chair, so all the house mapgen can use h in its "rows" array without needing to repeat this definition everywhere. It simply requires a reference to the palette, achieved by adding

    "palettes": [ "standard_domestic_palette" ]
    

    to the definition of each house.

    Each piece of mapgen can refer to multiple palettes. When two palettes both define meanings for the same symbol, both are applied. In some cases (such as spawning items) you can see the results of both in the final output. In other cases (such as setting terrain or furniture) one result must override the others. The rule is that the last palette listed overrides earlier ones, and definitions in the outer mapgen override anything in the palettes within.

    Palette definitions can contain any of the JSON described above for the JSON object definition where it is defining a meaning for a symbol. They cannot specify anything for a particular location (using "x" and "y" coordinates.

    Palettes can themselves include other palettes via a "palettes" key. So if two or more palettes would have many of the same symbols with the same meanings that common part can be pulled out into a new palette which each of them includes, so that the definitions need not be repeated.

    Palette ids as mapgen values

    The values in the "palettes" list need not be simple strings. They can be any mapgen value as described above. Most importantly, this means that they can use a "distribution" to select from a set of palettes at random.

    This selection works as if it were an overmap special-scoped mapgen parameter. So, all OMTs within a special will use the same palette. Moreover, you can see which palette was chosen by looking at the overmap special arguments displayed in the overmap editor (accessible via the debug menu).

    For example, the following JSON used in a cabin mapgen definition

    "palettes": [ { "distribution": [ [ "cabin_palette", 1 ], [ "cabin_palette_abandoned", 1 ] ] } ],
    

    causes half the cabins generated to use the regular cabin_palette and the other half to use cabin_palette_abandoned.

    Using update_mapgen

    update_mapgen is a variant of normal JSON mapgen. Instead of creating a new overmap tile, it updates an existing overmap tile with a specific set of changes. Currently, it only works within the NPC mission interface, but it will be expanded to be a general purpose tool for modifying existing maps.

    update_mapgen generally uses the same fields as JSON mapgen, with a few exceptions. update_mapgen has a few new fields to support missions, as well as ways to specify which overmap tile will be updated.

    Overmap tile specification

    update_mapgen updates an existing overmap tile. These fields provide a way to specify which tile to update.

    “assign_mission_target”

    assign_mission_target assigns an overmap tile as the target of a mission. Any update_mapgen in the same scope will update that overmap tile. The closet overmap terrain with the required terrain ID will be used, and if there is no matching terrain, an overmap special of om_special type will be created and then the om_terrain within that special will be used.

    FieldDescription
    om_terrain(required, string) the overmap terrain ID of the mission target
    om_special(required, string) the overmap special ID of the mission target

    “om_terrain”

    The closest overmap tile of type om_terrain in the closest overmap special of type om_special will be used. The overmap tile will be updated but will not be set as the mission target.

    FieldDescription
    om_terrain(required, string) the overmap terrain ID of the mission target
    om_special(required, string) the overmap special ID of the mission target

    Mission specials

    update_mapgen adds new optional keywords to a few mapgen JSON items.

    “target”

    place_npc, place_monster, and place_computer can take an optional target boolean. If they have "target": true and are invoked by update_mapgen with a valid mission, then the NPC, monster, or computer will be marked as the target of the mission.

    Mapgen Color Palette

    {
      "type": "mapgen_color_palette", // Mandatory type
      "id": "plaster_wall_palette", // Id of the palette
      "colors": [
        "Emerald Green", // Named Colors
        "Purple", // Fuzzy Matched Named Colors
        "Carmine Red", // With a default weight of 100
        {
          "color": "#ffffff", // Can also be hex codes
          "weight": 600, // With a specified weight
        },
      ],
    }
    

    Overmap Generation

    Overview

    The overmap is what you see in the game when you use the view map (m) command.

    It looks something like this:

    ...>│<......................│..............P.FFFF├─FF...
    ..┌─┼─┐.....................│..............FFFFF┌┘FFFF..
    ..│>│^│.....................│..............FF┌─┬┘FFFFF.F
    ──┘...└──┐..............>│<.│..............F┌┘F│FFFFFFF─
    .........└──┐........vvO>│v.│............FF┌┘FF│FFFFFFFF
    ............└┐.......─┬──┼─>│<........┌─T──┘FFF└┐FFFFFFF
    .............│.......>│<$│S.│<.......┌┘..FFFFFFF│FFF┌─┐F
    ..O.........┌┴──┐....v│gF│O.│<v......│...FFFFFF┌┘F.F│F└─
    .OOOOO.....─┘...└─────┼──┼──┼────────┤....FFFFF│FF..│FFF
    .O.O.....dddd.......^p│^>│OO│<^......└─┐FFFFFFF├────┴─FF
    .........dddd........>│tt│<>│..........│FFF..FF│FFFFF.FF
    .........dddd......┌──┘tT├──...........│FFF..F┌┘FFFFFFFF
    .........dddd......│....>│^^..H........└┐...FF│FFFFFFFFF
    ..................┌┘.....│<.............└─┐FF┌┘FFFFFFFFF
    ..................│......│................│FF│FFFFFFFFFF
    .................┌┘......│................│F┌┘FFFFFFFFFF
    ...FFF...........│......┌┘...............┌┘.│FFFFFFFFFFF
    FFFFFF...........│.....┌┘................│FF│FFFFFFFFFFF
    FFFFFF..FFFF.....│.....B..........─┐.....│┌─┘F..FFFFFFFF
    

    In the context of overmap generation, the overmap is the collection of data and features that define the locations in the game world at a more abstract level than the local map that the player directly interacts with, providing the necessary context for local map generation to occur.

    By example, the overmap tells the game:

    • where the cities are
    • where the roads are
    • where the buildings are
    • what types the buildings are

    but it does not tell the game:

    • what the actual road terrain looks like
    • what the actual building layout looks like
    • what items are in the building

    It can sometimes be useful to think of the overmap as the outline for the game world which will then be filled in as the player explores. The rest of this document is a discussion of how we can create that outline.

    Terminology and Types

    First we need to briefly discuss some of the data types used by the overmap.

    overmap_terrain

    The fundamental unit of the overmap is the overmap_terrain, which defines the id, name, symbol, color (and more, but we’ll get to that) used to represent a single location on the overmap. The overmap is 180 overmap terrains wide, 180 overmap terrains tall, and 21 overmap terrains deep (these are the z-levels).

    In this example snippet of an overmap, each character corresponds one entry in the overmap which references a given overmap terrain:

    .v>│......FFF│FF
    ──>│<....FFFF│FF
    <.>│<...FFFFF│FF
    O.v│vv.vvv┌──┘FF
    ───┼──────┘.FFFF
    F^^|^^^.^..F.FFF
    

    So for example, the F is a forest which has a definition like this:

    {
      "type": "overmap_terrain",
      "id": "forest",
      "name": "forest",
      "sym": "F",
      "color": "green"
    }
    

    and the ^ is a house which has a definition like this:

    {
      "type": "overmap_terrain",
      "id": "house",
      "name": "house",
      "sym": "^",
      "color": "light_green"
    }
    

    It’s important to note that a single overmap terrain definition is referenced for every usage of that overmap terrain in the overmap–if we were to change the color of our forest from green to red, every forest in the overmap would be red.

    overmap_special / city_building

    The next important concept for the overmap is that of the overmap_special and city_building. These types, which are similar in structure, are the mechanism by which multiple overmap terrains can be collected together into one conceptual entity for placement on the overmap. If you wanted to have a sprawling mansion, a two story house, a large pond, or a secret lair placed under an unassuming bookstore, you would need to use an overmap_special or a city_building.

    These types are effectively a list of the overmap terrains that compose them, the placement of those overmap terrains relative to each other, and some data used to drive the placement of the overmap special / city building (e.g. how far from a city, should be it connected to a road, can it be placed in a forest/field/river, etc).

    overmap_connection

    Speaking of roads, the concept of linear features like roads, sewers, subways, railroads, and forest trails are managed through a combination of overmap terrain attributes and another type called an overmap_connection.

    An overmap connection effectively defines the types of overmap terrain on which a given connection can be made, the “cost” to make that connection, and the type of terrain to be placed when making the connection. This, for example, is what allows us to say that:

    • a road may be placed on fields, forests, swamps and rivers
    • fields are preferred over forests, which are preferred over swamps, which are preferred over rivers
    • a road crossing a river will be a bridge

    The overmap_connection data will then be used to create a linear road feature connecting two points, applying the previously defined rules.

    overmap_location

    We’ve previously mentioned defining valid overmap terrain types for the placement of overmap specials, city buildings, and overmap connections, but one thing to clarify is these actually leverage another type called an overmap_location rather than referencing overmap_terrain values directly.

    Simply put, an overmap_location is just a named collection of overmap_terrain values.

    For example, here are two simple definitions.

    {
        "type": "overmap_location",
        "id": "forest",
        "terrains": ["forest"]
    },
    {
        "type": "overmap_location",
        "id": "wilderness",
        "terrains": ["forest", "field"]
    }
    

    The value of these is that they allow for a given overmap terrain to belong to several different locations and provide a level of indirection so that when new overmap terrains are added (or existing ones removed), only the relevant overmap_location entries need to be changed rather than every overmap_connection, overmap_special, and city_building that needs those groups.

    For example, with the addition of a new forest overmap terrain forest_thick, we only have to update these definitions as follows:

    {
        "type": "overmap_location",
        "id": "forest",
        "terrains": ["forest", "forest_thick"]
    },
    {
        "type": "overmap_location",
        "id": "wilderness",
        "terrains": ["forest", "forest_thick", "field"]
    }
    

    Overmap Terrain

    Rotation

    If an overmap terrain can be rotated (i.e. it does not have the NO_ROTATE flag), then when the game loads the definition from JSON, it will create the rotated definitions automatically, suffixing the id defined here with _north, _east, _south or _west. This will be particularly relevant if the overmap terrains are used in overmap_special or city_building definitions, because if those are allowed to rotate, it’s desirable to specify a particular rotation for the referenced overmap terrains (e.g. the _north version for all).

    Fields

    IdentifierDescription
    typeMust be overmap_terrain.
    idUnique id.
    nameName for the location shown in game.
    symSymbol used when drawing the location, like "F" (or you may use an ASCII value like 70).
    colorColor to draw the symbol in. See COLOR.md.
    looks_likeId of another overmap terrain to be used for the graphical tile, if this doesn’t have one.
    connect_groupSpecify that this overmap terrain might be graphically connected to its neighbours, should a tileset wish to. It will connect to any other overmap_terrain with the same connect_group.
    see_costAffects player vision on overmap. Higher values obstruct vision more.
    travel_costAffects pathfinding cost. Higher values are harder to travel through (reference: Forest = 10 )
    extrasReference to a named map_extras in region_settings, defines which map extras can be applied.
    mondensitySummed with values for adjacent overmap terrains to influence density of monsters spawned here.
    spawnsSpawns added once at mapgen. Monster group, % chance, population range (min/max).
    flagsSee Overmap terrains in json_flags.md.
    mapgenSpecify a C++ mapgen function. Don’t do this–use JSON.
    mapgen_straightSpecify a C++ mapgen function for a LINEAR feature variation. Prefer JSON instead.
    mapgen_curvedSpecify a C++ mapgen function for a LINEAR feature variation. Prefer JSON instead.
    mapgen_endSpecify a C++ mapgen function for a LINEAR feature variation. Prefer JSON instead.
    mapgen_teeSpecify a C++ mapgen function for a LINEAR feature variation. Prefer JSON instead.
    mapgen_four_waySpecify a C++ mapgen function for a LINEAR feature variation. Prefer JSON instead.

    Example

    A real overmap_terrain wouldn’t have all these defined at the same time, but in the interest of an exhaustive example…

    {
      "type": "overmap_terrain",
      "id": "field",
      "name": "field",
      "sym": ".",
      "color": "brown",
      "looks_like": "forest",
      "see_cost": 2,
      "extras": "field",
      "mondensity": 2,
      "spawns": { "group": "GROUP_FOREST", "population": [0, 1], "chance": 13 },
      "flags": ["NO_ROTATE"],
      "mapgen": [{ "method": "builtin", "name": "bridge" }],
      "mapgen_straight": [{ "method": "builtin", "name": "road_straight" }],
      "mapgen_curved": [{ "method": "builtin", "name": "road_curved" }],
      "mapgen_end": [{ "method": "builtin", "name": "road_end" }],
      "mapgen_tee": [{ "method": "builtin", "name": "road_tee" }],
      "mapgen_four_way": [{ "method": "builtin", "name": "road_four_way" }]
    }
    

    Overmap Special

    An overmap special is an entity that is placed in the overmap after the city generation process has completed–they are the “non-city” counterpart to the city_building type. They commonly are made up of multiple overmap terrains (though not always), may have overmap connections (e.g. roads, sewers, subways), and have JSON-defined rules guiding their placement.

    Placement rules

    For each special, mapgen first decides how many instances it wants to place by rolling a random number between min and max of its occurrences. This number will be adjusted with a few multipliers: configured specials density, terrain ratio, and crowdedness ratio.

    The “terrain ratio” is a number representing the ratio between land and lake tiles on the overmap. A 30% flooded overmap will have a 0.7 multiplier for land specials and a 0.3 multiplier for lake specials.

    The “crowdedness ratio” is a number representing the ratio between the total overmap area and the expected average area required to place all specials with the current range and density settings. It is capped and normally stays at x1. However, trying to spawn more specials than physically possible will cause it to decrease.

    After considering all these factors, it may result in a number such as 2.4, which means that the overmap will have a 60% chance to place 2 instances and a 40% chance to place 3 instances of that special. The final number will never be lower than the raw min value of occurrences.

    Once the exact amount is chosen, mapgen will search for places to spawn specials. If a special depends on a city, its instances will be distributed in the vicinity of different matching cities. For example, if mapgen wants to place three instances and the overmap has two cities of the required size, it won’t place more than two instances near the same city.

    Fixed vs mutable specials

    There are two subtypes of overmap special: fixed and mutable. Fixed overmap specials have a fixed defined layout which can span many OMTs, and can rotate (see below) but will always look essentially the same.

    Mutable overmap specials have a more flexible layout. They are defined in terms of a collection of overmap terrains and the ways they can fit together, like a jigsaw puzzle where pieces can fit together in multiple ways. This can be used to form more organic shapes, such as tunnels dug underground by giant ants, or larger sprawling buildings with mismatched wings and extensions.

    Mutable specials require a lot more care to design such that they can be reliably placed without error.

    Rotation

    In general, it is desirable to define your overmap special as allowing rotation–this will provide variety in the game world and allow for more possible valid locations when attempting to place the overmap special. A consequence of the relationship between rotating an overmap special and rotating the underlying overmap terrains that make up the special is that the overmap special should reference a specific rotated version of the associated overmap terrain–generally, this is the _north rotation as it corresponds to the way in which the JSON for mapgen is defined.

    Locations

    The overmap special has two mechanisms for specifying the valid locations (overmap_location) that it may be placed on. Each individual entry in overmaps may have the valid locations specified, which is useful if different parts of a special are allowed on different types of terrain (e.g. a dock that should have one part on the shore and one part in the water). If all values are the same, locations may instead be specified for the entire special using the top level locations key, The value for an individual entry takes precedence over the top level value, so you may define the top level value and then only specify it for individual entries that differ.

    Fields

    IdentifierDescription
    typeMust be "overmap_special".
    idUnique id.
    connectionsList of overmap connections and their relative [ x, y, z ] location within the special.
    place_nestedArray of { "point": [x, y, z], "special": id } with nested specials, relative to this one.
    subtypeEither "fixed" or "mutable". Defaults to "fixed" if not specified.
    locationsList of overmap_location ids that the special may be placed on.
    city_distanceMin/max distance from a city that the special may be placed. Use -1 for unbounded.
    city_sizesMin/max city size for a city that the special may be placed near. Use -1 for unbounded.
    occurrencesMin/max number of occurrences when placing the special. If UNIQUE flag is set, becomes X of Y chance.
    flagsSee Overmap specials in json_flags.md.
    rotateWhether the special can rotate. True if not specified.

    Depending on the subtype, there are further relevant fields:

    Further fields for fixed overmap specials

    IdentifierDescription
    overmapsList of overmap terrains and their relative [ x, y, z ] location within the special.
    absolute_spawn_locObject of { "x": 0, "y": 0, "do_absolute_spawn_loc": bool } which define the absolute overmap this will spawn in. Do absolute spawn loc is optional and is for overwriting mods

    Further fields for mutable overmap specials

    IdentifierDescription
    check_for_locationsList of pairs [ [ x, y, z ], [ locations, ... ] ] defining the locations that must exist for initial placement.
    check_for_locations_areaList of check_for_locations area objects to be considered in addition to the explicit check_for_locations pairs.
    overmapsDefinitions of the various overmaps and how they join to one another.
    rootThe initial overmap from which the mutable special will be grown.
    sharedList of multipliers defined as "id": value that can be used to scale some parts of the special.
    phasesA specification of how to grow the overmap special from the root OMT.

    Example fixed special

    [
      {
        "type": "overmap_special",
        "id": "campground",
        "overmaps": [
          { "point": [0, 0, 0], "overmap": "campground_1a_north", "locations": ["forest_edge"] },
          { "point": [1, 0, 0], "overmap": "campground_1b_north" },
          { "point": [0, 1, 0], "overmap": "campground_2a_north" },
          { "point": [1, 1, 0], "overmap": "campground_2b_north" }
        ],
        "connections": [{ "point": [1, -1, 0], "connection": "local_road", "from": [1, 0, 0] }],
        "locations": ["forest"],
        "city_distance": [10, -1],
        "city_sizes": [3, 12],
        "occurrences": [0, 5],
        "flags": ["CLASSIC"],
        "rotate": true
      }
    ]
    

    Fixed special overmaps

    IdentifierDescription
    point[ x, y, z] of the overmap terrain within the special.
    overmapId of the overmap_terrain to place at the location.
    locationsList of overmap_location ids that this overmap terrain may be placed on.

    Connections

    IdentifierDescription
    point[ x, y, z] of the connection end point. Cannot overlap an overmap terrain entry for the special.
    connectionId of the overmap_connection to build.
    fromOptional point [ x, y, z] within the special to treat as the origin of the connection.

    Example mutable special

    [
      {
        "type": "overmap_special",
        "id": "anthill",
        "subtype": "mutable",
        "locations": ["subterranean_empty"],
        "city_distance": [25, -1],
        "city_sizes": [0, 20],
        "occurrences": [0, 1],
        "flags": ["CLASSIC", "WILDERNESS"],
        "check_for_locations": [
          [[0, 0, 0], ["land"]],
          [[0, 0, -1], ["subterranean_empty"]],
          [[1, 0, -1], ["subterranean_empty"]],
          [[0, 1, -1], ["subterranean_empty"]],
          [[-1, 0, -1], ["subterranean_empty"]],
          [[0, -1, -1], ["subterranean_empty"]]
        ],
        "//1": "Same as writing out 'check_for_locations' 9 times with different points.",
        "check_for_locations_area": [
            [ { "type": [ "subterranean_empty" ], "from": [ 1, 1, -2 ], "to": [ -1, -1, -2 ] } ]
        ],
        "//2": "The anthill will have 3 possible sizes",
        "shared": { "size": [ 1, 3 ] },
        "joins": ["surface_to_tunnel", "tunnel_to_tunnel"],
        "overmaps": {
          "surface": { "overmap": "anthill", "below": "surface_to_tunnel", "locations": ["land"] },
          "below_entrance": {
            "overmap": "ants_nesw",
            "above": "surface_to_tunnel",
            "north": "tunnel_to_tunnel",
            "east": "tunnel_to_tunnel",
            "south": "tunnel_to_tunnel",
            "west": "tunnel_to_tunnel"
          },
          "crossroads": {
            "overmap": "ants_nesw",
            "north": "tunnel_to_tunnel",
            "east": "tunnel_to_tunnel",
            "south": "tunnel_to_tunnel",
            "west": "tunnel_to_tunnel"
          },
          "tee": {
            "overmap": "ants_nes",
            "north": "tunnel_to_tunnel",
            "east": "tunnel_to_tunnel",
            "south": "tunnel_to_tunnel"
          },
          "straight_tunnel": {
            "overmap": "ants_ns",
            "north": "tunnel_to_tunnel",
            "south": "tunnel_to_tunnel"
          },
          "corner": { "overmap": "ants_ne", "north": "tunnel_to_tunnel", "east": "tunnel_to_tunnel" },
          "dead_end": { "overmap": "ants_end_south", "north": "tunnel_to_tunnel" },
          "queen": { "overmap": "ants_queen", "north": "tunnel_to_tunnel" },
          "larvae": { "overmap": "ants_larvae", "north": "tunnel_to_tunnel" },
          "food": { "overmap": "ants_food", "north": "tunnel_to_tunnel" }
        },
        "root": "surface",
        "phases": [
          [{ "overmap": "below_entrance", "max": 1 }],
          [
            "//1": "Shared multiplier 'size' will affect the size",
            "//2": "of the tunnel system generated in this phase.",
            { "overmap": "straight_tunnel", "max": 10, "scale": "size" },
            { "overmap": "corner", "max": { "poisson": 2.5 }, "scale": "size" },
            { "overmap": "tee", "max": 5, "scale": "size" }
          ],
          [{ "overmap": "queen", "max": 1 }],
          [{ "overmap": "food", "max": 5 }, { "overmap": "larvae", "max": 5 }],
          [
            { "overmap": "dead_end", "weight": 2000 },
            { "overmap": "straight_tunnel", "weight": 100 },
            { "overmap": "corner", "weight": 100 },
            { "overmap": "tee", "weight": 10 },
            { "overmap": "crossroads", "weight": 1 }
          ]
        ]
      }
    ]
    

    How mutable specials are placed

    Overmaps and joins

    Note: “overmap” in the following context should not be confused with “overmap level” or “overmap” as a 180x180 chunk of OMTs that the near-infinite world map is divided into.

    A mutable special has a collection of overmaps which define the OMTs used to build it and joins which define the way in which they are permitted to connect with one another. Each overmap may specify a join for each of its edges (four cardinal directions, above, and below). These joins must match the opposite join for the adjacent overmap in that direction.

    In the above example, we see that the surface overmap specifies "below": "surface_to_tunnel", meaning that the join below it must be surface_to_tunnel. So, the overmap below must specify "above": "surface_to_tunnel". Only the below_entrance overmap does that, so we know that overmap must be placed beneath the surface overmap.

    Overmaps can always be rotated, so a north constraint can correspond to other directions. So, the above dead_end overmap can represent a dead end tunnel in any direction, but it’s important that the chosen OMT ants_end_south is consistent with the north join for the generated map to make sense.

    Overmaps can also specify connections. For example, an overmap might be defined as:

    "where_road_connects": {
      "overmap": "road_end_north",
      "west": "parking_lot_to_road",
      "connections": { "north": { "connection": "local_road" } }
    }
    

    Once the mutable special placement is complete, a local_road connection will be built from the north edge of this overmap (again, ‘north’ is a relative term, that will rotate as the overmap is rotated) in the same way as connections are built for fixed specials. ‘Existing’ connections are not supported for mutable specials.

    Placement rules can also declare point-based connections. The coordinates are relative to the rule’s origin and rotate with the rule, including when it places a multi-tile chunk:

    {
      "overmap": "where_road_connects",
      "connections": [{ "point": [2, 0, 0], "connection": "local_road" }]
    }
    

    The optional from point supplies an initial direction, as it does for fixed specials. Omitting from creates a disconnected connection: it can connect the specified point to an existing road from any direction, without requiring a connection to the placed overmap itself. If no existing connection can be reached, an undirected connection does not create a road stub. These rule-level connections can be used alongside directional connections on individual overmaps.

    Layout phases

    After all the joins and overmaps are defined, the manner in which the special is laid out is given by root and phases.

    root specifies the overmap which is placed first, at the origin point for this special.

    Then phases gives a list of growth phases used to place more overmaps. These phases are processed strictly in order.

    Each phase is a list of rules. Each rule specifies an overmap and an integer max and/or weight.

    Weight must always be a simple integer, but max may also be an object defining a probability distribution over integers. Each time the special is spawned, a value is sampled from that distribution. Poisson distribution is supported via an object such as { "poisson": 5 } where 5 will be the mean of the distribution (λ). Flat distribution is supported via [min, max] pairs. max can also be scaled by another multiplier shared within the special, allowing to scale amounts of multiple different overmaps proportionaly to each other. Each shared multiplier can be defined as a probability distribution same way as the max value, and it is also sampled once on special placement.

    Within each phase, the game looks for unsatisfied joins from the existing overmaps and attempts to find an overmap from amongst those available in its rules to satisfy that join. Priority is given to whichever joins are listed first in the list which defines the joins for this special, but if multiple joins of the same (highest priority) id are present then one is chosen at random.

    First the rules are filtered to contain only those which can satisfy the joins for a particular location, and then a weighted selection from the filtered list is made. The weight is given by the minimum of max and weight specified in the rule. The difference between max and weight is that each time a rule is used, max is decremented by one. Therefore, it limits the number of times that rule can be chosen. Rules which only specify weight can be chosen an arbitrary number of times.

    If no rule in the current phase is able to satisfy the joins for a particular location, that location is set aside to be tried again in later phases.

    Once all joins are either satisfied or set aside, the phase ends and generation proceeds to the next phase.

    If all phases complete and unsatisfied joins remain, this is considered an error and a debugmsg will be displayed with more details.

    Chunks

    A placement rule in the phases can specify multiple overmaps to be placed in a particular configuration. This is useful if you want to place some feature that’s larger than a single OMT. Here is an example from the microlab:

    {
      "name": "subway_chunk_at_-2",
      "chunk": [
        { "overmap": "microlab_sub_entry", "pos": [0, 0, 0], "rot": "north" },
        { "overmap": "microlab_sub_station", "pos": [0, -1, 0] },
        { "overmap": "microlab_subway", "pos": [0, -2, 0] }
      ],
      "max": 1
    }
    

    The "name" of a chunk is only for debugging messages when something goes wrong. "max" and "weight" are handled as above.

    The new feature is "chunk" which specifies a list of overmaps and their relative positions and rotations. The overmaps are taken from the ones defined for this special. Rotation of "north" is the default, so specifying that has no effect, but it’s included here to demonstrate the syntax.

    The postions and rotations are relative. The chunk can be placed at any offset and rotation, so long as all the overmaps are shifted and rotated together like a rigid body.

    Techniques to avoid placement errors

    To help avoid these errors, some additional features of the mutable special placement can help you.

    check_for_locations

    check_for_locations defines a list of extra constraints that are checked before the special is attempted to be placed. Each constraint is a pair of a position (relative to the root) and a set of locations. The existing OMT in each postion must fall into one of the given locations, else the attempted placement is aborted.

    The check_for_locations constraints ensure that the below_entrance overmap can be placed below the root and that all four cardinal-adjacent OMTs are subterranean_empty, which is needed to add any further overmaps satisfying the four other joins of below_entrance.

    check_for_locations_area lets you define an area to check instead of having to repeat check_for_locations for individual points.

    into_locations

    Each join also has an associated list of locations. This defaults to the locations for the special, but it can be overridden for a particular join like this:

    "joins": [
      { "id": "surface_to_surface", "into_locations": [ "land" ] },
      "tunnel_to_tunnel"
    ]
    

    For an overmap to be placed when satisfying an unresolved join, it is not sufficient for it to satisfy the existing joins adjacent to a particular location. Any residual joins it possesses beyond those which already match up must point to OMTs with terrains consistent with that join’s locations.

    For the particular case of the anthill example above, we can see how these two additions ensure that placement is always successful and no unsatisfied joins remain.

    The next few phases of placement will attempt to place various tunnels. The join constraints will ensure that the unsatisfied joins (the open ends of tunnels) will always point into subterranean_empty OMTs.

    Ensuring complete coverage in the final phase

    In the final phase, we have five different rules intended to cap off any unsatisfied joins without growing the anthill further. It is important that the rules whose overmaps have fewer joins get higher weights. In the normal case, every unsatisfied join will be simply closed off using dead_end. However, we also have to cater for the possibility that two unsatisfied joins point to the same OMT, in which case dead_end will not fit (and will be filtered out), but straight_tunnel or corner will, and one of those will likely be chosen since they have the highest weights. We don’t want tee to be chosen (even though it might fit) because that would lead to a new unsatisfied join and further grow the tunnels. But it’s not a big problem if tee is chosen occasionally in this situation; the new join will likely simply be satisfied using dead_end.

    When designing your own mutable overmap specials, you will have to think through these permutations to ensure that all joins will be satisfied by the end of the last phase.

    Optional joins

    Rather than having lots of rules designed to satisfy all possible situations in the final phase, in some situations you can make this easier using optional joins. This feature can also be used in other phases.

    When specifying the joins associated with an overmap in a mutable special, you can elaborate with a type, like this example from the Crater overmap special:

    "overmaps": {
      "crater_core": {
        "overmap": "crater_core",
        "north": "crater_to_crater",
        "east": "crater_to_crater",
        "south": "crater_to_crater",
        "west": "crater_to_crater"
      },
      "crater_edge": {
        "overmap": "crater",
        "north": "crater_to_crater",
        "east": { "id": "crater_to_crater", "type": "available" },
        "south": { "id": "crater_to_crater", "type": "available" },
        "west": { "id": "crater_to_crater", "type": "available" }
      }
    },
    

    The definition of crater_edge has one mandatory join to the north, and three ‘available’ joins to the other cardinal directions. The semantics of an ‘available’ join are that it will not be considered an unresolved join, and therefore will never cause more overmaps to be placed, but it can satisfy other joins into a particular tile when necessary to allow an existing unresolved join to be satisfied.

    The overmap will always be rotated in such a way that as many of its mandatory joins as possible are satisfied and available joins are left to point in other directions that don’t currently need joins.

    As such, this crater_edge overmap can satisfy any unresolved joins for the Crater special without generating any new unresolved joins of its own. This makes it great to finish off the special in the final phase.

    Third type of joins - ‘optional’, it’s a mix of both above - they do actively generate new unresolved joins to build upon, but such joins are not mandatory, and can be left unvesolved.

    Since ‘optional’ and ‘available’ joins does not require any kind of resolving they may end in undesired places, that can be preventrd by adding pseudo-join of ‘reject’ type, which will forbid other joins of same id linking to it.

    Asymmetric joins

    Sometimes you want two different OMTs to connect, but wouldn’t want either to connect with themselves. In this case you wouldn’t want to use the same join on both. Instead, you can define two joins which form a pair, by specifying one as the opposite of the other.

    Another situation where this can arise is when the two sides of a join need different location constraints. For example, in the anthill, the surface and subterranean components need different locations. We could improve the definition of its joins by making the join between surface and tunnels asymmetric, like this:

    "joins": [
      { "id": "surface_to_tunnel", "opposite": "tunnel_to_surface" },
      { "id": "tunnel_to_surface", "opposite": "surface_to_tunnel", "into_locations": [ "land" ] },
      "tunnel_to_tunnel"
    ],
    

    As you can see, the tunnel_to_surface part of the pair needs to override the default value of into_locations because it points towards the surface.

    Alternative joins

    Sometimes you want the next phase(s) of a mutable special to be able to link to existing unresolved joins without themselves generating any unresolved joins of that type. This helps to create a clean break between the old and the new.

    For example, this happens in the microlab_mutable special. This special has some structured hallway OMTs surrounded by a clump of microlab OMTs. The hallways have hallway_to_microlab joins pointing out to their sides, so we need microlab OMTs to have microlab_to_hallway joins (the opposite of hallway_to_microlab) in order to match them.

    However, we don’t want the unresolved edges of a microlab OMT to require more hallways all around, so we mostly want them to use microlab_to_microlab joins. How can we satisfy these apparently conflicting requirements without making many different variants of microlab with different numbers of each type of join? Alternative joins can help us here.

    The definition of the microlab overmap might look like this:

    "microlab": {
      "overmap": "microlab_generic",
      "north": { "id": "microlab_to_microlab", "alternatives": [ "microlab_to_hallway" ] },
      "east": { "id": "microlab_to_microlab", "alternatives": [ "microlab_to_hallway" ] },
      "south": { "id": "microlab_to_microlab", "alternatives": [ "microlab_to_hallway" ] },
      "west": { "id": "microlab_to_microlab", "alternatives": [ "microlab_to_hallway" ] }
    },
    

    This allows it to join with hallways which are already placed on the overmap, but new unresolved joins will only match more microlabs.

    Testing your new mutable special

    If you want to exhaustively test your mutable special for placement errors, and you are in a position to compile the game, then an easy way to do so is to use the existing test in tests/overmap_test.cpp.

    In that file, look for TEST_CASE( "mutable_overmap_placement". At the start of that function there is a list of mutable special ids that tests tries spawning. Replace one of them with your new special’s id, recompile and run the test.

    The test will attempt to place your special a few thousand times, and should find most ways in which placement might fail.

    Joins

    A join definition can be a simple string, which will be its id. Alternatively, it can be a dictionary with some of these keys:

    IdentifierDescription
    idId of the join being defined.
    oppositeId of the join which must match this one from the adjacent terrain.
    into_locationsList of overmap_location ids that this join may point towards.

    Mutable special overmaps

    The overmaps are a JSON dictionary. Each overmap must have an id (local to this special) which is the JSON dictionary key, and then the fields within the value may be:

    IdentifierDescription
    overmapId of the overmap_terrain to place at the location.
    locationsList of overmap_location ids that this overmap terrain may be placed on. If not specified, defaults to the locations value from the special definition.
    northJoin which must align with the north edge of this OMT
    eastJoin which must align with the east edge of this OMT
    southJoin which must align with the south edge of this OMT
    westJoin which must align with the west edge of this OMT
    aboveJoin which must link this to the OMT above
    belowJoin which must link this to the OMT below

    Each join associated with a direction can be a simple string, interpreted as a join id. Alternatively it can be a JSON object with the following keys:

    IdentifierDescription
    idId of the join used here.
    typeEither "mandatory" or "available". Default: "mandatory".
    alternativesList of join ids that may be used instead of the one listed under id, but only when placing this overmap. Unresolved joins created by its placement will only be the primary join id.

    Generation rules

    IdentifierDescription
    overmap or chunkId of the overmap to place, chunk configuration.
    joinId of join which must be resolved during current phase.
    zZ level restrictions for this phase.
    om_posAbsolute coordinates [ x, y ] of the overmap (180x180 chunk of the world) this phase is allowed to run in.
    rotateTrue or false, whether current piece can be rotated or not. Takes a priority over special’s rotatable property.
    maxMaximum number of times this rule should be used.
    scaleId of the shared multiplier to scale the max by.
    weightWeight with which to select this rule.

    Z level restrictions supports numbers, ["min", "mix"] ranges with absolute coordinate restrictions, “top”"bottom“ strings refering to boundaries of other tiles of special placed so far, and objects with “top”"bottom“ properties and offsets from above boundaries.

    One of max and weight must be specified. max will be used as the weight when weight is not specified.

    City Building

    A city building is an entity that is placed in the overmap during the city generation process–they are the “city” counterpart to the overmap_special type. The definition for a city building is a subset of that for an overmap special, and consequently will not be repeated in detail here.

    Mandatory Overmap Specials / Region Settings

    City buildings are not subject to the same quantity limitations as overmap specials, and in fact the occurrences attribute does not apply at all. Instead, the placement of city buildings is driven by the frequency assigned to the city building within the region_settings. Consult REGION_SETTINGS.md for more details.

    Fields

    IdentifierDescription
    typeMust be “city_building”.
    idUnique id.
    overmapsAs in overmap_special, with one caveat: all point x and y values must be >= 0.
    locationsAs in overmap_special.
    flagsAs in overmap_special.
    rotateAs in overmap_special.

    Example

    [
      {
        "type": "city_building",
        "id": "zoo",
        "locations": ["land"],
        "overmaps": [
          { "point": [0, 0, 0], "overmap": "zoo_0_0_north" },
          { "point": [1, 0, 0], "overmap": "zoo_1_0_north" },
          { "point": [2, 0, 0], "overmap": "zoo_2_0_north" },
          { "point": [0, 1, 0], "overmap": "zoo_0_1_north" },
          { "point": [1, 1, 0], "overmap": "zoo_1_1_north" },
          { "point": [2, 1, 0], "overmap": "zoo_2_1_north" },
          { "point": [0, 2, 0], "overmap": "zoo_0_2_north" },
          { "point": [1, 2, 0], "overmap": "zoo_1_2_north" },
          { "point": [2, 2, 0], "overmap": "zoo_2_2_north" }
        ],
        "flags": ["CLASSIC"],
        "rotate": true
      }
    ]
    

    Overmap Connection

    Fields

    IdentifierDescription
    typeMust be “overmap_connection”.
    idUnique id.
    default_terrainDefault overmap_terrain to use for undirected connections and existance checks.
    subtypesList of entries used to determine valid locations, terrain cost, and resulting overmap terrain.
    layout(Optional) Connections layout, default is city.

    With city layout each connection point will be linked to the center of closest city. With p2p layout each connection point will be linked to the closest connection of same type.

    Example

    [
      {
        "type": "overmap_connection",
        "id": "local_road",
        "subtypes": [
          { "terrain": "road", "locations": ["field", "road"] },
          { "terrain": "road", "locations": ["forest_without_trail"], "basic_cost": 20 },
          { "terrain": "road", "locations": ["forest_trail"], "basic_cost": 25 },
          { "terrain": "road", "locations": ["swamp"], "basic_cost": 40 },
          { "terrain": "road_nesw_manhole", "locations": [] },
          { "terrain": "bridge", "locations": ["water"], "basic_cost": 120 }
        ]
      },
      {
        "type": "overmap_connection",
        "id": "subway_tunnel",
        "subtypes": [
          { "terrain": "subway", "locations": ["subterranean_subway"], "flags": ["ORTHOGONAL"] }
        ]
      }
    ]
    

    Subtypes

    IdentifierDescription
    terrainovermap_terrain to be placed when the placement location matches locations.
    locationsList of overmap_location that this subtype applies to. Can be empty; signifies terrain is valid as is.
    basic_costCost of this subtype when pathfinding a route. Default 0.
    weightWeight of the item appearing over other items. Default 0.
    flagsSee Overmap connections in json_flags.md.

    Overmap Location

    Fields

    IdentifierDescription
    typeMust be “overmap_location”.
    idUnique id.
    terrainsList of overmap_terrain that can be considered part of this location.

    Example

    [
      {
        "type": "overmap_location",
        "id": "wilderness",
        "terrains": ["forest", "forest_thick", "field", "forest_trail"]
      }
    ]
    

    Region Settings

    The region_settings define the attributes for map generation that apply to an entire region. The general settings define the default overmap terrain and ground cover. Additional sections are as follows:

    SectionDescription
    region_terrain_and_furnitureDefines the resolution of regional terrain/furniture to actual types.
    field_coverageDefines the flora that cover the field overmap terrain.
    overmap_lake_settingsDefines parameters for generating lakes in the region.
    overmap_forest_settingsDefines parameters for generating forests and swamps in the region.
    forest_mapgen_settingsDefines flora (and “stuff”) that cover the forest terrain types.
    forest_trail_settingsDefines the overmap and local structure of forest trails.
    cityDefines the structural compositions of cities.
    map_extrasDefines the map extra groups referenced by overmap terrains.
    base_weatherReferences the base weather definition used by the region.
    overmap_feature_flag_settingsDefines operations on overmap features based on their flags.

    Note that for the default region, all attributes and sections are required.

    Fields

    IdentifierDescription
    typeType identifier. Must be “region_settings”.
    idUnique identifier for this region.
    default_oterDefault overmap terrain for this region.
    default_groundcoverList of terrain types and weights applied as default ground cover.
    base_weatherId of the base_weather definition used by this region.

    Example

    {
      "type": "region_settings",
      "id": "default",
      "default_oter": "field",
      "base_weather": "default",
      "default_groundcover": [
        ["t_grass", 4],
        ["t_dirt", 1]
      ]
    }
    

    Region Terrain / Furniture

    The region_terrain_and_furniture section defines the resolution of regional terrain/furniture to their actual terrain and furniture types for the region, with a weighted list for terrain/furniture entry that defines the relative weight of a given entry when mapgen resolves the regional entry to an actual entry.

    Fields

    IdentifierDescription
    terrainList of regional terrain and their corresponding weighted lists.
    furnitureList of regional furniture and their corresponding weighted lists.

    Example

    {
      "region_terrain_and_furniture": {
        "terrain": {
          "t_region_groundcover": {
            "t_grass": 4,
            "t_grass_long": 2,
            "t_dirt": 1
          }
        },
        "furniture": {
          "f_region_flower": {
            "f_black_eyed_susan": 1,
            "f_lily": 1,
            "f_flower_tulip": 1,
            "f_flower_spurge": 1,
            "f_chamomile": 1,
            "f_dandelion": 1,
            "f_datura": 1,
            "f_dahlia": 1,
            "f_bluebell": 1
          }
        }
      }
    }
    

    Field Coverage

    The field_coverage section defines the furniture and terrain that make up the flora that cover the field overmap terrain.

    Fields

    IdentifierDescription
    percent_coverage% of tiles in the overmap terrain that have a plant.
    default_terDefault terrain feature for plants.
    otherList of features with % chance when default_ter isn’t used.
    boost_chance% of field overmap terrains with boosted plant growth.
    boosted_percent_coverage% of tiles in the boosted that have a plant.
    boosted_otherList of features in the boosted with % chance when default_ter isn’t used.
    boosted_other_percent% of boosted_percent_coverage that will be covered by boosted_other.

    Example

    {
      "field_coverage": {
        "percent_coverage": 0.9333,
        "default_ter": "t_shrub",
        "other": {
          "t_shrub_blueberry": 0.4166,
          "t_shrub_strawberry": 0.4166,
          "f_mutpoppy": 8.3333
        },
        "boost_chance": 0.833,
        "boosted_percent_coverage": 2.5,
        "boosted_other": {
          "t_shrub_blueberry": 40.0,
          "f_dandelion": 6.6
        },
        "boosted_other_percent": 50.0
      }
    }
    

    Overmap Lake Settings

    The overmap_lake_settings section defines the attributes used in generating lakes on the overmap. The actual placement of these features is determined globally across all overmaps so that the edges of the features align, and these parameters are mostly about how those global features are interpreted.

    Fields

    IdentifierDescription
    noise_threshold_lake[0, 1], x > value spawns a lake_surface or lake_shore.
    lake_size_minMinimum size of the lake in overmap terrains for it to actually spawn.
    lake_depthDepth of lakes, expressed in Z-levels (e.g. -1 to -10).
    shore_extendable_overmap_terrainList of overmap terrains that can be extended to the shore if adjacent.
    shore_extendable_overmap_terrain_aliasesOvermap terrains to treat as different overmap terrain for extending shore.

    Example

    {
      "overmap_lake_settings": {
        "noise_threshold_lake": 0.25,
        "lake_size_min": 20,
        "lake_depth": -5,
        "shore_extendable_overmap_terrain": ["forest_thick", "forest_water", "field"],
        "shore_extendable_overmap_terrain_aliases": [
          { "om_terrain": "forest", "om_terrain_match_type": "TYPE", "alias": "forest_thick" }
        ]
      }
    }
    

    Overmap Forest Settings

    The overmap_forest_settings section defines the attributes used in generating forest and swamps on the overmap. The actual placement of these features is determined globally across all overmaps so that the edges of the features align, and these parameters are mostly about how those global features are interpreted.

    Fields

    IdentifierDescription
    noise_threshold_forest[0, 1], x > value spawns forest.
    noise_threshold_forest_thick[0, 1], x > value spawns forest_thick.
    noise_threshold_swamp_adjacent_water[0, 1], x > value spawns forest_water if forest near a waterbody.
    noise_threshold_swamp_isolated[0, 1], x > value spawns forest_water if forest isolated from water.
    river_floodplain_buffer_distance_minMinimum buffer distance in overmap terrains for river floodplains.
    river_floodplain_buffer_distance_maxMaximum buffer distance in overmap terrains for river floodplains.

    Example

    {
      "overmap_forest_settings": {
        "noise_threshold_forest": 0.25,
        "noise_threshold_forest_thick": 0.3,
        "noise_threshold_swamp_adjacent_water": 0.3,
        "noise_threshold_swamp_isolated": 0.6,
        "river_floodplain_buffer_distance_min": 3,
        "river_floodplain_buffer_distance_max": 15
      }
    }
    

    Forest Map Generation Settings

    The forest_mapgen_settings section defines the attributes used in generating forest (forest, forest_thick, forest_water) terrains, including their items, groundcover, terrain and furniture.

    General Structure

    At the top level, the forest_mapgen_settings is a collection of named configurations where each entry has the name of the overmap terrain that it applies to, e.g. forest, forest_thick, forest_water. It is possible to define settings for overmap terrains that are not rendered by the forest mapgen, but will be used when blending forest terrains with other terrain types.

    {
      "forest_mapgen_settings": {
        "forest": {},
        "forest_thick": {},
        "forest_water": {}
      }
    }
    

    Each terrain then has an independent set of configuration values that control the mapgen.

    Fields

    IdentifierDescription
    sparseness_adjacency_factorValue relative to neighbors controls how sparse the overmap terrain will be.
    item_groupItem group used to place items randomly within the overmap terrain.
    item_group_chance% chance, between 1 and 100, that an item will be placed.
    item_spawn_iterationsNumber of times that the item spawning will be called.
    clear_groundcoverClear all previously defined groundcover for this overmap terrain.
    groundcoverWeighted list of terrains used for base groundcover.
    clear_componentsClear all previously defined components for this overmap terrain.
    componentsCollection of components that make up the terrains and furniture placed.
    clear_terrain_furnitureClear all previously defined terrain_furniture for this overmap terrain.
    terrain_furnitureCollection of furniture conditionally placed based on terrain.

    Example

    {
      "forest": {
        "sparseness_adjacency_factor": 3,
        "item_group": "forest",
        "item_group_chance": 60,
        "item_spawn_iterations": 1,
        "clear_groundcover": false,
        "groundcover": {
          "t_grass": 3,
          "t_dirt": 1
        },
        "clear_components": false,
        "components": {},
        "clear_terrain_furniture": false,
        "terrain_furniture": {}
      }
    }
    

    Components

    The components are a collection of named objects with a sequence, chance, and set of types that, during mapgen, are rolled in sequence to pick a feature to be placed at a given location. The names for the components are only relevant for the purposes of overriding them in region overlays.

    Fields

    IdentifierDescription
    sequenceSequence in which components are processed.
    chanceOne in X chance that something from this component will be placed.
    clear_typesClear all previously defined types for this component.
    typesWeighted list of terrains and furniture that make up this component.

    Example

    {
      "trees": {
        "sequence": 0,
        "chance": 12,
        "clear_types": false,
        "types": {
          "t_tree_young": 128,
          "t_tree": 32,
          "t_tree_birch": 32,
          "t_tree_pine": 32,
          "t_tree_maple": 32,
          "t_tree_willow": 32,
          "t_tree_hickory": 32,
          "t_tree_blackjack": 8,
          "t_tree_coffee": 8,
          "t_tree_apple": 2,
          "t_tree_apricot": 2,
          "t_tree_cherry": 2,
          "t_tree_peach": 2,
          "t_tree_pear": 2,
          "t_tree_plum": 2,
          "t_tree_deadpine": 1,
          "t_tree_hickory_dead": 1,
          "t_tree_dead": 1
        }
      },
      "shrubs_and_flowers": {
        "sequence": 1,
        "chance": 10,
        "clear_types": false,
        "types": {
          "t_underbrush": 8,
          "t_shrub_blueberry": 1,
          "t_shrub_strawberry": 1,
          "t_shrub": 1,
          "f_chamomile": 1,
          "f_dandelion": 1,
          "f_datura": 1,
          "f_dahlia": 1,
          "f_bluebell": 1,
          "f_mutpoppy": 1
        }
      }
    }
    

    Terrain Furniture

    The terrain furniture are a collection of terrain ids with a chance of having furniture picked from a weighted list for that given terrain and placed on it during mapgen after the normal mapgen has completed. This is used, for example, to place cattails on fresh water in swamps. Cattails could be simply placed in the components section and placed during the normal forest mapgen, but that would not guarantee their placement on fresh water only, while this does.

    Fields

    IdentifierDescription
    chanceOne in X chance that furniture from this component will be placed.
    clear_furnitureClear all previously defined furniture for this terrain.
    furnitureWeighted list of furniture that will be placed on this terrain.

    Example

    {
      "t_water_sh": {
        "chance": 2,
        "clear_furniture": false,
        "furniture": {
          "f_cattails": 1
        }
      }
    }
    

    Forest Trail Settings

    The forest_trail_settings section defines the attributes used in generating trails in the forests, including their likelihood of spawning, their connectivity, their chance for spawning trailheads, and some general tuning of the actual trail width/position in mapgen.

    Fields

    IdentifierDescription
    chanceOne in X chance a contiguous forest will have a trail system.
    border_point_chanceOne in X chance that the N/S/E/W-most point of the forest will be part of the trail system.
    minimum_forest_sizeMinimum contiguous forest size before a trail system can be spawned.
    random_point_minMinimum # of random points from contiguous forest used to form trail system.
    random_point_maxMaximum # of random points from contiguous forest used to form trail system.
    random_point_size_scalarForest size is divided by this and added to the minimum number of random points.
    trailhead_chanceOne in X chance a trailhead will spawn at end of trail near field.
    trailhead_road_distanceMaximum distance trailhead can be from a road and still be created.
    trail_center_varianceCenter of the trail in mapgen is offset in X and Y by a random amount between +/- variance
    trail_width_offset_minTrail width in mapgen is offset by rng(trail_width_offset_min, trail_width_offset_max).
    trail_width_offset_maxTrail width is mapgen offset by rng(trail_width_offset_min, trail_width_offset_max).
    clear_trail_terrainClear all previously defined trail_terrain.
    trail_terrainWeighted list of terrain that will used for the trail.
    trailheadsWeighted list of overmap specials / city buildings that will be placed as trailheads.

    Example

    {
      "forest_trail_settings": {
        "chance": 2,
        "border_point_chance": 2,
        "minimum_forest_size": 100,
        "random_point_min": 4,
        "random_point_max": 50,
        "random_point_size_scalar": 100,
        "trailhead_chance": 1,
        "trailhead_road_distance": 6,
        "trail_center_variance": 3,
        "trail_width_offset_min": 1,
        "trail_width_offset_max": 3,
        "clear_trail_terrain": false,
        "trail_terrain": {
          "t_dirt": 1
        },
        "trailheads": {
          "trailhead_basic": 50
        }
      }
    }
    

    City

    The city section defines the possible overmap terrains and specials that may be used as buildings in a city, their weighted chances of placement, and some attributes that control the relative placements of various classes of buildings.

    Fields

    IdentifierDescription
    typeCity type identifier–currently unused.
    shop_radiusRadial frequency of shop placement. Smaller number = more shops.
    park_radiusRadial frequency of park placement. Smaller number = more parks.
    housesWeighted list of overmap terrains and specials used for houses.
    parksWeighted list of overmap terrains and specials used for parks.
    shopsWeighted list of overmap terrains and specials used for shops.

    Placing shops, parks, and houses

    When picking a building to place in a given location, the game considers the city size, the location’s distance from the city center, and finally the shop_radius and park_radius values for the region. It then tries to place a shop, then a park, and finally a house, where the chance to place the shop or park are based on the formula rng( 0, 99 ) > X_radius * distance from city center / city size.

    Example

    {
      "city": {
        "type": "town",
        "shop_radius": 80,
        "park_radius": 90,
        "houses": {
          "house_two_story_basement": 1,
          "house": 1000,
          "house_base": 333,
          "emptyresidentiallot": 20
        },
        "parks": {
          "park": 4,
          "pool": 1
        },
        "shops": {
          "s_gas": 5,
          "s_pharm": 3,
          "s_grocery": 15
        }
      }
    }
    

    Map Extras

    The map_extras section defines the named collections of map extras–special mapgen events applied on top of the defined mapgen–that may be referenced by the extras property of an overmap terrain. This includes both the chance of an extra occurring as well as the weighted list of extras.

    Fields

    IdentifierDescription
    chanceOne in X chance that the overmap terrain will spawn a map extra.
    extrasWeighted list of map extras that can spawn.

    Example

    {
      "map_extras": {
        "field": {
          "chance": 90,
          "extras": {
            "mx_helicopter": 40,
            "mx_portal_in": 1
          }
        }
      }
    }
    

    Base Weather

    region_settings and region_overlay now select weather with a base_weather id that points to JSON objects of type base_weather.

    New content should prefer:

    {
      "base_weather": "default"
    }
    

    For compatibility, the loader also accepts these legacy forms:

    • "weather": "default" as an alias for "base_weather": "default"
    • "weather": { ... } as an inline weather definition

    base_weather fields

    IdentifierDescription
    idUnique identifier for this base_weather definition.
    spring_tempAverage spring temperature for the region.
    summer_tempAverage summer temperature for the region.
    autumn_tempAverage autumn temperature for the region.
    winter_tempAverage winter temperature for the region.
    spring_humidity_manual_modHumidity modifier applied during spring.
    summer_humidity_manual_modHumidity modifier applied during summer.
    autumn_humidity_manual_modHumidity modifier applied during autumn.
    winter_humidity_manual_modHumidity modifier applied during winter.
    base_humidityBase humidity for the region in relative humidity %.
    base_pressureBase pressure for the region in millibars.
    base_acidBase acid value for the region. Value >= 1 is considered acidic.
    base_windBase wind for the region in km/h or m/s, e.g. "16 km/h". Roughly the yearly average. Legacy numbers are read as mph.
    base_wind_distrib_peaksHow high the wind peaks can go. Higher values produce windier days.
    base_wind_season_variationHow wind varies with season. Lower values produce more variation.
    temperature_daily_amplitudeHalf the difference between the coldest and warmest parts of the day.
    temperature_noise_amplitudeHalf the difference contributed by 3D weather noise.
    weather_typesIds of the weather types allowed in this region. The first entry is the default weather type. Declaration order affects weather selection; see WEATHER_TYPE.md for details.
    weather_patternsOptional list of weather_pattern ids applied on top of the base weather. Patterns add location and time dependent modifiers and can gate weather types that require specific pattern values.

    Example

    [
      {
        "type": "base_weather",
        "id": "example_weather",
        "spring_temp": 7,
        "summer_temp": 16,
        "autumn_temp": 6,
        "winter_temp": -14,
        "base_humidity": 66.0,
        "summer_humidity_manual_mod": -10,
        "winter_humidity_manual_mod": 12,
        "base_pressure": 1015.0,
        "base_acid": 0.0,
        "base_wind": "9 km/h",
        "base_wind_distrib_peaks": 30,
        "base_wind_season_variation": 64,
        "weather_types": [
          "clear",
          "sunny",
          "cloudy",
          "light_drizzle",
          "drizzle",
          "rain",
          "thunder",
          "lightning",
          "acid_drizzle",
          "acid_rain",
          "flurries",
          "snowing",
          "snowstorm"
        ]
      },
      {
        "type": "region_settings",
        "id": "example_region",
        "default_oter": "field",
        "default_groundcover": [
          ["t_grass", 4],
          ["t_dirt", 1]
        ],
        "base_weather": "example_weather"
      }
    ]
    

    weather_pattern

    weather_pattern is a generic factory used by base_weather.weather_patterns. Each pattern samples 4D noise based on map position, time, and world seed, then uses the result to push the generated weather away from the base averages.

    For each generated weather point, the pattern computes:

    pattern_value = offset + noise * multiplier

    That value is stored under the pattern id and then used to:

    • add to humidity, pressure, windpower, and temperature through the *_mod fields
    • satisfy weather_type entries that require this pattern to reach a minimum value
    • optionally mark the generated weather as acidic for legacy compatibility when acidic is true and pattern_value >= active_threshold

    This means weather_pattern is best used for intermittent regional effects such as acid fronts, storm bands, or other weather variants that should fade in and out over space and time instead of being applied as a constant modifier.

    weather_pattern fields

    IdentifierDescription
    idUnique identifier for this weather_pattern definition.
    x_scaleHorizontal noise scale on the x axis. Larger values make the pattern change faster over distance.
    y_scaleHorizontal noise scale on the y axis. Larger values make the pattern change faster over distance.
    z_scaleTime scale for the noise. Larger values make the pattern change faster over time.
    seed_offsetExtra offset added to the world seed before sampling noise. Use this to decorrelate multiple patterns.
    multiplierMultiplies the sampled noise before other effects are applied. Higher values make stronger swings.
    offsetConstant value added after scaling the noise. Use this to shift the whole pattern upward or downward.
    humidity_modHumidity change applied as humidity_mod * pattern_value.
    pressure_modPressure change applied as pressure_mod * pattern_value.
    windpower_modWind speed change applied as windpower_mod * pattern_value. Uses the same units as base_wind.
    temperature_modTemperature change applied as temperature_mod * pattern_value.
    active_thresholdThreshold commonly used by weather types that check this pattern’s value.
    acidicLegacy compatibility field. When true, weather generated while pattern_value >= active_threshold is treated as acidic.

    weather_pattern example

    [
      {
        "type": "weather_pattern",
        "id": "acidic_front",
        "multiplier": 8.0,
        "active_threshold": 1.0
      },
      {
        "type": "base_weather",
        "id": "example_weather",
        "copy-from": "default",
        "weather_patterns": ["acidic_front"]
      }
    ]
    

    Overmap Feature Flag Settings

    The overmap_feature_flag_settings section defines operations that operate on the flags assigned to overmap features. This is currently used to provide a mechanism for whitelisting and blacklisting locations on a per-region basis.

    Fields

    IdentifierDescription
    clear_blacklistClear all previously defined blacklist.
    blacklistList of flags. Any location with a matching flag will be excluded from overmap generation.
    clear_whitelistClear all previously defined whitelist.
    whitelistList of flags. Only locations with a matching flag will be included in overmap generation.

    Example

    {
      "overmap_feature_flag_settings": {
        "clear_blacklist": false,
        "blacklist": ["FUNGAL"],
        "clear_whitelist": false,
        "whitelist": []
      }
    }
    

    Region Overlay

    A region_overlay allows the specification of region_settings values which will be applied to specified regions, merging with or overwriting the existing values. It is only necessary to specify those values which should be changed.

    For weather changes, overlays should normally set base_weather to another loaded base_weather id instead of embedding a new inline weather object.

    Fields

    IdentifierDescription
    typeType identifier. Must be “region_overlay”.
    idUnique identifier for this region overlay.
    regionsA list of regions to which this overlay should be applied. “all” will apply to all regions.

    All additional fields and sections are the same as for region_settings. Scalar values such as base_weather replace the current value, while nested sections merge into the existing region.

    Example

    [
      {
        "type": "region_overlay",
        "id": "example_overlay",
        "regions": ["all"],
        "city": {
          "parks": {
            "examplepark": 1
          }
        }
      },
      {
        "type": "region_overlay",
        "id": "example_weather_overlay",
        "regions": ["default"],
        "base_weather": "example_weather"
      }
    ]
    

    ter_furn_transform

    A ter_furn_transform is a type of json object that allows you to specify a transformation of a tile from one terrain to another terrain, and from one furniture to another furniture.

    [
      {
        "type": "ter_furn_transform",
        "id": "example",
        "terrain": [
          {
            "result": "t_dirt",
            "valid_terrain": ["t_sand"],
            "message": "sandy!",
            "message_good": true
          }
        ]
      }
    ]
    

    The example above turns “sand” into “dirt”. It does so by comparing the direct terrain ids. In addition, we can add a fail message to the transform. If, however, we wanted to turn sand into “dirt or grass” we can do:

    "terrain": [
      {
        "fail_message": "no sand!",
        "result": [ "t_dirt", "t_grass" ],
        "valid_terrain": [ "t_sand" ],
        "message": "sandy!"
      }
    ]
    

    message_good is optional and defaults to true. This example chooses either dirt or grass at a 1:1 ratio. But, if you want a 4:1 ratio:

    "terrain": [
      {
        "result": [ [ "t_dirt", 4 ], "t_grass" ],
        "valid_terrain": [ "t_sand" ],
        "message": "sandy!"
      }
    ]
    

    As you can see, you can mix and match arrays with weights with single strings. Each single string has a weight of 1.

    All of the above applies to furniture as well.

    "furniture": [
      {
        "result": [ [ "f_null", 4 ], "f_chair" ],
        "valid_furniture": [ "f_hay", "f_woodchips" ],
       "message": "I need a chair"
      }
    ]
    

    You can also use flags instead of specific IDs for both furniture and terrain.

    "terrain": [
      {
        "result": "t_floor",
        "valid_flags": [ "FLAT" ],
        "message": "flooring"
      }
    ]
    

    To target any diggable terrain, use the boolean.

    "terrain": [
      {
        "result": "t_dirt",
        "diggable": true,
        "message": "digdug"
      }
    ]
    

    A ter_furn_transform can have both terrain and furniture fields. It treats them separately, so no “if dirt, add chair.”

    Weather Types

    Weather type specifies conditions under which it can occur (temperature, humidity, pressure, windpower, time of day, etc.) and what effects it causes on the game world and reality bubble.

    When selecting weather type, the game goes over the list defined in region settings and selects the last entry that is considered eligible under current conditions. If none of the entries are eligible, invalid weather type "none" will be used.

    Fields

    IdentifierDescription
    id(mandatory) Unique ID. Must be one continuous word, use underscores if necessary.
    name(mandatory) In-game name displayed.
    glyph(mandatory) Glyph used on overmap.
    color(optional) Color of in-game name.
    map_color(optional) Color of overmap glyph.
    ranged_penalty(mandatory) Penalty to ranged attacks.
    sight_penalty(mandatory) Sight penalty, aka multiplier to tile transparency.
    light_modifier(mandatory) Flat bonus to ambient light.
    sound_attn(mandatory) Sound attenuation (flat reduction to volume).
    dangerous(mandatory) If true, prompts for activity interrupt.
    precip(mandatory) Amount of associated precipitation. Valid values are: none, very_light, light and heavy.
    rains(mandatory) Whether said precipitation falls as rain.
    acidic(optional) Whether said precipitation is acidic.
    sound_category(optional) Sound effects to play. Valid values are: silent, drizzle, rainy, thunder, flurries, snowstorm and snow.
    sun_intensity(mandatory) Sunlight intensity. Valid values are: none, light, normal, and high. Normal and high are considered “direct sunlight”.
    animation(optional) Weather animation in reality bubble. Details
    screen_color_overlay(optional) Full-screen color overlay in tiles mode. Object with color (RGB hex string) and alpha (0-255).
    effects(optional) [string, int] pair array for the effects the weather causes. Details
    requirements(optional) Conditions under which this weather type will be eligible to be selected. Details

    animation

    All members are mandatory.

    IdentifierDescription
    factorDisplay density: 0 is none, 1 will blot out the screen.
    glyphGlyph to use in ASCII mode.
    colorGlyph color.
    tileGraphical tile to use in TILES mode.

    effects

    Universal fields

    IdentifierDescription
    name(mandatory) One of the below listed effects, completely changes the json loaded for some
    intensity(mandatory) Intensity of the effect to give
    Names
    • morale: Gives player morale, requires additional defined fields
    • effect: Gives players an effect, requires additional defined fields
    • wet: Causes players to become wet, amount is intensity
    • thunder: Thunder is caused with a one in intensity chance
    • lightning: Lighning is caused with a one in intensity chance

    Morale

    IdentifierDescription
    intensity(mandatory) This effect is applied every x turns
    bonus(mandatory) Amount of morale each stack gives
    max_bonus(mandatory) Max amount of morale gained
    duration(mandatory) Duration of the morale effect
    decay_start(mandatory) How long until the effect starts to lower in intensity, total duration is this and duration added
    morale_id_str(mandatory) Id of the morale effect applied
    morale_msg(mandatory) Message to give when gaining the morale
    morale_msg_frequency(mandatory) Percent chance to display the message on gaining effect
    message_type(mandatory) Type of message; 0 == Good, 1 == Bad, 2 == Mixed, 3 == Warning, 4 == Info, 5 == Neutral
    Example:
    {
      "name": "morale",
      "intensity": 3,
      "bonus": 2,
      "bonus_max": 60,
      "duration": "180 s",
      "decay_start": "60 s",
      "morale_id_str": "morale_weather_rainbow",
      "morale_msg": "You stare in awe at the rainbow.",
      "morale_msg_frequency": 8,
      "message_type": 0
    }
    

    Effect

    IdentifierDescription
    intensity(mandatory) This effect will be applied every x turns
    duration(mandatory) How long the effect lasts
    effect_id_str(mandatory) String of the effect id to give
    effect_intensity(mandatory) Intensity of the effect to give
    bodypart_string(optional) Bodypart to apply the effect to, default whole body
    effect_msg(mandatory) Message to give when gaining the effect
    effect_msg_frequency(mandatory) Percent chance to display the message on gaining effect
    effect_msg_blocked_frequency(mandatory) Percent chance to display the protection message on preventing effect
    message_type(mandatory) Type of message; 0 == Good, 1 == Bad, 2 == Mixed, 3 == Warning, 4 == Info, 5 == Neutral
    precipitation_name(mandatory) Name to display in string “Your umbrella protects you from the precipitation_name”
    protection_data(optional) Array of check flags or traits ( along with DEFAULT which is always applied ) and odds ( one in x chance ) to be protected from the effect
    Example:
    {
      "name": "effect",
      "intensity": 3,
      "duration": "30 s",
      "effect_id_str": "emp",
      "effect_intensity": 0,
      "precipitation_name": "brain waves",
      "bodypart_string": "head",
      "effect_msg": "You feel an odd wave-like sensation pass through your head.",
      "effect_msg_frequency": 16,
      "effect_msg_blocked_frequency": 32,
      "message_type": 2,
      "protection_data": [
        { "check": "RAIN_PROTECT", "odds": 1 },
        { "check": "ACIDPROOF", "odds": 1 },
        { "check": "DEFAULT", "odds": 2 }
      ]
    }
    

    requirements

    All members are optional.

    IdentifierDescription
    pressure_minMin pressure
    pressure_maxMax pressure
    humidity_minMin humidity
    humidity_maxMax humidity
    temperature_minMin temperature
    temperature_maxMax temperature
    windpower_minMin wind speed in km/h or m/s, e.g. "20 km/h". Legacy numbers are read as mph.
    windpower_maxMax wind speed. Uses the same units as windpower_min.
    humidity_and_pressureIf there are pressure and humidity requirements are they both required or just one
    timeTime of day. Valid values are: day, night, and both.
    required_weathersWill only be selected if conditions match for any of the specified types, i.e. rain can only happen if the conditions for clouds, light drizzle or drizzle are present. Required weathers should be “before” this one in the region weather list.
    required_weather_patternsRequires one or more weather_pattern values. Use an array to require patterns at value >= 0, or an object to set explicit minimum values per pattern id.

    For acid weather and similar variants, prefer required_weather_patterns over the legacy acidic requirement flag. For example:

    "requirements": {
      "required_weathers": [ "drizzle" ],
      "required_weather_patterns": { "acidic": 1.0 }
    }
    

    Example

    {
      "id": "lightning",
      "type": "weather_type",
      "name": "Lightning Storm",
      "color": "c_yellow",
      "map_color": "h_yellow",
      "glyph": "%",
      "ranged_penalty": 4,
      "sight_penalty": 1.25,
      "light_modifier": -45,
      "sound_attn": 8,
      "dangerous": false,
      "precip": "heavy",
      "rains": true,
      "acidic": false,
      "effects": [{ "name": "thunder", "intensity": 50 }, { "name": "lightning", "intensity": 600 }],
      "tiles_animation": "weather_rain_drop",
      "weather_animation": { "factor": 0.04, "color": "c_light_blue", "glyph": "," },
      "screen_color_overlay": { "color": "#bfd6ff", "alpha": 24 },
      "sound_category": "thunder",
      "sun_intensity": "none",
      "requirements": { "pressure_max": 990, "required_weathers": ["thunder"] }
    }
    

    World Types

    World types are used to store data about dimensions. Including the default one

    Warning

    Dimensions are still somewhat experimental, use at your own risk

    Fields

    IdentifierDescription
    id(mandatory) Unique ID.
    name(mandatory) In-game name displayed.
    description(optional) Description of the dimension
    region_settings(optional) Default is default, id of region settings to use.
    generate_overmap(optional) Default true, should connections lakes forests and swamps be generated.
    infinite_bounds(optional) Default true, is the dimension unbounded like the default dimension.
    boundary_terrain(optional) Default “boundary_terrain”, what terrain to put around the bounds of the dimension.
    save_prefix(optional) What string to prefix saves with.
    allow_npc_travel(optional) Default false, weather to allow NPCs to travel to the dimension.
    allow_vehicle_travel(optional) Default false, weather to allow vehicles to travel to the dimension.
    scale_num(optional) Scale of travel in this dimension. 2 means 2x longer travel.
    scale_den(optional) Scale of travel in this dimension. 2 means 2x shorter travel.
    sunrise_summer(optional) Default -1 ( use game options ), hour of sunrise in summer
    sunset_summer(optional) Default -1 ( use game options ), hour of sunset in summer
    sunset_winter(optional) Default -1 ( use game options ), hour of sunset in winter
    sunset_winter(optional) Default -1 ( use game options ), hour of sunset in winter
    sunrise_equinox(optional) Default -1 ( use game options ), hour of sunrise in equinox
    sunset_equinox(optional) Default -1 ( use game options ), hour of sunset in equinox
    pernament_daylight(optional) Default -1 ( use game options ), sets weather it is always day
    pernament_night(optional) Default -1 ( use game options ), sets weather it is always night

    Damage

    Damage instances and simmilar inline values that are commonly reused.

    Kept here for global reference.

    Caution

    This data is not standalone, it is always within another object

    Damage Instance

    There are two ways to define a damage insance, one as if it was a damage unit The other is below

    Fields

    IdentifierDescription
    values(mandatory) An array of damage units

    Example

    {
      "values": [
        {
          "damage_type": "acid",
          "amount": 10,
          "armor_penetration": 4,
          "armor_multiplier": 2.5
        }
      ]
    }
    

    Damage Unit

    Fields

    IdentifierDescription
    damage_type(mandatory) A type of damage
    amount(mandatory) How much damage to do
    armor_penetration(mandatory) How much armor to penetrate per armor piece
    armor_multiplier(mandatory) Multiplier on remaining armor after armor_penetration is applied

    Example

    {
      "damage_type": "acid",
      "amount": 10,
      "armor_penetration": 4,
      "armor_multiplier": 2.5
    }
    

    Damage Types

    The below is a list of all damage types in the game

    • true
    • biological
    • bash
    • cut
    • acid
    • stab
    • bullet
    • heat
    • cold
    • dark
    • light
    • psi
    • electric

    Explosion Data

    This is a piece of inline data reused across many different files Kept here for global reference.

    Caution

    This data is not standalone, it is always within another object

    Fields

    Note

    This doesn’t list the legacy fields and what they do

    IdentifierDescription
    damage(optional) The amount of damage the explosion does
    radius(optional) The radius of the explosion
    fragment(optional) See projectiles
    fragment_effect(optional) Array of fragment effects
    fire(optional) Also spawns fire fields

    Fragment Effect

    IdentifierDescription
    effect(optional) Id of effect to apply
    odds(optional) One in odds chance to apply effect
    min_turns(optional) Minimum turns applied
    max_turns(optional) Maxiumum turns applied

    Example

    {
      "damage": 50,
      "radius": 2,
      "fire": false,
      "fragment_effect": [{ "effect": "onfire", "odds": 2, "min_turns": 4, "max_turns": 8 }],
      "fragment": {
        "impact": { "damage_type": "bullet", "amount": 70, "armor_multiplier": 1 },
        "range": 5
      }
    }
    

    Projectile

    This is a piece of inline data reused across many different files Kept here for global reference.

    Caution

    This data is not standalone, it is always within another object

    Fields

    IdentifierDescription
    impact(mandatory) A damage instance for each projectile
    range(mandatory) The range of the projectile
    speed(optional) Speed of the projectile in meters per second
    aimedcritbonus(optional) The minimum bonus from a crit
    aimedcritmaxbonus(optional) The maximum bonus from a crit

    Example

    {
      "impact": { "damage_type": "bullet", "amount": 70, "armor_multiplier": 1 },
      "range": 5,
      "speed": 1000,
      "aimedcritbonus": 0.0,
      "aimedcritmaxbonus": 0.0
    }
    

    Construction Info

    Note

    This article was recently split off from JSON INFO and likely could use additional work

    Constructions

    "id": "constr_pit_spiked",                                          // Identifier of the construction
    "group": "spike_pit",                                               // Construction group, used to provide description and group related constructions in UI (e.g. different stages of some construction).
    "category": "DIG",                                                  // Construction category
    "required_skills": [ [ "survival", 1 ] ],                           // Skill levels required to undertake construction
    "time": "30 m",                                                     // Time required to complete construction. Integers will be read as minutes or a time string can be used.
    "components": [ [ [ "spear_wood", 4 ], [ "pointy_stick", 4 ] ] ],   // Items used in construction
    "using": [ [ "welding_standard", 5 ] ],                             // (Optional) External requirements to use
    "pre_note": "I am a dwarf and I'm digging a hole!",                 // (Optional) Annotation
    "pre_flags": [ "FLAT" ],                                // (Optional) Flags the terrain must have to be built on
    "needs_diggable": true,                                          // (Optional) Whether the pre-terrain must be diggable
    "pre_terrain": "t_pit",                                             // (Optional) Required terrain to build on
    "pre_furniture": "f_sandbag_half",                                  // (Optional) Required furniture to build on
    "pre_special": "check_down_OK",                                     // (Optional) Hardcoded tile validity checks, refer to construction.cpp 
    "post_terrain": "t_pit_spiked",                                     // (Optional) Terrain type after construction is complete
    "post_furniture": "f_sandbag_wall",                                 // (Optional) Furniture type after construction is complete
    "post_special": "done_dig_stair",                                   // (Optional) Hardcoded completion function, refer to construction.cpp
    "post_flags": [ "keep_items" ],                                     // (Optional) Additional hardcoded effects, refer to construction.cpp. The only one available as of September 2022 is `keep_items`
    "byproducts": [ { "item": "pebble", "charges": [ 3, 6 ] } ],        // (Optional) construction byproducts
    "vehicle_start": false,                                             // (Optional, default false) Whether it will create a vehicle (for hardcode purposes)
    "on_display": false,                                                // (Optional, default true) Whether it will show in player's UI
    "dark_craftable": true,                                             // (Optional, default false) Whether it can be constructed in dark
    

    Construction groups

    "id": "build_wooden_door",            // Group identifier
    "name": "Build Wooden Door",          // Description string displayed in the construction menu
    

    Construction sequences

    Constuction sequences are needed for automatic calculation of basecamp blueprint requirements. Each construction sequence describes steps needed to construct specified terrain or furniture on an empty dirt tile. At any moment, only 1 construction sequence may be defined for any terrain or furniture. For convenience, each non-blacklisted construction recipe that starts from an empty dirt tile automatically generates a one-element-long construction sequence, but only as long as there are no other such construction recipes that would produce the same sequence and there isn’t an explicitly defined sequence with same results.

    "id": "f_workbench",                // Sequence identifier
    "blacklisted": false,               // (Optional) Whether this sequence is blacklisted
    "post_furniture": "f_workbench",    // (Optional) Identifier of resulting furniture
    "post_terrain": "t_rootcellar",     // (Optional) Identifier of resulting terrain
    "elems": [                          // Array of construction identifiers.
      "constr_pit",                     //   First construction must start from an empty dirt tile,
      "constr_rootcellar"               //   and last construction must result in either post_furniture
    ]                                   //   or post_terrain, whichever one has been specified.
                                        //   Leave it empty to exclude the terrain/furniture from blueprint autocalc.
    

    Furniture and Terrain

    Furniture

    {
      "type": "furniture",
      "id": "f_toilet",
      "name": "toilet",
      "symbol": "&",
      "looks_like": "chair",
      "color": "white",
      "move_cost_mod": 2,
      "light_emitted": 5,
      "required_str": 18,
      "flags": ["TRANSPARENT", "BASHABLE", "FLAMMABLE_HARD"],
      "crafting_pseudo_item": "anvil",
      "examine_action": "toilet",
      "close": "f_foo_closed",
      "open": "f_foo_open",
      "lockpick_result": "f_safe_open",
      "lockpick_message": "With a click, you unlock the safe.",
      "provides_liquids": "beer",
      "bash": "TODO",
      "deconstruct": "TODO",
      "max_volume": "1000 L",
      "examine_action": "workbench",
      "workbench": { "multiplier": 1.1, "mass": 10000, "volume": "50L" },
      "boltcut": {
        "result": "f_safe_open",
        "duration": "1 seconds",
        "message": "The safe opens.",
        "sound": "Gachunk!",
        "byproducts": [{ "item": "scrap", "count": 3 }]
      },
      "hacksaw": {
        "result": "f_safe_open",
        "duration": "12 seconds",
        "message": "The safe is hacksawed open!",
        "sound": "Gachunk!",
        "byproducts": [{ "item": "scrap", "count": 13 }]
      },
      "default_vars": {
        "CATEGORYIDS": "[ \"CSC_FOOD_MEAT\", \"CSC_FOOD_VEGGI\", \"CSC_FOOD_PASTA\" ]",
        "CHARGE_PER_MIN": "5",
        "CHARGE_START": "100",
        "CRAFTSPEEDMULT": "1.0"
      }
    }
    

    type

    Fixed string, must be furniture to identify the JSON object as such.

    "id", "name", "symbol", "looks_like", "color", "bgcolor", "max_volume", "open", "close", "bash", "deconstruct", "examine_action", "flgs

    Same as for terrain, see below in the chapter “Common to furniture and terrain”.

    move_cost_mod

    Movement cost modifier (-10 = impassable, 0 = no change). This is added to the movecost of the underlying terrain.

    lockpick_result

    (Optional) When the furniture is successfully lockpicked, this is the furniture it will turn into.

    lockpick_message

    (Optional) When the furniture is successfully lockpicked, this is the message that will be printed to the player. When it is missing, a generic "The lock opens…" message will be printed instead.

    oxytorch

    (Optional) Data for using with an oxytorch.

    oxytorch: {
        "result": "furniture_id", // (optional) furniture it will become when done, defaults to f_null
        "duration": "1 seconds", // ( optional ) time required for oxytorching, default is 1 second
        "message": "You quickly cut the metal", // ( optional ) message that will be displayed when finished
        "byproducts": [ // ( optional ) list of items that will be spawned when finished
            {
                "item": "item_id",
                "count": 100 // exact amount
            },
            {
                "item": "item_id",
                "count": [ 10, 100 ] // random number in range ( inclusive )
            }
        ]
    }
    

    light_emitted

    How much light the furniture produces. 10 will light the tile it’s on brightly, 15 will light that tile and the tiles around it brightly, as well as slightly lighting the tiles two tiles away from the source. For examples: An overhead light is 120, a utility light, 240, and a console, 10.

    boltcut

    (Optional) Data for using with an bolt cutter.

    "boltcut": {
        "result": "furniture_id", // (optional) furniture it will become when done, defaults to f_null
        "duration": "1 seconds", // ( optional ) time required for bolt cutting, default is 1 second
        "message": "You finish cutting the metal.", // ( optional ) message that will be displayed when finished
        "sound": "Gachunk!", // ( optional ) description of the sound when finished
        "byproducts": [ // ( optional ) list of items that will be spawned when finished
            {
                "item": "item_id",
                "count": 100 // exact amount
            },
            {
                "item": "item_id",
                "count": [ 10, 100 ] // random number in range ( inclusive )
            }
        ]
    }
    

    hacksaw

    (Optional) Data for using with an hacksaw.

    "hacksaw": {
        "result": "furniture_id", // (optional) furniture it will become when done, defaults to f_null
        "duration": "1 seconds", // ( optional ) time required for hacksawing, default is 1 second
        "message": "You finish cutting the metal.", // ( optional ) message that will be displayed when finished
        "byproducts": [ // ( optional ) list of items that will be spawned when finished
            {
                "item": "item_id",
                "count": 100 // exact amount
            },
            {
                "item": "item_id",
                "count": [ 10, 100 ] // random number in range ( inclusive )
            }
        ]
    }
    

    required_str

    Strength required to move the furniture around. Negative values indicate an unmovable furniture.

    crafting_pseudo_item

    (Optional) Id of an item (tool) that will be available for crafting when this furniture is range (the furniture acts as an item of that type). Can be made into an array. Example: "crafting_pseudo_item": [ "fake_gridwelder", "fake_gridsolderingiron" ],

    workbench

    (Optional) Can craft here. Must specify a speed multiplier, allowed mass, and allowed volume. Mass/volume over these limits incur a speed penalty. Must be paired with a "workbench" examine_action to function.

    plant_data

    (Optional) This is a plant. Must specify a plant transform, and a base depending on context. You can also add a harvest or growth multiplier if it has the GROWTH_HARVEST flag.

    surgery_skill_multiplier

    (Optional) Surgery skill multiplier (float) applied by this furniture to survivor standing next to it for the purpose of surgery.

    provides_liquids

    (Optional) Dispenses infinite amounts of specified liquid item when interacted. Must be used with "examine_action": "liquid_source" to work.

    fluid_grid

    (Optional) Connects the furniture to a fluid grid. The role determines how it interacts with the grid: tank adds storage, fixture dispenses stored liquids, and transformer or rain_collector changes or produces liquids. Every fluid-grid object must set allow_input, allow_output, and allowed_liquids.

    allowed_liquids can be an array of liquid item ids, or the string "universal". An array limits the object to those liquids. A non-universal output fixture must be assigned one of its allowed liquids that is already stored in the grid; it will then dispense only that liquid until reassigned. Assigning a fixture requires a plumbing kit and consumes one rubber hose; unassigning it requires the kit and returns the hose. A fixture must be unassigned before it can be assigned to another liquid. "universal" lets a fixture select any liquid in the grid each time it is used. For example, use a water allowlist for a sink, and use "universal" only for a fixture that should dispense arbitrary liquids.

    Tank objects also need a positive capacity or use_keg_capacity: true (which uses the furniture’s keg_capacity), and a connected_variant or disconnected_variant furniture id. Universal tanks are assigned one liquid at a time for dispensing. Assigning or unassigning a tank requires a plumbing kit. Assignment consumes one rubber hose, and unassignment returns it. Unassigning does not remove liquid from the tank furniture or shared fluid grid. To change an assignment, unassign the tank, then assign it to a liquid already stored in the connected grid.

    The optional autofill boolean is only valid with allowed_liquids: "universal". It lets an unassigned tank’s capacity be automatically assigned to a liquid when that liquid needs more grid capacity. This is useful when a grid has multiple universal tanks: tanks already assigned to one liquid keep that assignment, while unassigned autofill tanks can be allocated as more storage is needed.

    "fluid_grid": {
      "role": "tank",
      "allow_input": true,
      "allow_output": true,
      "allowed_liquids": "universal",
      "autofill": true,
      "disconnected_variant": "f_standing_tank",
      "use_keg_capacity": true
    }
    

    enchanter_info

    (Optional) array of enchant info objects The following is an enchant info object

    {
      "id": "CVD_DIAMOND_CUT", // Id of the enchantment info, used for saveload ( mandatory )
      "name": "Cutting Diamonds", // Display name on the enchantment ui ( mandatory )
      "enchant": "ENCH_CVD_MACHINE_CUT", // Enchantment id to give ( mandatory )
      "time_to_enchant": "10 minutes", // Time duration of the enchantment ( mandatory )
      "volume_per_time": "250 ml", // Every x volume will multiply time required
      "volume_time_effect": true, // Weather `volume_per_time` is used
      "using": "cvd_diamond", // Requirement info ( mandatory )
      "volume_per_batch": "250 ml", // Every x volume will multiply requirement info
      "volume_batch_effect": true, // Weather `volume_per_batch` is used
      "count_var": "DIAMONDIZE", // Item variable for counting how many can be applied
      "max_count": 10, // Maximum count
      "applied_flag": "DIAMOND", // Flag to apply ( generally useful for editing description)
      "can_use_on": "cvd_machine", // Name of the `enchanter_can_use_on` lua function ( params: ench_id, item ); Checked per item
      "can_make": "cvd_machine", // Name of the `enchanter_can_make` lua function ( params: ench_id ); Checked once per menu opening
      "required_skills": [ { "skill": "magic", "level": 2 } ] // Array of skills needed to do this
    },
    

    default_vars

    (Optional) Default string variables for objects, always a string string pair; Can be used to store arbitrary data or for some data for iuses such as

    • Multicooker
      • “CATEGORYIDS”; String is a json array of categories for applicable recipes
      • “RECIPEIDS”: String is a json array of valid recipes
      • “CHARGE_PER_MIN”: Charges consumed per minute
      • “CHARGE_START”: Charges consumed at start
      • “CRAFTSPEEDMULT”: Multiplier on craft speed

    Terrain

    {
      "type": "terrain",
      "id": "t_spiked_pit",
      "name": "spiked pit",
      "symbol": "0",
      "looks_like": "pit",
      "color": "ltred",
      "move_cost": 10,
      "light_emitted": 10,
      "trap": "spike_pit",
      "fill_result": "t_dirt", // Terrain result from filling this terrain in
      "fill_minutes": 10, // Number of minutes to fill terrain in
      "max_volume": "1000 L",
      "flags": ["TRANSPARENT"],
      "digging_results": {
        "digging_min": 1,
        "result_ter": "t_pit_shallow",
        "num_minutes": 60,
        "items": "digging_sand_50L"
      },
      "connects_to": "WALL",
      "close": "t_foo_closed",
      "open": "t_foo_open",
      "lockpick_result": "t_door_unlocked",
      "lockpick_message": "With a click, you unlock the door.",
      "nail_pull_result": "t_fence_post", // terrain ID to transform into when you use a hammer to pull the nails out
      "nail_pull_items": [8, 5], // nails and planks (respectively) to drop as a result of pulling nails with a hammer. Defaults to 0,0 and thus technically optional even if you add a nail_pull_result.
      "bash": "TODO",
      "deconstruct": "TODO",
      "harvestable": "blueberries",
      "transforms_into": "t_tree_harvested",
      "harvest_season": "WINTER",
      "roof": "t_roof",
      "examine_action": "pit",
      "boltcut": {
        "result": "t_door_unlocked",
        "duration": "1 seconds",
        "message": "The door opens.",
        "sound": "Gachunk!",
        "byproducts": [{ "item": "scrap", "2x4": 3 }]
      },
      "hacksaw": {
        "result": "t_door_unlocked",
        "duration": "12 seconds",
        "message": "The door is hacksawed open!",
        "sound": "Gachunk!",
        "byproducts": [{ "item": "scrap", "2x4": 13 }]
      }
    }
    

    type

    Fixed string, must be “terrain” to identify the JSON object as such.

    "id", "name", "symbol", "looks_like", "color", "bgcolor", "max_volume", "open", "close", "bash", "deconstruct", "examine_action", "flgs

    Same as for furniture, see below in the chapter “Common to furniture and terrain”.

    move_cost

    Move cost to move through. A value of 0 means it’s impassable (e.g. wall). You should not use negative values. The positive value is multiple of 50 move points, e.g. value 2 means the player uses 2 * 50 = 100 move points when moving across the terrain.

    light_emitted

    How much light the terrain emits. 10 will light the tile it’s on brightly, 15 will light that tile and the tiles around it brightly, as well as slightly lighting the tiles two tiles away from the source. For examples: An overhead light is 120, a utility light, 240, and a console, 10.

    digging_results

    (Optional) Fields relating to digging terrain using a shovel

    • "digging_min" - minimum digging quality required for digging this terrain
    • "result_ter" - resulting terrain ID from digging
    • "num_minutes" - number of minutes spent digging
    • "items" - (Optional) either an array of items, or an existing itemgroup ID. Defaults to digging_soil_loam_200L

    lockpick_result

    (Optional) When the terrain is successfully lockpicked, this is the terrain it will turn into.

    lockpick_message

    (Optional) When the terrain is successfully lockpicked, this is the message that will be printed to the player. When it is missing, a generic "The lock opens…" message will be printed instead.

    oxytorch

    (Optional) Data for using with an oxytorch.

    oxytorch: {
        "result": "terrain_id", // terrain it will become when done
        "duration": "1 seconds", // ( optional ) time required for oxytorching, default is 1 second
        "message": "You quickly cut the bars", // ( optional ) message that will be displayed when finished
        "byproducts": [ // ( optional ) list of items that will be spawned when finished
            {
                "item": "item_id",
                "count": 100 // exact amount
            },
            {
                "item": "item_id",
                "count": [ 10, 100 ] // random number in range ( inclusive )
            }
        ]
    }
    

    trap

    (Optional) Id of the build-in trap of that terrain.

    For example the terrain t_pit has the built-in trap tr_pit. Every tile in the game that has the terrain t_pit also has, therefore, an implicit trap tr_pit on it. The two are inseparable (the player can not deactivate the built-in trap, and changing the terrain will also deactivate the built-in trap).

    A built-in trap prevents adding any other trap explicitly (by the player and through mapgen).

    harvestable

    (Optional) If defined, the terrain is harvestable. This entry defines the item type of the harvested fruits (or similar). To make this work, you also have to set one of the harvest_* examine_action functions.

    boltcut

    (Optional) Data for using with an bolt cutter.

    "boltcut": {
        "result": "terrain_id", // terrain it will become when done
        "duration": "1 seconds", // ( optional ) time required for bolt cutting, default is 1 second
        "message": "You finish cutting the metal.", // ( optional ) message that will be displayed when finished
        "sound": "Gachunk!", // ( optional ) description of the sound when finished
        "byproducts": [ // ( optional ) list of items that will be spawned when finished
            {
                "item": "item_id",
                "count": 100 // exact amount
            },
            {
                "item": "item_id",
                "count": [ 10, 100 ] // random number in range ( inclusive )
            }
        ]
    }
    

    hacksaw

    (Optional) Data for using with an hacksaw.

    "hacksaw": {
        "result": "terrain_id", // terrain it will become when done
        "duration": "1 seconds", // ( optional ) time required for hacksawing, default is 1 second
        "message": "You finish cutting the metal.", // ( optional ) message that will be displayed when finished
        "byproducts": [ // ( optional ) list of items that will be spawned when finished
            {
                "item": "item_id",
                "count": 100 // exact amount
            },
            {
                "item": "item_id",
                "count": [ 10, 100 ] // random number in range ( inclusive )
            }
        ]
    }
    

    transforms_into

    (Optional) Used for various transformation of the terrain. If defined, it must be a valid terrain id. Used for example:

    • When harvesting fruits (to change into the harvested form of the terrain).
    • In combination with the HARVESTED flag and harvest_season to change the harvested terrain back into a terrain with fruits.

    harvest_season

    (Optional) On of “SUMMER”, “AUTUMN”, “WINTER”, “SPRING”, used in combination with the “HARVESTED” flag to revert the terrain back into a terrain that can be harvested.

    roof

    (Optional) The terrain of the terrain on top of this (the roof).

    Common To Furniture And Terrain

    Some values can/must be set for terrain and furniture. They have the same meaning in each case.

    id

    Id of the object, this should be unique among all object of that type (all terrain or all furniture types). By convention (but technically not needed), the id should have the “f_” prefix for furniture and the “t_” prefix for terrain. This is not translated. It must not be changed later as that would break save compatibility.

    name

    Displayed name of the object. This will be translated.

    flags

    (Optional) Various additional flags, see “doc/json_flags.md”.

    connects_to

    (Optional) The group of terrains to which this terrain connects. This affects tile rotation and connections, and the ASCII symbol drawn by terrain with the flag “AUTO_WALL_SYMBOL”.

    Current values:

    • CHAINFENCE
    • RAILING
    • WALL
    • WATER
    • WOODFENCE
    • GUTTER

    Example: - , | , X and Y are terrain which share the same connects_to value. O does not have it. X and Y also have the AUTO_WALL_SYMBOL flag. X will be drawn as a T-intersection (connected to west, south and east), Y will be drawn as a horizontal line (going from west to east, no connection to south).

    -X-    -Y-
     |      O
    

    symbol

    ASCII symbol of the object as it appears in the game. The symbol string must be exactly one character long. This can also be an array of 4 strings, which define the symbol during the different seasons. The first entry defines the symbol during spring. If it’s not an array, the same symbol is used all year round.

    comfort

    How comfortable this terrain/furniture is. Impact ability to fall asleep on it. uncomfortable = -999, neutral = 0, slightly_comfortable = 3, comfortable = 5, very_comfortable = 10

    floor_bedding_warmth

    Bonus warmth offered by this terrain/furniture when used to sleep.

    bonus_fire_warmth_feet

    Increase warmth received on feet from nearby fire (default = 300)

    looks_like

    id of a similar item that this item looks like. The tileset loader will try to load the tile for that item if this item doesn’t have a tile. looks_like entries are implicitly chained, so if ‘throne’ has looks_like ‘big_chair’ and ‘big_chair’ has looks_like ‘chair’, a throne will be displayed using the chair tile if tiles for throne and big_chair do not exist. If a tileset can’t find a tile for any item in the looks_like chain, it will default to the ascii symbol.

    color or bgcolor

    Color of the object as it appears in the game. “color” defines the foreground color (no background color), “bgcolor” defines a solid background color. As with the “symbol” value, this can be an array with 4 entries, each entry being the color during the different seasons.

    NOTE: You must use ONLY ONE of “color” or “bgcolor”

    max_volume

    (Optional) Maximal volume that can be used to store items here. Volume in ml and L can be used - “50 ml” or “2 L”

    examine_action

    (Optional) The json function that is called when the object is examined. See “src/iexamine.h”. "lua:NAME" calls game.examine_functions["NAME"] instead (see the Lua cookbook).

    forage_class

    (Optional) Which AUTO_FORAGING options harvest this object automatically: "bushes", "trees", "flowers", or an array of them ([ "bushes", "trees" ]). Terrain is foraged for bushes and trees, furniture for flowers. When omitted, the class follows examine_action: the built-in harvest actions keep their usual classes (shrub_wildveggies/shrub_marloss: bushes, harvest_ter/tree_marloss: trees, harvest_ter_nectar: bushes and trees, harvest_furn/harvest_furn_nectar: flowers) and other actions are not foraged. An entry that sets its own examine_action does not inherit forage_class. Lua examine actions need an explicit forage_class to be auto-foraged.

    close" And "open

    (Optional) The value should be a terrain id (inside a terrain entry) or a furniture id (in a furniture entry). If either is defined, the player can open / close the object. Opening / closing will change the object at the affected tile to the given one. For example one could have object “safe_c”, which “open“s to “safe_o” and “safe_o” in turn “close“s to “safe_c”. Here “safe_c” and “safe_o” are two different terrain (or furniture) types that have different properties.

    bash

    (Optional) Defines whether the object can be bashed and if so, what happens. See “map_bash_info”.

    deconstruct

    (Optional) Defines whether the object can be deconstructed and if so, what the results shall be. See “map_deconstruct_info”.

    pry

    (Optional) Defines whether the object can be pried open and if so, what happens. See “prying_result”.

    map_bash_info

    Defines the various things that happen when the player or something else bashes terrain or furniture.

    {
      "str_min": 80,
      "str_max": 180,
      "str_min_blocked": 15,
      "str_max_blocked": 100,
      "str_min_supported": 15,
      "str_max_supported": 100,
      "sound": "crunch!",
      "sound_vol": 2,
      "sound_fail": "whack!",
      "sound_fail_vol": 2,
      "ter_set": "t_dirt",
      "furn_set": "f_rubble",
      "explosive": 1,
      "collapse_radius": 2,
      "destroy_only": true,
      "bash_below": true,
      "tent_centers": ["f_groundsheet", "f_fema_groundsheet", "f_skin_groundsheet"],
      "items": "bashed_item_result_group"
    }
    

    str_min, str_max, str_min_blocked, str_max_blocked, str_min_supported, str_max_supported

    TODO

    sound, sound_fail, sound_vol, sound_fail_vol

    (Optional) Sound and volume of the sound that appears upon destroying the bashed object or upon unsuccessfully bashing it (failing). The sound strings are translated (and displayed to the player).

    furn_set, ter_set

    The terrain / furniture that will be set when the original is destroyed. This is mandatory for bash entries in terrain, but optional for entries in furniture (it defaults to no furniture).

    explosive

    (Optional) If greater than 0, destroying the object causes an explosion with this strength (see game::explosion).

    destroy_only

    TODO

    bash_below

    TODO

    tent_centers, collapse_radius

    (Optional) For furniture that is part of tents, this defines the id of the center part, which will be destroyed as well when other parts of the tent get bashed. The center is searched for in the given “collapse_radius” radius, it should match the size of the tent.

    items

    (Optional) An item group (inline) or an id of an item group, see doc/ITEM_SPAWN.md. The default subtype is “collection”. Upon successful bashing, items from that group will be spawned.

    map_deconstruct_info

    {
      "furn_set": "f_safe",
      "ter_set": "t_dirt",
      "items": "deconstructed_item_result_group"
    }
    

    furn_set, ter_set

    The terrain / furniture that will be set after the original has been deconstructed. “furn_set” is optional (it defaults to no furniture), “ter_set” is only used upon “deconstruct” entries in terrain and is mandatory there.

    items

    (Optional) An item group (inline) or an id of an item group, see doc/ITEM_SPAWN.md. The default subtype is “collection”. Upon deconstruction the object, items from that group will be spawned.

    prying_result

    {
      "success_message": "You pry open the door.",
      "fail_message": "You pry, but cannot pry open the door.",
      "break_message": "You damage the door!",
      "pry_quality": 2,
      "pry_bonus_mult": 3,
      "noise": 12,
      "break_noise": 10,
      "sound": "crunch!",
      "break_sound": "crack!",
      "breakable": true,
      "difficulty": 8,
      "new_ter_type": "t_door_o",
      "new_furn_type": "f_crate_o",
      "break_ter_type": "t_door_b",
      "break_furn_type": "f_null",
      "break_items": [
        { "item": "2x4", "prob": 25 },
        { "item": "wood_panel", "prob": 10 },
        { "item": "splinter", "count": [1, 2] },
        { "item": "nail", "charges": [0, 2] }
      ]
    }
    

    new_ter_type, new_furn_type

    The terrain / furniture that will be set after the original has been pried open. “furn_set” is optional (it defaults to no furniture), “ter_set” is only used upon “pry” entries in terrain and is mandatory there.

    success_message, fail_message, break_message

    Messages displayed on successfully prying open the terrain / furniture, on failure, or should the terrain / furniture break into something else from a failed pry attempt. break_message is only required if breakable is set to true and break_ter_type is defined.

    pry_quality, pry_bonus_mult, difficulty

    This determines the minimum prying quality needed to attempt to pry open the terrain / furniture, and the chance of successfully prying it open. From iuse.cpp:

    int diff = pry->difficulty;
    diff -= ( ( pry_level - pry->pry_quality ) * pry->pry_bonus_mult );
    
    if( dice( 4, diff ) < dice( 4, p->str_cur ) ) {
        p->add_msg_if_player( m_good, pry->success_message );
    

    difficulty is compared to the character’s current strength during the prying attempt. If the available prying quality of your tool is above the required pry_quality, effective difficulty is reduced at a rate determined by pry_bonus_mult. pry_bonus_mult is optional, and defaults to 1 (meaning for every level of prying quality your tool has beyond the minimum, diff will be reduced by 1).

    noise, break_noise, ‘sound’, ‘break_sound’

    If noise is specified, successfully prying the terrain / furniture open will play sound at the specified volume. If breakable is true and break_noise is specified, breaking the terrain / furniture on a failed prying attempt will play break_noise at the specified volume.

    If noise or break_noise are not specified then prying or breaking the terrain / furniture in question will simply be silent and make no sound, making them optional. sound and break_sound are also optional, with default messages of “crunch!” and “crack!” respectively.

    breakable, break_ter_type, break_furn_type

    If breakable is set to true, then failed pry attempts have a chance of breaking the terrain / furniture instead. For terrain, break_ter_type is mandatory if breakable is set to true, break_furn_type is optional and defaults to null.

    break_items

    (Optional) An item group (inline) or an id of an item group, see doc/ITEM_SPAWN.md. The default subtype is “collection”. If breakable is set to true, breaking the object from a failed pry attempt will spawn items from that group.

    Plants

    Note

    This article was recently split off from JSON INFO and likely could use additional work

    plant_data

    {
      "transform": "f_planter_harvest",
      "base": "f_planter",
      "growth_multiplier": 1.2,
      "harvest_multiplier": 0.8
    }
    

    transform

    What the PLANT furniture turn into when it grows a stage, or what a PLANTABLE furniture turns into when it is planted on.

    base

    What the ‘base’ furniture of the PLANT furniture is - what it would be if there was not a plant growing there. Used when monsters ‘eat’ the plant to preserve what furniture it is.

    growth_multiplier

    A flat multiplier on the growth speed on the plant. For numbers greater than one, it will take longer to grow, and for numbers less than one it will take less time to grow.

    harvest_multiplier

    A flat multiplier on the harvest count of the plant. For numbers greater than one, the plant will give more produce from harvest, for numbers less than one it will give less produce from harvest.

    Traps

    trap

    {
      "type": "trap",                // Defines this as a trap
      "id": "tr_caltrops_glass",     // Unique identifier
      "name": "glass caltrops",      // Displayed name
      "color": "dark_gray",          // Color of symbol displayed if tiles are disabled or if no sprite is defined for it
      "symbol": "_",                 // Symbol display if tiles are disabled or if no sprite is defined
      "looks_like": "tr_caltrops",   // hint to tilesets if this part has no tile, use the looks_like tile
      "visibility": 6,               // Difficulty of spotting this trap if not placed by the player, checked against perception. 0 means the trap is never concealed from the player
      "avoidance": 6,                // How likely the trap is to be set off when stepped into. 0 means the trap will never be set off if stepped onto
      "difficulty": 0,               // How hard the trap is to disarm, higher is harder.
      "action": "caltrops_glass",    // What the trap does when triggered, see trapfunc.cpp or below for more info
      "spell_data": { "id": "spell_trap_can_alarm_trigger" },   // `id` of spell cast by a trap with the `spell` trap action
      "map_regen": "microlab_shifting_hall",    // Used by traps with the `map_regen` action, defines what `mapgen_update` entry is used for the area it's applied to.
      "remove_on_trigger": true,     // Does the trap remove itself after being set off? Omit if the trap is intended to stick around and trigger repeatedly, not recommended for traps generated by terrain
      "trigger_items": [ "tripwire", "shotgun_d", { "item": "shot_hull", "quantity": 2, "charges": 1 } ],   // What items spawn when the trap is triggered, times `quantity` and of `charges` amount (used if item has a default stack size like ammo). Note that the `beartrap`, `snare_light`, `snare_heavy`, `pit_spikes`, `pit_glass`, and `crossbow` still have some items that are spawned by hardcoded behavior for various reasons.
      "drops": [ "tripwire", "shotgun_d", { "item": "shot_00", "quantity": 2, "charges": 1 } ],   // That items drop when the trap is succesfully disarmed. Optional use of `quantity` or `charges` follows same conventions as with `trigger_items`
      "vehicle_data": {              // Block of behaviors that occur when a vehicle's wheel rolls over this trap, separate from normal behaviors of traps being set off by players or monsters
        "do_explosion": true,        // If true, create an explosion instead of simply applying damage value to the exact vehicle tile that triggered the trap
        "damage": 1000,              // Direct damage applied to the vehicle tile that triggered it, or base damage at epicenter, depending on if `do_explosion` is true
        "shrapnel": 8,               // Fragmentation damage if set to explode
        "sound_volume": 10,          // Volume of sound, if specified, that plays when triggering
        "sound": "Boom!",            // Sound description as posted in message log, in the form of "You hear %s"
        "sound_type": "explosion",   // Possible types are: background, weather, music, movement, speech, activity, destructive_activity, alarm, combat, alert, order
        "sound_variant": "default"   // Sound variant used
      },
      "benign": true,                // This means it's not a trap meant to be set off but something harmless like a rollmat or funnel, so won't ask the player if they're really sure about stepping into it, and monsters with the `PATH_AVOID_DANGER_2` monflag won't care about avoiding these. Using this with an `action` that can actually cause harm is a Bad Idea
      "funnel_radius": 200           // Used for funnels, when it's raining this trap will collect water at a rate based on this value, automatically filling empty container items placed on the same tile as it
      "floor_bedding_warmth": -1000, // Used for rollmats and the like, bonus warmth offered by this terrain/furniture when used to sleep.
    },
    

    action

    The following actions are available as defined in trapfunc.cpp:

    • none - Does nothing, used for funnels and other things where no trap behavior is necessary.
    • bubble - Makes a pop sound from stepping on bubble wrap, and that’s all.
    • glass - Deals minor cutting damage to whatever steps on it, crunchy glass noises.
    • cot - Perfectly safe and cozy if you’re a player or NPC, but monsters will stumble over it and lose a turn.
    • beartrap - Deals damage and keeps the victim locked to that tile until they break free. If so, the item itself is dropped later on once they free themselves.
    • board - Deals some minor damage to whatever steps on it, and subtracts some moves from them.
    • caltrops - Deals damage to whatever steps on it, and subtracts some moves from them.
    • caltrops_glass - Same basic effect as caltrops_glass but with more glass crunching noises.
    • tripwire - Deals minor damage if it successfully trips the victim, knocking them back and substracting moves from them.
    • crossbow - Deals piercing damage with a chance of missing, the ammunition being dropped afterward is still hardcoded into this due to having a random chance to spawn.
    • shotgun - Deals heavy ballistic damage to whoever sets it off. If the trap’s ID is specifically tr_shotgun_2, the victim is hit twice instead of only once.
    • blade - Lashes out and strikes whoever sets it off with direct bashing and cutting damage.
    • snare_light - Deals damage and keeps the victim locked to that tile until they break free, spawning the relevant items when the effect wears off.
    • snare_heavy - Comparable to snare_light but higher damage, and different item spawns when the target frees themselves.
    • landmine - Explosion with moderate damage and heavy fragmentation.
    • boobytrap - Same effect as landmine but different message printed on trigger.
    • telepad - Teleports the victim to a random space within 8 tiles, with risk of teleporting into a wall, and inflicts teleglow on them.
    • goo - Players and NPCs have a chance of taking damage and are slowed down by slime, non-slime monsters take a speed debuff and non-robot monsters get turned into slimes.
    • dissector - Deals cutting damage to victims, creatures of species ROBOT are immune.
    • pit - Victim takes falling damage and is held in place until they climb back out.
    • pit_spikes - As with pit but additional damage from spikes. Random chance of the spikes breaking, spawning additional items and converting underlying terrain to t_pit.
    • pit_glass - Similiar to pit_spikes, except when it decides to break it spawns glass shards instead of wooden spears.
    • lava - High levels of heat damage dealt to whatever sets it off.
    • portal - Currently aliases to telepad and triggers the exact same effects.
    • sinkhole - If triggered, converts the underlying terrain to t_pit and triggers the effect of falling into a pit. Players can attempt to prevent this if they have a grappling hook, bullwhip, or long rope in their inventory, or if they have the Web Diver mutation.
    • ledge - Fall down a level to whatever is below, triggering potential falling damage.
    • temple_flood - Used in strange temples to trigger the hardcoded event that floors that converts floor in the area to deep water. Only the player can set this off, not NPCs or monsters.
    • temple_toggle - Used in strange temples, toggles red/green/blue puzzle tiles between floor and wall forms. Only the player can set this off, not NPCs or monsters.
    • glow - Random chance of irradiating and flashbanging players and NPCs, monsters have a chance of suffering acid damage and a speed debuff instead.
    • hum - Makes a humming noise of a randomized volume, ranging from barely audiable to deafening.
    • shadow - Summons shadow monsters nearby. Only the player can set this off, not NPCs or monsters.
    • map_regen - Applies the mapgen update specified in the trap’s map_regen to the map tile the trap is in, for altering the map. If used, remove_on_trigger and trigger_items aren’t processed as the mapgen update could just as easily remove the trap, change it to something else, or do any number of things that would otherwise disrupt the trap cleanup function.
    • drain - Deals a tiny amount of damage to the target, ignores armor and immunities.
    • spell - Casts the spell specified by the trap’s spell_data, centered on whatever set it off. Note that the spell used generally requires a min_aoe defined to work successfully, and not all spell effects can be expected to work properly with this.
    • snake - Similar to shadow trap effect, summons shadow snakes nearby. Main difference is NPCs and monsters are capable of setting it off.

    Vehicles

    Note

    This page is currently under-construction and was recently split off from JSON INFO

    Vehicle Parts

    Vehicle components when installed on a vehicle.

    "id": "wheel",                // Unique identifier
    "name": "wheel",              // Displayed name
    "symbol": "0",                // ASCII character displayed when part is working
    "looks_like": "small_wheel",  // hint to tilesets if this part has no tile, use the looks_like tile
    "color": "dark_gray",         // Color used when part is working
    "broken_symbol": "x",         // ASCII character displayed when part is broken
    "broken_color": "light_gray", // Color used when part is broken
    "damage_modifier": 50,        // (Optional, default = 100) Dealt damage multiplier when this part hits something, as a percentage. Higher = more damage to creature struck
    "durability": 200,            // How much damage the part can take before breaking
    "description": "A wheel."     // A description of this vehicle part when installing it
    "size": 2000                  // If vehicle part has flag "FLUIDTANK" then capacity in mLs, else divide by 4 for volume on space
    "wheel_width": 9,             /* (Optional, default = 0)
                                   * SPECIAL: A part may have at most ONE of the following fields:
                                   *    wheel_width = base wheel width in inches
                                   *    size        = trunk/box storage volume capacity
                                   *    power       = base engine power in watts
                                   *    bonus       = bonus granted; muffler = noise reduction%, seatbelt = bonus to not being thrown from vehicle
                                   *    par1        = generic value used for unique bonuses, like the headlight's light intensity */
    "wheel_type":                 // (Optional: standard, off-road)
    "contact_area":               // (Optional) Affects vehicle ground pressure
    "cargo_weight_modifier": 33,  // (Optional, default = 100) Modifies cargo weight by set percentage
    "weight_modifier": 33,        // (Optional, default = 100) Modifies base part weight by set percentage
    "fuel_type": "NULL",          // (Optional, default = "NULL") Type of fuel/ammo the part consumes, as an item id
    
    "item": "wheel",              // The item used to install this part, and the item obtained when removing this part
    "difficulty": 4,              // Your mechanics skill must be at least this level to install this part
    "breaks_into" : [             // When the vehicle part is destroyed, items from this item group (see ITEM_SPAWN.md) will be spawned around the part on the ground.
      {"item": "scrap", "count": [0,5]} // instead of an array, this can be an inline item group,
    ],
    "breaks_into" : "some_item_group", // or just the id of an item group.
    	"flags": [                    // Flags associated with the part
    	     "EXTERNAL", "MOUNT_OVER", "WHEEL", "MOUNT_POINT", "VARIABLE_SIZE"
    	],
    	"rotating_light": {           // Optional for light parts. Emits rotating directional cone light instead of the light flag's normal shape.
    	  "arc": 30,                  // Cone width in degrees. Default 30.
    	  "step": 90,                 // Degrees advanced every period. Negative values rotate in reverse. Default 90.
    	  "phase": 0,                 // Initial direction offset in degrees. Default 0.
    	  "period": "1 turns",        // Time between rotation steps. Can also be an integer turn count. Default 1 turn.
    	  "beams": 2                  // Number of simultaneous evenly spaced beams. Default 2.
    	},
    	"damage_reduction" : {        // Flat reduction of damage, as described below. If not specified, set to zero
    	    "all" : 10,
    	    "physical" : 5
    },
                                  // The following optional fields are specific to ENGINEs.
    "m2c": 50,                    // Mandatory field for parts with the ENGINE flag, indicates ratio of cruise power to maximum power
    "backfire_threshold": 0.5,    // Optional field, defaults to 0. Indicates maximum ratio of damaged HP to max HP to trigger backfires
    "backfire_freq": 20,          // Optional field unless backfire threshold > 0, then mandatory, defaults to 0. One in X chance of a backfire.
    "noise_factor": 15,           // Optional field, defaults to 0. Multiple engine power by this number to declare noise.
    "damaged_power_factor": 0.5,  // Optional field, defaults to 0. If more than 0, power when damaged is scaled to power * ( damaged_power_factor + ( 1 - damaged_power_factor ) * ( damaged HP / max HP )
    "muscle_power_factor": 0,     // Optional field, defaults to 0. If more than 0, each point of the survivor's Strength over 8 adds this much power to the engine, and each point less than 8 removes this much power.
    "exclusions": [ "souls" ]     // Optional field, defaults to empty. A list of words. A new engine can't be installed on the vehicle if any engine on the vehicle shares a word from exclusions.
    "fuel_options": [ "soul", "black_soul" ] // Optional field, defaults to fuel_type.  A list of words. An engine can be fueled by any fuel type in its fuel_options.  If provided, it overrides fuel_type and should include the fuel in fuel_type.
    "comfort": 3,                 // Optional field, defaults to 0. How comfortable this terrain/furniture is. Impact ability to fall asleep on it. (uncomfortable = -999, neutral = 0, slightly_comfortable = 3, comfortable = 5, very_comfortable = 10)
    "floor_bedding_warmth": 300,  // Optional field, defaults to 0. Bonus warmth offered by this terrain/furniture when used to sleep.
    "bonus_fire_warmth_feet": 200,// Optional field, defaults to 300. Increase warmth received on feet from nearby fire.
    "height": 5,                  // Optional field, height of balloons in meters ( aka multiplie of their lift )
    "lift_coff": 0.5,             // Optional field, multiplier of wing effectiveness
    "propeller_diameter": 0.5,    // Optional field, diameter of propeller
    "length": 3,                  // Optional field, z-level length of ladder
    "default_color": "#622625"    // Optional field, default tint color when none other is defined
    

    Integrated Tools

    "integrated_tools": [ "foo" ],
    

    An option array of tools that this vehiclepart will provide for crafting purposes, compare and contrast crafting_pseudo_item for furniture. Requires the vehiclepart to have the CRAFTING flag to function.

    Most legacy crafting vehiclepart flags have been removed and should be replaced with equivalent tools. The WATER_PURIFIER, FAUCET and the WATER_FAUCET flags, which provide specific functions on examine, have been retained.

    "integrated_tools": [ "pot", "pan", "hotplate" ],  // Replaces the `KITCHEN` flag
    "integrated_tools": [ "dehydrator", "vac_sealer", "food_processor", "press" ],  // Replaces the `CRAFTRIG` flag
    "integrated_tools": [ "chemistry_set", "electrolysis_kit" ],  // Replaces the `CHEMLAB` flag
    "integrated_tools": [ "forge" ],  // Replaces the `FORGE` flag
    "integrated_tools": [ "fake_adv_butchery" ],  // Needed with the `BUTCHER_EQ` flag
    "integrated_tools": [ "kiln" ],  // Replaces the `KILN` flag
    "integrated_tools": [ "soldering_iron", "welder" ],  // Replaces the tools
    "integrated_tools": [ "water_purifier" ],  // Replaces the tools, but not the ability to purify water in vehicle tanks, of the `WATER_PURIFIER` flag
    

    Converters

    An field for vehicles with the CONVERTER flag which allows vehicles to convert from one liquid to another within the fuel tanks

    This does not work for items nor for working with nearby liquid sources

    "converter": {
      "input": "input_itype_id",   // What itype is being inputed
      "input_step": 3,             // For each iteration how much of input is consumed
      "output": "output_itype_id", // What itype is being outputed
      "output_step": 1,            // For each iteration how much of output is consumed
      "max_steps": 10,             // Maximum iterations per minute
      "charge_cost": 100           // How many kJ does each iteration take ( this is smallest unit for vehicles )
    }
    

    Part Resistance

    "all" : 0.0f,        // Initial value of all resistances, overridden by more specific types
    "physical" : 10,     // Initial value for bash, cut and stab
    "non_physical" : 10, // Initial value for acid, heat, cold, electricity and biological
    "biological" : 0.2f, // Resistances to specific types. Those override the general ones.
    "bash" : 3,
    "cut" : 3,
    "acid" : 3,
    "stab" : 3,
    "heat" : 3,
    "cold" : 3,
    "electric" : 3
    

    Shapes

    A field to automatically create the copy from versions of vehicle parts with different sprites

    This will automatically create proper objects out of abstracts.

    Note: this field does not support copy from, it must be defined on each object

    "shapes": [
      {
        "direction": "left",     // What is appended to the id, so wing_metal would become wing_metal_left. Additionally is appended to the looks_like field
        "symbol": "y",           // Same as the symbol definition above
        "broken_symbol": "y",    // Same as the broken symbol definition above
        "looks_like": "board_nw" // Same as the looks_like definition above, overwrites changes from direction
      },
    ]
    

    Vehicles

    See also vehicles_spawning.md

    "id": "shopping_cart",                     // Internally-used name.
    "name": "Shopping Cart",                   // Display name, subject to i18n.
    "blueprint": "#",                          // Preview of vehicle - ignored by the code, so use only as documentation
    "parts": [                                 // Parts list
        {"x": 0, "y": 0, "part": "box"},       // Part definition, positive x direction is to the left, positive y is to the right
        {"x": 0, "y": 0, "part": "casters"}    // See vehicle_parts.json for part ids
    ]
                                               /* Important! Vehicle parts must be defined in the same order you would install
                                                * them in the game (ie, frames and mount points first).
                                                * You also cannot break the normal rules of installation
                                                * (you can't stack non-stackable part flags). */
    

    Spawning vehicles

    Vehicle prototypes are used to spawn stock vehicles. After a vehicle has been spawned, it is saved in a different format.

    Vehicle prototypes do not currently accept copy-from

    vehicle prototypes

    "type": "vehicle",
    "id": "sample_vehicle",                    // Unique ID. Must be one continuous word,
                                               // use underscores if necessary.
    "name": "Sample Vehicle",                  // In-game name displayed
    "blueprint": [                             // Preview of vehicle; Can be used as documentation
        "o#o",                                 // Or with palette to be a way to define parts
        "o#o"                                  // Partial definition with palette is also fine
    ],
    "blueprint_origin": { "x": 10, "y": 3 },   // Used by palettes to locate the offset
    "palette": {                               // Palette used by blueprint to set parts on a tile
      "O": [ "airship_balloon_external" ]      // Can only be an array not one string
      "J": [ { "part": "tank", "fuel": "gasoline" }, "battery_car" ], // All part types supported
    },
    "color_palette": "car_standard",           // Vehicle Color Palette used by this car
    "parts": [                                 // Parts list
        { "x": 0, "y": 0, "part": "frame" },   // Part definition, positive x direction is up,
        { "x": 0, "y": 0, "part": "seat" },    // positive y is to the right
        { "x": 0, "y": 0, "part": "controls"}, // See vehicle_parts.json for part ids
        { "x": 0, "y": 1, "parts: [ "frame", "seat" ] }, // Arrays of parts on the same space
        { "x": 0, "y": 1, "parts: [ { "part": "tank", "fuel": "gasoline" }, "battery_car" },
        { "x": 0, "y": 1, "part": "stereo" },  // parts arrays and part may be mixed on the same space
        { "x": 1, "y": 0, "parts: [ "frame, "wheel" ] },
        { "x": 1, "y": 1, "parts: [ "frame, "wheel" ] },
        { "x": -1, "y": 0, "parts: [ "frame, "wheel" ] },
        { "x": -1, "y": 1, "parts: [ "frame, "wheel" ] }
    ],
    "items": [                                 // Item spawn list
        { "x": 0, "y": 0, "items": "helmet_army" },   // individual item
        { "x": 0, "y": 0, "item_groups": "army_uniform" }, // item or items from an item_group
        { "x": 0, "y": 1, "items": [ "matchbook", "two_by_four" ] }, // all items in the list spawn
        { "x": 0, "y": 0, "item_groups": [ "army_uniform", "rare_guns" ] } all item_groups are processed
    ]
    

    .* Important! *. Vehicle parts must be defined in the same order you would install them in the game (ie, frames and mount points first). You also cannot break the normal rules of installation (you can’t stack non-stackable part flags).

    Parts list

    The part list contains an arbitary number of lines. Each line is of the form: { "x": X, "y": Y, "part": PARTID, ... } or { "x": X, "y": Y, "parts": [ PARTID1, ... ] }

    In the first form, the line defines a single part at location X,Y of vehicle part type PARTID. It can have the optional “ammo”, “ammo_types”, “ammo_qty”, or “fuel” keys with an appropriate value following.

    In the second form, the line defines several parts at location X, Y. Each part is either defined by its PARTID string, or can be an object of the form { “part”: PARTID, … } with any of the optional keys “ammo”, “ammo_types”, “ammo_qty”, or “fuel” as above.

    Several different lines can have the same X, Y co-ordinates and each one adds additional parts to that location. Parts must be added in the correct order ie: A wheel hub must be added prior to the wheel, but after the frame.

    Items list

    The items list contains an arbitrary number of lines. Each line is of the form: { “x”: X, “y”: Y, TYPE: DATA }, and describes the items that may spawn at that location. TYPE and DATA may be one of:

    "items": "itemid"                              // single item of that type
    "items": [ "itemid1", "itemid2", ... ]         // all the items in the array
    "item_groups": "groupid"                       // one or more items in the group, depending on
                                                   // whether the group is a collection or distribution
    "item_groups": [ "groupid1", "groupid2" ... ]  // one or more items for each group
    

    the optional keyword “chance” provides an X in 100 chance that a particular item definition will spawn.

    Multiple lines of items may share the same X and Y values.

    Vehicle Groups

    "id":"city_parked",            // Unique ID. Must be one continuous word, use underscores if necessary
    "vehicles":[                 // List of potential vehicle ID's. Chance of a vehicle spawning is X/T, where
      ["suv", 600],           //    X is the value linked to the specific vehicle and T is the total of all
      ["pickup", 400],          //    vehicle values in a group
      ["car", 4700],
      ["road_roller", 300]
    ]
    

    Vehicle Placement

    "id":"road_straight_wrecks",  // Unique ID. Must be one continuous word, use underscores if necessary
    "locations":[ {               // List of potential vehicle locations. When this placement is used, one of those locations will be chosen at random.
      "x" : [0,19],               // The x placement. Can be a single value or a range of possibilities.
      "y" : 8,                    // The y placement. Can be a single value or a range of possibilities.
      "facing" : [90,270]         // The facing of the vehicle. Can be a single value or an array of possible values.
    } ]
    

    Vehicle Spawn

    "id":"default_city",            // Unique ID. Must be one continuous word, use underscores if necessary
    "spawn_types":[ {       // List of spawntypes. When this vehicle_spawn is applied, it will choose from one of the spawntypes randomly, based on the weight.
      "description" : "Clear section of road",           //    A description of this spawntype
      "weight" : 33,          //    The chance of this spawn type being used.
      "vehicle_function" : "jack-knifed_semi", // This is only needed if the spawntype uses a built-in json function.
      "vehicle_json" : {      // This is only needed for a json-specified spawntype.
      "vehicle" : "car",      // The vehicle or vehicle_group to spawn.
      "placement" : "%t_parked",  // The vehicle_placement to use when spawning the vehicle. This is not needed if the x, y, and facing are specified.
      "x" : [0,19],     // The x placement. Can be a single value or a range of possibilities. Not needed if placement is specified.
      "y" : 8,   // The y placement. Can be a single value or a range of possibilities. Not needed if placement is specified.
      "facing" : [90,270], // The facing of the vehicle. Can be a single value or an array of possible values. Not needed if placement is specified.
      "number" : 1, // The number of vehicles to spawn.
      "fuel" : -1, // The fuel of the new vehicles.
      "status" : 1  // The status of the new vehicles.
    } } ]
    

    Vehicle Color Palette

    "type": "vehicle_color_palette",
    "id": "car_standard",                                      // Unique ID
    "palette": [
      {
        "fuzzy_ids": [ "board", "windshield", "door", "roo" ], // List of fuzzily matched ids for tinting the below selected color
        "colors": [
          { "color": "White aluminium", "weight": 8 },         // Color & Weight, This uses named color
          { "color": "#622625", "weight": 8 },                 // It can also be a hex code
          { "color": "Grey", "weight": 8 },                    // Or a fuzzy matched named color
        ]
      }
    ]
    

    Vehicle Blacklist

    {
      "type": "vehicle_blacklist", // Mandatory type
      "vehicles": [ // List of Vehicle Prototype Ids to blacklist
        "car", // They can still be debug spawned and such
        "4x4_car", // They are just prevented from spawning via vehicle groups
        "beetle",
      ],
    }
    

    Modding guide

    Caution

    Some documentation is not complete

    Some parts of the documentation are incomplete or have not been properly updated from older documentation. Contributions to fix this are greatly appreciated.

    Certain features of the game can be modified without rebuilding the game from source code. This includes professions, monsters, npcs, and more. Just modify the pertinent files and run the game to see your changes.

    The majority of modding is done by editing JSON files. An in-depth review of all json files and their appropriate fields is available in JSON_INFO.

    The basics

    Creating a barebones mod

    A mod is created by creating a folder within Cataclysm’s data/mods directory. The mod’s properties are set by the modinfo.json file that is present within that folder. In order for Cataclysm to recognize the folder as a mod, it must have a modinfo.json file present within it.

    Modinfo.json

    The modinfo.json file is a file that contains metadata for your mod. Every mod must have a modinfo.json file in order for Cataclysm to find it. A barebones modinfo.json file looks like this:

    [
      {
        "type": "MOD_INFO",
        "id": "Mod_ID",
        "name": "Mod's Display Name",
        "authors": ["Your name here", "Your friend's name if you want"],
        "description": "Your description here",
        "category": "content",
        "dependencies": ["bn"]
      }
    ]
    

    The category attribute denotes where the mod will appear in the mod selection menu. These are the available categories to choose from, with some examples chosen from mods that existed when this document was written. Pick whichever one applies best to your mod when writing your modinfo file.

    • content - A mod that adds a lot of stuff. Typically reserved for very large mods or complete game overhauls (eg: Core game files, Aftershock)
    • items - A mod that adds new items and recipes to the game (eg: More survival tools)
    • creatures - A mod that adds new creatures or NPCs to the game (eg: Modular turrets)
    • misc_additions - Miscellaneous content additions to the game (eg: Alternative map key, Crazy cataclysm)
    • buildings - New overmap locations and structures (eg: Fuji’s more buildings). If you’re blacklisting buildings from spawning, this is also a usable category (eg: No rail stations).
    • vehicles - New cars or vehicle parts (eg: Tanks and other vehicles)
    • rebalance - A mod designed to rebalance the game in some way (eg: Safe autodocs).
    • magical - A mod that adds something magic-related to the game (eg: Necromancy)
    • item_exclude - A mod that stops items from spawning in the world (eg: No survivor armor, No drugs)
    • monster_exclude - A mod that stops certain monster varieties from spawning in the world (eg: No fungal monsters, No ants)
    • graphical - A mod that adjusts game graphics in some way (eg: Graphical overmap)

    The dependencies attribute is used to tell Cataclysm that your mod is dependent on something present in another mod. If you have no dependencies outside of the core game, then just including bn in the list is good enough. If your mod depends on another one to work properly, adding that mod’s id attribute to the array causes Cataclysm to force that mod to load before yours.

    For more details on MOD_INFO object, see JSON_INFO.md.

    Actually adding things to your mod

    Now that you have a basic mod, you can get around to actually putting some stuff into it!

    File structure

    It’s a good idea to put different categories of additions into different json files. Any json files that are present in the mod folder or its subfolders will be detected and read by Cataclysm, but otherwise, there are no restrictions on what you can put where.

    JSON_INFO.md

    It’s worth reading JSON_INFO.md to get a comprehensive list of everything you can do with these mods. The rest of this document will have a few examples to copy and paste, but it is by no means comprehensive. The base game’s data is also defined in the same way as any mod you write, so taking a look through the game’s json files (in data/json) can also teach you a lot. If the game finds any issues in your JSON syntax when you try to load a game world, it will spit out an error message, and you won’t be able to load that game until the issue is fixed.

    Adding a scenario

    Scenarios are what the game uses to determine your general situation when you create a character. They determine when and where your character may spawn in the world, and what professions can be used. They are also used to determine whether those professions can have mutations starting out. Below you will find the JSON definition for the game’s built-in Large Building scenario.

    [
      {
        "type": "scenario",
        "id": "largebuilding",
        "name": "Large Building",
        "points": -2,
        "description": "Whether due to stubbornness, ignorance, or just plain bad luck, you missed the evacuation, and are stuck in a large building full of the risen dead.",
        "allowed_locs": [
          "mall_a_12",
          "mall_a_30",
          "apartments_con_tower_114",
          "apartments_con_tower_014",
          "apartments_con_tower_104",
          "apartments_con_tower_004",
          "hospital_1",
          "hospital_2",
          "hospital_3",
          "hospital_4",
          "hospital_5",
          "hospital_6",
          "hospital_7",
          "hospital_8",
          "hospital_9"
        ],
        "start_name": "In Large Building",
        "surround_groups": [["GROUP_BLACK_ROAD", 70.0]],
        "flags": ["CITY_START", "LONE_START"]
      }
    ]
    

    Adding a profession.

    Professions are what the game calls the character classes you can choose from when the game starts. Professions can start with traits, skills, items, and even pets! Below is the definition for the Police Officer profession:

    [
      {
        "type": "profession",
        "id": "cop",
        "name": "Police Officer",
        "description": "Just a small-town deputy when you got the call, you were still ready to come to the rescue.  Except that soon it was you who needed rescuing - you were lucky to escape with your life.  Who's going to respect your authority when the government this badge represents might not even exist anymore?",
        "points": 2,
        "skills": [{ "level": 3, "name": "gun" }, { "level": 3, "name": "pistol" }],
        "traits": ["PROF_POLICE"],
        "items": {
          "both": {
            "items": [
              "pants_army",
              "socks",
              "badge_deputy",
              "sheriffshirt",
              "police_belt",
              "smart_phone",
              "boots",
              "whistle",
              "wristwatch"
            ],
            "entries": [
              { "group": "charged_two_way_radio" },
              { "item": "ear_plugs", "custom-flags": ["no_auto_equip"] },
              { "item": "usp_45", "ammo-item": "45_acp", "charges": 12, "container-item": "holster" },
              { "item": "legpouch_large", "contents-group": "army_mags_usp45" }
            ]
          },
          "male": ["boxer_shorts"],
          "female": ["bra", "boy_shorts"]
        }
      }
    ]
    

    Adding an item

    Items are where you really want to read the JSON_INFO file, just because there’s so much that you can do with them, and every category of item is a little bit different.

    [
      {
        "id": "family_photo",
        "type": "GENERIC",
        "//": "Unique mission item for the CITY_COP.",
        "category": "other",
        "name": "family photo",
        "description": "A photo of a smiling family on a camping trip.  One of the parents looks like a cleaner, happier version of the person you know.",
        "weight": "1 g",
        "volume": 0,
        "price": 800,
        "material": ["paper"],
        "symbol": "*",
        "color": "light_gray"
      }
    ]
    

    Preventing monsters from spawning

    This kind of mod is relatively simple, but very useful. If you don’t want to deal with certain types of monsters in your world, this is how you do it. There are two ways to go about this, and both will be detailed below. You can blacklist entire monster groups, or you can blacklist certain monsters. In order to do either of those things, you need that monster’s ID. These can be found in the relevant data files. For the core game, these are in the data/json/monsters directory. The example below is from the No Ants mod, and will stop any kind of ant from spawning in-game.

    [
      {
        "type": "MONSTER_BLACKLIST",
        "categories": ["GROUP_ANT", "GROUP_ANT_ACID"]
      },
      {
        "type": "MONSTER_BLACKLIST",
        "monsters": [
          "mon_ant_acid_larva",
          "mon_ant_acid_soldier",
          "mon_ant_acid_queen",
          "mon_ant_larva",
          "mon_ant_soldier",
          "mon_ant_queen",
          "mon_ant_acid",
          "mon_ant"
        ]
      }
    ]
    

    Preventing locations from spawning

    Preventing certain types of locations from spawning in-game is a little trickier depending on the type of thing you want to target. An overmap building can either be a standard building, or an overmap special. If you want to block things with a specific flag from spawning, you can blacklist those in a very similar manner to monsters. The example below is also from the No Ants mod, and stops all anthills from spawning.

    [
      {
        "type": "region_overlay",
        "regions": ["all"],
        "overmap_feature_flag_settings": { "blacklist": ["ANT"] }
      }
    ]
    

    If the location you want to blacklist is an overmap special, you’ll likely have to copy it from its definition, and manually set it’s occurrences attribute to read [ 0, 0 ].

    Finally, if you’re trying to blacklist something that spawns inside of cities, you can do that with a region overlay. The below example is used in the No rail stations mod, and stops railroad stations from spawning inside of cities. It doesn’t stop the railroad station overmap special from spawning, though.

    [
      {
        "type": "region_overlay",
        "regions": ["all"],
        "city": { "houses": { "railroad_city": 0 } }
      }
    ]
    

    Changing regional weather

    Region overlays can also patch weather by switching the target region to a different base_weather definition. This is the preferred modern approach for weather mods because it keeps the weather generator reusable and lets the overlay stay small.

    [
      {
        "type": "weather_pattern",
        "id": "storm_front",
        "multiplier": 4.0,
        "humidity_mod": 6.0,
        "pressure_mod": -10.0,
        "windpower_mod": 8.0
      },
      {
        "type": "base_weather",
        "id": "my_stormy_weather",
        "copy-from": "default",
        "base_humidity": 75,
        "base_pressure": 1008,
        "base_wind": 14,
        "base_wind_distrib_peaks": 120,
        "extend": {
          "weather_patterns": ["storm_front"]
        },
        "delete": {
          "weather_types": [
            "sunny",
            "light_drizzle",
            "acid_drizzle",
            "acid_rain",
            "light_flurries",
            "flurries",
            "snowing",
            "snowstorm"
          ]
        }
      },
      {
        "type": "region_overlay",
        "regions": ["default"],
        "base_weather": "my_stormy_weather"
      }
    ]
    

    The older "weather" field is still accepted for compatibility, but new content should use "base_weather": "id". When you are starting from an existing weather setup, prefer "copy-from" with "extend" and "delete" over duplicating the whole base_weather object.

    Disabling certain scenarios

    The SCENARIO_BLACKLIST can be either a blacklist or a whitelist. When it is a whitelist, it blacklists all scenarios but the ones specified. No more than one blacklist can be specified at one time - this is in all json loaded for a particular game (all mods + base game), not just your specific mod. The format is as follows:

    [
      {
        "type": "SCENARIO_BLACKLIST",
        "subtype": "whitelist",
        "scenarios": ["largebuilding"]
      }
    ]
    

    Valid values for subtype are whitelist and blacklist. scenarios is an array of the scenario ids that you want to blacklist or whitelist.

    Monster Adjustment

    [
      {
        "type": "monster_adjustment",
        "species": "ZOMBIE",
        "flag": { "name": "REVIVES", "value": false },
        // Any flag will work here.
        "stat": { "name": "speed", "modifier": 10 },
        // stat only allows speed and HP as stat names.
        "special": "nightvision",
        // nightvision gives all monsters of this type night vision.
        // no_zombify removes any "zombify_into" entries for the monster.
      }
    

    Important note on json files

    The following characters: [ { , } ] : " are very important when adding or modifying JSON files. This means a single missing , or [ or } can be the difference between a working file and a hanging game at startup. If you want to include these characters in whatever you are doing (for instance, if you want to put a quote inside an item’s description), you can do so by putting a backslash before the relevant character. This is known as “escaping” that character. For instance, I can make an item’s description contain a quote if I want by doing this:

    ...
    "description": "This is a shirt that says \"I wanna kill ALL the zombies\" on the front.",
    ...
    

    In game, that appears like this: This is a shirt that says "I wanna kill ALL the zombies" on the front.

    Many editors have features that let you track { [ and ] } to see if they’re balanced (ie, have a matching opposite); These editors will also respect escaped characters properly. Notepad++ is a popular, free editor on Windows that contains this feature. On Linux, there are a plethora of options, and you probably already have a preferred one 🙂

    You may also want to use some online or offline JSON validator, e.g. https://dev.narc.ro/cataclysm/format.html , or json_formatter bundled with every release of the game (just drag-and-drop the .json file on it).

    Addendum

    Lua hooks

    Hooks live in game.hooks and are lists of callbacks.

    Registering hooks

    Use game.add_hook to register a hook:

    game.add_hook("on_game_save", function(params)
      -- ...
    end)
    

    Automatically captures the current mod ID during registration.

    You can also pass a table to set priority:

    game.add_hook("on_game_save", {
      priority = 10,        -- optional (higher runs first, default 0)
      fn = function(params)
        -- ...
      end
    })
    

    Execution order

    Hooks are executed in descending priority order. For equal priorities, insertion order is preserved (stable).

    Chaining and results

    When a hook runs, it receives a params table.

    • params.results: shared results table for this cata.run_hooks call. Hooks may freely read and modify it.
    • params.prev: the previous hook’s return value (or nil for the first hook).

    cata.run_hooks( name ) returns the same params.results table.

    If any hook returns boolean false, the results table will contain:

    results.allowed = false
    

    Hooks may return boolean true or false to indicate success or failure of an operation. Call sites may also request early exit using { .exit_early = true } on the first false for performance.

    Example usage

    function table_to_string(table)
      local result = "{ "
      for k, v in pairs(table) do
        if type(v) == "table" then
          result = result .. tostring(k) .. " = " .. table_to_string(v) .. ", "
        else
          result = result .. tostring(k) .. " = " .. tostring(v) .. ", "
        end
      end
      result = result .. " }"
      return result
    end
    
    game.add_hook("on_character_try_move", {
      priority = 50,
      fn = function(params)
        gapi.add_msg("50 priority hook: " .. table_to_string(params))
        local map = gapi.get_map()
        local to = params.to
        local ter_id = map:get_ter_at(to):str_id()
        if ter_id:str() == "t_grass" then
          gapi.add_msg("The floor is lava!")
          return false
        end
        return true
      end,
    })
    game.add_hook("on_character_try_move", {
      priority = 100,
      fn = function(params)
        params.results.extra_info = "Checked by highest priority hook"
        gapi.add_msg("100 priority hook: " .. table_to_string(params))
      end,
    })
    game.add_hook("on_character_try_move", {
      priority = 0,
      fn = function(params)
        gapi.add_msg("0 priority hook: " .. table_to_string(params))
      end,
    })
    

    will produce log output like:

    turn=1335125   time="  1  second" type=neutral  message="100 priority hook: { to = (66,60,0), from = (65,60,0), results = { extra_info = Checked by highest priority hook, allowed = true,  }, char = sol.avatar *: 0x7effcc33ea58, via_ramp = false, movement_mode = 1,  }"
    turn=1335125   time="  1  second" type=neutral  message="50 priority hook: { to = (66,60,0), from = (65,60,0), results = { 1 = { mod_id = <unknown>, priority = 100,  }, extra_info = Checked by highest priority hook, allowed = true,  }, char = sol.avatar *: 0x7effcc33ea58, via_ramp = false, movement_mode = 1,  }"
    turn=1335125   time="  1  second" type=neutral  message="0 priority hook: { to = (66,60,0), from = (65,60,0), results = { 1 = { mod_id = <unknown>, priority = 100,  }, 2 = { mod_id = <unknown>, priority = 50, result = true,  }, 3 = { mod_id = bn, priority = 0, result = true,  }, extra_info = Checked by highest priority hook, allowed = true,  }, char = sol.avatar *: 0x7effcc33ea58, prev = true, via_ramp = false, movement_mode = 1,  }"
    turn=1335125   time="  1  second" type=warning  message="Moving onto this mound of dirt is slow!"
    turn=1335126   time="  0 seconds" type=neutral  message="100 priority hook: { to = (67,60,0), from = (66,60,0), results = { extra_info = Checked by highest priority hook, allowed = true,  }, char = sol.avatar *: 0x3fe77c38, via_ramp = false, movement_mode = 1,  }"
    turn=1335126   time="  0 seconds" type=neutral  message="50 priority hook: { to = (67,60,0), from = (66,60,0), results = { 1 = { mod_id = <unknown>, priority = 100,  }, extra_info = Checked by highest priority hook, allowed = true,  }, char = sol.avatar *: 0x3fe77c38, via_ramp = false, movement_mode = 1,  }"
    turn=1335126   time="  0 seconds" type=neutral  message="The floor is lava!"
    

    you can see when ‘the floor is lava’, 0 priority hook gets cancelled, due to on_character_try_move having .exit_early set to true at the call site.

    Typed Coordinates in Lua

    The game uses a typed coordinate system to make position arithmetic safe and self-documenting. Every coordinate carries two pieces of metadata: an origin and a scale. Mixing incompatible coordinates (e.g. adding an overmap position to a map-square position) is a runtime error rather than a silent wrong result.

    This applies equally in Lua. Prefer typed coordinates everywhere. Reserve the raw Tripoint and Point types for pure offset arithmetic; cases where you are computing a dimensionless 2D or 3D vector (e.g. a direction or a fixed displacement) and the result will be immediately added to or subtracted from a typed coordinate.


    Origins

    The origin of a coordinate describes the reference frame it was measured from.

    Origin stringMeaning
    "rel"Dimensionless offset. Can be added to any coordinate at the same scale.
    "abs"Absolute game-world position. The only globally stable origin.
    "bub"Relative to the corner of the current reality bubble (the loaded map region).
    "mnt"Local vehicle (mount) space, including rotation. Used with the veh scale.
    "sm"Relative to the corner of a specific submap.
    "omt"Relative to the corner of a specific overmap terrain tile.
    "mmr"Relative to the corner of a memory-map region.
    "seg"Relative to the corner of a segment.
    "om"Relative to the corner of a specific overmap.

    The "rel" origin is special: it acts as a typed displacement value. Subtracting two matching absolute coordinates produces a "rel" result; adding a "rel" coordinate to a non-relative one produces the same non-relative origin back.


    Scales

    The scale of a coordinate describes the unit size of each step.

    Scale stringAbbreviationSize
    "map_square"ms1 game tile
    "vehicle"vehVehicle-local tile
    "submap"sm12 × 12 map squares
    "overmap_terrain"omt2 submaps (24 × 24 map squares)
    "mem_map_region"mmrMM_REG_SIZE submaps
    "segment"segSEG_SIZE overmap terrain tiles
    "overmap"omOMAPX overmap terrain tiles

    The abbreviated form (ms, sm, omt, etc.) is used in all factory function names and in the string arguments accepted by the projection functions.


    Type names

    A typed coordinate’s Lua type name is formed by combining origin and scale in PascalCase:

    Tripoint<Origin><Scale>   →   TripointAbsMs, TripointBubSm, TripointRelOmt, …
    Point<Origin><Scale>      →   PointAbsMs, PointRelSm, PointBubMs, …
    

    There are 31 valid origin–scale combinations. Attempting to construct an unsupported combination (e.g. TripointAbsVeh) throws a runtime error.


    Creating typed coordinates

    Factory functions (functional style)

    The coords library exposes coords.tripoint_<origin>_<scale>(x, y, z) and coords.point_<origin>_<scale>(x, y) for every supported combination:

    local player_pos  = gapi.get_avatar():get_pos_ms()   -- TripointBubMs from the API
    local spawn_point = coords.tripoint_abs_ms(100, 200, 0)
    local delta       = coords.tripoint_rel_ms(5, 0, 0)   -- typed offset
    local omt_pos     = coords.tripoint_abs_omt(12, 8, 0)
    

    There is also a generic constructor that takes origin and scale as strings:

    local p = coords.tripoint("abs", "ms", 100, 200, 0)
    local q = coords.point("rel", "sm", 3, 3)
    

    Named constructors (OOP style)

    Every typed coordinate also has a named constructor table in global scope:

    local p = TripointAbsMs.new(100, 200, 0)      -- from x, y, z
    local q = TripointAbsMs.new(raw_tripoint)      -- from raw Tripoint
    local r = TripointAbsMs.new(point_coord, z)    -- from matching PointAbsMs + z
    local s = TripointAbsMs.new()                  -- zero
    

    Both styles produce identical objects. The factory style is generally more concise.


    Reading coordinate components

    local p = coords.tripoint_abs_ms(10, 20, 1)
    
    print(p:x(), p:y(), p:z())   -- 10  20  1
    print(p:origin())             -- "abs"
    print(p:scale())              -- "ms"
    print(p:type())               -- "TripointAbsMs"
    
    local xy = p:xy()             -- PointAbsMs(10, 20); drops z, preserves origin/scale
    local raw = p:raw()           -- raw Tripoint(10, 20, 1); strips all tags
    

    Components can be mutated with set_x, set_y, set_z.


    Arithmetic

    Addition

    A typed coordinate can be added to:

    • A raw Point or raw Tripoint; the result keeps the original origin and scale
    • A "rel" typed coordinate at the same scale; same result type
    • Another "rel" typed coordinate plus the operand is non-relative: the non-relative origin wins
    local pos     = coords.tripoint_abs_ms(10, 20, 0)
    local offset  = coords.tripoint_rel_ms(3, 0, 0)  -- typed relative offset
    
    local new_pos = pos + offset          -- TripointAbsMs(13, 20, 0)
    local also    = pos + Tripoint.new(0, 5, 0)  -- TripointAbsMs(10, 25, 0)  (raw as vector)
    

    Subtraction

    Subtracting a "rel" coordinate or raw value works like addition in reverse. Subtracting two matching non-relative coordinates of the same origin and scale produces a "rel" result:

    local a   = coords.tripoint_abs_ms(15, 20, 0)
    local b   = coords.tripoint_abs_ms(10, 20, 0)
    local rel = a - b                              -- TripointRelMs(5, 0, 0)
    

    Multiplication

    Only "rel" coordinates can be multiplied by an integer scalar:

    local step  = coords.tripoint_rel_ms(1, 0, 0)
    local five  = step * 5                          -- TripointRelMs(5, 0, 0)
    

    Equality and ordering

    Two typed coordinates are equal only when they share the same origin, scale, and raw values. The < operator orders by (origin, scale, raw) lexicographically, making typed coordinates safe to use as table keys and in sorted containers.


    Projection

    Projection converts a coordinate from one scale to another while preserving the origin. The game’s scale hierarchy runs:

    ms  <  sm  <  omt  <  mmr  <  seg  <  om
    

    Projecting to a coarser scale rounds toward negative infinity (floor division).

    local abs_ms  = coords.tripoint_abs_ms(25, 26, 2)
    local abs_omt = abs_ms:to_omt()   -- TripointAbsOmt(1, 1, 2)
    local abs_sm  = abs_ms:to_sm()    -- TripointAbsSm(2, 2, 2)
    

    Convenience shorthand methods exist for every target scale: :to_ms(), :to_sm(), :to_omt(), :to_mmr(), :to_seg(), :to_om(). A generic :to(scale_string) form is also available.

    project_remain: split into quotient and remainder

    When you need to know both which coarser tile a fine coordinate falls in and where within that tile it sits, use project_remain. It returns two values:

    local abs_ms = coords.tripoint_abs_ms(25, 26, 2)
    local quotient, remainder = abs_ms:project_remain_omt()
    -- quotient  → TripointAbsOmt(1, 1, 2):   which overmap terrain tile
    -- remainder → PointOmtMs(1, 2):          offset within that tile (fine scale, omt origin)
    

    Shorthand methods: :project_remain_sm(), :project_remain_omt(), :project_remain_mmr(), :project_remain_seg(), :project_remain_om(). Or the generic form: :project_remain("omt").

    The coords library also exposes these as free functions: coords.project_remain(coord, scale_string), coords.project_remain_omt(coord), etc.

    project_combine: reconstruct from quotient and remainder

    project_combine is the inverse of project_remain. Given a coarse coordinate and a fine offset, it produces the fine-scale absolute coordinate:

    local quotient, remainder = abs_ms:project_remain_omt()
    local restored = coords.project_combine(quotient, remainder)
    -- restored → TripointAbsMs(25, 26, 2)
    

    This is also available as an instance method: quotient:project_combine(remainder).


    Distance functions

    Distance between two typed coordinates requires them to share the same origin and scale:

    local a = coords.tripoint_abs_ms(10, 10, 0)
    local b = coords.tripoint_abs_ms(13, 14, 0)
    
    local rl  = coords.rl_dist(a, b)      -- rectilinear (Manhattan / Chebyshev) distance
    local trig = coords.trig_dist(a, b)   -- Euclidean distance
    local sq  = coords.square_dist(a, b)  -- square (Chebyshev) distance
    

    Instance methods are also provided: a:rl_dist(b), a:trig_dist(b), a:square_dist(b).


    Tile enumeration helpers

    The coords library provides utilities that return arrays of typed point coordinates covering a standard tile region, useful for iterating over areas:

    local sm_tiles  = coords.submap_tiles()           -- all PointSmMs in one submap
    local bub_tiles = coords.tinymap_tiles()          -- all PointBubMs in the tinymap
    local omt_tiles = coords.overmap_terrain_tiles()  -- all PointOmtMs in one overmap terrain tile
    local om_tiles  = coords.overmap_tiles()          -- all PointOmMs in one overmap
    

    When to use raw Point and Tripoint

    Point and Tripoint are untagged 2D/3D integer vectors. Use them only when:

    • Computing a pure offset with no inherent game-world meaning (e.g. a direction constant, a neighbour delta, a rotation result).
    • The value will be immediately added to or subtracted from a typed coordinate rather than stored.
    -- Acceptable: raw Tripoint as a throwaway displacement vector
    local neighbour = player_pos + Tripoint.new(1, 0, 0)
    
    -- Preferred: named typed offset when the displacement has a scale context
    local step = coords.tripoint_rel_ms(1, 0, 0)
    local next  = player_pos + step
    

    Do not store positions as raw Tripoint or Point values when a typed equivalent exists. The typed form catches mismatched-scale bugs at the point of arithmetic rather than silently producing wrong map coordinates.


    Valid origin–scale combinations

    Not every origin is meaningful at every scale. The supported combinations are:

    OriginValid scales
    relall scales
    absms, sm, omt, mmr, seg, om
    bubms, sm
    mntveh only
    smms only
    omtms, sm
    mmrms, sm, omt
    segms, sm, omt, mmr
    omms, sm, omt, mmr, seg

    Constructing an unsupported combination throws a runtime error with a message identifying the invalid type name.


    Quick-reference: coords library API

    FunctionDescription
    coords.tripoint(origin, scale, x, y, z)Generic typed tripoint constructor
    coords.point(origin, scale, x, y)Generic typed point constructor
    coords.tripoint_<o>_<s>(x, y, z)Typed tripoint factory (e.g. coords.tripoint_abs_ms)
    coords.point_<o>_<s>(x, y)Typed point factory
    coords.project_remain(coord, scale)Split coordinate into quotient + remainder
    coords.project_remain_sm/omt/mmr/seg/om(coord)Shorthand project_remain variants
    coords.project_combine(coarse, fine)Reconstruct fine coordinate from split pair
    coords.rl_dist(a, b)Rectilinear (Manhattan/Chebyshev) distance
    coords.trig_dist(a, b)Euclidean distance
    coords.square_dist(a, b)Square (Chebyshev) distance
    coords.submap_tiles()Array of all PointSmMs offsets within one submap
    coords.tinymap_tiles()Array of all PointBubMs offsets within the tinymap
    coords.overmap_terrain_tiles()Array of all PointOmtMs offsets within one OMT
    coords.overmap_tiles()Array of all PointOmMs offsets within one overmap

    C++ Lua integration

    This document describes implementation details behind Lua integration in Cataclysm: Bright Nights.

    BN uses Lua 5.3.6 to run scripts and relies on sol2 v3.3.0 for bindings on C++ side.

    C++ layout

    Lua source files

    To simplify build setup and improve portability we bundle Lua 5.3.6 source code in src/lua/ directory and have the build systems compile it and link into the game executable and library for tests.

    Sol2 source files

    Sol2 makes it easy to bundle, we have sol2 v3.3.0 single-header amalgamated version in src/sol/ and just include it as needed. The header is quite large, so the less source files include it the better.

    • sol/config.hpp - Configuration header, we have a few options defined there
    • sol/forward.hpp - Forward declarations, a lightweight header that should be included in game headers instead of sol/sol.hpp
    • sol/sol.hpp - Main sol2 header file, quite large, avoid including in game headers

    Game source files

    All Lua-related game source files have the catalua prefix.

    If you want to add new bindings, consider looking at existing examples in src/catalua_bindings.cpp and reading relevant part of Sol2 docs.

    • catalua.h (and catalua.cpp) - Main Lua interface. It’s the only header most of the codebase will have to include, and it provides a public interface.
    • catalua_sol.h and catalua_sol_fwd.h - Wrappers for sol/sol.hpp and sol/forward.hpp with custom pragmas to make them compile.
    • catalua_bindings* - Game Lua bindings live here. The coordinate bindings (catalua_bindings_coords*.cpp, catalua_coord.h) are particularly complex; see coordinates.md for the Lua-facing API and design rationale.
    • catalua_console.h(.cpp) - Ingame Lua console.
    • catalua_impl.h(.cpp) - Implementation details for catalua.h(.cpp).
    • catalua_iuse_actor.h(.cpp) - Lua-driven iuse_actor.
    • catalua_log.h(.cpp) - In-memory logging for the console.
    • catalua_luna.h - Usertype registration interface with automatic doc generation, aka luna.
    • catalua_luna_doc.h - List of types registration through luna or exposed to its doc generator.
    • catalua_readonly.h(.cpp) - Functions for marking Lua tables as read-only.
    • catalua_serde.h(.cpp) - Lua table to/from JSON (de-)serialization.
    • catalua_type_operators.h - Macro that helps with implementing bindings for string_ids

    Lua Style Guide

    As Lua ecosystem is a new addition to the project, we only have formatting guidelines.

    Formatting

    We format Lua files with dprint-plugin-stylua with default configuration.

    To format lua files, run:

    deno task dprint fmt
    

    Formatting Lua files in VSCode

    1. Install dprint vscode extension.
    2. Add following lines on .vscode/settings.json:
    {
      "[lua]": {
        "editor.formatOnSave": true,
        "editor.defaultFormatter": "dprint.dprint"
      }
    }
    

    now saving your lua files will also format them.

    Binding new type

    Adding new type to the doc generator without binding internals

    If a C++ type has not been registered in the doc generator, it will show up as <cppval: **gibberish** >. To mitigate this problem, you can add LUNA_VAL( your_type, "YourType" ) in catalua_luna_doc.h, and the generator will use YourType string for argument type.

    Binding new type to Lua

    First, we need to register the new type with the bindings system. It needs to be done for many reasons, including so that the doc generator understands it, and the runtime can deserialize from JSON any Lua table that contains that type. If you don’t you’ll get a compile error saying Type must implement luna_traits<T>.

    1. In catala_luna_doc.h, add declaration for your type. For example, if we’re binding an imaginary horde type (which is a struct), it will be a single line near the top of the file:

      struct horde;
      

      Complex templated types may need to actually pull in the relevant header, but please avoid it as it heavily impacts compilation times.

    2. In the same file, register your type with the doc generator. Continuing with the horde example, it’s done like this:

      LUNA_VAL( horde, "Horde" );
      

      While C++ types use all kinds of style for their names, on Lua side they all should be in CamelCase.

    Now we can actually get to the details. The bindings are implemented in catalua_bindings*.cpp files. They are spread out into multiple .cpp files to speed up compilation and make it easy to navigate, so you can put yours into any existing catalua_bindings*.cpp file or make your own similar file. They are also spread out into functions, for the same reasons. Let’s register our horde type, and put it in a new file and a new function:

    1. Add a new function declaration in catalua_bindings.h:
      void reg_horde( sol::state &lua );
      
    2. Call the function in reg_all_bindings in catalua_bindings.cpp:
      reg_horde( lua );
      
    3. Make a new file, catalua_bindings_horde.cpp, with the following contents:
      #include "catalua_bindings.h"
      
      #include "horde.h" // Replace with the header where your type is defined
      
      void cata::detail::reg_horde( sol::state &lua )
      {
          sol::usertype<horde> ut =
              luna::new_usertype<horde>(
                  lua,
                  luna::no_bases,
                  luna::constructors <
                      // Define your actual constructors here
                      horde(),
                      horde( const point & ),
                      horde( int, int )
                      > ()
                  );
          
          // Register all needed members
          luna::set( ut, "pos", &horde::pos );
          luna::set( ut, "size", &horde::size );
      
          // Register all needed methods
          luna::set_fx( ut, "move_to", &horde::move_to );
          luna::set_fx( ut, "update", &horde::update );
          luna::set_fx( ut, "get_printable_name", &horde::get_printable_name );
      
          // Add (de-)serialization functions so we can carry
          // our horde over the save/load boundary
          reg_serde_functions( ut );
      
          // Add more stuff like arithmetic operators, to_string operator, etc.
      }
      
    4. That’s it. Your type is now visible in Lua under name Horde, and you can use the binded methods and members.

    Binding new type to Lua (using Neovim’s regex)

    Binding classes/structs to Lua by hand can be quite tedious, which is why another way to bind a class is by transforming its header file. For the third step of the second part from previously, it’s possible to use Neovim’s built-in regex and C++ macros to bind the class for us.

    1. Make a copy of the class definition.
    2. Apply both: %s@class \([^{]\)\+\n*{@private:@ %s@struct \([^{]\)\+\n*{@public:@
    3. Manually remove the constructors/unwanted methods at the beginning.
    4. Delete all private/protected methods: %s@\(private:\|protected:\)\_.\{-}\(public:\|};\)@\2
    5. Remove }; at the end of the class definition.
    6. Delete public labels: %s@ *public:\n@
    7. Delete comments: %s@\( *\/\*\_.\{-}\*\/\n\{,1\}\)\|\( *\/\/\_.\{-}\(\n\)\)@\3@g
    8. Unindent until there is zero base indentation.
    9. Turn method definitions into declarations: %s@ *{\(}\|\_.\{-}\n^}\)@;
    10. Push most method declarations into a single line: %s@\((\|,\)\n *@\1@g
    11. Remove default values: %s@ *= *\_.\{-}\( )\|;\|,\)@\1@g
    12. Remove overriden/static methods/members and usings: %s@.*\(override\|static\|using\).*\n@@g
    13. Remove templates: %s@^template<.*>\n.*\n@@g
    14. Remove virtual tag: %s@^virtual *@
    15. Check if all lines end in a semicolon: %s@\([^;]\)\n@\0@gn
    16. Count how many functions there are: %s@\(.*(.*).*\)@@nc
    17. Push first found function to the end: %s@\(.*(.*).*\)\n\(\n*\)\(\_.*\)@\3\1\2
    18. Now you’ll want to repeat step 16 for the number of matches in step 15 minus one. For Neovim, input the match count minus one, ‘@’, then ‘:’, e.g. ‘217@:’ repeats the last command 217 times.
    19. Clean up new lines: %s@\n\{3,}@\r\r
    20. Wrap methods into a macro: %s@\(.*\) \+\([^ ]\+\)\((.*\);@SET_FX_T( \2, \1\3 );
    21. Wrap members into a macro; make sure to select which lines to affect first: s@.\{-}\([^ ]\+\);@SET_MEMB( \1 );
    22. Make the previously multi-line method declarations span multiple lines again: %s@\(,\)\([^ ]\)@\1\r \2@g

    Now what’s left to do is to take the chunk of text and use it in a Lua binding. Continuing with the horde example, this is how the code should look like with these macros:

    #include "catalua_bindings.h"
    #include "catalua_bindings_utils.h"
    
    #include "horde.h" // Replace with the header where your type is defined
    
    void cata::detail::reg_horde( sol::state &lua )
    {
        #define UT_TYPE horde
        sol::usertype<UT_TYPE> ut =
        luna::new_usertype<UT_TYPE>(
            lua,
            luna::no_bases,
            luna::constructors <
                // Define your actual constructors here
                UT_TYPE(),
                UT_TYPE( const point & ),
                UT_TYPE( int, int )
                > ()
           );
    
        // Register all needed members
        SET_MEMB( pos );
        SET_MEMB( size );
    
        // Register all needed methods
        SET_FX_T( move_to, ... ); // Instead of ..., there'd be the type declaration of the method.
        SET_FX_T( update, ... );
        SET_FX_T( get_printable_name, ... );
    
        // Add (de-)serialization functions so we can carry
        // our horde over the save/load boundary
        reg_serde_functions( ut );
    
        // Add more stuff like arithmetic operators, to_string operator, etc.
        // ...
        #undef UT_TYPE // #define UT_TYPE horde
    }
    

    This method of binding to Lua lacks template method bindings and may be broken: compiler errors, linker freezes, so it’s best to assume these bindings will be broken by default, only needing slight fixes / manual additions.

    Binding new enum to Lua

    Binding enums is similar to binding types. Let’s bind an imaginary horde_type enum here:

    1. If enum does not have an explicitly defined container (the : type part after enum name in the header where it’s defined), you’ll have to specify the container first, for example:
        // hordes.h
      - enum class horde_type {
      + enum class horde_type : int {
          animals,
          robots,
          zombies
        }
      
    2. Add the declaration to catalua_luna_doc.h
      enum horde_type : int;
      
    3. Register it in catalua_luna_doc.h with
      LUNA_ENUM( horde_type, "HordeType" )
      
    4. Ensure the enum implements the automatic conversion to/from std::string, see enum_conversions.h for details. Some enums will already have it, but most won’t. Usually it’s just a matter of specializing enum_traits<T> for your enum T in the header, then defining io::enum_to_string<T> in the .cpp file with enum -> string conversion. Some enums won’t have the “last” value required for enum_traits<T>. In that case, you’d have to add one:
        enum class horde_type : int {
          animals,
          robots,
      -   zombies
      +   zombies,
      +   num_horde_types
        }
      
      Note that this only works for “monotonic” enums, i.e. ones that start with 0 and don’t skip any values. In the example above, animals has implicit value of 0, robots has implicit value of 1 and zombies has implicit value of 2, so we can easily add num_horde_types, which will have correct and expected implicit value of 3.
    5. Bind enum fields in reg_enums function in catalua_bindings.cpp:
      reg_enum<horde_type>( lua );
      
      This uses the automatic convertion from step 4, so we have equal names between JSON and Lua.

    Binding new string_id<T> or int_id<T> to Lua

    Binding these can be done separately from binding T itself.

    1. Register your type T with the doc generator if you haven’t already (see relevant docs).
    2. Replace LUNA_VAL from step 1 with LUNA_ID.
    3. Ensure your type T implements operators < and ==. It’s usually easy implement them manually, and can be done semi-automatically with macro LUA_TYPE_OPS found in catalua_type_operators.h.
    4. Ensure your type T has a null string_id. You can add one if it doesn’t exist in string_id_null_ids.cpp. Use the MAKE_CLASS_NULL_ID macro if T is defined as a class, MAKE_STRUCT_NULL_ID macro otherwise.
    5. Ensure your type’s T string_id has obj() and is_valid() methods implemented. These methods are implemented on a case-by-case basis. Checking other string_ids as example is recommended.
    6. In the appropriate catalua_bindings_ids_*.cpp chunk, add the header where your type T is defined:
      #include "your_type_definition.h"
      
    7. In that chunk’s reg_game_ids_* function, register it like so:
      reg_id<T, true>( lua );
      

    That true can be replaced with false if you only want to bind string_id<T> and don’t care about (or can’t implement) int_id<T>.

    You may get linker errors at this stage, e.g. about is_valid() or NULL_ID() methods, which are for various reasons not implemented forall string or int ids. In this case, you’ll have to define these manually, see relevant docs on string_id and int_id for more info.

    And that’s it. Now, your type T will show up in Lua with Raw postfix, string_id<T> will have Id postfix, and int_id<T> will have IntId postfix. As example, for LUNA_ID( horde, "Horde" ), we’ll get:

    • horde -> HordeRaw
    • string_id<horde> -> HordeId
    • int_id<horde> -> HordeIntId All type conversions between the 3 are implemented automatically by the system. Actual fields and methods of T can be binded to Lua same way as usual.

    Lua scripting cookbook

    Here are some snippets to help you get familiar with Lua APIs and learn how to use them. To test these examples, paste the code into the in-game Lua console by pressing the ` (backtick) key.

    Items

    Getting list of all wielded and worn items in your inventory

    local you = gapi.get_avatar()
    local items = you:all_items(false)
    
    for _, item in pairs(items) do
      local status = ""
      if you:is_wielding(item) then
        status = "wielded: "
      elseif you:is_wearing(item) then
        status = "worn: "
      end
      print(status .. item:tname(1, false, 0))
    end
    
    Example output
    wielded: smartphone
    worn: bra
    worn: panties
    worn: pair of socks
    worn: jeans
    worn: long-sleeved shirt
    worn: pair of sneakers
    worn: messenger bag
    worn: wrist watch
    pocket knife
    matchbook
    clean water (plastic bottle)
    clean water
    

    Monsters

    Spawning a dog near the player

    local avatar = gapi.get_avatar()
    local coords = avatar:get_pos_ms()
    local dog_mtype = MonsterTypeId.new("mon_dog_bcollie")
    local doggy = gapi.place_monster_around(dog_mtype, coords, 5)
    if doggy == nil then
        gdebug.log_info("Could not spawn doggy :(")
    else
        gdebug.log_info(string.format("Spawned Doggy at %s", doggy:get_pos_ms()))
    end
    

    Combat

    Printing details about a combat technique when it is used

    First, define the function.

    on_creature_performed_technique = function(params)
      local char = params.char
      local technique = params.technique
      local target = params.target
      local damage_instance = params.damage_instance
      local move_cost = params.move_cost
      gdebug.log_info(
              string.format(
                      "%s performed %s on %s (DI: %s , MC: %s)",
                      char:get_name(),
                      technique.name,
                      target:get_name(),
                      damage_instance:total_damage(),
                      move_cost
              )
      )
    end
    

    Then connect the hook to the function ONLY ONCE.

    game.add_hook("on_creature_performed_technique", function(...) return on_creature_performed_technique(...) end)
    
    Example output
    Ramiro Waters performed Power Hit on zombie (DI: 27.96 , MC: 58)
    

    Item Durability

    Checking and modifying item damage

    local you = gapi.get_avatar()
    local wielding = you:all_items(false)[1]
    print(wielding:get_damage())
    print(wielding:get_damage_level(4))
    wielding:mod_damage(2000)
    print(wielding:get_damage_level(4))
    

    Monsters

    Adding items to a monster’s inventory

    local target_monster = -- [[ your monster reference ]]
    local scraps = gapi.create_item(ItypeId.new("scrap"), 3)
    target_monster:as_monster():add_item(scraps)
    

    Randomly blocking monster interaction

    Paste this into the Lua console to give monster interaction a 50% chance to fail:

    game.add_hook("on_try_monster_interaction", function(params)
        local monster = params.monster
    
        gapi.add_msg(string.format("you try to talk to %s", monster:get_name()))
        if math.random(2) == 1 then
            gapi.add_msg(MsgType.warning, string.format("you are too shy to interact with %s!", monster:get_name()))
            return false
        end
    end)
    

    Return false to block the normal pet, mech, or friendly-monster interaction, or true to let it continue.

    NPCs

    Spawning and erasing NPCs

    local player = gapi.get_avatar()
    local map = gapi.get_map()
    local player_pos = player:get_pos_ms()
    local place_point = player_pos:xy() + Point.new(0, 2)
    local new_npc = map:place_npc(place_point, "thug")
    
    -- Later, you can erase the NPC silently
    new_npc:erase()
    

    Reacting when control swaps to an NPC

    Use on_control_npc when a mod needs to refresh state after the player takes control of a follower NPC. The hook runs after the swap, so read the currently controlled character with gapi.get_avatar().

    local mod = game.mod_runtime[game.current_mod]
    game.add_hook("on_control_npc", function(...) return mod.on_control_npc(...) end)
    
    mod.on_control_npc = function(params)
        local controlled = gapi.get_avatar()
    
        gapi.add_msg(MsgType.good, string.format("Now controlling %s.", controlled:get_name()))
    end
    

    Dimensions

    Checking the current dimension

    local map = gapi.get_map()
    
    print("game dimension:", gapi.get_current_dimension_id())
    print("map dimension:", map:get_bound_dimension())
    print("is far-away point out of bounds:", map:is_out_of_bounds(coords.tripoint_bub_ms(500, 500, 0)))
    

    Entering and re-entering a pocket dimension

    Use world_type and both bounds when creating a new pocket dimension. Optional overmap_terrain is a z/y/x table anchored at bounds_min_omt. While that dimension remains loaded in the current session, you can re-enter it with only dimension_id and target_omt.

    home_dimension = "sky_island_home"
    overworld_pos = gapi.get_avatar():abs_pos()
    home_omt = overworld_pos:to_omt()
    local home_bounds_radius = coords.tripoint_rel_omt(2, 2, 0)
    
    local entered = gapi.place_player_dimension_at({
      dimension_id = home_dimension,
      target_omt = home_omt,
      world_type = "pocket_dimension",
      bounds_min_omt = home_omt - home_bounds_radius,
      bounds_max_omt = home_omt + home_bounds_radius,
      boundary_terrain = "t_pd_border",
      boundary_overmap_terrain = "pd_border",
      overmap_terrain = {
        {
          { "forest", "field", "forest" },
          { "field", "field", "field" },
          { "forest", "field", "forest" },
        },
      },
    })
    
    if entered then
      gapi.add_msg("Pocket home loaded.")
    end
    

    Returning to the overworld

    Use the overworld_pos captured before entering to return to the exact map square.

    gapi.place_player_dimension_at({
      dimension_id = "",
      target_ms = overworld_pos,
    })
    

    After returning, re-enter the loaded pocket dimension with its ID and destination. Travel returns false and restores the original dimension and position if no passable, unoccupied landing tile exists within 10 tiles of the destination. The player does not count as an occupant when choosing a landing tile.

    local reentered = gapi.place_player_dimension_at({
      dimension_id = home_dimension,
      target_omt = home_omt,
    })
    

    Resetting or deleting an expedition dimension

    The integration target is the CBN-Sky-Island expedition flow, which needs fresh expedition terrain for issue #9589. Give the expedition a non-primary dimension ID, return to the overworld, update mod state, and then reset its generated data:

    local expedition_dimension = "sky_island_expedition"
    local storage = game.mod_storage[game.current_mod]
    local returned = gapi.place_player_dimension_at({
      dimension_id = "",
      target_ms = overworld_pos,
    })
    
    if returned then
      storage.is_away_from_home = false
      gapi.reset_dimension(expedition_dimension)
    end
    

    Both cleanup functions reject "" because the primary overworld cannot be removed. They also reject the current dimension and any dimension with active load requests, such as a portal preloading its destination. Release those requests before retrying cleanup. reset_dimension keeps the dimension metadata for re-entry, while delete_dimension requires the full generation options on the next entry. Cleanup makes a full save before removing dimension data, so update persistent Lua state before calling it.

    Weather Hooks

    Reacting to weather changes

    First, set up the hook in your preload.lua:

    local mod = game.mod_runtime[game.current_mod]
    game.add_hook("on_weather_changed", function(...) mod.weather_changed_alert(...) end)
    game.add_hook("on_weather_updated", function(...) mod.weather_report(...) end)
    

    Then define the handlers in your main.lua:

    local mod = game.mod_runtime[game.current_mod]
    
    -- Called when weather changes (e.g., clear -> rain)
    mod.weather_changed_alert = function(params)
        local msg = string.format(
            "Weather changed from %s to %s!",
            params.old_weather_id,
            params.weather_id
        )
        gdebug.log_info(msg)
    end
    
    -- Called every 5 minutes with current weather data
    mod.weather_report = function(params)
        local msg = string.format(
            "Current Weather: %s, Temperature: %.1f°C, Wind: %d km/h, Humidity: %d%%",
            params.weather_id,
            params.temperature,
            params.windspeed,
            params.humidity
        )
        gdebug.log_info(msg)
    end
    

    Combat Ranged

    Reacting to shots fired and thrown items

    First, set up the hooks in your preload.lua:

    local mod = game.mod_runtime[game.current_mod]
    game.add_hook("on_shoot", function(...) return mod.on_shoot_fun(...) end)
    game.add_hook("on_throw", function(...) return mod.on_throw_fun(...) end)
    

    Then define the handlers in your main.lua:

    local mod = game.mod_runtime[game.current_mod]
    
    mod.on_shoot_fun = function(params)
        ---@type Item
        local gun = params.gun
        ---@type Item
        local ammo_item = params.ammo
        local ammo = ItypeId.NULL_ID()
        if not ammo_item then
            ammo = gun:ammo_current()
        else
            ammo = ammo_item:get_type()
        end
        local shoot_noise = ammo:obj():slot_ammo().loudness
        gdebug.log_info(string.format("Gun sound: %d.", shoot_noise))
    end
    
    mod.on_throw_fun = function(params)
        ---@type Character
        local thrower = params.thrower
        ---@type Item
        local thrown = params.thrown
        if thrown:is_gun() then
            gdebug.log_info("Hey! Guns are not for throwing!")
        end
    end
    

    Overmap Queries

    Finding and manipulating items on the overmap

    -- Find all items on the overmap at a specific location
    local om_pos = OmPos.new(0, 0, 0)
    local items = gapi.overmap_find_items_around(om_pos, 0)
    
    -- Get an item from the map and keep it in Lua even if the map unloads
    local map_pos = MapPos.new(100, 100, 0)
    local item = gapi.get_map():find_item_at(map_pos)
    if item then
        local detached = gapi.create_detached_item(item)
        -- Later, you can reattach it to a location
        local reattached = gapi.reattach_item(detached, map_pos)
    end
    
    -- Teleport items within the same map
    local source_pos = MapPos.new(100, 100, 0)
    local dest_pos = MapPos.new(110, 110, 0)
    gapi.get_map():move_item_at(source_pos, dest_pos)
    

    Death Hooks

    Tracking when monsters die

    -- In preload.lua
    local mod = game.mod_runtime[game.current_mod]
    game.add_hook("on_mon_death", function(...) return mod.on_mon_death(...) end)
    
    -- In main.lua
    local mod = game.mod_runtime[game.current_mod]
    
    mod.on_mon_death = function(params)
        ---@type Creature
        local monster = params.creature
        ---@type Character|nil
        local killer = params.killer
    
        local killer_name = killer and killer:get_name() or "Unknown"
        gdebug.log_info(string.format("%s was killed by %s", monster:get_name(), killer_name))
    end
    

    Tracking character deaths

    -- In preload.lua
    local mod = game.mod_runtime[game.current_mod]
    game.add_hook("on_char_death", function(...) return mod.on_char_death(...) end)
    
    -- In main.lua
    local mod = game.mod_runtime[game.current_mod]
    
    mod.on_char_death = function(params)
        ---@type Character
        local char = params.char
        ---@type Character|nil
        local killer = params.killer
    
        if char == gapi.get_avatar() then
            gdebug.log_info("You have died!")
        end
    end
    

    Character Combat Stats

    Getting attack and stamina costs

    local you = gapi.get_avatar()
    local items = you:all_items(false)
    
    for _, item in pairs(items) do
        print(
            item:tname(1, false, 0) 
            .. " { attack cost: " .. item:attack_cost() 
            .. ", stamina cost: " .. item:stamina_cost()
            .. ", melee stamina cost: " .. you:get_melee_stamina_cost(item)
            .. " }"
        )
    end
    
    -- Check for special abilities
    print("Uncanny dodge: " .. (you:uncanny_dodge() and "yes" or "no"))
    

    Character Magics

    Learn a new spell and forget it

    learning a spell:

    local u = gapi.get_avatar()
    local km = u:get_magic()
    local ex_sp = SpellTypeId.new("example_template")
    km:learn_spell(ex_sp, u, true) -- learn forced
    print( km:knows_spell(ex_sp) ) -- check
    

    forgetting a spell:

    local u = gapi.get_avatar()
    local km = u:get_magic()
    local ex_sp = SpellTypeId.new("example_template")
    km:forget_spell(ex_sp)         -- forget
    print( km:knows_spell(ex_sp) ) -- check again
    

    Dynamic Item Actions

    All item, bionic, and mutation callback tables are keyed by string id and take a table of optional callback functions. Every callback receives a single params table with named fields.

    game.iuse_functions

    Callbacksparams fields
    useuser, item, pos
    can_useuser, item, pos

    use returns an int (time cost in moves). can_use returns bool.

    game.iuse_functions["my_custom_item"] = {
        use = function(params)
            local user = params.user
            local item = params.item
            gdebug.log_info("Using: " .. item:tname(1))
            return 0  -- Return time cost in moves
        end,
    
        can_use = function(params)
            -- Return true to allow use, false to prevent
            return true
        end
    }
    

    Item lifecycle callbacks

    Several additional callback tables let you react to item events.

    game.iwieldable_functions

    Callbacksparams fields
    on_wielduser, item, move_cost
    on_unwield, can_wield, can_unwielduser, item

    game.iwearable_functions

    Callbacksparams fields
    on_wear, on_takeoff, can_wear, can_takeoffuser, item

    game.iequippable_functions

    Callbacksparams fields
    on_durability_changeuser, item, old_damage, new_damage
    on_repair, on_breakuser, item

    game.istate_functions

    Callbacksparams fields
    on_tick, on_dropuser, item, pos
    on_pickupuser, item

    game.iconsume_functions

    Keyed by item id. on_try_consume runs before the food’s edibility checks and eat-confirmation prompt, or before medication is applied (even before the required-tool check): modify the params fields to override the values the game applies, return false to interrupt the consume. Callback side effects persist even if the checks then fail or the player declines, and the item is left alone unless the callback changed it — so the callback can implement its own consumption (params.item:mod_charges( -1 )) and return false.

    Callbacksparams fields
    on_try_consumechar, item, nutrition, thirst, fun, fun_max, skip_cannibalism
    on_consumechar, item, nutrition, thirst, fun, fun_max
    game.iconsume_functions["blood"] = {
        on_try_consume = function( params )
            -- Blood without the guilt.
            params.skip_cannibalism = true
            params.fun = 10
            params.fun_max = 10
        end
    }
    

    The character-wide equivalent is the on_character_try_consume hook: it receives the same values in its params and returns a table with the override fields (allowed, nutrition, thirst, fun, fun_max, skip_cannibalism) instead of mutating params.

    on_consume is the post-consume counterpart: it runs after the item has actually been consumed (charges deducted, effects applied), receives the values the game applied (char, item, nutrition, thirst, fun, fun_max), and its return value is ignored. The character-wide equivalent is the on_character_consume hook with the same params fields.

    params.item is still the consumed item, so params.item.charges can be 0 when the last charge was eaten; the game removes the item afterwards. Do not keep a reference to it.

    Food and medication both run these callbacks. That covers eating, taking medication, and medication that an NPC accepts in dialogue. For parenteral medication (NO_INGEST, such as injections) nutrition and thirst are 0. Other consumption paths (bionic fuel, furnace feeding, the fake item of consume_drug actions) do not run them.

    game.iconsume_functions["blood"] = {
        on_consume = function( params )
            gdebug.log_info( params.char:get_name() .. " drank "
                .. tostring( params.nutrition ) .. " kcal of blood" )
        end
    }
    

    game.imelee_functions

    Callbacksparams fields
    on_melee_attackuser, target, item
    on_hituser, target, item, damage_instance
    on_blockuser, source, item, damage_blocked
    on_missuser, item

    game.iranged_functions

    Callbacksparams fields
    on_fireuser, item, target_pos, shots
    on_reload, can_fire, can_reloaduser, item

    can_* callbacks return bool — return false to block the action.

    game.iwieldable_functions["cursed_sword"] = {
        on_wield = function(params)
            gdebug.log_info(params.user:get_name() .. " draws " .. params.item:tname(1))
        end,
        can_unwield = function(params)
            -- Cursed sword can't be put down
            return false
        end
    }
    

    Bionic callbacks

    game.bionic_functions is keyed by bionic string id. Each callback receives a single params table.

    Callbackparams fieldsWhen fired
    on_activateuser, bionicAfter bionic is activated
    on_deactivateuser, bionicAfter bionic is deactivated
    on_installeduser, bionic_idAfter bionic is installed
    on_removeduser, bionic_idAfter bionic is removed
    game.bionic_functions["bio_laser"] = {
        on_activate = function(params)
            gdebug.log_info(params.user:get_name() .. " activated bio_laser")
        end,
        on_installed = function(params)
            gdebug.log_info("Installed: " .. tostring(params.bionic_id))
        end
    }
    

    Mutation callbacks

    game.mutation_functions is keyed by trait string id.

    Callbackparams fieldsWhen fired
    on_activateuser, trait_idAfter mutation is toggled on
    on_deactivateuser, trait_idAfter mutation is toggled off
    on_gainuser, trait_idAfter mutation is gained
    on_lossuser, trait_idAfter mutation is lost
    game.mutation_functions["TRAIT_QUICK"] = {
        on_gain = function(params)
            gdebug.log_info(params.user:get_name() .. " gained " .. tostring(params.trait_id))
        end,
        on_loss = function(params)
            gdebug.log_info(params.user:get_name() .. " lost " .. tostring(params.trait_id))
        end
    }
    

    More Combat Hooks

    Reacting to dodge, block, and technique events

    -- In preload.lua
    local mod = game.mod_runtime[game.current_mod]
    game.add_hook("on_creature_dodged", function(...) return mod.on_creature_dodged(...) end)
    game.add_hook("on_creature_blocked", function(...) return mod.on_creature_blocked(...) end)
    game.add_hook("on_creature_performed_technique", function(...) return mod.on_creature_performed_technique(...) end)
    game.add_hook("on_creature_melee_attacked", function(...) return mod.on_creature_melee_attacked(...) end)
    
    -- In main.lua
    local mod = game.mod_runtime[game.current_mod]
    
    mod.on_creature_dodged = function(params)
        ---@type Character
        local char = params.char
        ---@type Creature
        local source = params.source
        local difficulty = params.difficulty
        gdebug.log_info(string.format("%s dodged %s (DC: %d)", char:get_name(), source:get_name(), difficulty))
    end
    
    mod.on_creature_blocked = function(params)
        ---@type Character
        local char = params.char
        ---@type Creature
        local source = params.source
        local bodypart_id = params.bodypart_id
        local damage_blocked = params.damage_blocked
        gdebug.log_info(string.format(
            "%s blocked %s on %s (blocked: %.1f damage)",
            char:get_name(),
            source:get_name(),
            bodypart_id,
            damage_blocked
        ))
    end
    
    mod.on_creature_melee_attacked = function(params)
        ---@type Character
        local char = params.char
        ---@type Creature
        local target = params.target
        if params.success then
            gdebug.log_info(string.format("%s hit %s", char:get_name(), target:get_name()))
        else
            gdebug.log_info(string.format("%s missed %s", char:get_name(), target:get_name()))
        end
    end
    

    Item Type Information

    Querying item type properties via ItypeId

    local item_type = ItypeId.new("9mm")
    
    -- Get the item type object (ItypeRaw)
    local itype_raw = item_type:obj()
    
    -- Access item type specific data (e.g., for ammo)
    if itype_raw:slot_ammo() then
        local ammo_data = itype_raw:slot_ammo()
        print("Ammo damage: " .. ammo_data.damage)
        print("Ammo range: " .. ammo_data.range)
    end
    
    -- For containers
    if itype_raw:slot_container() then
        local container_data = itype_raw:slot_container()
        print("Capacity: " .. container_data.capacity)
    end
    
    -- For tools
    if itype_raw:slot_tool() then
        local tool_data = itype_raw:slot_tool()
        print("Tool quality: " .. tool_data.quality)
    end
    

    Character Trap Awareness

    Checking and remembering traps

    First, set a trap at a location:

    local u = gapi.get_avatar()
    local m = gapi.get_map()
    local pos = u:get_pos_ms()
    local pos4x = pos + Tripoint.new(4, 0, 0)
    -- tr_landmine_buried has visibility 20. very hard to find.
    local mine = TrapId.new("tr_landmine_buried"):int_id()
    m:set_trap_at(pos4x, mine)
    print(tostring(u:knows_trap(pos4x)))
    

    Then, make the character aware of the trap:

    local u = gapi.get_avatar()
    local m = gapi.get_map()
    local pos = u:get_pos_ms()
    local pos4x = pos + Tripoint.new(4, 0, 0)
    u:add_known_trap(pos4x, m:get_trap_at(pos4x))
    print(tostring(u:knows_trap(pos4x)))
    

    After running the second script, you can see where the trap is located instead of stepping on it.

    Time and Space

    Sun and moon, inside and outside

    local u_pos = gapi.get_avatar():get_pos_ms()
    local map = gapi.get_map()
    local now = gapi.current_turn()
    
    -- Found the key name from MoonPhase entries
    local moon = ""
    for name, num in pairs(MoonPhase) do
       if num == now:moon_phase() then
          moon = name
       end
    end
    
    print( "Are you outside?: " .. tostring(map:is_outside(u_pos)) )
    print( "Are you sheltered?: " .. tostring(map:is_sheltered(u_pos)) )
    print( "Today moon phase is: " .. moon )
    print( "Sunset time is: " .. now:sunset():to_string_time_of_day() )
    

    Localized Weather Overrides

    Spawn a local lightning storm around the player

    gapi.set_omt_weather_override applies a weather type to every overmap terrain tile in a radius around a center point. The radius is measured in OMTs, so even a small value affects a noticeable area.

    local avatar = gapi.get_avatar()
    local center_omt = gapi.bub_to_abs(avatar:get_pos_ms()):to_omt()
    
    -- Radius is in OMT tiles.
    gapi.set_omt_weather_override(center_omt, 2, "lightning")
    

    You can also give it an expiration time:

    local avatar = gapi.get_avatar()
    local center_omt = gapi.bub_to_abs(avatar:get_pos_ms()):to_omt()
    local expires_at = gapi.current_turn() + TimeDuration.from_minutes(30)
    
    gapi.set_omt_weather_override(center_omt, 2, "lightning", expires_at)
    

    Check and clear a local weather override

    local avatar = gapi.get_avatar()
    local center_omt = gapi.bub_to_abs(avatar:get_pos_ms()):to_omt()
    
    print("Override active: " .. tostring(gapi.has_omt_weather_override(center_omt)))
    print("Current override: " .. tostring(gapi.get_omt_weather_override(center_omt)))
    
    gapi.clear_omt_weather_override(center_omt, 2)
    -- or clear everything:
    -- gapi.clear_all_omt_weather_overrides()
    

    Use "thunder" instead of "lightning" if you want thunderstorm weather without the stronger lightning-storm variant.

    Terrain, Furniture and Plant Examine

    Terrain and furniture can dispatch their examine interaction to Lua. In the terrain or furniture JSON, set "examine_action": "lua:NAME" and register a callback in game.examine_functions:

    Callbackparams fields
    (single)user, pos, terrain, furniture

    terrain is the TerId at pos; furniture is the FurnId, or nil when the tile has no furniture. Use :str() for the id string and :int_id() for map functions such as set_ter_at.

    game.examine_functions["my_shrine"] = function( params )
        gdebug.log_info( params.user:get_name() .. " examines " .. params.terrain:str() )
        params.user:mod_fatigue( 5 )
    end
    
    {
      "type": "furniture",
      "id": "f_my_shrine",
      "name": "shrine",
      "description": "An old shrine.",
      "symbol": "&",
      "color": "white",
      "move_cost_mod": 1,
      "required_str": -1,
      "examine_action": "lua:my_shrine"
    }
    

    Auto-foraging

    The AUTO_FORAGING option automatically harvests adjacent flora. Which flora qualify is defined per terrain/furniture by the JSON field "forage_class" instead of a hardcoded whitelist, so Lua-examinable flora participate too:

    "forage_class": "bushes"
    

    Valid values are "bushes", "trees", and "flowers", or an array to combine them ("forage_class": [ "bushes", "trees" ]). Terrain is foraged for bushes and trees, furniture for flowers. A lua: examine action needs an explicit forage_class to be auto-foraged.

    Without forage_class, the class follows the examine action: the built-in harvest actions keep the classes they always had (shrub_wildveggies and shrub_marloss: bushes; harvest_ter and tree_marloss: trees; harvest_ter_nectar: bushes and trees; harvest_furn and harvest_furn_nectar: flowers), and every other action is not foraged. An entry that sets its own examine_action (also through copy-from or a mod override) does not inherit forage_class; set it again if needed.

    Seed harvest callbacks

    When a plant is harvested, the behavior is normally chosen from the seed’s seed_data. A seed may instead delegate its entire harvest to Lua by setting "harvest_action": "lua:NAME" inside its seed_data; the callback in game.harvest_functions["NAME"] then fully replaces the hardcoded harvest (including the special fungal seed handling):

    Callbackparams fields
    (single)user, pos, seed, from_activity

    from_activity is true when a farm-zone activity harvests the plant (the C++ harvest tags the produce with the harvester’s name in that case).

    {
      "type": "COMESTIBLE",
      "id": "marloss_seed",
      "name": { "str": "Marloss seed" },
      "//": "…",
      "seed_data": {
        "fruit": "null",
        "plant_name": "marloss berry",
        "grow": "14 days",
        "harvest_action": "lua:marloss_harvest"
      }
    }
    
    ---@param params { user: Character, pos: TripointBubMs, seed: Item, from_activity: boolean }
    game.harvest_functions["marloss_harvest"] = function( params )
        local map = gapi.get_map()
        map:set_ter_at( params.pos, TerId.new( "t_marloss" ):int_id() )
        -- Remove the grown plant and the planted seed item, as the C++ harvest
        -- would have.
        map:set_furn_at( params.pos, FurnId.new( "f_null" ):int_id() )
        map:i_clear( params.pos )
        -- The C++ harvest takes 10 seconds.
        params.user:mod_moves( -1000 )
    end
    

    The C++ harvest does not run, so the callback is responsible for the whole harvest: it must replace the grown plant furniture (the furniture with the GROWTH_HARVEST flag) and clear or transform the planted seed item, and it should charge the time it takes. If the grown plant is still there after the callback, the game reports an error and applies the plant’s default transform (clearing the tile’s items), because farm zones would otherwise harvest the same tile forever. That fallback is triggered by the GROWTH_HARVEST flag itself, so multi-stage crops cannot skip the transform: a callback that turns the plant into a different harvestable stage has that stage immediately replaced by the new furniture’s own default transform.

    Lua API reference

    Note

    This page is auto-generated from data/raw/generate_docs.lua and should not be edited directly.

    Warning

    In Lua, functions can be called with a : and pass the object itself as the first argument, eg:

    Members where this behaviour is intended to be used are marked as 🇲 Methods
    Their signature documentation hides the first argument to reflect that

    • Call 🇫 Function members with a .
    • Call 🇲 Method members with a :

    Alternatively, you can still call 🇲 Methods with a ., from the class type or the variable itself but a value of the given type must be passed as the first parameter (that is hidden)

    All of these do the same thing:

    • print(Angle.from_radians(3):to_degrees())
      
    • print(Angle.to_degrees(Angle.from_radians(3)))
      
    • local a = Angle.from_radians(3)
      print(a:to_degrees())
      
    • local a = Angle.from_radians(3)
      print(a.to_degrees(a))
      
    • local a = Angle.from_radians(3)
      print(Angle.to_degrees(a))
      

    ActivityTypeId

    Bases

    No base classes.

    Constructors

    • ActivityTypeId.new( )
    • ActivityTypeId.new( ActivityTypeId )
    • ActivityTypeId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> ActivityTypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> ActivityTypeRaw

    str

    🇲 Method –> ( ) -> string

    AmmunitionEffectId

    Bases

    No base classes.

    Constructors

    Members

    NULL_ID

    🇫 Function –> ( ) -> AmmunitionEffectId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    int_id

    🇲 Method –> ( ) -> AmmunitionEffectIntId

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> AmmunitionEffectRaw

    str

    🇲 Method –> ( ) -> string

    AmmunitionEffectIntId

    Bases

    No base classes.

    Constructors

    Members

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> AmmunitionEffectRaw

    str_id

    🇲 Method –> ( ) -> AmmunitionEffectId

    AmmunitionTypeId

    Bases

    No base classes.

    Constructors

    • AmmunitionTypeId.new( )
    • AmmunitionTypeId.new( AmmunitionTypeId )
    • AmmunitionTypeId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> AmmunitionTypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> AmmunitionTypeRaw

    str

    🇲 Method –> ( ) -> string

    Angle

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    from_arcmin

    🇫 Function –> ( number ) -> Angle

    from_degrees

    🇫 Function –> ( number ) -> Angle

    from_radians

    🇫 Function –> ( number ) -> Angle

    to_arcmin

    🇲 Method –> ( ) -> number

    to_degrees

    🇲 Method –> ( ) -> number

    to_radians

    🇲 Method –> ( ) -> number

    ArmorPortionData

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    coverage

    🇻 Variable –> integer

    encumber

    🇻 Variable –> integer

    max_encumber

    🇻 Variable –> integer

    get_covered_parts

    🇲 Method –> ( ) -> BodyPartTypeIntId[]

    Avatar

    Bases

    • Player
    • Character
    • Creature

    Constructors

    No constructors.

    Members

    get_active_missions

    🇲 Method –> ( ) -> Mission[]

    get_completed_missions

    🇲 Method –> ( ) -> Mission[]

    get_failed_missions

    🇲 Method –> ( ) -> Mission[]

    Bionic

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    ammo_count

    🇻 Variable –> integer

    charge_timer

    🇻 Variable –> integer

    energy_stored

    🇻 Variable –> Energy

    incapacitated_time

    🇻 Variable –> TimeDuration

    invlet

    🇻 Variable –> integer

    powered

    🇻 Variable –> boolean

    show_sprite

    🇻 Variable –> boolean

    activate

    🇲 Method –> ( Character, boolean? ) -> boolean

    Activates this bionic on the given character. Optional block_message (default true) suppresses messages.

    ammo_loaded

    🇲 Method –> ( ) -> string

    deactivate

    🇲 Method –> ( Character, boolean? ) -> boolean

    Deactivates this bionic on the given character. Optional block_message (default true) suppresses messages.

    get_auto_start_thresh

    🇲 Method –> ( ) -> number

    get_quality

    🇲 Method –> ( string ) -> integer

    has_flag

    🇲 Method –> ( string ) -> boolean

    id

    🇲 Method –> ( ) -> BionicDataId

    info

    🇲 Method –> ( ) -> BionicDataRaw

    Returns the BionicData definition for this bionic.

    is_auto_start_keep_full

    🇲 Method –> ( ) -> boolean

    is_auto_start_on

    🇲 Method –> ( ) -> boolean

    is_fueled_by

    🇲 Method –> ( string ) -> boolean

    remove_flag

    🇲 Method –> ( string )

    set_auto_start_thresh

    🇲 Method –> ( number )

    set_flag

    🇲 Method –> ( string )

    toggle_auto_start_mod

    🇲 Method –> ( )

    toggle_safe_fuel_mod

    🇲 Method –> ( )

    BionicDataId

    Bases

    No base classes.

    Constructors

    • BionicDataId.new( )
    • BionicDataId.new( BionicDataId )
    • BionicDataId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> BionicDataId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> BionicDataRaw

    str

    🇲 Method –> ( ) -> string

    BionicDataRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    activated

    🇻 Variable –> boolean

    can_uninstall

    🇻 Variable –> boolean

    capacity

    🇻 Variable –> Energy

    charge_time

    🇻 Variable –> integer

    exothermic_power_gen

    🇻 Variable –> boolean

    fuel_capacity

    🇻 Variable –> integer

    fuel_efficiency

    🇻 Variable –> number

    fuel_multiplier

    🇻 Variable –> integer

    included

    🇻 Variable –> boolean

    is_remote_fueled

    🇻 Variable –> boolean

    kcal_trigger

    🇻 Variable –> integer

    no_uninstall_reason

    🇻 Variable –> string

    passive_fuel_efficiency

    🇻 Variable –> number

    points

    🇻 Variable –> integer

    power_activate

    🇻 Variable –> Energy

    power_deactivate

    🇻 Variable –> Energy

    power_over_time

    🇻 Variable –> Energy

    power_trigger

    🇻 Variable –> Energy

    remote_fuel_draw

    🇻 Variable –> Energy

    starting_bionic

    🇻 Variable –> boolean

    weight_capacity_bonus

    🇻 Variable –> Mass

    weight_capacity_modifier

    🇻 Variable –> number

    available_upgrades

    🇲 Method –> ( ) -> string[]

    Available upgrade paths for this bionic.

    bash_protec

    🇲 Method –> ( ) -> table<string, integer>

    Bash protection by body part.

    bullet_protec

    🇲 Method –> ( ) -> table<string, integer>

    Bullet protection by body part.

    canceled_mutations

    🇲 Method –> ( ) -> string[]

    Mutations/traits removed when this bionic is installed.

    coverage_power_gen_penalty

    🇲 Method –> ( ) -> number?

    Returns the coverage power gen penalty, or nil if not set.

    cut_protec

    🇲 Method –> ( ) -> table<string, integer>

    Cut protection by body part.

    description

    🇲 Method –> ( ) -> string

    Returns the translated description of this bionic.

    enchantments

    🇲 Method –> ( ) -> string[]

    Returns enchantment IDs as string values.

    encumbrance

    🇲 Method –> ( ) -> table<string, integer>

    Encumbrance caused by this bionic on each body part.

    env_protec

    🇲 Method –> ( ) -> table<string, integer>

    Environmental protection by body part.

    fake_item

    🇲 Method –> ( ) -> string

    flags

    🇲 Method –> ( ) -> string[]

    Returns the set of flag IDs on this bionic definition.

    fuel_opts

    🇲 Method –> ( ) -> string[]

    Returns fuel type IDs that can power this bionic.

    get_all

    🇫 Function –> ( ) -> BionicDataRaw[]

    Returns a list of every bionic definition in the game.

    has_flag

    🇲 Method –> ( string ) -> boolean

    Checks whether this bionic has a specific flag.

    id

    🇲 Method –> ( ) -> BionicDataId

    included_bionics

    🇲 Method –> ( ) -> string[]

    Bionics automatically installed alongside this one.

    learned_spells

    🇲 Method –> ( ) -> table<string, integer>

    Spells learned when this bionic is installed, mapped to level.

    name

    🇲 Method –> ( ) -> string

    Returns the translated name of this bionic.

    occupied_bodyparts

    🇲 Method –> ( ) -> table<string, integer>

    Body parts occupied by this bionic and slot space required.

    power_gen_emission

    🇲 Method –> ( ) -> string

    required_bionics

    🇲 Method –> ( ) -> string[]

    Other bionics required for this one to be installed.

    stat_bonus

    🇲 Method –> ( ) -> table<string, integer>

    Returns stat bonuses as a table mapping stat name to bonus value. Stat names are the translated abbreviations (STR, DEX, INT, PER in English).

    upgraded_bionic

    🇲 Method –> ( ) -> string

    BodyPartTypeId

    Bases

    No base classes.

    Constructors

    Members

    NULL_ID

    🇫 Function –> ( ) -> BodyPartTypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    int_id

    🇲 Method –> ( ) -> BodyPartTypeIntId

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> BodyPartTypeRaw

    str

    🇲 Method –> ( ) -> string

    BodyPartTypeIntId

    Bases

    No base classes.

    Constructors

    Members

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> BodyPartTypeRaw

    str_id

    🇲 Method –> ( ) -> BodyPartTypeId

    BookRecipe

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    hidden

    🇻 Variable –> boolean

    name

    🇻 Variable –> CppVal<translation>

    recipe

    🇻 Variable –> RecipeRaw

    skill_level

    🇻 Variable –> integer

    Character

    Bases

    • Creature

    Constructors

    No constructors.

    Members

    cash

    🇻 Variable –> integer

    focus_pool

    🇻 Variable –> integer

    follower_ids

    🇻 Variable –> CharacterId[]

    male

    🇻 Variable –> boolean

    mutation_category_level

    🇻 Variable –> table<MutationCategoryTraitId, integer>

    Strength of each mutation category, computed from the character’s mutations and their prerequisites. Categories without mutations are absent.

    name

    🇻 Variable –> string

    activate_bionic

    🇲 Method –> ( BionicDataId, boolean? ) -> boolean

    activate_mutation

    🇲 Method –> ( MutationBranchId )

    activate_mutation_id

    🇲 Method –> ( MutationBranchId )

    add_addiction

    🇲 Method –> ( AddictionType, integer )

    add_bionic

    🇲 Method –> ( BionicDataId )

    add_item

    🇲 Method –> ( Detached<Item> )

    Adds a detached item to the player inventory

    add_known_trap

    🇲 Method –> ( TripointBubMs, TrapIntId )

    Character learns that the given trap is on the given tripoint. If the trap is null, the character learns that there is no trap there.

    add_morale

    🇲 Method –> ( MoraleTypeDataId, integer, integer, TimeDuration, TimeDuration, boolean, ItypeRaw? )

    add_perk

    🇲 Method –> ( PerkId )

    addiction_level

    🇲 Method –> ( AddictionType ) -> integer

    age

    🇲 Method –> ( ) -> integer

    all_items

    🇲 Method –> ( boolean ) -> Item[]

    Gets all items

    all_items_with_flag

    🇲 Method –> ( JsonFlagId, boolean ) -> Item[]

    Gets all items with the given flag

    assign_activity

    🇲 Method –> ( ActivityTypeId, integer, integer, integer, string )

    assign_lua_activity

    🇲 Method –> ( table )

    Assigns a Lua-backed activity.
    The callbacks receive a table with keys user (Character), activity (PlayerActivity), name, data and pos.
    Takes a table with keys:

    • type (ActivityTypeId): Activity type.
    • duration (TimeDuration): How long the activity takes.
    • on_finish (string, optional): Key in game.activity_functions called when the activity finishes.
    • on_turn (string, optional): Key in game.activity_functions called every turn of the activity.
    • data (table, optional): Serializable Lua state passed back to the callbacks as params.data.
    • pos (TripointBubMs, optional): Activity position. Callbacks receive it as params.pos in absolute coordinates.
    • name (string, optional): Activity name, passed to the callbacks as params.name.
    • interruptable (boolean, optional): Whether a key press can interrupt the activity. Defaults to true.

    base_age

    🇲 Method –> ( ) -> integer

    base_height

    🇲 Method –> ( ) -> integer

    bionic_armor_bonus

    🇲 Method –> ( BodyPartTypeIntId, DamageType ) -> number

    bionics_weight

    🇲 Method –> ( ) -> Mass

    blood_loss

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    blossoms

    🇲 Method –> ( )

    bodypart_exposure

    🇲 Method –> ( ) -> table<BodyPartTypeIntId, number>

    Returns how exposed each body part is through worn items, from 0.0 (fully covered) to 1.0 (bare).

    bodyweight

    🇲 Method –> ( ) -> Mass

    bonus_from_enchantments

    🇲 Method –> ( number, EnchantmentValueId, boolean? ) -> number

    Gets the bonus from the enchantment value. Doesn’t handle max logic itself.

    can_hear

    🇲 Method –> ( TripointBubMs, integer ) -> boolean

    can_mount

    🇲 Method –> ( Monster ) -> boolean

    can_pick_volume

    🇲 Method –> ( Volume ) -> boolean

    can_pick_weight

    🇲 Method –> ( Mass, boolean ) -> boolean

    can_run

    🇲 Method –> ( ) -> boolean

    can_takeoff

    🇲 Method –> ( Item ) -> boolean

    Checks if a given <code>[Item](#sol::Item)</code> can be taken off.

    can_unwield

    🇲 Method –> ( Item ) -> boolean

    can_wear

    🇲 Method –> ( Item, boolean ) -> boolean

    Checks if creature can wear a given item. If boolean parameter is true, ignores already worn items

    can_wield

    🇲 Method –> ( Item ) -> boolean

    cancel_activity

    🇲 Method –> ( )

    check_mount_is_spooked

    🇲 Method –> ( ) -> boolean

    check_mount_will_move

    🇲 Method –> ( TripointBubMs ) -> boolean

    clear_bionics

    🇲 Method –> ( )

    clear_morale

    🇲 Method –> ( )

    clear_mutations

    🇲 Method –> ( )

    clear_skills

    🇲 Method –> ( )

    consume_items

    🇲 Method –> ( CppVal<item_comp>[] )

    Consumes items from inventory based on item component list

    consume_requirement

    🇲 Method –> ( RequirementData, table ) -> boolean

    Consumes a requirement’s item components from the inventory and nearby map. Tools and qualities are not used. Returns false if the player cancels a component choice.
    Takes a table with keys:

    • range (integer, optional): Radius for nearby map items. Defaults to the pickup range.
    • count (integer, optional): Number of times to consume the requirement. Defaults to 1.

    consume_tools

    🇲 Method –> ( CppVal<tool_comp>[] )

    Consumes tool charges from inventory based on tool component list

    cough

    🇲 Method –> ( boolean, integer )

    crafting_inventory

    🇲 Method –> ( ) -> Inventory

    Returns the crafting inventory for this character (includes nearby items)

    create_item

    🇲 Method –> ( ItypeId, integer ) -> Item

    Creates an item with the given id and adds it to the player inventory. count sets the item’s charges, not the number of items: exactly one item is created. For stackable (count-by-charges) items such as ammo, count is the stack size. For non-stackable items, pass a negative value (e.g. -1), since a positive one is still applied as charges. Tools spawned with a negative value get their default charges.

    crossed_threshold

    🇲 Method –> ( ) -> boolean

    deactivate_bionic

    🇲 Method –> ( BionicDataId, boolean? ) -> boolean

    deactivate_mutation

    🇲 Method –> ( MutationBranchId )

    deactivate_mutation_id

    🇲 Method –> ( MutationBranchId )

    dismount

    🇲 Method –> ( )

    drench

    🇲 Method –> ( integer, BodyPartTypeIntId[], boolean )

    drop_all_items

    🇲 Method –> ( )

    Drops all items (inventory, worn, wielded) at the character’s current position.

    drop_inv

    🇲 Method –> ( integer )

    enough_power_for

    🇲 Method –> ( BionicDataId ) -> boolean

    expose_to_disease

    🇲 Method –> ( DiseaseTypeId )

    fall_asleep

    🇲 Method –> ( )
    🇲 Method –> ( TimeDuration )

    forced_dismount

    🇲 Method –> ( )

    getID

    🇲 Method –> ( ) -> CharacterId

    get_activity

    🇲 Method –> ( ) -> PlayerActivity

    get_all_skills

    🇲 Method –> ( ) -> SkillLevelMap

    get_armor_acid

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_auto_start_thresh

    🇲 Method –> ( BionicDataId ) -> number

    get_base_traits

    🇲 Method –> ( ) -> MutationBranchId[]

    get_bionic

    🇲 Method –> ( BionicDataId ) -> Bionic

    get_bionics

    🇲 Method –> ( ) -> BionicDataId[]

    get_dependant_worn_items

    🇲 Method –> ( Item ) -> Item[]

    get_dex

    🇲 Method –> ( ) -> integer

    get_dex_base

    🇲 Method –> ( ) -> integer

    get_dex_bonus

    🇲 Method –> ( ) -> integer

    get_faction_id

    🇲 Method –> ( ) -> FactionId

    get_fatigue

    🇲 Method –> ( ) -> integer

    get_free_bionics_slots

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_healthy

    🇲 Method –> ( ) -> number

    get_healthy_mod

    🇲 Method –> ( ) -> number

    get_highest_category

    🇲 Method –> ( ) -> MutationCategoryTraitId

    get_hostile_creatures

    🇲 Method –> ( integer ) -> Creature[]

    get_int

    🇲 Method –> ( ) -> integer

    get_int_base

    🇲 Method –> ( ) -> integer

    get_int_bonus

    🇲 Method –> ( ) -> integer

    get_item_with_id

    🇲 Method –> ( ItypeId, boolean ) -> Item

    Gets the first occurrence of an item with the given id

    get_items_if

    🇲 Method –> ( table ) -> Item[]

    Returns items from the inventory, wielded and worn, matching every given filter as an array of Item.
    Takes a table where each key is a filter; unknown keys show a debug message and are ignored. Available filters:

    • category (string or string[]): Item category id is one of these, e.g. “food”.
    • type (ItemTypeId or ItemTypeId[]): Item type is one of these.
    • is_food (boolean): Whether the item is food.
    • flags (FlagId or FlagId[]): Item has at least one of these flags.
    • need_charges (boolean): Tool items must have charges left.
    • has_charges (table): { id = ItemTypeId, amount = integer }: item type is id and has at least amount charges.
    • addiction_type (AddictionType, string, or array of those): Comestible’s addiction type is one of these, e.g. <code>[AddictionType](#sol::AddictionType)</code>.ALCOHOL or "alcohol".
    • material (MaterialTypeId, string, or array of those): Item is made of at least one of these materials, e.g. "stone".
    • worn (boolean): Whether the item is worn.
    • wielded (boolean): Whether the item is wielded.

    get_kcal_percent

    🇲 Method –> ( ) -> number

    get_lowest_hp

    🇲 Method –> ( ) -> integer

    get_magic

    🇲 Method –> ( ) -> KnownMagic

    Access the character’s spellbook and mana pool.

    get_max_power_level

    🇲 Method –> ( ) -> Energy

    get_melee_stamina_cost

    🇲 Method –> ( Item ) -> integer

    get_morale

    🇲 Method –> ( MoraleTypeDataId ) -> integer

    get_morale_level

    🇲 Method –> ( ) -> integer

    get_movement_mode

    🇲 Method –> ( ) -> CharacterMoveMode

    get_mutations

    🇲 Method –> ( boolean ) -> MutationBranchId[]

    get_painkiller

    🇲 Method –> ( ) -> integer

    get_part_encumbrance

    🇲 Method –> ( BodyPartTypeId ) -> integer

    get_part_temp_btu

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    Deprecated: use get_part_temp_celsius instead. Gets the current temperature of a specific body part in legacy Body Temperature Units.

    get_part_temp_celsius

    🇲 Method –> ( BodyPartTypeIntId ) -> Temperature

    Gets the current temperature of a specific body part in Celsius.

    get_per

    🇲 Method –> ( ) -> integer

    get_per_base

    🇲 Method –> ( ) -> integer

    get_per_bonus

    🇲 Method –> ( ) -> integer

    get_power_level

    🇲 Method –> ( ) -> Energy

    get_rad

    🇲 Method –> ( ) -> integer

    get_shout_volume

    🇲 Method –> ( ) -> integer

    get_skill_level

    🇲 Method –> ( SkillId ) -> integer

    get_skill_level_object

    🇲 Method –> ( SkillId ) -> SkillLevel

    get_sleep_deprivation

    🇲 Method –> ( ) -> integer

    get_stamina

    🇲 Method –> ( ) -> integer

    get_stamina_max

    🇲 Method –> ( ) -> integer

    get_stim

    🇲 Method –> ( ) -> integer

    get_stored_kcal

    🇲 Method –> ( ) -> integer

    get_str

    🇲 Method –> ( ) -> integer

    get_str_base

    🇲 Method –> ( ) -> integer

    get_str_bonus

    🇲 Method –> ( ) -> integer

    get_temp_btu

    🇲 Method –> ( ) -> table<BodyPartTypeIntId, integer>

    Deprecated: use get_temp_celsius instead. Gets all bodyparts and their associated temperatures in legacy Body Temperature Units.

    get_temp_celsius

    🇲 Method –> ( ) -> table<BodyPartTypeIntId, Temperature>

    Gets all bodyparts and their associated temperatures in Celsius.

    get_thirst

    🇲 Method –> ( ) -> integer

    get_time_died

    🇲 Method –> ( ) -> TimePoint

    get_total_bionics_slots

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_used_bionics_slots

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_visible_creatures

    🇲 Method –> ( integer ) -> Creature[]

    get_working_arm_count

    🇲 Method –> ( ) -> integer

    get_working_leg_count

    🇲 Method –> ( ) -> integer

    get_worn_items

    🇲 Method –> ( ) -> Item[]

    global_sm_location

    🇲 Method –> ( ) -> TripointAbsSm

    global_square_location

    🇲 Method –> ( ) -> TripointAbsMs

    has_active_bionic

    🇲 Method –> ( BionicDataId ) -> boolean

    has_active_mutation

    🇲 Method –> ( MutationBranchId ) -> boolean

    has_activity

    🇲 Method –> ( ActivityTypeId ) -> boolean

    has_addiction

    🇲 Method –> ( AddictionType ) -> boolean

    has_alarm_clock

    🇲 Method –> ( ) -> boolean

    has_any_bionic

    🇲 Method –> ( ) -> boolean

    has_base_trait

    🇲 Method –> ( MutationBranchId ) -> boolean

    has_bionic

    🇲 Method –> ( BionicDataId ) -> boolean

    has_bionics

    🇲 Method –> ( ) -> boolean

    has_child_flag

    🇲 Method –> ( MutationBranchId ) -> boolean

    has_enchantment_flag

    🇲 Method –> ( EnchantmentFlagId ) -> boolean

    has_item_with_flag

    🇲 Method –> ( JsonFlagId, boolean ) -> boolean

    Checks for an item with the given flag

    has_item_with_id

    🇲 Method –> ( ItypeId, boolean ) -> boolean

    Checks for an item with the given id

    has_mabuff

    🇲 Method –> ( MartialArtsBuffId ) -> boolean

    has_max_power

    🇲 Method –> ( ) -> boolean

    has_morale

    🇲 Method –> ( MoraleTypeDataId ) -> boolean

    has_morale_to_craft

    🇲 Method –> ( ) -> boolean

    has_morale_to_read

    🇲 Method –> ( ) -> boolean

    has_opposite_trait

    🇲 Method –> ( MutationBranchId ) -> boolean

    has_perk

    🇲 Method –> ( PerkId ) -> boolean

    has_power

    🇲 Method –> ( ) -> boolean

    has_trait_flag

    🇲 Method –> ( JsonTraitFlagId ) -> boolean

    has_trait_type

    🇲 Method –> ( string ) -> boolean

    has_two_arms

    🇲 Method –> ( ) -> boolean

    has_watch

    🇲 Method –> ( ) -> boolean

    heal

    🇲 Method –> ( BodyPartTypeIntId, integer )

    healall

    🇲 Method –> ( integer )

    healing_rate

    🇲 Method –> ( number ) -> number

    healing_rate_medicine

    🇲 Method –> ( number, BodyPartTypeIntId ) -> number

    hearing_ability

    🇲 Method –> ( ) -> number

    height

    🇲 Method –> ( ) -> integer

    hitall

    🇲 Method –> ( integer, integer, Creature ) -> integer

    hurtall

    🇲 Method –> ( integer, Creature, boolean )

    in_climate_control

    🇲 Method –> ( ) -> boolean

    invalidate_crafting_inventory

    🇲 Method –> ( )

    Invalidates the cached crafting inventory

    irradiate

    🇲 Method –> ( number, boolean ) -> boolean

    is_armed

    🇲 Method –> ( ) -> boolean

    is_auto_start_keep_full

    🇲 Method –> ( BionicDataId ) -> boolean

    is_auto_start_on

    🇲 Method –> ( BionicDataId ) -> boolean

    is_blind

    🇲 Method –> ( ) -> boolean

    is_deaf

    🇲 Method –> ( ) -> boolean

    is_hauling

    🇲 Method –> ( ) -> boolean

    is_invisible

    🇲 Method –> ( ) -> boolean

    is_limb_broken

    🇲 Method –> ( BodyPartTypeIntId ) -> boolean

    is_limb_disabled

    🇲 Method –> ( BodyPartTypeIntId ) -> boolean

    is_max_power

    🇲 Method –> ( ) -> boolean

    is_mounted

    🇲 Method –> ( ) -> boolean

    is_quiet

    🇲 Method –> ( ) -> boolean

    is_rad_immune

    🇲 Method –> ( ) -> boolean

    is_stealthy

    🇲 Method –> ( ) -> boolean

    is_throw_immune

    🇲 Method –> ( ) -> boolean

    is_weak_to_water

    🇲 Method –> ( ) -> boolean

    is_wearing

    🇲 Method –> ( Item ) -> boolean

    is_wearing_active_optcloak

    🇲 Method –> ( ) -> boolean

    is_wearing_active_power_armor

    🇲 Method –> ( ) -> boolean

    is_wearing_helmet

    🇲 Method –> ( ) -> boolean

    is_wearing_on_bp

    🇲 Method –> ( ItypeId, BodyPartTypeIntId ) -> boolean

    is_wearing_power_armor

    🇲 Method –> ( boolean ) -> boolean

    is_wielding

    🇲 Method –> ( Item ) -> boolean

    is_worn

    🇲 Method –> ( Item ) -> boolean

    item_worn_with_flag

    🇲 Method –> ( JsonFlagId, BodyPartTypeIntId ) -> Item

    item_worn_with_id

    🇲 Method –> ( ItypeId, BodyPartTypeIntId ) -> Item

    items_with

    🇲 Method –> ( bool ) -> Item[]

    Filters items

    knows_martial_art

    🇲 Method –> ( MartialArtsId ) -> boolean

    knows_recipe

    🇲 Method –> ( RecipeId ) -> boolean

    knows_trap

    🇲 Method –> ( TripointBubMs ) -> boolean

    Whether the character knows about the trap at the given tripoint.

    learn_martial_art

    🇲 Method –> ( MartialArtsId )

    learn_recipe

    🇲 Method –> ( RecipeId )

    mabuff_armor_bonus

    🇲 Method –> ( DamageType ) -> integer

    mabuff_arpen_bonus

    🇲 Method –> ( DamageType ) -> integer

    mabuff_attack_cost_mult

    🇲 Method –> ( ) -> number

    mabuff_attack_cost_penalty

    🇲 Method –> ( ) -> integer

    mabuff_block_bonus

    🇲 Method –> ( ) -> integer

    mabuff_damage_bonus

    🇲 Method –> ( DamageType ) -> integer

    mabuff_damage_mult

    🇲 Method –> ( DamageType ) -> number

    mabuff_dodge_bonus

    🇲 Method –> ( ) -> number

    mabuff_speed_bonus

    🇲 Method –> ( ) -> integer

    mabuff_tohit_bonus

    🇲 Method –> ( ) -> number

    max_stored_kcal

    🇲 Method –> ( ) -> integer

    metabolic_rate

    🇲 Method –> ( ) -> number

    mod_base_age

    🇲 Method –> ( integer )

    mod_base_height

    🇲 Method –> ( integer )

    mod_dex_bonus

    🇲 Method –> ( integer )

    mod_fatigue

    🇲 Method –> ( integer )

    mod_healthy

    🇲 Method –> ( number )

    mod_healthy_mod

    🇲 Method –> ( number, number )

    mod_int_bonus

    🇲 Method –> ( integer )

    mod_max_power_level

    🇲 Method –> ( Energy )

    mod_painkiller

    🇲 Method –> ( integer )

    mod_per_bonus

    🇲 Method –> ( integer )

    mod_power_level

    🇲 Method –> ( Energy )

    mod_rad

    🇲 Method –> ( integer )

    mod_skill_level

    🇲 Method –> ( SkillId, integer )

    mod_sleep_deprivation

    🇲 Method –> ( integer )

    mod_speed_bonus

    🇲 Method –> ( integer )

    mod_stamina

    🇲 Method –> ( integer )

    mod_stim

    🇲 Method –> ( integer )

    mod_stored_kcal

    🇲 Method –> ( integer )

    mod_str_bonus

    🇲 Method –> ( integer )

    mod_thirst

    🇲 Method –> ( integer )

    mount_creature

    🇲 Method –> ( Monster )

    mutate

    🇲 Method –> ( )

    mutate_category

    🇲 Method –> ( MutationCategoryTraitId )
    🇲 Method –> ( MutationCategoryTraitId, boolean )

    mutate_towards

    🇲 Method –> ( MutationBranchId[], integer ) -> boolean
    🇲 Method –> ( MutationBranchId ) -> boolean

    mutation_armor

    🇲 Method –> ( BodyPartTypeIntId, DamageType ) -> number

    mutation_effect

    🇲 Method –> ( MutationBranchId )

    mutation_loss_effect

    🇲 Method –> ( MutationBranchId )

    mutation_ok

    🇲 Method –> ( MutationBranchId, boolean, boolean ) -> boolean

    mutation_value

    🇲 Method –> ( string ) -> number

    practice

    🇲 Method –> ( SkillId, integer, integer, boolean )

    read_speed

    🇲 Method –> ( boolean ) -> integer

    rem_addiction

    🇲 Method –> ( AddictionType )

    rem_morale

    🇲 Method –> ( MoraleTypeDataId )

    remove_bionic

    🇲 Method –> ( BionicDataId )

    remove_child_flag

    🇲 Method –> ( MutationBranchId )

    remove_item

    🇲 Method –> ( Item ) -> Detached<Item>

    Removes given <code>[Item](#sol::Item)</code> from character’s inventory. The <code>[Item](#sol::Item)</code> must be in the inventory, neither wielded nor worn.

    remove_items_if

    🇲 Method –> ( table ) -> Detached<Item>[]

    Removes and returns items from the inventory, wielded and worn, matching every given filter as an array of Item.
    Accepts the same filter table as get_items_if.

    remove_mutation

    🇲 Method –> ( MutationBranchId, boolean )

    remove_perk

    🇲 Method –> ( PerkId )

    remove_worn

    🇲 Method –> ( Item ) -> Detached<Item>?

    Attempts to remove the worn <code>[Item](#sol::Item)</code> from character.

    reset

    🇲 Method –> ( )

    reset_encumbrance

    🇲 Method –> ( )

    rest_quality

    🇲 Method –> ( ) -> number

    restore_scent

    🇲 Method –> ( )

    rooted

    🇲 Method –> ( )

    rust_rate

    🇲 Method –> ( ) -> integer

    setID

    🇲 Method –> ( CharacterId, boolean )

    set_auto_start_thresh

    🇲 Method –> ( BionicDataId, number )

    set_base_age

    🇲 Method –> ( integer )

    set_base_height

    🇲 Method –> ( integer )

    set_dex_bonus

    🇲 Method –> ( integer )

    set_faction_id

    🇲 Method –> ( FactionId )

    set_fatigue

    🇲 Method –> ( integer )

    set_healthy

    🇲 Method –> ( number )

    set_healthy_mod

    🇲 Method –> ( number )

    set_int_bonus

    🇲 Method –> ( integer )

    set_max_power_level

    🇲 Method –> ( Energy )

    set_movement_mode

    🇲 Method –> ( CharacterMoveMode )

    set_mutation

    🇲 Method –> ( MutationBranchId )

    set_painkiller

    🇲 Method –> ( integer )

    set_part_temp_btu

    🇲 Method –> ( BodyPartTypeIntId, integer )

    Deprecated: use set_part_temp_celsius instead. Sets a specific body part to a given legacy Body Temperature Units value.

    set_part_temp_celsius

    🇲 Method –> ( BodyPartTypeIntId, Temperature )

    Sets a specific body part to a temperature in Celsius.

    set_per_bonus

    🇲 Method –> ( integer )

    set_power_level

    🇲 Method –> ( Energy )

    set_rad

    🇲 Method –> ( integer )

    set_skill_level

    🇲 Method –> ( SkillId, integer )

    set_sleep_deprivation

    🇲 Method –> ( integer )

    set_speed_bonus

    🇲 Method –> ( integer )

    set_stamina

    🇲 Method –> ( integer )

    set_stim

    🇲 Method –> ( integer )

    set_stored_kcal

    🇲 Method –> ( integer )

    set_str_bonus

    🇲 Method –> ( integer )

    set_temp_btu

    🇲 Method –> ( integer )

    Deprecated: use set_temp_celsius instead. Sets ALL body parts on a creature to the given legacy Body Temperature Units value.

    set_temp_celsius

    🇲 Method –> ( Temperature )

    Sets ALL body parts on a creature to the given temperature in Celsius.

    set_thirst

    🇲 Method –> ( integer )

    shout

    🇲 Method –> ( string, boolean )

    sight_impaired

    🇲 Method –> ( ) -> boolean

    sound_hallu

    🇲 Method –> ( )

    spores

    🇲 Method –> ( )

    suffer

    🇲 Method –> ( )

    takeoff

    🇲 Method –> ( Item ) -> boolean

    Attempts to take off the worn <code>[Item](#sol::Item)</code> from character.

    toggle_auto_start_mod

    🇲 Method –> ( BionicDataId )

    toggle_safe_fuel_mod

    🇲 Method –> ( BionicDataId )

    uncanny_dodge

    🇲 Method –> ( ) -> boolean

    unset_mutation

    🇲 Method –> ( MutationBranchId )

    unwield

    🇲 Method –> ( ) -> boolean

    use_charges

    🇲 Method –> ( ItypeId, integer ) -> Detached<Item>[]
    🇲 Method –> ( ItypeId, integer, function ) -> Detached<Item>[]

    use_charges_if_avail

    🇲 Method –> ( ItypeId, integer ) -> boolean

    vitamin_get

    🇲 Method –> ( VitaminId ) -> integer

    vitamin_mod

    🇲 Method –> ( VitaminId, integer, boolean ) -> integer

    vitamin_set

    🇲 Method –> ( VitaminId, integer ) -> boolean

    volume_capacity

    🇲 Method –> ( ) -> Volume

    volume_carried

    🇲 Method –> ( ) -> Volume

    vomit

    🇲 Method –> ( )

    wake_up

    🇲 Method –> ( )

    wear

    🇲 Method –> ( Item, boolean ) -> boolean

    Attempts to wear an item in the creature inventory. If boolean parameter is false, item is worn instantly

    wear_detached

    🇲 Method –> ( Detached<Item>, boolean ) -> boolean

    Attempts to wear an item not in the creature inventory. If boolean parameter is false, item is worn instantly

    wearing_something_on

    🇲 Method –> ( BodyPartTypeIntId ) -> boolean

    weight_carried

    🇲 Method –> ( ) -> Mass

    wield

    🇲 Method –> ( Item ) -> boolean

    wielded_items

    🇲 Method –> ( ) -> Item[]

    worn_with_flag

    🇲 Method –> ( JsonFlagId, BodyPartTypeIntId ) -> boolean

    worn_with_id

    🇲 Method –> ( ItypeId, BodyPartTypeIntId ) -> boolean

    CharacterId

    Bases

    No base classes.

    Constructors

    • CharacterId.new( )
    • CharacterId.new( int )

    Members

    get_value

    🇲 Method –> ( ) -> integer

    is_valid

    🇲 Method –> ( ) -> boolean

    Creature

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    abs_pos

    🇲 Method –> ( ) -> TripointAbsMs

    add_effect

    🇲 Method –> ( EffectTypeId, TimeDuration, BodyPartTypeId?, integer? )

    Effect type, duration, bodypart and intensity

    apply_damage

    🇲 Method –> ( Creature, BodyPartTypeIntId, integer, boolean )

    as_avatar

    🇲 Method –> ( ) -> Avatar

    as_character

    🇲 Method –> ( ) -> Character

    as_monster

    🇲 Method –> ( ) -> Monster

    as_npc

    🇲 Method –> ( ) -> Npc

    attitude_to

    🇲 Method –> ( Creature ) -> Attitude

    bub_pos

    🇲 Method –> ( ) -> TripointBubMs

    clear_effects

    🇲 Method –> ( )

    deal_damage

    🇲 Method –> ( Creature, BodyPartTypeIntId, DamageInstance ) -> DealtDamageInstance

    digging

    🇲 Method –> ( ) -> boolean

    disp_name

    🇲 Method –> ( possessive: boolean, capitalize_first: boolean ) -> string

    dodge_roll

    🇲 Method –> ( ) -> number

    erase

    🇲 Method –> ( )

    Removes this creature from the game without death notifications or a corpse.

    get_all_body_parts

    🇲 Method –> ( boolean ) -> BodyPartTypeIntId[]

    get_armor_bash

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_armor_bash_base

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_armor_bash_bonus

    🇲 Method –> ( ) -> integer

    get_armor_bullet

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_armor_bullet_base

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_armor_bullet_bonus

    🇲 Method –> ( ) -> integer

    get_armor_cut

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_armor_cut_base

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_armor_cut_bonus

    🇲 Method –> ( ) -> integer

    get_armor_type

    🇲 Method –> ( DamageType, BodyPartTypeIntId ) -> integer

    get_block_bonus

    🇲 Method –> ( ) -> integer

    get_dodge

    🇲 Method –> ( ) -> number

    get_dodge_base

    🇲 Method –> ( ) -> number

    get_dodge_bonus

    🇲 Method –> ( ) -> number

    get_effect

    🇲 Method –> ( EffectTypeId, BodyPartTypeId? ) -> Effect

    get_effect_dur

    🇲 Method –> ( EffectTypeId, BodyPartTypeId? ) -> TimeDuration

    get_effect_int

    🇲 Method –> ( EffectTypeId, BodyPartTypeId? ) -> integer

    get_env_resist

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_grammatical_genders

    🇲 Method –> ( ) -> string[]

    get_hit

    🇲 Method –> ( ) -> number

    get_hit_base

    🇲 Method –> ( ) -> number

    get_hit_bonus

    🇲 Method –> ( ) -> number

    get_hp

    🇲 Method –> ( BodyPartTypeIntId? ) -> integer

    get_hp_max

    🇲 Method –> ( BodyPartTypeIntId? ) -> integer

    get_melee

    🇲 Method –> ( ) -> number

    get_moves

    🇲 Method –> ( ) -> integer

    get_name

    🇲 Method –> ( ) -> string

    get_num_blocks

    🇲 Method –> ( ) -> integer

    get_num_dodges

    🇲 Method –> ( ) -> integer

    get_pain

    🇲 Method –> ( ) -> integer

    get_part_healed_total

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_part_hp_cur

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_part_hp_max

    🇲 Method –> ( BodyPartTypeIntId ) -> integer

    get_perceived_pain

    🇲 Method –> ( ) -> integer

    get_pos_ms

    🇲 Method –> ( ) -> TripointBubMs

    get_random_body_part

    🇲 Method –> ( boolean ) -> BodyPartTypeIntId

    get_size

    🇲 Method –> ( ) -> MonsterSize

    get_speed

    🇲 Method –> ( ) -> integer

    get_speed_base

    🇲 Method –> ( ) -> integer

    get_speed_bonus

    🇲 Method –> ( ) -> integer

    get_speed_mult

    🇲 Method –> ( ) -> number

    get_value

    🇲 Method –> ( string ) -> string

    Retrieves an arbitrary entry using the same key format as set_value.

    get_weight

    🇲 Method –> ( ) -> Mass

    get_weight_capacity

    🇲 Method –> ( ) -> integer

    has_effect

    🇲 Method –> ( EffectTypeId, BodyPartTypeId? ) -> boolean

    has_effect_with_flag

    🇲 Method –> ( JsonFlagId, BodyPartTypeId? ) -> boolean

    has_flag

    🇲 Method –> ( MonsterFlag ) -> boolean

    has_grab_break_tec

    🇲 Method –> ( ) -> boolean

    has_trait

    🇲 Method –> ( MutationBranchId ) -> boolean

    has_weapon

    🇲 Method –> ( ) -> boolean

    hp_percentage

    🇲 Method –> ( ) -> integer

    in_species

    🇲 Method –> ( SpeciesTypeId ) -> boolean

    is_avatar

    🇲 Method –> ( ) -> boolean

    is_dead

    🇲 Method –> ( ) -> boolean

    is_elec_immune

    🇲 Method –> ( ) -> boolean

    is_hallucination

    🇲 Method –> ( ) -> boolean

    is_immune_damage

    🇲 Method –> ( DamageType ) -> boolean

    is_immune_effect

    🇲 Method –> ( EffectTypeId ) -> boolean

    is_monster

    🇲 Method –> ( ) -> boolean

    is_npc

    🇲 Method –> ( ) -> boolean

    is_on_ground

    🇲 Method –> ( ) -> boolean

    is_underwater

    🇲 Method –> ( ) -> boolean

    is_warm

    🇲 Method –> ( ) -> boolean

    knock_back_to

    🇲 Method –> ( TripointBubMs )

    mod_all_parts_hp_cur

    🇲 Method –> ( integer )

    mod_moves

    🇲 Method –> ( integer )

    mod_pain

    🇲 Method –> ( integer )

    mod_pain_noresist

    🇲 Method –> ( integer )

    mod_part_hp_cur

    🇲 Method –> ( BodyPartTypeIntId, integer )

    mod_part_hp_max

    🇲 Method –> ( BodyPartTypeIntId, integer )

    power_rating

    🇲 Method –> ( ) -> number

    ranged_target_size

    🇲 Method –> ( ) -> number

    remove_effect

    🇲 Method –> ( EffectTypeId, BodyPartTypeId? ) -> boolean

    remove_value

    🇲 Method –> ( string )

    Removes an arbitrary entry using the same key format as set_value.

    sees

    🇲 Method –> ( TripointBubMs ) -> boolean

    set_all_parts_hp_cur

    🇲 Method –> ( integer )

    set_all_parts_hp_to_max

    🇲 Method –> ( )

    set_armor_bash_bonus

    🇲 Method –> ( integer )

    set_armor_bullet_bonus

    🇲 Method –> ( integer )

    set_armor_cut_bonus

    🇲 Method –> ( integer )

    set_moves

    🇲 Method –> ( integer )

    set_pain

    🇲 Method –> ( integer )

    set_part_hp_cur

    🇲 Method –> ( BodyPartTypeIntId, integer )

    set_part_hp_max

    🇲 Method –> ( BodyPartTypeIntId, integer )

    set_pos

    🇲 Method –> ( TripointBubMs )
    🇲 Method –> ( TripointAbsMs )

    set_pos_ms

    🇲 Method –> ( TripointBubMs )

    set_underwater

    🇲 Method –> ( boolean )

    set_value

    🇲 Method –> ( string, string )

    Sets an arbitrary key : value pair for the creature.NPC dialogue system uses this, with the format(“npctalk_var” + “” + type_var + “” + var_context + “_” + var_base_name) used for the key, skipping type or context if empty.

    sight_range

    🇲 Method –> ( integer ) -> integer

    size_melee_penalty

    🇲 Method –> ( ) -> integer

    skin_name

    🇲 Method –> ( ) -> string

    speed_rating

    🇲 Method –> ( ) -> number

    stability_roll

    🇲 Method –> ( ) -> number

    values_table

    🇲 Method –> ( ) -> table

    Returns all stored creature vars as a table mapping each key (string) to its value (string), as written by set_value.

    DamageInstance

    Represents a bunch of damage amounts
    Constructors are:
    new(damageType, amount, armorPen, remainingArmorMultiplier, damageMultiplier)

    Bases

    No base classes.

    Constructors

    • DamageInstance.new( )
    • DamageInstance.new( DamageType, double, double, double, double )

    Members

    damage_units

    🇻 Variable –> DamageUnit[]

    add

    🇲 Method –> ( DamageUnit )

    add_damage

    🇲 Method –> ( DamageType, number, number, number, number )

    clear

    🇲 Method –> ( )

    empty

    🇲 Method –> ( ) -> boolean

    mult_damage

    🇲 Method –> ( number, boolean )

    total_damage

    🇲 Method –> ( ) -> number

    type_damage

    🇲 Method –> ( DamageType ) -> number

    DamageUnit

    Represents a damage amount
    Constructors are:
    new()
    new(damageType, amount, armorPen, remainingArmorMultiplier, damageMultiplier)

    Bases

    No base classes.

    Constructors

    • DamageUnit.new( DamageType, double, double, double, double )

    Members

    amount

    🇻 Variable –> number

    damage_multiplier

    🇻 Variable –> number

    res_mult

    🇻 Variable –> number

    res_pen

    🇻 Variable –> number

    type

    🇻 Variable –> DamageType

    DealtDamageInstance

    Represents the final dealt damage

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    bp_hit

    🇻 Variable –> BodyPartTypeId

    dealt_dams

    🇻 Variable –> integer[]

    total_damage

    🇲 Method –> ( ) -> integer

    type_damage

    🇲 Method –> ( DamageType ) -> integer

    DiseaseTypeId

    Bases

    No base classes.

    Constructors

    • DiseaseTypeId.new( )
    • DiseaseTypeId.new( DiseaseTypeId )
    • DiseaseTypeId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> DiseaseTypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> DiseaseTypeRaw

    str

    🇲 Method –> ( ) -> string

    DistributionGrid

    A grid that organizes producers, storage and consumers of a resource like electricity

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    empty

    🇲 Method –> ( ) -> boolean

    Check if grid is empty

    get_contents

    🇲 Method –> ( ) -> TripointAbsMs[]

    Get current resource amount. Boolean argument (optional) controls recursive behavior (default true) Get vector of absolute map square coordinates of grid contents

    get_power_stat

    🇲 Method –> ( ) -> PowerStat

    Get power generation and consumption statistics for the grid

    get_resource

    🇲 Method –> ( boolean? ) -> integer

    Modify resource amount. First argument is amount, second (optional) controls recursive behavior (default true)

    is_valid

    🇲 Method –> ( ) -> boolean

    Check if grid is valid

    mod_resource

    🇲 Method –> ( integer, boolean? ) -> integer

    update

    🇲 Method –> ( TimePoint )

    Update the grid to the given time point

    DistributionGridTracker

    Manages all active distribution grids

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    debug_grid_id

    🇲 Method –> ( TripointAbsOmt ) -> integer

    Get unique identifier for grid at given overmap tile (for debug purposes, returns 0 if no grid)

    grid_at

    🇲 Method –> ( TripointAbsMs ) -> DistributionGrid
    🇲 Method –> ( TripointAbsMs ) -> DistributionGrid

    Get grid at absolute map square position

    on_changed

    🇲 Method –> ( TripointAbsMs )

    Notify tracker that a tile at the given position has changed

    on_options_changed

    🇲 Method –> ( )

    Notify tracker that game options have changed

    update

    🇲 Method –> ( TimePoint )

    Update all grids to the given time point

    Effect

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    activated

    🇲 Method –> ( TimePoint, string, integer, boolean, number ) -> boolean

    decay

    🇲 Method –> ( TimePoint, boolean ) -> boolean

    disp_desc

    🇲 Method –> ( boolean ) -> string

    disp_name

    🇲 Method –> ( ) -> string

    disp_short_desc

    🇲 Method –> ( boolean ) -> string

    get_addict_mod

    🇲 Method –> ( string, integer ) -> number

    get_amount

    🇲 Method –> ( string, boolean ) -> integer

    get_avg_mod

    🇲 Method –> ( string, boolean ) -> integer

    get_blocks_effects

    🇲 Method –> ( ) -> EffectTypeId[]

    get_bp

    🇲 Method –> ( ) -> BodyPartTypeId

    get_dur_add_perc

    🇲 Method –> ( ) -> integer

    get_duration

    🇲 Method –> ( ) -> TimeDuration

    get_harmful_cough

    🇲 Method –> ( ) -> boolean

    get_id

    🇲 Method –> ( ) -> EffectTypeId

    get_int_add_val

    🇲 Method –> ( ) -> integer

    get_int_dur_factor

    🇲 Method –> ( ) -> TimeDuration

    get_intensity

    🇲 Method –> ( ) -> integer

    get_max_duration

    🇲 Method –> ( ) -> TimeDuration

    get_max_intensity

    🇲 Method –> ( ) -> integer

    get_max_val

    🇲 Method –> ( string, boolean ) -> integer

    get_min_val

    🇲 Method –> ( string, boolean ) -> integer

    get_mod

    🇲 Method –> ( string, boolean ) -> integer

    get_percentage

    🇲 Method –> ( string, integer, boolean ) -> number

    get_removes_effects

    🇲 Method –> ( ) -> EffectTypeId[]

    get_resist_effects

    🇲 Method –> ( ) -> EffectTypeId[]

    get_resist_traits

    🇲 Method –> ( ) -> MutationBranchId[]

    get_sizing

    🇲 Method –> ( string ) -> boolean

    get_start_time

    🇲 Method –> ( ) -> TimePoint

    get_type

    🇲 Method –> ( ) -> EffectTypeRaw

    has_flag

    🇲 Method –> ( JsonFlagId ) -> boolean

    is_permanent

    🇲 Method –> ( ) -> boolean

    mod_duration

    🇲 Method –> ( TimeDuration, boolean )

    mod_intensity

    🇲 Method –> ( integer, boolean ) -> integer

    mult_duration

    🇲 Method –> ( number, boolean )

    set_duration

    🇲 Method –> ( TimeDuration, boolean )

    set_intensity

    🇲 Method –> ( integer, boolean ) -> integer

    set_permanent

    🇲 Method –> ( )

    use_part_descs

    🇲 Method –> ( ) -> boolean

    EffectTypeId

    Bases

    No base classes.

    Constructors

    • EffectTypeId.new( )
    • EffectTypeId.new( EffectTypeId )
    • EffectTypeId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> EffectTypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> EffectTypeRaw

    str

    🇲 Method –> ( ) -> string

    EnchantmentFlagId

    Bases

    No base classes.

    Constructors

    • EnchantmentFlagId.new( )
    • EnchantmentFlagId.new( EnchantmentFlagId )
    • EnchantmentFlagId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> EnchantmentFlagId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> EnchantmentFlagRaw

    str

    🇲 Method –> ( ) -> string

    EnchantmentId

    Bases

    No base classes.

    Constructors

    • EnchantmentId.new( )
    • EnchantmentId.new( EnchantmentId )
    • EnchantmentId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> EnchantmentId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> Enchantment

    str

    🇲 Method –> ( ) -> string

    EnchantmentValueId

    Bases

    No base classes.

    Constructors

    • EnchantmentValueId.new( )
    • EnchantmentValueId.new( EnchantmentValueId )
    • EnchantmentValueId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> EnchantmentValueId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> EnchantmentValueRaw

    str

    🇲 Method –> ( ) -> string

    Energy

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    from_joule

    🇫 Function –> ( integer ) -> Energy

    from_kilojoule

    🇫 Function –> ( integer ) -> Energy

    to_joule

    🇲 Method –> ( ) -> integer

    to_kilojoule

    🇲 Method –> ( ) -> integer

    ExplosionData

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    damage

    🇻 Variable –> integer

    Damage dealt by the explosion

    fire

    🇻 Variable –> boolean

    Whether the explosion creates fire

    radius

    🇻 Variable –> number

    Radius of the explosion

    safe_range

    🇲 Method –> ( ) -> integer

    Returns the safe range of the explosion

    FactionId

    Bases

    No base classes.

    Constructors

    • FactionId.new( )
    • FactionId.new( FactionId )
    • FactionId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> FactionId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> FactionRaw

    str

    🇲 Method –> ( ) -> string

    FactionRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    str_id

    🇲 Method –> ( ) -> FactionId

    FaultId

    Bases

    No base classes.

    Constructors

    • FaultId.new( )
    • FaultId.new( FaultId )
    • FaultId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> FaultId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> FaultRaw

    str

    🇲 Method –> ( ) -> string

    FieldEmitId

    Bases

    No base classes.

    Constructors

    • FieldEmitId.new( )
    • FieldEmitId.new( FieldEmitId )
    • FieldEmitId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> FieldEmitId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> FieldEmitRaw

    str

    🇲 Method –> ( ) -> string

    FieldTypeId

    Bases

    No base classes.

    Constructors

    Members

    NULL_ID

    🇫 Function –> ( ) -> FieldTypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    int_id

    🇲 Method –> ( ) -> FieldTypeIntId

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> FieldTypeRaw

    str

    🇲 Method –> ( ) -> string

    FieldTypeIntId

    Bases

    No base classes.

    Constructors

    Members

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> FieldTypeRaw

    str_id

    🇲 Method –> ( ) -> FieldTypeId

    FieldTypeRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    moppable

    🇻 Variable –> boolean

    FurnId

    Bases

    No base classes.

    Constructors

    • FurnId.new( )
    • FurnId.new( FurnId )
    • FurnId.new( FurnIntId )
    • FurnId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> FurnId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    int_id

    🇲 Method –> ( ) -> FurnIntId

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> FurnRaw

    str

    🇲 Method –> ( ) -> string

    FurnIntId

    Bases

    No base classes.

    Constructors

    Members

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> FurnRaw

    str_id

    🇲 Method –> ( ) -> FurnId

    FurnRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    close

    🇻 Variable –> FurnId

    open

    🇻 Variable –> FurnId

    transforms_into

    🇻 Variable –> FurnId

    get_coverage

    🇲 Method –> ( ) -> integer

    get_flags

    🇲 Method –> ( ) -> string[]

    get_light_emitted

    🇲 Method –> ( ) -> integer

    get_max_volume

    🇲 Method –> ( ) -> Volume

    get_movecost

    🇲 Method –> ( ) -> integer

    has_flag

    🇲 Method –> ( string ) -> boolean

    int_id

    🇲 Method –> ( ) -> FurnIntId

    name

    🇲 Method –> ( ) -> string

    set_coverage

    🇲 Method –> ( integer )

    set_flag

    🇲 Method –> ( string )

    set_light_emitted

    🇲 Method –> ( integer )

    set_max_volume

    🇲 Method –> ( Volume )

    set_movecost

    🇲 Method –> ( integer )

    str_id

    🇲 Method –> ( ) -> FurnId

    Inventory

    Represents a character’s inventory

    Bases

    No base classes.

    Constructors

    • Inventory.new( )

    Members

    clear

    🇲 Method –> ( )

    Clear all items from the inventory

    count_item

    🇲 Method –> ( ItypeId ) -> integer

    Count items of a specific type

    find_item

    🇲 Method –> ( integer ) -> Item

    Find item at position

    has_charges

    🇲 Method –> ( ItypeId, integer ) -> boolean

    Check if inventory has the specified charges

    has_components

    🇲 Method –> ( ItypeId, integer ) -> boolean

    Check if inventory has the specified components

    has_tools

    🇲 Method –> ( ItypeId, integer ) -> boolean

    Check if inventory has the specified tool

    position_by_type

    🇲 Method –> ( ItypeId ) -> integer

    Get item position by type

    size

    🇲 Method –> ( ) -> integer

    Get the number of item stacks in the inventory

    volume

    🇲 Method –> ( ) -> Volume

    Get the total volume of the inventory

    weight

    🇲 Method –> ( ) -> Mass

    Get the total weight of the inventory

    IslotAmmo

    Bases

    • RangedData

    Constructors

    No constructors.

    Members

    ammo_effects

    🇻 Variable –> AmmunitionEffectId[]

    ammo_id

    🇻 Variable –> AmmunitionTypeId

    Ammo type, basically the “form” of the ammo that fits into the gun/tool

    casing_id

    🇻 Variable –> ItypeId?

    Type id of casings, if any

    cookoff

    🇻 Variable –> boolean

    Should this ammo explode in fire?

    def_charges

    🇻 Variable –> integer

    Default charges

    dont_recover_one_in

    🇻 Variable –> integer

    Chance to fail to recover the ammo used.

    drop

    🇻 Variable –> ItypeId

    drop_active

    🇻 Variable –> boolean

    drop_count

    🇻 Variable –> integer

    force_stat_display

    🇻 Variable –> boolean?

    loudness

    🇻 Variable –> integer

    Base loudness of ammo (possibly modified by gun/gunmods)

    recoil

    🇻 Variable –> integer

    Recoil (per shot), roughly equivalent to kinetic energy (in Joules)

    special_cookoff

    🇻 Variable –> boolean

    Should this ammo apply a special explosion effect when in fire?

    speed

    🇻 Variable –> integer

    Base speed of ammo (possibly modified by gun/gunmods)

    IslotArmor

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    env_resist

    🇻 Variable –> integer

    Resistance to environmental effects

    env_resist_w_filter

    🇻 Variable –> integer

    Environmental protection of a gas mask with installed filter

    layer_data

    🇻 Variable –> ArmorPortionData[]

    Layer, encumbrance and coverage information

    resistance

    🇻 Variable –> Resistances

    Damage negated by this armor. Usually calculated from materials+thickness

    sided

    🇻 Variable –> boolean

    Whether this item can be worn on either side of the body

    storage

    🇻 Variable –> Volume

    How much storage this items provides when worn

    thickness

    🇻 Variable –> integer

    Multiplier on resistances provided by armor’s materials. Damaged armors have lower effective thickness, low capped at 1. Note: 1 thickness means item retains full resistance when damaged.

    valid_mods

    🇻 Variable –> string[]

    Whitelisted clothing mods. Restricted clothing mods must be listed here by id to be compatible.

    warmth

    🇻 Variable –> integer

    How much warmth this item provides

    weight_capacity_bonus

    🇻 Variable –> Mass

    Bonus to weight capacity

    weight_capacity_modifier

    🇻 Variable –> number

    Factor modifying weight capacity

    IslotArtifact

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    charge_req

    🇻 Variable –> ArtifactChargeReq

    charge_type

    🇻 Variable –> ArtifactCharge

    dream_freq_met

    🇻 Variable –> integer

    dream_freq_unmet

    🇻 Variable –> integer

    dream_msg_met

    🇻 Variable –> string[]

    dream_msg_unmet

    🇻 Variable –> string[]

    effects_activated

    🇻 Variable –> ArtifactEffectPassive[]

    effects_carried

    🇻 Variable –> ArtifactEffectActive[]

    effects_wielded

    🇻 Variable –> ArtifactEffectActive[]

    effects_worn

    🇻 Variable –> ArtifactEffectActive[]

    charge_req_description

    🇲 Method –> ( ) -> string

    charge_type_description

    🇲 Method –> ( ) -> string

    effects_activated_descriptions

    🇲 Method –> ( ) -> string[]

    effects_activated_names

    🇲 Method –> ( ) -> string[]

    effects_carried_descriptions

    🇲 Method –> ( ) -> string[]

    effects_carried_names

    🇲 Method –> ( ) -> string[]

    effects_wielded_descriptions

    🇲 Method –> ( ) -> string[]

    effects_wielded_names

    🇲 Method –> ( ) -> string[]

    effects_worn_descriptions

    🇲 Method –> ( ) -> string[]

    effects_worn_names

    🇲 Method –> ( ) -> string[]

    IslotBattery

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    max_capacity

    🇻 Variable –> Energy

    Maximum energy the battery can store

    IslotBionic

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    bionic_id

    🇻 Variable –> BionicDataId

    Id of the bionic

    difficulty

    🇻 Variable –> integer

    Arbitrary difficulty scale

    installation_data

    🇻 Variable –> ItypeId

    Item with installation data that can be used to provide almost guaranteed successful install of corresponding bionic

    is_upgrade

    🇻 Variable –> boolean

    Whether this CBM is an upgrade of another

    IslotBook

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    chapters

    🇻 Variable –> integer

    Fun books have chapters; after all are read, the book is less fun.

    fun

    🇻 Variable –> integer

    How fun reading this is, can be negative

    intelligence

    🇻 Variable –> integer

    Intelligence required to read it

    martial_art

    🇻 Variable –> MartialArtsId

    Which martial art it teaches. Can be MartialArtsId.NULL_ID

    recipes

    🇻 Variable –> BookRecipe[]

    Recipes contained in this book

    skill

    🇻 Variable –> SkillId

    Which skill it upgrades, if any. Can be SkillId.NULL_ID

    skill_max

    🇻 Variable –> integer

    The skill level the book provides

    skill_min

    🇻 Variable –> integer

    The skill level required to understand it

    time

    🇻 Variable –> integer

    How long in minutes it takes to read. “To read” means getting 1 skill point, not all of them.

    IslotBrewable

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    results

    🇻 Variable –> ItypeId[]

    What are the results of fermenting this item

    time

    🇻 Variable –> TimeDuration

    How long for this brew to ferment

    IslotComestible

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    addict_type

    🇻 Variable –> AddictionType

    effects of addiction

    addict_value

    🇻 Variable –> integer

    addiction potential

    comest_type

    🇻 Variable –> string

    comestible subtype - eg. FOOD, DRINK, MED

    contamination

    🇻 Variable –> table<DiseaseTypeId, integer>

    List of diseases carried by this comestible and their associated probability

    cooks_like

    🇻 Variable –> ItypeId

    Reference to other item that replaces this one as a component in recipe results

    def_charges

    🇻 Variable –> integer

    Defaults # of charges (drugs, loaf of bread? etc)

    fatigue_mod

    🇻 Variable –> integer

    fatigue altering effect

    freeze_point

    🇻 Variable –> integer

    freezing point in degrees Fahrenheit, below this temperature item can freeze

    healthy

    🇻 Variable –> integer

    latent_heat

    🇻 Variable –> number

    monotony_penalty

    🇻 Variable –> integer

    A penalty applied to fun for every time this food has been eaten in the last 48 hours

    parasites

    🇻 Variable –> integer

    chance (odds) of becoming parasitised when eating (zero if never occurs)

    petfood

    🇻 Variable –> string[]

    pet food category

    quench

    🇻 Variable –> integer

    effect on character thirst (may be negative)

    radiation

    🇻 Variable –> integer

    Amount of radiation you get from this comestible

    rot_spawn

    🇻 Variable –> MonsterGroupId

    The monster group that is drawn from when the item rots away

    rot_spawn_chance

    🇻 Variable –> integer

    Chance the above monster group spawns

    smoking_result

    🇻 Variable –> ItypeId

    Reference to item that will be received after smoking current item

    specific_heat_liquid

    🇻 Variable –> number

    specific heats in J/(g K) and latent heat in J/g

    specific_heat_solid

    🇻 Variable –> number

    spoils

    🇻 Variable –> TimeDuration

    Time until becomes rotten at standard temperature, or zero if never spoils

    stimulant_type

    🇻 Variable –> integer

    stimulant effect

    tool

    🇻 Variable –> ItypeId

    tool needed to consume (e.g. lighter for cigarettes)

    get_default_nutr

    🇲 Method –> ( ) -> integer

    get_default_nutrition

    🇲 Method –> ( ) -> table<VitaminId, integer>

    Nutrition values to use for this type when they aren’t calculated from components

    has_calories

    🇲 Method –> ( ) -> boolean

    IslotContainer

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    contains

    🇻 Variable –> Volume

    Inner volume of the container

    preserves

    🇻 Variable –> boolean

    Contents do not spoil

    seals

    🇻 Variable –> boolean

    Can be resealed

    unseals_into

    🇻 Variable –> ItypeId

    If this is set to anything but “null”, changing this container’s contents in any way will turn this item into that type

    watertight

    🇻 Variable –> boolean

    Can hold liquids

    IslotEngine

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    displacement

    🇻 Variable –> integer

    For combustion engines, the displacement

    IslotFuel

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    energy

    🇻 Variable –> number

    Energy of the fuel (kilojoules per charge)

    explosion_data

    🇻 Variable –> CppVal<fuel_explosion>

    has_explosion_data

    🇻 Variable –> boolean

    pump_terrain

    🇻 Variable –> TerIntId

    IslotGun

    Bases

    • RangedData

    Constructors

    No constructors.

    Members

    ammo

    🇻 Variable –> AmmunitionTypeId[]

    What type of ammo this gun uses

    ammo_effects

    🇻 Variable –> AmmunitionEffectId[]

    Effects that are applied to the ammo when fired

    ammo_to_fire

    🇻 Variable –> integer

    How much ammo is consumed per shot

    barrel_volume

    🇻 Variable –> Volume

    Volume of material removed by sawing down the barrel, if left unspecified barrel can’t be sawed down

    blackpowder_tolerance

    🇻 Variable –> integer

    One in X chance for gun to require major cleanup after firing blackpowder shot

    built_in_mods

    🇻 Variable –> ItypeId[]

    Built in mods. string is id of mod. These mods will get the IRREMOVABLE flag set

    burst

    🇻 Variable –> integer

    Burst size for AUTO mode (legacy field for items not migrated to specify modes )

    clip

    🇻 Variable –> integer

    For guns with an integral magazine what is the capacity?

    default_mods

    🇻 Variable –> ItypeId[]

    Default mods, string is id of mod. These mods are removable but are default on the weapon

    durability

    🇻 Variable –> integer

    Gun durability, affects gun being damaged during shooting

    handling

    🇻 Variable –> integer

    How easy is control of recoil? If unset value automatically derived from weapon type

    loudness

    🇻 Variable –> integer

    Modifies base loudness as provided by the currently loaded ammo

    min_cycle_recoil

    🇻 Variable –> integer

    Minimum ammo recoil for gun to be able to fire more than once per attack

    recoil

    🇻 Variable –> integer

    Additional recoil applied per shot before effects of handling are considered, useful for adding recoil effect to guns which otherwise consume no ammo

    reload_noise

    🇻 Variable –> string

    Noise displayed when reloading the weapon

    reload_noise_volume

    🇻 Variable –> Sound

    Volume of the noise made when reloading this weapon

    reload_time

    🇻 Variable –> integer

    Reload time, in moves

    sight_dispersion

    🇻 Variable –> integer

    Maximum aim achievable using base weapon sights

    skill_used

    🇻 Variable –> SkillId

    What skill this gun uses

    speed

    🇻 Variable –> integer

    Modifies projectile speed as provided by the currently loaded ammo

    ups_charges

    🇻 Variable –> integer

    If this uses UPS charges, how many (per shoot), 0 for no UPS charges at all

    get_gunmod_locations

    🇲 Method –> ( ) -> table<string, integer>

    Location for gun mods. Key is the location (untranslated!), value is the number of mods that the location can have. The value should be > 0

    get_modes

    🇲 Method –> ( ) -> string[]

    Firing modes are supported by the gun. Always contains at least DEFAULT mode

    IslotGunmod

    Bases

    • RangedData

    Constructors

    No constructors.

    Members

    aim_speed

    🇻 Variable –> integer

    For sights (see @ref sight_dispersion), this value affects time cost of aiming. Higher is better. In case of multiple usable sights, the one with highest aim speed is used.

    ammo_effects

    🇻 Variable –> AmmunitionEffectId[]

    ammo_to_fire_modifier

    🇻 Variable –> integer

    Increases base gun ammo to fire by this value per shot

    ammo_to_fire_multiplier

    🇻 Variable –> number

    Increases base gun ammo to fire by this many times per shot

    consume_chance

    🇻 Variable –> integer

    Percentage value change to the gun’s loading time. Higher is less likely

    consume_divisor

    🇻 Variable –> integer

    Divsor to scale back gunmod consumption damage. lower is more damaging. Affected by ammo loudness and recoil, see ranged.cpp for how much.

    exclusion

    🇻 Variable –> CppVal<std_unordered_set<string_id<itype>>>

    What kind of weapons this gunmod can’t be used with

    exclusion_category

    🇻 Variable –> CppVal<std_unordered_set<string_id<weapon_category>>>[]

    What category of weapons this gunmod can’t be used with

    handling

    🇻 Variable –> integer

    Relative adjustment to base gun handling

    install_time

    🇻 Variable –> integer

    How many moves does this gunmod take to install?

    loudness

    🇻 Variable –> integer

    Modifies base loudness as provided by the currently loaded ammo

    min_str_required_mod

    🇻 Variable –> integer

    Modifies base strength required

    reload_modifier

    🇻 Variable –> integer

    Percentage value change to the gun’s loading time. Higher is slower

    sight_dispersion

    🇻 Variable –> integer

    If this value is set (non-negative), this gunmod functions as a sight. A sight is only usable to aim by a character whose current Character::recoil is at or below this value.

    speed

    🇻 Variable –> integer

    Modifies projectile speed as provided by the currently loaded ammo

    ups_charges_modifier

    🇻 Variable –> integer

    Increases base gun UPS consumption by this value per shot

    ups_charges_multiplier

    🇻 Variable –> number

    Increases base gun UPS consumption by this many times per shot

    usable

    🇻 Variable –> CppVal<std_unordered_set<string_id<itype>>>

    What kind of weapons this gunmod can be used with

    usable_category

    🇻 Variable –> CppVal<std_unordered_set<string_id<weapon_category>>>[]

    What category of weapons this gunmod can be used with

    volume_multiplier

    🇻 Variable –> number

    Increases gun volume by this many times

    weight_multiplier

    🇻 Variable –> number

    Increases gun weight by this many times

    get_added_slots

    🇲 Method –> ( ) -> table<string, integer>

    Additional gunmod slots to add to the gun. Key is the location (untranslated!), value is the number of extra mods that location can hold.

    get_location

    🇲 Method –> ( ) -> string

    Where is this gunmod installed (e.g. “stock”, “rail”)?

    get_mod_blacklist

    🇲 Method –> ( ) -> string[]

    Not compatible on weapons that have this mod slot

    get_mode_modifiers

    🇲 Method –> ( ) -> string[]

    Firing modes added to or replacing those of the base gun

    IslotMagazine

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    ammo_type

    🇻 Variable –> AmmunitionTypeId[]

    What type of ammo this magazine can be loaded with

    capacity

    🇻 Variable –> integer

    Capacity of magazine (in equivalent units to ammo charges)

    count

    🇻 Variable –> integer

    Default amount of ammo contained by a magazine (often set for ammo belts)

    default_ammo

    🇻 Variable –> ItypeId

    Default type of ammo contained by a magazine (often set for ammo belts)

    linkage

    🇻 Variable –> ItypeId?

    For ammo belts one linkage (of given type) is dropped for each unit of ammo consumed

    protects_contents

    🇻 Variable –> boolean

    If false, ammo will cook off if this mag is affected by fire

    reliability

    🇻 Variable –> integer

    How reliable this magazine on a range of 0 to 10?

    reload_time

    🇻 Variable –> integer

    How long it takes to load each unit of ammo into the magazine

    IslotMilling

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    conversion_rate

    🇻 Variable –> integer

    converts_into

    🇻 Variable –> ItypeId

    IslotMod

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    acceptable_ammo

    🇻 Variable –> AmmunitionTypeId[]

    If non-empty restrict mod to items with those base (before modifiers) ammo types

    ammo_modifier

    🇻 Variable –> AmmunitionTypeId[]

    If set modifies parent ammo to this type

    capacity_multiplier

    🇻 Variable –> number

    Proportional adjustment of parent item ammo capacity

    magazine_adaptor

    🇻 Variable –> table<AmmunitionTypeId, ItypeId[]>

    If non-empty replaces the compatible magazines for the parent item

    IslotPetArmor

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    bodytype

    🇻 Variable –> string

    What animal bodytype can wear this armor

    env_resist

    🇻 Variable –> integer

    Resistance to environmental effects

    env_resist_w_filter

    🇻 Variable –> integer

    Environmental protection of a gas mask with installed filter

    max_vol

    🇻 Variable –> Volume

    The maximum volume a pet can be and wear this armor

    min_vol

    🇻 Variable –> Volume

    The minimum volume a pet can be and wear this armor

    storage

    🇻 Variable –> Volume

    How much storage this items provides when worn

    thickness

    🇻 Variable –> integer

    Multiplier on resistances provided by this armor

    IslotSeed

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    byproducts

    🇻 Variable –> ItypeId[]

    Additionally items (a list of their item ids) that will spawn when harvesting the plant.

    fruit_div

    🇻 Variable –> integer

    Amount of harvested charges of fruits is divided by this number.

    fruit_id

    🇻 Variable –> ItypeId

    Type id of the fruit item.

    grow

    🇻 Variable –> TimeDuration

    Time it takes for a seed to grow (based of off a season length of 91 days).

    get_plant_name

    🇲 Method –> ( integer ) -> string

    Name of the plant.

    IslotTool

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    ammo_id

    🇻 Variable –> AmmunitionTypeId[]

    charge_factor

    🇻 Variable –> integer

    charges_per_use

    🇻 Variable –> integer

    def_charges

    🇻 Variable –> integer

    default_ammo

    🇻 Variable –> ItypeId

    max_charges

    🇻 Variable –> integer

    power_draw

    🇻 Variable –> integer

    rand_charges

    🇻 Variable –> integer[]

    revert_msg

    🇻 Variable –> string

    revert_to

    🇻 Variable –> ItypeId?

    subtype

    🇻 Variable –> ItypeId

    turns_active

    🇻 Variable –> integer

    turns_per_charge

    🇻 Variable –> integer

    ups_eff_mult

    🇻 Variable –> integer

    ups_recharge_rate

    🇻 Variable –> integer

    IslotWheel

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    diameter

    🇻 Variable –> integer

    Diameter of wheel in millimeters. Integer JSON values are legacy inches.

    width

    🇻 Variable –> integer

    Width of wheel in millimeters. Integer JSON values are legacy inches.

    Item

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    charges

    🇻 Variable –> integer

    activate

    🇲 Method –> ( )

    add_enchantment

    🇲 Method –> ( EnchantmentId ) -> boolean
    🇲 Method –> ( Enchantment ) -> boolean

    Adds an enchantment to this item

    add_item_with_id

    🇲 Method –> ( ItypeId, integer )

    Creates an item with the given id and adds it to contents. count sets the item’s charges, not the number of items: exactly one item is created. For stackable (count-by-charges) items such as ammo, count is the stack size. For non-stackable items, pass a negative value (e.g. -1), since a positive one is still applied as charges. Tools spawned with a negative value get their default charges.

    add_technique

    🇲 Method –> ( MartialArtsTechniqueId )

    Adds the technique. It isn’t treated original, but additional.

    ammo_capacity

    🇲 Method –> ( boolean ) -> integer

    Gets the maximum capacity of a magazine

    ammo_consume

    🇲 Method –> ( integer, TripointBubMs ) -> integer

    ammo_current

    🇲 Method –> ( ) -> ItypeId

    ammo_data

    🇲 Method –> ( ) -> ItypeRaw

    ammo_remaining

    🇲 Method –> ( ) -> integer

    Get remaining ammo, works with batteries & stuff too

    ammo_required

    🇲 Method –> ( ) -> integer

    ammo_set

    🇲 Method –> ( ItypeId, integer )

    ammo_unset

    🇲 Method –> ( )

    attack_cost

    🇲 Method –> ( ) -> integer

    can_contain

    🇲 Method –> ( Item ) -> boolean

    Checks if this item can contain another

    clear_vars

    🇲 Method –> ( )

    Erase all variables

    conductive

    🇲 Method –> ( ) -> boolean

    convert

    🇲 Method –> ( ItypeId )

    Converts the item as given <code>[ItypeId](#sol::ItypeId)</code>.

    covers

    🇲 Method –> ( BodyPartTypeIntId ) -> boolean

    Checks if the item covers a bodypart

    current_magazine

    🇲 Method –> ( ) -> Item

    Gets the current magazine

    deactivate

    🇲 Method –> ( )

    display_name

    🇲 Method –> ( integer ) -> string

    Display name with all bells and whistles like ammo and prefixes

    energy_remaining

    🇲 Method –> ( ) -> Energy

    erase_var

    🇲 Method –> ( string )

    Erase variable

    get_category_id

    🇲 Method –> ( ) -> string

    Gets the category id this item is in

    get_comestible_fun

    🇲 Method –> ( ) -> integer

    get_counter

    🇲 Method –> ( ) -> integer

    get_damage

    🇲 Method –> ( ) -> integer

    Get current item damage value (durability). Higher values mean more damaged. Default range is -1000 (min) to 4000 (max), configurable via ‘damage_states’ in JSON.

    get_damage_level

    🇲 Method –> ( ) -> integer
    🇲 Method –> ( integer ) -> integer

    Get item damage as a level from 0 to max. Used for UI display and damage thresholds.

    get_dispersion_bonus

    🇲 Method –> ( ) -> integer

    get_kcal

    🇲 Method –> ( ) -> integer

    get_max_damage

    🇲 Method –> ( ) -> integer

    Get maximum possible damage value before item is destroyed. Default is 4000, configurable via ‘damage_states’ in JSON.

    get_melee_damage_bonus

    🇲 Method –> ( ) -> DamageInstance

    get_melee_hit_bonus

    🇲 Method –> ( ) -> integer

    get_min_damage

    🇲 Method –> ( ) -> integer

    Get minimum possible damage value (can be negative for reinforced items). Default is -1000, configurable via ‘damage_states’ in JSON.

    get_mtype

    🇲 Method –> ( ) -> MonsterTypeId

    Almost for a corpse.

    get_owner

    🇲 Method –> ( ) -> FactionId

    Gets the faction id that owns this item

    get_owner_name

    🇲 Method –> ( ) -> string

    get_quench

    🇲 Method –> ( ) -> integer

    get_range_bonus

    🇲 Method –> ( ) -> integer

    get_ranged_damage_bonus

    🇲 Method –> ( ) -> DamageInstance

    get_recoil_bonus

    🇲 Method –> ( ) -> integer

    get_relative_health

    🇲 Method –> ( ) -> number

    Get relative health as ratio 0.0-1.0, where 1.0 is undamaged and 0.0 is destroyed

    get_reload_time

    🇲 Method –> ( ) -> integer

    get_rot

    🇲 Method –> ( ) -> TimeDuration

    Gets the TimeDuration until this item rots

    get_techniques

    🇲 Method –> ( ) -> MartialArtsTechniqueId[]

    Gets all techniques. Including original techniques.

    get_type

    🇲 Method –> ( ) -> ItypeId

    get_var_num

    🇲 Method –> ( string, number ) -> number

    Get variable as float number

    get_var_str

    🇲 Method –> ( string, string ) -> string

    Get variable as string

    get_var_tri

    🇲 Method –> ( string, Tripoint ) -> Tripoint

    Get variable as tripoint

    has_flag

    🇲 Method –> ( JsonFlagId ) -> boolean

    has_infinite_charges

    🇲 Method –> ( ) -> boolean

    has_item_with_id

    🇲 Method –> ( ItypeId ) -> boolean

    Checks item contents for a given item id

    has_own_flag

    🇲 Method –> ( JsonFlagId ) -> boolean

    has_technique

    🇲 Method –> ( MartialArtsTechniqueId ) -> boolean

    Checks if this item has the technique as an addition. Doesn’t check original techniques.

    has_use

    🇲 Method –> ( string ) -> CppVal<use_function>

    has_var

    🇲 Method –> ( string ) -> boolean

    Check for variable of any type

    invoke_at

    🇲 Method –> ( TripointBubMs ) -> integer

    Immediately invokes this item’s use action at the given map-square position. Returns the charges consumed by the use action.

    is_active

    🇲 Method –> ( ) -> boolean

    is_ammo

    🇲 Method –> ( ) -> boolean

    is_ammo_belt

    🇲 Method –> ( ) -> boolean

    is_ammo_container

    🇲 Method –> ( ) -> boolean

    is_armor

    🇲 Method –> ( ) -> boolean

    is_artifact

    🇲 Method –> ( ) -> boolean

    is_bandolier

    🇲 Method –> ( ) -> boolean

    is_bionic

    🇲 Method –> ( ) -> boolean

    is_book

    🇲 Method –> ( ) -> boolean

    is_brewable

    🇲 Method –> ( ) -> boolean

    is_bucket

    🇲 Method –> ( ) -> boolean

    is_bucket_nonempty

    🇲 Method –> ( ) -> boolean

    is_comestible

    🇲 Method –> ( ) -> boolean

    is_container

    🇲 Method –> ( ) -> boolean

    is_container_empty

    🇲 Method –> ( ) -> boolean

    is_corpse

    🇲 Method –> ( ) -> boolean

    is_craft

    🇲 Method –> ( ) -> boolean

    is_dangerous

    🇲 Method –> ( ) -> boolean

    is_deployable

    🇲 Method –> ( ) -> boolean

    is_emissive

    🇲 Method –> ( ) -> boolean

    is_engine

    🇲 Method –> ( ) -> boolean

    is_faulty

    🇲 Method –> ( ) -> boolean

    is_firearm

    🇲 Method –> ( ) -> boolean

    is_food

    🇲 Method –> ( ) -> boolean

    is_food_container

    🇲 Method –> ( ) -> boolean

    is_fuel

    🇲 Method –> ( ) -> boolean

    is_gun

    🇲 Method –> ( ) -> boolean

    is_gunmod

    🇲 Method –> ( ) -> boolean

    is_holster

    🇲 Method –> ( ) -> boolean

    is_irremovable

    🇲 Method –> ( ) -> boolean

    is_made_of

    🇲 Method –> ( MaterialTypeId ) -> boolean

    is_magazine

    🇲 Method –> ( ) -> boolean

    Is this a magazine? (batteries are magazines)

    is_map

    🇲 Method –> ( ) -> boolean

    is_med_container

    🇲 Method –> ( ) -> boolean

    is_medication

    🇲 Method –> ( ) -> boolean

    is_melee

    🇲 Method –> ( DamageType ) -> boolean

    Is this item an effective melee weapon for the given damage type?

    is_money

    🇲 Method –> ( ) -> boolean

    is_non_resealable_container

    🇲 Method –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_owned_by

    🇲 Method –> ( Character, boolean ) -> boolean

    Checks if this item owned by a character

    is_power_armor

    🇲 Method –> ( ) -> boolean

    is_relic

    🇲 Method –> ( boolean ) -> boolean

    is_reloadable

    🇲 Method –> ( ) -> boolean

    is_salvageable

    🇲 Method –> ( boolean ) -> boolean

    is_seed

    🇲 Method –> ( ) -> boolean

    is_sided

    🇲 Method –> ( ) -> boolean

    is_silent

    🇲 Method –> ( ) -> boolean

    is_soft

    🇲 Method –> ( ) -> boolean

    is_stackable

    🇲 Method –> ( ) -> boolean

    is_tainted

    🇲 Method –> ( ) -> boolean

    is_tool

    🇲 Method –> ( ) -> boolean

    is_toolmod

    🇲 Method –> ( ) -> boolean

    is_transformable

    🇲 Method –> ( ) -> boolean

    is_unarmed_weapon

    🇲 Method –> ( ) -> boolean

    is_upgrade

    🇲 Method –> ( ) -> boolean

    is_watertight_container

    🇲 Method –> ( ) -> boolean

    is_wheel

    🇲 Method –> ( ) -> boolean

    made_of

    🇲 Method –> ( ) -> MaterialTypeId[]

    mod_charges

    🇲 Method –> ( integer )

    mod_damage

    🇲 Method –> ( integer ) -> boolean
    🇲 Method –> ( integer, DamageType ) -> boolean

    Modify item damage by given amount. Returns true if item should be destroyed.

    price

    🇲 Method –> ( boolean ) -> number

    Cents of the item. bool is whether it is a post-cataclysm value.

    remaining_capacity_for_id

    🇲 Method –> ( ItypeId, boolean ) -> integer

    Gets the remaining space available for a type of liquid

    remove_technique

    🇲 Method –> ( MartialArtsTechniqueId )

    Removes the additional technique. Doesn’t affect originial techniques.

    set_charges

    🇲 Method –> ( integer )

    set_counter

    🇲 Method –> ( integer )

    set_damage

    🇲 Method –> ( integer )

    Set item damage to specified value. Clamped between min_damage and max_damage.

    set_dispersion_bonus

    🇲 Method –> ( integer )

    set_flag

    🇲 Method –> ( JsonFlagId )

    set_flag_recursive

    🇲 Method –> ( JsonFlagId )

    set_melee_damage_bonus

    🇲 Method –> ( DamageInstance )

    set_melee_hit_bonus

    🇲 Method –> ( integer )

    set_owner

    🇲 Method –> ( FactionId )
    🇲 Method –> ( Character )

    Sets the ownership of this item to a faction or character

    set_range_bonus

    🇲 Method –> ( integer )

    set_ranged_damage_bonus

    🇲 Method –> ( DamageInstance )

    set_recoil_bonus

    🇲 Method –> ( integer )

    set_var_col

    🇲 Method –> ( string, RGBColor )

    set_var_num

    🇲 Method –> ( string, number )

    set_var_str

    🇲 Method –> ( string, string )

    set_var_tri

    🇲 Method –> ( string, Tripoint )

    spawn

    🇫 Function –> ( ItypeId, integer ) -> Detached<Item>

    Spawns a new item. Same as gapi.create_item count sets the item’s charges, not the number of items: exactly one item is created. For stackable (count-by-charges) items such as ammo, count is the stack size. For non-stackable items, pass a negative value (e.g. -1), since a positive one is still applied as charges. Tools spawned with a negative value get their default charges.

    stamina_cost

    🇲 Method –> ( ) -> integer

    tname

    🇲 Method –> ( integer, boolean, integer ) -> string

    Translated item name with prefixes

    total_capacity

    🇲 Method –> ( ) -> Volume

    Gets maximum volume this item can hold (liquids, ammo, etc)

    unset_flag

    🇲 Method –> ( JsonFlagId )

    unset_flags

    🇲 Method –> ( )

    vars_table

    🇲 Method –> ( ) -> table

    Returns all stored item vars as a table mapping each var name (string) to its raw value (string).

    volume

    🇲 Method –> ( boolean? ) -> Volume

    Volume of the item. bool is whether it is integral_volume.

    weapon_categories

    🇲 Method –> ( ) -> WeaponCategoryId[]

    Gets the weapon category of the item.

    weight

    🇲 Method –> ( boolean?, boolean? ) -> Mass

    Weight of the item. The first bool is whether including contents, second bool is whether it is integral_weight.

    ItemStack

    Iterate over this using pairs() for reading. Can also be indexed.

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    amount_can_fit

    🇲 Method –> ( Item ) -> integer

    clear

    🇲 Method –> ( ) -> Detached<Item>[]

    count

    🇲 Method –> ( ) -> integer

    count_limit

    🇲 Method –> ( ) -> integer

    free_volume

    🇲 Method –> ( ) -> Volume

    insert

    🇲 Method –> ( Detached<Item> )

    items

    🇲 Method –> ( ) -> Item[]

    Modifying the stack while iterating may cause problems. This returns a frozen copy of the items in the stack for safe modification of the stack (eg. removing items while iterating).

    max_volume

    🇲 Method –> ( ) -> Volume

    move_all_to

    🇲 Method –> ( ItemStack )

    only_item

    🇲 Method –> ( ) -> Item

    remove

    🇲 Method –> ( Item ) -> Detached<Item>

    stacks_with

    🇲 Method –> ( Item ) -> Item

    stored_volume

    🇲 Method –> ( ) -> Volume

    ItypeId

    Bases

    No base classes.

    Constructors

    • ItypeId.new( )
    • ItypeId.new( ItypeId )
    • ItypeId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> ItypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> ItypeRaw

    str

    🇲 Method –> ( ) -> string

    ItypeRaw

    Slots for various item type properties. Each slot may contain a valid value or nil

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    attacks

    🇻 Variable –> table<string, CppVal<attack_statblock>>

    Attacks this weapon can perform, keyed by attack id.

    countdown_destroy

    🇻 Variable –> boolean

    countdown_interval

    🇻 Variable –> integer

    default_container

    🇻 Variable –> ItypeId?

    emits

    🇻 Variable –> FieldEmitId[]

    explode_in_fire

    🇻 Variable –> boolean

    explosion_data

    🇻 Variable –> ExplosionData

    faults

    🇻 Variable –> FaultId[]

    integral_volume

    🇻 Variable –> Volume

    integral_weight

    🇻 Variable –> Mass

    item_tags

    🇻 Variable –> JsonFlagId[]

    layer

    🇻 Variable –> CppVal<layer_level>

    light_emission

    🇻 Variable –> integer

    looks_like

    🇻 Variable –> ItypeId

    materials

    🇻 Variable –> MaterialTypeId[]

    melee_to_hit

    🇻 Variable –> integer

    min_dex

    🇻 Variable –> integer

    min_int

    🇻 Variable –> integer

    min_per

    🇻 Variable –> integer

    min_skills

    🇻 Variable –> table<SkillId, integer>

    Minimum skill levels required to use this item, keyed by skill.

    min_str

    🇻 Variable –> integer

    phase

    🇻 Variable –> Phase

    properties

    🇻 Variable –> table<string, string>

    Free-form string properties from the item’s JSON properties field, keyed by property name.

    qualities

    🇻 Variable –> table<QualityId, integer>

    Tool qualities this item provides, mapped to their level.

    recipes

    🇻 Variable –> RecipeId[]

    repair

    🇻 Variable –> ItypeId[]

    repairs_like

    🇻 Variable –> ItypeId

    rigid

    🇻 Variable –> boolean

    stack_size

    🇻 Variable –> integer

    techniques

    🇻 Variable –> MartialArtsTechniqueId[]

    thrown_damage

    🇻 Variable –> DamageInstance

    volume

    🇻 Variable –> Volume

    weapon_category

    🇻 Variable –> WeaponCategoryId[]

    weight

    🇻 Variable –> Mass

    can_have_charges

    🇲 Method –> ( ) -> boolean

    can_use

    🇲 Method –> ( string ) -> boolean

    charge_factor

    🇲 Method –> ( ) -> integer

    charges_default

    🇲 Method –> ( ) -> integer

    charges_per_volume

    🇲 Method –> ( Volume ) -> integer

    charges_to_use

    🇲 Method –> ( ) -> integer

    damage_max

    🇲 Method –> ( ) -> integer

    damage_min

    🇲 Method –> ( ) -> integer

    get_countdown_action

    🇲 Method –> ( ) -> string

    get_description

    🇲 Method –> ( integer ) -> string

    get_drop_action

    🇲 Method –> ( ) -> string

    get_flags

    🇲 Method –> ( ) -> JsonFlagId[]

    get_name

    🇲 Method –> ( integer ) -> string

    get_uses

    🇲 Method –> ( ) -> string[]

    has_flag

    🇲 Method –> ( JsonFlagId ) -> boolean

    has_use

    🇲 Method –> ( ) -> boolean

    is_stackable

    🇲 Method –> ( ) -> boolean

    maximum_charges

    🇲 Method –> ( ) -> integer

    price

    🇲 Method –> ( ) -> integer

    price_post

    🇲 Method –> ( ) -> integer

    slot_ammo

    🇲 Method –> ( ) -> IslotAmmo

    slot_armor

    🇲 Method –> ( ) -> IslotArmor

    slot_artifact

    🇲 Method –> ( ) -> IslotArtifact

    slot_battery

    🇲 Method –> ( ) -> IslotBattery

    slot_bionic

    🇲 Method –> ( ) -> IslotBionic

    slot_book

    🇲 Method –> ( ) -> IslotBook

    slot_brewable

    🇲 Method –> ( ) -> IslotBrewable

    slot_comestible

    🇲 Method –> ( ) -> IslotComestible

    slot_container

    🇲 Method –> ( ) -> IslotContainer

    slot_engine

    🇲 Method –> ( ) -> IslotEngine

    slot_fuel

    🇲 Method –> ( ) -> IslotFuel

    slot_gun

    🇲 Method –> ( ) -> IslotGun

    slot_gunmod

    🇲 Method –> ( ) -> IslotGunmod

    slot_magazine

    🇲 Method –> ( ) -> IslotMagazine

    slot_milling

    🇲 Method –> ( ) -> IslotMilling

    slot_mod

    🇲 Method –> ( ) -> IslotMod

    slot_pet_armor

    🇲 Method –> ( ) -> IslotPetArmor

    slot_relic

    🇲 Method –> ( ) -> Relic

    slot_seed

    🇲 Method –> ( ) -> IslotSeed

    slot_tool

    🇲 Method –> ( ) -> IslotTool

    slot_wheel

    🇲 Method –> ( ) -> IslotWheel

    source_mod

    🇲 Method –> ( ) -> ModInfoId[]

    type_id

    🇲 Method –> ( ) -> ItypeId

    JsonFlagId

    Bases

    No base classes.

    Constructors

    • JsonFlagId.new( )
    • JsonFlagId.new( JsonFlagId )
    • JsonFlagId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> JsonFlagId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> JsonFlagRaw

    str

    🇲 Method –> ( ) -> string

    JsonTraitFlagId

    Bases

    No base classes.

    Constructors

    • JsonTraitFlagId.new( )
    • JsonTraitFlagId.new( JsonTraitFlagId )
    • JsonTraitFlagId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> JsonTraitFlagId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> JsonTraitFlagRaw

    str

    🇲 Method –> ( ) -> string

    KnownMagic

    Represents a character’s spellbook and mana pool. Manages all spells known by a character, their mana, and spell learning/forgetting.

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    casting_ignore

    🇻 Variable –> boolean

    Whether casting ignores all distractions. Can be read and written.

    available_mana

    🇲 Method –> ( ) -> integer

    Get the current available mana.

    can_learn_spell

    🇲 Method –> ( Character, SpellTypeId ) -> boolean

    Check if the character can learn a specific spell, considering traits and other restrictions.

    forget_spell

    🇲 Method –> ( SpellTypeId )

    Forget a known spell by spell_id.

    get_spell

    🇲 Method –> ( SpellTypeId ) -> Spell

    Get a reference to a known spell for editing. Returns the spell associated with the given spell_id.

    get_spells

    🇲 Method –> ( ) -> Spell[]

    Get all known spells as a vector of spell pointers.

    has_enough_energy

    🇲 Method –> ( Character, Spell ) -> boolean

    Check if the character has enough energy (of the appropriate type) to cast the given spell.

    knows_spell

    🇲 Method –> ( SpellTypeId ) -> boolean
    🇲 Method –> ( ) -> boolean

    Check if the character knows a specific spell by spell_id.

    learn_spell

    🇲 Method –> ( SpellTypeId, Character, boolean? )

    Learn a new spell. Requires a Character reference and spell_id. Optional force(boolean) parameter bypasses restrictions.

    mana_regen_rate

    🇲 Method –> ( Character ) -> number

    Get the mana regeneration rate in units per turn for the given character.

    max_mana

    🇲 Method –> ( Character ) -> integer

    Get the maximum mana for the given character.

    mod_mana

    🇲 Method –> ( Character, integer )

    Modify the current mana by adding or subtracting an amount.

    set_mana

    🇲 Method –> ( integer )

    Set the current mana to a specific value.

    spells

    🇲 Method –> ( ) -> SpellTypeId[]

    Get a vector of all known spell IDs.

    time_to_learn_spell

    🇲 Method –> ( Character, SpellTypeId ) -> integer

    Calculate the time in moves required for the character to memorize/learn a spell.

    Map

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    abs_to_bub

    🇲 Method –> ( TripointAbsMs ) -> TripointBubMs
    🇲 Method –> ( TripointAbsSm ) -> TripointBubSm

    Convert absolute coordinates to bubble coordinates.

    add_field_at

    🇲 Method –> ( TripointBubMs, FieldTypeIntId, integer, TimeDuration ) -> boolean

    add_item

    🇲 Method –> ( TripointBubMs, Detached<Item> ) -> Detached<Item>
    🇲 Method –> ( Tripoint, Detached<Item> ) -> Detached<Item>

    Places a detached item onto the map. Returns nil on success (item now owned by map), or returns the item back if placement failed.

    ambient_light_at

    🇲 Method –> ( TripointBubMs ) -> number

    bub_to_abs

    🇲 Method –> ( TripointBubMs ) -> TripointAbsMs
    🇲 Method –> ( TripointBubSm ) -> TripointAbsSm

    Convert bubble coordinates to absolute coordinates.

    clear_items_at

    🇲 Method –> ( TripointBubMs )
    🇲 Method –> ( Tripoint )

    create_corpse_at

    🇲 Method –> ( TripointBubMs, MonsterTypeId?, TimePoint?, string?, integer? )

    Creates a new corpse at a position on the map. You can skip Opt ones by omitting them or passing nil. <code>[MonsterTypeId](#sol::MonsterTypeId)</code> specifies which monster’s body it is, <code>[TimePoint](#sol::TimePoint)</code> indicates when it died, string gives it a custom name, and int determines the revival time if the monster has the REVIVES flag.

    create_item_at

    🇲 Method –> ( TripointBubMs, ItypeId, integer )

    Creates a new item at a position on the map. count sets the item’s charges, not the number of items: exactly one item is created. For stackable (count-by-charges) items such as ammo, count is the stack size. For non-stackable items, pass a negative value (e.g. -1), since a positive one is still applied as charges. Tools spawned with a negative value get their default charges. Returns nil. Use gapi.create_item and Map:add_item to modify before placement.

    destroy

    🇲 Method –> ( TripointBubMs )

    detach_item_at

    🇲 Method –> ( TripointBubMs, Item ) -> Detached<Item>
    🇲 Method –> ( Tripoint, Item ) -> Detached<Item>

    Removes an item from the map and returns it as a detached_ptr. The item is now owned by Lua - store it in a table to keep it alive, or let it be GC’d to destroy it. Use add_item to place it back on a map.

    disarm_trap_at

    🇲 Method –> ( TripointBubMs )

    Disarms a trap using your skills and stats, with consequences depending on success or failure.

    drain_vehicle_fuel_at

    🇲 Method –> ( TripointBubMs, string, ItypeId, integer ) -> integer

    Drains fuel charges from the vehicle when the position has a part with the given feature. Returns the charges drained.

    draw_fill_background

    🇲 Method –> ( string )

    erase_furn_var_at

    🇲 Method –> ( TripointBubMs, string ) -> boolean

    Removes a furniture variable at the position. Returns whether a variable was removed.

    erase_ter_var_at

    🇲 Method –> ( TripointBubMs, string ) -> boolean

    Removes a terrain variable at the position. Returns whether a variable was removed.

    get_bound_dimension

    🇲 Method –> ( ) -> string

    Returns the dimension id currently bound to this map. Empty string means the overworld.

    get_field_age_at

    🇲 Method –> ( TripointBubMs, FieldTypeIntId ) -> TimeDuration

    get_field_ids_at

    🇲 Method –> ( TripointBubMs ) -> FieldTypeIntId[]

    get_field_int_at

    🇲 Method –> ( TripointBubMs, FieldTypeIntId ) -> integer

    get_field_name_at

    🇲 Method –> ( TripointBubMs, FieldTypeIntId ) -> string

    get_furn_at

    🇲 Method –> ( TripointBubMs ) -> FurnIntId

    get_furn_var_at

    🇲 Method –> ( TripointBubMs, string, string? ) -> string

    Returns a furniture variable at the position, or default (empty string if omitted) when it is not set.

    get_furn_vars_table_at

    🇲 Method –> ( TripointBubMs ) -> table

    Returns all furniture variables at the position as a table mapping each name to its value.

    get_items_at

    🇲 Method –> ( TripointBubMs ) -> MapStack
    🇲 Method –> ( Tripoint ) -> MapStack

    get_items_in_radius

    🇲 Method –> ( TripointBubMs, integer ) -> MapStack[]

    get_map_size

    🇲 Method –> ( ) -> integer

    In map squares

    get_map_size_in_submaps

    🇲 Method –> ( ) -> integer

    get_temperature_c

    🇲 Method –> ( TripointBubMs ) -> number

    Get the local ambient temperature in degrees Celsius at a map-square position.

    get_ter_at

    🇲 Method –> ( TripointBubMs ) -> TerIntId

    get_ter_var_at

    🇲 Method –> ( TripointBubMs, string, string? ) -> string

    Returns a terrain variable at the position, or default (empty string if omitted) when it is not set.

    get_ter_vars_table_at

    🇲 Method –> ( TripointBubMs ) -> table

    Returns all terrain variables at the position as a table mapping each name to its value.

    get_trap_at

    🇲 Method –> ( TripointBubMs ) -> TrapIntId

    get_vehicle_fuel_left_at

    🇲 Method –> ( TripointBubMs, string, ItypeId, boolean? ) -> integer

    Returns the vehicle’s available fuel charges when the position has a part with the given feature.

    get_vehicles

    🇲 Method –> ( ) -> WrappedVehicle[]

    Returns every vehicle currently on the map.

    has_field_at

    🇲 Method –> ( TripointBubMs, FieldTypeIntId ) -> boolean

    has_flag_at

    🇲 Method –> ( string, TripointBubMs ) -> boolean

    has_furn_flag_at

    🇲 Method –> ( string, TripointBubMs ) -> boolean

    has_furn_var_at

    🇲 Method –> ( TripointBubMs, string ) -> boolean

    Returns whether a furniture variable is set at the position.

    has_items_at

    🇲 Method –> ( TripointBubMs ) -> boolean
    🇲 Method –> ( Tripoint ) -> boolean

    has_ter_flag_at

    🇲 Method –> ( string, TripointBubMs ) -> boolean

    has_ter_var_at

    🇲 Method –> ( TripointBubMs, string ) -> boolean

    Returns whether a terrain variable is set at the position.

    has_vehicle_part_with_feature_at

    🇲 Method –> ( TripointBubMs, string, boolean? ) -> boolean

    Returns whether a vehicle at this position has an available part with the given feature.

    is_in_sunlight

    🇲 Method –> ( TripointBubMs ) -> boolean

    is_ot_match

    🇫 Function –> ( string, OterIntId, OtMatchType ) -> boolean

    is_out_of_bounds

    🇲 Method –> ( TripointBubMs ) -> boolean

    Returns whether a local map position lies outside the current dimension bounds.

    is_outside

    🇲 Method –> ( TripointBubMs ) -> boolean

    is_sheltered

    🇲 Method –> ( TripointBubMs ) -> boolean

    make_rubble

    🇲 Method –> ( TripointBubMs, FurnIntId, TerIntId )

    mod_field_age_at

    🇲 Method –> ( TripointBubMs, FieldTypeIntId, TimeDuration ) -> TimeDuration

    mod_field_int_at

    🇲 Method –> ( TripointBubMs, FieldTypeIntId, integer ) -> integer

    move_item_to

    🇲 Method –> ( TripointBubMs, Item, TripointBubMs )

    Moves an item from one position to another, preserving all item state including contents.

    place_items

    🇲 Method –> ( string, integer, TripointBubMs, TripointBubMs, boolean )

    place_npc

    🇲 Method –> ( TripointBubMs, string ) -> Npc

    Forcibly places an npc using a template at a position on the map. Returns the npc.

    place_spawns

    🇲 Method –> ( string, integer, TripointBubMs, TripointBubMs, number, boolean )

    points_in_radius

    🇲 Method –> ( TripointBubMs, integer, integer? ) -> TripointBubMs[]

    Returns all points within a radius from the center point. radiusz defaults to 0.

    remove_field_at

    🇲 Method –> ( TripointBubMs, FieldTypeIntId )

    remove_item_at

    🇲 Method –> ( TripointBubMs, Item )
    🇲 Method –> ( Tripoint, Item )

    remove_trap_at

    🇲 Method –> ( TripointBubMs )

    Simpler version of set_trap_at with trap_null.

    replace_vehicle

    🇲 Method –> ( WrappedVehicle, string, table? ) -> boolean
    🇲 Method –> ( TripointBubMs, string, table? ) -> boolean

    Replaces a specific vehicle with a different prototype at the same origin tile.
    Returns false if the vehicle id or an option is invalid.
    Pass an optional table with keys:

    • orientation (Angle or number, optional): Facing of the new vehicle, as an Angle or in degrees. Defaults to the old vehicle’s facing.
    • status (integer, optional): Initial damage. -1 is light damage, 0 is undamaged, 1 is disabled (destroyed tires or engine). Defaults to -1.
    • locks (boolean, optional): If false, removes locking door parts and spawns the vehicle unlocked with keys. Otherwise locks follow the normal spawn rules.

    rotate

    🇲 Method –> ( integer )

    set_field_age_at

    🇲 Method –> ( TripointBubMs, FieldTypeIntId, TimeDuration, boolean ) -> TimeDuration

    set_field_int_at

    🇲 Method –> ( TripointBubMs, FieldTypeIntId, integer, boolean ) -> integer

    set_furn_at

    🇲 Method –> ( TripointBubMs, FurnIntId )

    set_furn_var_at

    🇲 Method –> ( TripointBubMs, string, string ) -> boolean

    Sets a furniture variable at the position. Returns false if the position is out of bounds.

    set_temperature

    🇲 Method –> ( TripointBubMs, integer )

    set_ter_at

    🇲 Method –> ( TripointBubMs, TerIntId ) -> boolean

    set_ter_var_at

    🇲 Method –> ( TripointBubMs, string, string ) -> boolean

    Sets a terrain variable at the position. Returns false if the position is out of bounds.

    set_trap_at

    🇲 Method –> ( TripointBubMs, TrapIntId )

    Set a trap at a position on the map. It can also replace existing trap, even with trap_null.

    spawn_artifact_at

    🇲 Method –> ( TripointBubMs )

    Spawns a random artifact at a position on the map.

    spawn_natural_artifact_at

    🇲 Method –> ( TripointBubMs, string? )

    Spawns a natural artifact at a position on the map. Omit property to choose one at random.

    MapStack

    Bases

    • ItemStack

    Constructors

    No constructors.

    Members

    as_item_stack

    🇲 Method –> ( ) -> ItemStack

    MapgenConstructor

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    add_field_at

    🇲 Method –> ( PointOmtMs, FieldTypeIntId, integer, TimeDuration ) -> boolean

    add_item

    🇲 Method –> ( PointOmtMs, Detached<Item> ) -> Detached<Item>

    clear_items_at

    🇲 Method –> ( PointOmtMs )

    create_corpse_at

    🇲 Method –> ( PointOmtMs, MonsterTypeId?, TimePoint?, string?, integer? )

    create_item_at

    🇲 Method –> ( PointOmtMs, ItypeId, integer )

    Creates a new item at a position on the mapgen surface. count sets the item’s charges, not the number of items: exactly one item is created. For stackable (count-by-charges) items such as ammo, count is the stack size. For non-stackable items, pass a negative value (e.g. -1), since a positive one is still applied as charges. Tools spawned with a negative value get their default charges.

    destroy

    🇲 Method –> ( PointOmtMs )

    draw_fill_background

    🇲 Method –> ( string )

    erase_furn_var_at

    🇲 Method –> ( PointOmtMs, string ) -> boolean

    Removes a furniture variable at the position. Returns whether a variable was removed.

    erase_ter_var_at

    🇲 Method –> ( PointOmtMs, string ) -> boolean

    Removes a terrain variable at the position. Returns whether a variable was removed.

    get_furn_at

    🇲 Method –> ( PointOmtMs ) -> FurnIntId

    get_furn_var_at

    🇲 Method –> ( PointOmtMs, string, string? ) -> string

    Returns a furniture variable at the position, or default (empty string if omitted) when it is not set.

    get_furn_vars_table_at

    🇲 Method –> ( PointOmtMs ) -> table

    Returns all furniture variables at the position as a table mapping each name to its value.

    get_items_at

    🇲 Method –> ( PointOmtMs ) -> MapStack

    get_items_in_radius

    🇲 Method –> ( PointOmtMs, integer ) -> MapStack[]

    get_map_size

    🇲 Method –> ( ) -> integer

    get_map_size_in_submaps

    🇲 Method –> ( ) -> integer

    get_temperature

    🇲 Method –> ( PointOmtMs ) -> integer

    get_ter_at

    🇲 Method –> ( PointOmtMs ) -> TerIntId

    get_ter_var_at

    🇲 Method –> ( PointOmtMs, string, string? ) -> string

    Returns a terrain variable at the position, or default (empty string if omitted) when it is not set.

    get_ter_vars_table_at

    🇲 Method –> ( PointOmtMs ) -> table

    Returns all terrain variables at the position as a table mapping each name to its value.

    get_trap_at

    🇲 Method –> ( PointOmtMs ) -> TrapIntId

    get_vehicles

    🇲 Method –> ( ) -> CppVal<vehicle>[]

    has_flag_at

    🇲 Method –> ( string, PointOmtMs ) -> boolean

    has_furn_flag_at

    🇲 Method –> ( string, PointOmtMs ) -> boolean

    has_furn_var_at

    🇲 Method –> ( PointOmtMs, string ) -> boolean

    Returns whether a furniture variable is set at the position.

    has_ter_flag_at

    🇲 Method –> ( string, PointOmtMs ) -> boolean

    has_ter_var_at

    🇲 Method –> ( PointOmtMs, string ) -> boolean

    Returns whether a terrain variable is set at the position.

    is_ot_match

    🇫 Function –> ( string, OterIntId, OtMatchType ) -> boolean

    make_rubble

    🇲 Method –> ( PointOmtMs, FurnIntId, TerIntId )

    place_items

    🇲 Method –> ( string, integer, PointOmtMs, PointOmtMs, boolean )

    place_npc

    🇲 Method –> ( PointOmtMs, string ) -> Npc

    Forcibly places an npc using a template at a position on the mapgen surface. Returns the npc.

    place_spawns

    🇲 Method –> ( string, integer, PointOmtMs, PointOmtMs, number, boolean )

    points_in_radius

    🇲 Method –> ( PointOmtMs, integer ) -> PointOmtMs[]

    remove_field_at

    🇲 Method –> ( PointOmtMs, FieldTypeIntId )

    remove_trap_at

    🇲 Method –> ( PointOmtMs )

    replace_vehicle

    🇲 Method –> ( CppVal<vehicle>, string, table? ) -> boolean

    Replaces a vehicle spawned by mapgen with a different prototype at the same position.
    Returns false if the vehicle id or an option is invalid.
    Pass an optional table with keys:

    • orientation (Angle or number, optional): Facing of the new vehicle, as an Angle or in degrees. Defaults to the old vehicle’s facing.
    • status (integer, optional): Initial damage. -1 is light damage, 0 is undamaged, 1 is disabled (destroyed tires or engine). Defaults to -1.
    • locks (boolean, optional): If false, removes locking door parts and spawns the vehicle unlocked with keys. Otherwise locks follow the normal spawn rules.

    rotate

    🇲 Method –> ( integer )

    set_furn_at

    🇲 Method –> ( PointOmtMs, FurnIntId )

    set_furn_var_at

    🇲 Method –> ( PointOmtMs, string, string ) -> boolean

    Sets a furniture variable at the position. Returns false if the position is out of bounds.

    set_temperature

    🇲 Method –> ( PointOmtMs, integer )

    set_ter_at

    🇲 Method –> ( PointOmtMs, TerIntId ) -> boolean

    set_ter_var_at

    🇲 Method –> ( PointOmtMs, string, string ) -> boolean

    Sets a terrain variable at the position. Returns false if the position is out of bounds.

    set_trap_at

    🇲 Method –> ( PointOmtMs, TrapIntId )

    MapgenData

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    above

    🇲 Method –> ( ) -> OterIntId

    Gets the oter id to the above.

    below

    🇲 Method –> ( ) -> OterIntId

    Gets the oter id to the below.

    east

    🇲 Method –> ( ) -> OterIntId

    Gets the oter id to the east.

    fill_groundcover

    🇲 Method –> ( )

    Fills the ground with default terrain.

    generate

    🇲 Method –> ( string )

    Generates Normal Mapgen

    get_nesw

    🇲 Method –> ( integer ) -> OterIntId

    Returns t_nesw at index i

    get_rot_suffix

    🇲 Method –> ( ) -> string

    Gets rotation string

    get_rotation

    🇲 Method –> ( ) -> integer

    Gets rotation

    id

    🇲 Method –> ( ) -> OterIntId

    Gets it’s oter id.

    neast

    🇲 Method –> ( ) -> OterIntId

    Gets the oter id to the neast.

    nest

    🇲 Method –> ( string, PointRelMs )

    Generates Nested Mapgen

    north

    🇲 Method –> ( ) -> OterIntId

    Gets the oter id to the north.

    nwest

    🇲 Method –> ( ) -> OterIntId

    Gets the oter id to the nwest.

    seast

    🇲 Method –> ( ) -> OterIntId

    Gets the oter id to the seast.

    set_dir

    🇲 Method –> ( integer, integer )

    Sets the direction of the mapgen.

    south

    🇲 Method –> ( ) -> OterIntId

    Gets the oter id to the south.

    swest

    🇲 Method –> ( ) -> OterIntId

    Gets the oter id to the swest.

    west

    🇲 Method –> ( ) -> OterIntId

    Gets the oter id to the west.

    zlevel

    🇲 Method –> ( ) -> integer

    Gets the z-level that it is generated at.

    MartialArtsBuffId

    Bases

    No base classes.

    Constructors

    • MartialArtsBuffId.new( )
    • MartialArtsBuffId.new( MartialArtsBuffId )
    • MartialArtsBuffId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> MartialArtsBuffId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MartialArtsBuffRaw

    str

    🇲 Method –> ( ) -> string

    MartialArtsId

    Bases

    No base classes.

    Constructors

    • MartialArtsId.new( )
    • MartialArtsId.new( MartialArtsId )
    • MartialArtsId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> MartialArtsId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MartialArtsRaw

    str

    🇲 Method –> ( ) -> string

    MartialArtsTechniqueId

    Bases

    No base classes.

    Constructors

    • MartialArtsTechniqueId.new( )
    • MartialArtsTechniqueId.new( MartialArtsTechniqueId )
    • MartialArtsTechniqueId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> MartialArtsTechniqueId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MartialArtsTechniqueRaw

    str

    🇲 Method –> ( ) -> string

    MartialArtsTechniqueRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    avatar_message

    🇻 Variable –> string

    block_counter

    🇻 Variable –> boolean

    controlled_knockback

    🇻 Variable –> boolean

    crit_ok

    🇻 Variable –> boolean

    crit_tec

    🇻 Variable –> boolean

    defensive

    🇻 Variable –> boolean

    disarms

    🇻 Variable –> boolean

    dodge_counter

    🇻 Variable –> boolean

    down_dur

    🇻 Variable –> integer

    force_unarmed

    🇻 Variable –> boolean

    grab_break

    🇻 Variable –> boolean

    knockback_dist

    🇻 Variable –> integer

    knockback_follow

    🇻 Variable –> boolean

    knockback_spread

    🇻 Variable –> number

    miss_recovery

    🇻 Variable –> boolean

    name

    🇻 Variable –> string

    npc_message

    🇻 Variable –> string

    powerful_knockback

    🇻 Variable –> boolean

    side_switch

    🇻 Variable –> boolean

    stun_dur

    🇻 Variable –> integer

    take_weapon

    🇻 Variable –> boolean

    get_description

    🇲 Method –> ( ) -> string

    Mass

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    from_gram

    🇫 Function –> ( integer ) -> Mass

    from_kilogram

    🇫 Function –> ( integer ) -> Mass

    from_milligram

    🇫 Function –> ( integer ) -> Mass

    from_newton

    🇫 Function –> ( integer ) -> Mass

    to_gram

    🇲 Method –> ( ) -> integer

    to_kilogram

    🇲 Method –> ( ) -> integer

    to_milligram

    🇲 Method –> ( ) -> integer

    to_newton

    🇲 Method –> ( ) -> integer

    MaterialTypeId

    Bases

    No base classes.

    Constructors

    • MaterialTypeId.new( )
    • MaterialTypeId.new( MaterialTypeId )
    • MaterialTypeId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> MaterialTypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MaterialTypeRaw

    str

    🇲 Method –> ( ) -> string

    MaterialTypeRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    name

    🇲 Method –> ( ) -> string

    str_id

    🇲 Method –> ( ) -> MaterialTypeId

    Mission

    Bases

    No base classes.

    Constructors

    • Mission.new( )

    Members

    assign

    🇲 Method –> ( Avatar )

    Assigns this mission to the given avatar.

    fail

    🇲 Method –> ( )

    Fails the mission.

    get_deadline

    🇲 Method –> ( ) -> TimePoint

    Returns the mission’s deadline as a time_point.

    get_description

    🇲 Method –> ( ) -> string

    Returns the mission description.

    get_follow_up

    🇲 Method –> ( ) -> MissionTypeIdRaw

    Returns the follow-up mission type ID.

    get_id

    🇲 Method –> ( ) -> integer

    Returns the mission’s unique ID.

    get_item_id

    🇲 Method –> ( ) -> ItypeId

    Returns the item ID associated with the mission.

    get_likely_rewards

    🇲 Method –> ( ) -> (integer, ItypeId)[]

    Returns the likely rewards of the mission (vector of (int chance, itype_id) pairs).

    get_npc_id

    🇲 Method –> ( ) -> CharacterId

    Returns the NPC character ID associated with the mission.

    get_target_point

    🇲 Method –> ( ) -> TripointAbsOmt

    Returns the target of the mission as absolute overmap terrain coordinates.

    get_type

    🇲 Method –> ( ) -> MissionType

    Returns the mission type of the target (pointer to mission_type).

    get_value

    🇲 Method –> ( ) -> integer

    Returns the mission’s value as an integer.

    has_deadline

    🇲 Method –> ( ) -> boolean

    Returns true if the mission has a deadline.

    has_failed

    🇲 Method –> ( ) -> boolean

    Returns true if the mission has failed.

    has_follow_up

    🇲 Method –> ( ) -> boolean

    Returns true if the mission has a follow-up mission.

    has_generic_rewards

    🇲 Method –> ( ) -> boolean

    Returns true if the mission has generic rewards.

    has_target

    🇲 Method –> ( ) -> boolean

    Returns true if the mission has a target.

    in_progress

    🇲 Method –> ( ) -> boolean

    Returns true if the mission is currently in progress.

    is_assigned

    🇲 Method –> ( ) -> boolean

    Returns true if the mission is currently assigned.

    is_complete

    🇲 Method –> ( CharacterId? ) -> boolean

    Returns true if the mission goal has been completed (optionally checked against given NPC ID).

    mission_id

    🇲 Method –> ( ) -> MissionTypeIdRaw

    Returns the mission type ID of this mission.

    name

    🇲 Method –> ( ) -> string

    Returns the mission’s name as a string.

    reserve_new

    🇫 Function –> ( MissionTypeIdRaw, CharacterId ) -> Mission

    Reserves a new mission of the given type for the specified NPC. Returns the new mission.

    reserve_random

    🇫 Function –> ( MissionOrigin, TripointAbsOmt, CharacterId ) -> Mission

    Reserves a random mission at the specified origin and position for the given NPC. Returns the new mission.

    step_complete

    🇲 Method –> ( integer )

    Marks a mission step as complete, taking an integer step index.

    wrap_up

    🇲 Method –> ( )

    Wraps up the mission successfully.

    MissionType

    Bases

    No base classes.

    Constructors

    • MissionType.new( )

    Members

    deadline_high

    🇻 Variable –> TimeDuration

    Returns the maximum allowed deadline for the mission.

    deadline_low

    🇻 Variable –> TimeDuration

    Returns the minimum allowed deadline for the mission.

    description

    🇻 Variable –> CppVal<translation>

    Returns the mission’s description as a string.

    dialogue

    🇻 Variable –> table<string, CppVal<translation>>

    Returns any associated dialogue for the mission, keyed by situation: describe, offer, accepted, rejected, advice, inquire, success, success_lie and failure.

    difficulty

    🇻 Variable –> integer

    Returns the mission’s difficulty as an integer.

    empty_container

    🇻 Variable –> ItypeId

    Returns true if the mission requires the container to be empty.

    follow_up

    🇻 Variable –> MissionTypeIdRaw

    Returns any follow-up mission type ID.

    goal

    🇻 Variable –> MissionGoal

    Returns the mission’s goal text.

    has_generic_rewards

    🇻 Variable –> boolean

    Returns true if the mission has generic rewards.

    item_count

    🇻 Variable –> integer

    Returns the count of items involved in the mission.

    item_id

    🇻 Variable –> ItypeId

    Returns the ID of the mission’s main item target, if applicable.

    likely_rewards

    🇻 Variable –> (integer, ItypeId)[]

    Returns a vector of likely rewards (chance, itype_id pairs).

    monster_kill_goal

    🇻 Variable –> integer

    Returns the number of monsters required to kill for this mission.

    monster_type

    🇻 Variable –> MonsterTypeId

    Returns the monster type associated with the mission, if any.

    origins

    🇻 Variable –> MissionOrigin[]

    Returns a list of origins from which this mission can be generated.

    remove_container

    🇻 Variable –> boolean

    Returns true if the mission requires removing a container.

    target_npc_id

    🇻 Variable –> CharacterId

    Returns the ID of the target NPC for the mission, if any.

    urgent

    🇻 Variable –> boolean

    Returns true if the mission is marked as urgent.

    value

    🇻 Variable –> integer

    Returns the mission’s reward value as an integer.

    get_all

    🇫 Function –> ( ) -> MissionType[]

    Returns all available missions.

    get_random_mission_id

    🇫 Function –> ( MissionOrigin, TripointAbsOmt ) -> MissionTypeIdRaw

    Returns a random mission type ID at the specified origin and overmap tile position.

    tname

    🇲 Method –> ( ) -> string

    MissionTypeIdRaw

    Bases

    No base classes.

    Constructors

    • MissionTypeIdRaw.new( string )

    Members

    No members.

    ModInfoId

    Bases

    No base classes.

    Constructors

    • ModInfoId.new( )
    • ModInfoId.new( ModInfoId )
    • ModInfoId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> ModInfoId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> ModInfoRaw

    str

    🇲 Method –> ( ) -> string

    Mongroup

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    diffuse

    🇻 Variable –> boolean

    horde

    🇻 Variable –> boolean

    horde_behaviour

    🇻 Variable –> string

    interest

    🇻 Variable –> integer

    population

    🇻 Variable –> integer

    radius

    🇻 Variable –> integer

    type

    🇻 Variable –> MonsterGroupId

    abs_pos

    🇲 Method –> ( ) -> TripointAbsSm

    Get the group position in absolute submap coordinates.

    avg_speed

    🇲 Method –> ( ) -> number

    Average movement speed of monsters in the group.

    clear

    🇲 Method –> ( )

    Remove all monsters and clear population.

    dec_interest

    🇲 Method –> ( integer )

    Decrease horde interest by the given amount (clamped 15..100).

    inc_interest

    🇲 Method –> ( integer )

    Increase horde interest by the given amount (clamped 15..100).

    is_empty

    🇲 Method –> ( ) -> boolean

    Check if the group has no members or population.

    is_safe

    🇲 Method –> ( ) -> boolean

    Check if the group is safe.

    monsters

    🇲 Method –> ( ) -> Monster[]

    Get individual monster instances tracked inside the horde (if any).

    nemesis_target

    🇲 Method –> ( ) -> TripointAbsSm

    Get the nemesis target for this group.

    set_interest

    🇲 Method –> ( integer )

    Set horde interest directly (clamped 15..100).

    set_nemesis_target

    🇲 Method –> ( TripointAbsSm )

    Set the nemesis target for this group using absolute submap coordinates.

    set_pos

    🇲 Method –> ( TripointAbsSm )

    Set the group position in absolute submap coordinates.

    set_target

    🇲 Method –> ( TripointAbsSm )

    Set the current target in absolute submap coordinates.

    target

    🇲 Method –> ( ) -> TripointAbsSm

    Get the current target in absolute submap coordinates.

    Monster

    Bases

    • Creature

    Constructors

    No constructors.

    Members

    anger

    🇻 Variable –> integer

    death_drops

    🇻 Variable –> boolean

    faction

    🇻 Variable –> MonsterFactionIntId

    friendly

    🇻 Variable –> integer

    morale

    🇻 Variable –> integer

    pet_bond_level

    🇻 Variable –> integer

    Bond level with the character this pet is bonded to.

    training_level

    🇻 Variable –> integer

    Pet training level gained through pet training.

    unique_name

    🇻 Variable –> string

    add_armor_item

    🇲 Method –> ( Detached<Item> ) -> Detached<Item>

    add_battery_item

    🇲 Method –> ( Detached<Item> ) -> Detached<Item>

    add_detached_item

    🇲 Method –> ( Detached<Item> )

    add_faction_anger

    🇲 Method –> ( string, integer )

    add_item

    🇲 Method –> ( Item )

    add_saddle_item

    🇲 Method –> ( Detached<Item> ) -> Detached<Item>

    add_storage_item

    🇲 Method –> ( Detached<Item> ) -> Detached<Item>

    attack_target

    🇲 Method –> ( ) -> Creature

    Hostile creature this monster sees at its move target, or nil while wandering.

    attitude

    🇲 Method –> ( Character ) -> MonsterAttitude

    bash_at

    🇲 Method –> ( TripointBubMs ) -> boolean
    🇲 Method –> ( Tripoint ) -> boolean

    can_act

    🇲 Method –> ( ) -> boolean

    Whether this monster has moves left and is not stunned, downed or webbed.

    can_climb

    🇲 Method –> ( ) -> boolean

    can_dig

    🇲 Method –> ( ) -> boolean

    can_drown

    🇲 Method –> ( ) -> boolean

    can_hear

    🇲 Method –> ( ) -> boolean

    can_see

    🇲 Method –> ( ) -> boolean

    can_submerge

    🇲 Method –> ( ) -> boolean

    can_upgrade

    🇲 Method –> ( ) -> boolean

    clear_items

    🇲 Method –> ( ) -> Detached<Item>[]

    clear_move_target

    🇲 Method –> ( )

    clear_special_attack_budget

    🇲 Method –> ( )

    Frees the budget so a further use_special_attack can run in the same action. Only for a deliberately multi-attack action; the budget is what stops Lua and the stock scheduler from stacking attacks onto one action.

    climbs

    🇲 Method –> ( ) -> boolean

    digs

    🇲 Method –> ( ) -> boolean

    drop_items

    🇲 Method –> ( TripointBubMs )

    drop_items_here

    🇲 Method –> ( )

    flies

    🇲 Method –> ( ) -> boolean

    get_armor_item

    🇲 Method –> ( ) -> Item

    get_battery_item

    🇲 Method –> ( ) -> Item

    get_faction_anger

    🇲 Method –> ( string ) -> integer

    get_grab_strength

    🇲 Method –> ( ) -> integer

    Intensity of the grabbed effect this monster applies.

    get_items

    🇲 Method –> ( ) -> Item[]

    get_saddle_item

    🇲 Method –> ( ) -> Item

    get_special_attack_cooldown

    🇲 Method –> ( string ) -> integer?

    Remaining cooldown in turns, or nil for attacks this monster does not have.

    get_special_attack_ids

    🇲 Method –> ( ) -> string[]

    Sorted IDs of every special attack this monster’s current type defines.

    get_storage_item

    🇲 Method –> ( ) -> Item

    get_type

    🇲 Method –> ( ) -> MonsterTypeId

    get_upgrade_time

    🇲 Method –> ( ) -> integer

    has_special_attack

    🇲 Method –> ( string ) -> boolean

    Whether this monster’s current type and runtime state contain the exact attack ID.

    hasten_upgrade

    🇲 Method –> ( )

    heal

    🇲 Method –> ( integer, boolean ) -> integer

    is_dead_or_dying

    🇲 Method –> ( ) -> boolean

    Whether this monster is dead or at 0 HP. Unlike is_dead, which checks only HP, this also includes monsters that already died with HP left, e.g. by self-destructing.

    is_fleeing

    🇲 Method –> ( Character ) -> boolean

    Whether this monster flees from the given character.

    is_wandering

    🇲 Method –> ( ) -> boolean

    made_of

    🇲 Method –> ( MaterialTypeId ) -> boolean

    make_ally

    🇲 Method –> ( Monster )

    make_friendly

    🇲 Method –> ( )

    make_fungus

    🇲 Method –> ( ) -> boolean

    make_pet

    🇲 Method –> ( )

    move_target

    🇲 Method –> ( ) -> TripointBubMs

    move_to

    🇲 Method –> ( TripointBubMs, boolean, boolean, number ) -> boolean
    🇲 Method –> ( Tripoint, boolean, boolean, number ) -> boolean

    movement_impaired

    🇲 Method –> ( ) -> boolean

    Whether this monster has an effect that impairs movement.

    name

    🇲 Method –> ( integer ) -> string

    name_with_armor

    🇲 Method –> ( ) -> string

    refill_udders

    🇲 Method –> ( )

    remove_armor_item

    🇲 Method –> ( ) -> Detached<Item>

    remove_battery_item

    🇲 Method –> ( ) -> Detached<Item>

    remove_item

    🇲 Method –> ( Item ) -> Detached<Item>

    remove_saddle_item

    🇲 Method –> ( ) -> Detached<Item>

    remove_storage_item

    🇲 Method –> ( ) -> Detached<Item>

    run_normal_ai_turn

    🇲 Method –> ( )

    set_attitude

    🇲 Method –> ( MonsterAttitude )

    set_hp

    🇲 Method –> ( integer )

    set_move_target

    🇲 Method –> ( TripointBubMs )
    🇲 Method –> ( Tripoint )

    set_special_attack_cooldown

    🇲 Method –> ( string, integer )

    Sets the remaining cooldown in turns. Negative values are clamped to 0. Does nothing for attacks this monster does not have.

    set_special_attack_enabled

    🇲 Method –> ( string, boolean )

    Enables or disables an attack without touching its cooldown. The enabled flag is serialized, so it persists across save/load. A disabled attack is skipped by the stock scheduler and by special_attack_ready.

    set_target

    🇲 Method –> ( Creature )

    spawn

    🇲 Method –> ( TripointBubMs )

    special_attack_budget_spent

    🇲 Method –> ( ) -> boolean

    Whether this action’s one special attack has already been spent.

    special_attack_enabled

    🇲 Method –> ( string ) -> boolean

    Whether the attack is enabled. False for attacks this monster does not have.

    special_attack_ready

    🇲 Method –> ( string ) -> boolean

    Checks only enabled state and zero cooldown; does not predict range, target, sight or ammo.

    swims

    🇲 Method –> ( ) -> boolean

    try_reproduce

    🇲 Method –> ( )

    try_upgrade

    🇲 Method –> ( boolean )

    use_special_attack

    🇲 Method –> ( string ) -> boolean

    Calls a ready special attack once. True means the actor handled use, not necessarily a hit or shot. Resets cooldown only on true. Actor side effects are not rolled back on false. Does not apply the scheduler’s pacified/hallucination restrictions or plan a target. On true the stock scheduler skips its own pick for the rest of this action.

    wander_to

    🇲 Method –> ( TripointBubMs, integer )

    MonsterFactionId

    Bases

    No base classes.

    Constructors

    Members

    NULL_ID

    🇫 Function –> ( ) -> MonsterFactionId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    int_id

    🇲 Method –> ( ) -> MonsterFactionIntId

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MonsterFactionRaw

    str

    🇲 Method –> ( ) -> string

    MonsterFactionIntId

    Bases

    No base classes.

    Constructors

    Members

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MonsterFactionRaw

    str_id

    🇲 Method –> ( ) -> MonsterFactionId

    MonsterGroupEntry

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    conditions

    🇻 Variable –> string[]

    cost_multiplier

    🇻 Variable –> integer

    ends

    🇻 Variable –> TimeDuration

    frequency

    🇻 Variable –> integer

    name

    🇻 Variable –> MonsterTypeId

    pack_maximum

    🇻 Variable –> integer

    pack_minimum

    🇻 Variable –> integer

    starts

    🇻 Variable –> TimeDuration

    lasts_forever

    🇲 Method –> ( ) -> boolean

    MonsterGroupId

    Bases

    No base classes.

    Constructors

    • MonsterGroupId.new( )
    • MonsterGroupId.new( MonsterGroupId )
    • MonsterGroupId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> MonsterGroupId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MonsterGroupRaw

    str

    🇲 Method –> ( ) -> string

    MonsterGroupRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    defaultMonster

    🇻 Variable –> MonsterTypeId

    freq_total

    🇻 Variable –> integer

    is_animal

    🇻 Variable –> boolean

    is_safe

    🇻 Variable –> boolean

    monster_group_time

    🇻 Variable –> TimeDuration

    monsters

    🇻 Variable –> MonsterGroupEntry[]

    name

    🇻 Variable –> MonsterGroupId

    new_monster_group

    🇻 Variable –> MonsterGroupId

    replace_monster_group

    🇻 Variable –> boolean

    contains

    🇲 Method –> ( MonsterTypeId ) -> boolean

    Check if a monster type appears in this group.

    MonsterTypeId

    Bases

    No base classes.

    Constructors

    • MonsterTypeId.new( )
    • MonsterTypeId.new( MonsterTypeId )
    • MonsterTypeId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> MonsterTypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MonsterTypeRaw

    str

    🇲 Method –> ( ) -> string

    MonsterTypeRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    difficulty

    🇻 Variable –> integer

    difficulty_base

    🇻 Variable –> integer

    grab_strength

    🇻 Variable –> integer

    Intensity of the grabbed effect this monster type applies.

    id

    🇻 Variable –> MonsterTypeId

    melee_damage

    🇻 Variable –> DamageInstance

    Base melee attack damage.

    melee_dice

    🇻 Variable –> integer

    Number of dice of bonus bashing damage on melee hit.

    melee_sides

    🇻 Variable –> integer

    Number of sides of the melee bonus damage dice.

    nname

    🇲 Method –> ( integer ) -> string

    MoraleTypeDataId

    Bases

    No base classes.

    Constructors

    • MoraleTypeDataId.new( )
    • MoraleTypeDataId.new( MoraleTypeDataId )
    • MoraleTypeDataId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> MoraleTypeDataId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MoraleTypeDataRaw

    str

    🇲 Method –> ( ) -> string

    MutationBranchId

    Bases

    No base classes.

    Constructors

    • MutationBranchId.new( )
    • MutationBranchId.new( MutationBranchId )
    • MutationBranchId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> MutationBranchId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MutationBranchRaw

    str

    🇲 Method –> ( ) -> string

    MutationBranchRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    activated

    🇻 Variable –> boolean

    Whether this mutation can be activated at will.

    allow_soft_gear

    🇻 Variable –> boolean

    Mutation allows soft gear to be worn over otherwise-restricted parts.

    attackcost_modifier

    🇻 Variable –> number

    bleed_resist

    🇻 Variable –> number

    bodytemp_max_btu

    🇻 Variable –> CppVal<units_quantity<int,units_temperature_delta_in_millidegree_celsius_tag>>

    bodytemp_min_btu

    🇻 Variable –> CppVal<units_quantity<int,units_temperature_delta_in_millidegree_celsius_tag>>

    bodytemp_sleep_btu

    🇻 Variable –> CppVal<units_quantity<int,units_temperature_delta_in_millidegree_celsius_tag>>

    construction_speed_modifier

    🇻 Variable –> number

    Construction speed multiplier. 2.0 doubles construction speed; 0.5 halves it.

    cooldown

    🇻 Variable –> integer

    Costs are incurred every ‘cooldown’ turns.

    cost

    🇻 Variable –> integer

    crafting_speed_modifier

    🇻 Variable –> number

    Crafting speed multiplier. 2.0 doubles crafting speed; 0.5 halves it.

    debug

    🇻 Variable –> boolean

    Whether or not this mutation is limited to debug use.

    dodge_modifier

    🇻 Variable –> number

    falling_damage_multiplier

    🇻 Variable –> number

    fatigue

    🇻 Variable –> boolean

    Mutation causes fatigue when used.

    fatigue_modifier

    🇻 Variable –> number

    fatigue_regen_modifier

    🇻 Variable –> number

    healing_awake

    🇻 Variable –> number

    Healing per turn from mutation.

    healing_resting

    🇻 Variable –> number

    Healing per turn from mutation, while asleep.

    healthy_rate

    🇻 Variable –> number

    How quickly health (not HP) trends toward healthy_mod.

    hearing_modifier

    🇻 Variable –> number

    hp_adjustment

    🇻 Variable –> number

    Flat adjustment to HP.

    hp_modifier

    🇻 Variable –> number

    Bonus HP multiplier. 1.0 doubles HP; -0.5 halves it.

    hp_modifier_secondary

    🇻 Variable –> number

    Secondary HP multiplier; stacks with the other one. 1.0 doubles HP; -0.5 halves it.

    hunger

    🇻 Variable –> boolean

    Mutation deducts calories when used.

    id

    🇻 Variable –> MutationBranchId

    local_detail_sight

    🇻 Variable –> number

    max_stamina_modifier

    🇻 Variable –> number

    mending_modifier

    🇻 Variable –> number

    Multiplier applied to broken limb regeneration. Normally 0.25; clamped to 0.25..1.0.

    metabolism_modifier

    🇻 Variable –> number

    mixed_effect

    🇻 Variable –> boolean

    Whether this mutation has positive /and/ negative effects.

    movecost_flatground_modifier

    🇻 Variable –> number

    movecost_modifier

    🇻 Variable –> number

    movecost_obstacle_modifier

    🇻 Variable –> number

    movecost_swim_modifier

    🇻 Variable –> number

    night_vision_range

    🇻 Variable –> number

    noise_modifier

    🇻 Variable –> number

    overmap_multiplier

    🇻 Variable –> number

    overmap_sight

    🇻 Variable –> number

    packmule_modifier

    🇻 Variable –> number

    Packmule multiplier. 2.0 doubles backpack/container volume; 0.5 halves it.

    pain_recovery

    🇻 Variable –> number

    Pain recovery per turn from mutation.

    player_display

    🇻 Variable –> boolean

    Whether or not this mutation shows up in the status (@) menu.

    points

    🇻 Variable –> integer

    Point cost in character creation(?).

    profession

    🇻 Variable –> boolean

    Whether this trait is ONLY gained through professional training/experience (and/or quests).

    purifiable

    🇻 Variable –> boolean

    Whether this mutation is possible to remove through Purifier. False for ‘special’ mutations.

    reading_speed_multiplier

    🇻 Variable –> number

    scent_modifier

    🇻 Variable –> number

    skill_rust_multiplier

    🇻 Variable –> number

    speed_modifier

    🇻 Variable –> number

    stamina_regen_modifier

    🇻 Variable –> number

    starting_trait

    🇻 Variable –> boolean

    Whether this trait can normally be taken during character generation.

    starts_active

    🇻 Variable –> boolean

    Whether a mutation activates when granted.

    stealth_modifier

    🇻 Variable –> number

    str_modifier

    🇻 Variable –> number

    Adjustment to Strength that doesn’t affect HP.

    temperature_speed_modifier

    🇻 Variable –> number

    thirst

    🇻 Variable –> boolean

    Mutation dehydrates when used.

    thirst_modifier

    🇻 Variable –> number

    threshold

    🇻 Variable –> boolean

    Whether this is a Threshold mutation, and thus especially difficult to mutate. One per character.

    ugliness

    🇻 Variable –> integer

    How physically unappealing the mutation is. Can be negative.

    valid

    🇻 Variable –> boolean

    Whether this mutation is available through generic mutagen.

    visibility

    🇻 Variable –> integer

    How visible the mutation is to others.

    weight_capacity_modifier

    🇻 Variable –> number

    addition_mutations

    🇲 Method –> ( ) -> MutationBranchId[]

    categories

    🇲 Method –> ( ) -> MutationCategoryTraitId[]

    Lists the categories this mutation belongs to.

    conflicts_with

    🇲 Method –> ( ) -> MutationBranchId[]

    Lists conflicting mutations.

    desc

    🇲 Method –> ( ) -> string

    get_all

    🇫 Function –> ( ) -> MutationBranchRaw[]

    Returns a (long) list of every mutation in the game.

    mutation_types

    🇲 Method –> ( ) -> string[]

    Lists the type(s) of this mutation. Mutations of a given type are mutually exclusive.

    name

    🇲 Method –> ( ) -> string

    other_prerequisites

    🇲 Method –> ( ) -> MutationBranchId[]

    Lists the secondary mutation(s) needed to gain this mutation.

    prerequisites

    🇲 Method –> ( ) -> MutationBranchId[]

    Lists the primary mutation(s) needed to gain this mutation.

    replaced_by

    🇲 Method –> ( ) -> MutationBranchId[]

    Lists mutations that replace (e.g. evolve from) this one.

    thresh_requirements

    🇲 Method –> ( ) -> MutationBranchId[]

    Lists the threshold mutation(s) required to gain this mutation.

    MutationCategoryTraitId

    Bases

    No base classes.

    Constructors

    • MutationCategoryTraitId.new( )
    • MutationCategoryTraitId.new( MutationCategoryTraitId )
    • MutationCategoryTraitId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> MutationCategoryTraitId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> MutationCategoryTraitRaw

    str

    🇲 Method –> ( ) -> string

    MutationCategoryTraitRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    id

    🇻 Variable –> MutationCategoryTraitId

    iv_additional_mutations

    🇻 Variable –> integer

    iv_additional_mutations_chance

    🇻 Variable –> integer

    iv_fatigue

    🇻 Variable –> integer

    iv_hunger

    🇻 Variable –> integer

    iv_message

    🇻 Variable –> CppVal<std_basic_string<char>()const>

    iv_min_mutations

    🇻 Variable –> integer

    iv_morale

    🇻 Variable –> integer

    iv_morale_max

    🇻 Variable –> integer

    iv_noise

    🇻 Variable –> integer

    iv_pain

    🇻 Variable –> integer

    iv_sleep

    🇻 Variable –> boolean

    iv_sleep_dur

    🇻 Variable –> integer

    iv_sleep_message

    🇻 Variable –> CppVal<std_basic_string<char>()const>

    iv_sound

    🇻 Variable –> boolean

    iv_sound_id

    🇻 Variable –> CppVal<std_basic_string<char>()const>

    iv_sound_message

    🇻 Variable –> CppVal<std_basic_string<char>()const>

    iv_sound_variant

    🇻 Variable –> CppVal<std_basic_string<char>()const>

    iv_thirst

    🇻 Variable –> integer

    junkie_message

    🇻 Variable –> CppVal<std_basic_string<char>()const>

    memorial_message_female

    🇻 Variable –> CppVal<std_basic_string<char>()const>

    memorial_message_male

    🇻 Variable –> CppVal<std_basic_string<char>()const>

    mutagen_fatigue

    🇻 Variable –> integer

    mutagen_hunger

    🇻 Variable –> integer

    mutagen_message

    🇻 Variable –> CppVal<std_basic_string<char>()const>

    mutagen_morale

    🇻 Variable –> integer

    mutagen_pain

    🇻 Variable –> integer

    mutagen_thirst

    🇻 Variable –> integer

    threshold_muts

    🇻 Variable –> MutationBranchId[]

    The traits that you gain when you break the thresholds for this category.

    get_mutations

    🇲 Method –> ( ) -> MutationBranchId[]

    Returns a list of all mutations in this category.

    name

    🇲 Method –> ( ) -> string

    Npc

    Bases

    • Player
    • Character
    • Creature

    Constructors

    No constructors.

    Members

    current_activity_id

    🇻 Variable –> ActivityTypeId

    hit_by_player

    🇻 Variable –> boolean

    marked_for_death

    🇻 Variable –> boolean

    needs

    🇻 Variable –> NpcNeed[]

    op_of_u

    🇻 Variable –> NpcOpinion

    patience

    🇻 Variable –> integer

    personality

    🇻 Variable –> NpcPersonality

    can_move_to

    🇲 Method –> ( TripointBubMs, boolean ) -> boolean

    can_open_door

    🇲 Method –> ( TripointBubMs, boolean ) -> boolean

    complain

    🇲 Method –> ( ) -> boolean

    Finds something to complain about and complains. Returns if complained.

    complain_about

    🇲 Method –> ( string, TimeDuration, string, boolean? ) -> boolean

    Complain about an issue if enough time has passed. The first string is the issue identifier, with the second being the complaint text. The optional bool allows you to force a complaint without concern for the input time.

    current_ally

    🇲 Method –> ( ) -> Creature

    Returns the npc’s current ally, if it has one.

    current_target

    🇲 Method –> ( ) -> Creature

    Returns the npc’s current target as a creature, if it has one.

    danger_assessment

    🇲 Method –> ( ) -> number

    Gets a value based on the npc’s perspective of the area’s danger.

    evaluate_enemy

    🇲 Method –> ( Creature ) -> number

    Rates how dangerous a target is from 0 (harmless) to 1 (max danger).

    follow_distance

    🇲 Method –> ( ) -> integer

    Gets the npc’s follow distance. This can only be a few values, and is determined by npc rules.

    get_attitude

    🇲 Method –> ( ) -> NpcAttitude

    get_first_topic

    🇲 Method –> ( ) -> string

    Returns the first topic of the npc’s chatbin.

    get_monster_faction

    🇲 Method –> ( ) -> MonsterFactionIntId

    Returns the npc’s faction id. If it’s part of a monster faction, it returns the id of the monster faction.

    guaranteed_hostile

    🇲 Method –> ( ) -> boolean

    Returns true if the npc would be hostile to the player on sight regardless of their current attitude.

    has_activity

    🇲 Method –> ( ) -> boolean

    has_omt_destination

    🇲 Method –> ( ) -> boolean

    has_player_activity

    🇲 Method –> ( ) -> boolean

    hostile_anger_level

    🇲 Method –> ( ) -> integer

    is_ally

    🇲 Method –> ( Character ) -> boolean

    is_enemy

    🇲 Method –> ( ) -> boolean

    is_following

    🇲 Method –> ( ) -> boolean

    is_friendly

    🇲 Method –> ( Character ) -> boolean

    is_guarding

    🇲 Method –> ( ) -> boolean

    is_leader

    🇲 Method –> ( ) -> boolean

    is_minion

    🇲 Method –> ( ) -> boolean

    Returns true if the npc is a player ally and their op_of_u.trust is >= 5.

    is_obeying

    🇲 Method –> ( Character ) -> boolean

    is_patrolling

    🇲 Method –> ( ) -> boolean

    is_player_ally

    🇲 Method –> ( ) -> boolean

    is_simulated

    🇲 Method –> ( ) -> boolean

    True if this NPC is in a simulated (fully loaded, AI-eligible) submap.

    is_stationary

    🇲 Method –> ( boolean ) -> boolean

    is_travelling

    🇲 Method –> ( ) -> boolean

    Returns true if the npc has the ‘NPC_MISSION_TRAVELLING’ mission.

    is_walking_with

    🇲 Method –> ( ) -> boolean

    make_angry

    🇲 Method –> ( )

    move_to

    🇲 Method –> ( TripointBubMs, boolean? )

    Attempts to move the NPC to an adjacent map square.

    mutiny

    🇲 Method –> ( )

    Causes the npc to leave your faction, incur various negative opinion maluses, and say explatives to the player.

    npc_menu

    🇲 Method –> ( boolean? )

    Triggers the npc menu to open.

    saw_player_recently

    🇲 Method –> ( ) -> boolean

    say

    🇲 Method –> ( string )

    Has the npc say the given string in the sidebar.

    set_attitude

    🇲 Method –> ( NpcAttitude )

    set_faction_id

    🇲 Method –> ( FactionId )

    set_first_topic

    🇲 Method –> ( string )

    Sets the first topic of the npc’s chatbin. Note that some circumstances may cause this to not be the first topic used, such as player allies.

    set_move_target

    🇲 Method –> ( TripointBubMs, boolean?, boolean? ) -> boolean
    🇲 Method –> ( Tripoint, boolean?, boolean? ) -> boolean

    smash_ability

    🇲 Method –> ( ) -> integer

    Gets the npc’s blunt damage with their currently equipped weapon.

    talk_to_u

    🇲 Method –> ( string?, boolean? )

    Causes the npc to talk to you. Passing a topic will force that topic to be used in place of all others, including code enforced topics such as ‘TALK_STOLE_ITEM’.

    turned_hostile

    🇲 Method –> ( ) -> boolean

    warn_about

    🇲 Method –> ( string, TimeDuration, string, integer, TripointBubMs )

    Wrapper for complain_about that warns about a specific type of threat, with different warnings for hostile or friendly NPCs and hostile NPCs always complaining.

    NpcOpinion

    Bases

    No base classes.

    Constructors

    • NpcOpinion.new( )
    • NpcOpinion.new( int, int, int, int, int )

    Members

    anger

    🇻 Variable –> integer

    fear

    🇻 Variable –> integer

    owed

    🇻 Variable –> integer

    trust

    🇻 Variable –> integer

    value

    🇻 Variable –> integer

    NpcPersonality

    Bases

    No base classes.

    Constructors

    • NpcPersonality.new( )

    Members

    aggression

    🇻 Variable –> integer

    altruism

    🇻 Variable –> integer

    bravery

    🇻 Variable –> integer

    collector

    🇻 Variable –> integer

    OmtFindParams

    Bases

    No base classes.

    Constructors

    • OmtFindParams.new( )

    Members

    exclude_types

    🇻 Variable –> (string, OtMatchType)[]

    Vector of (terrain_type, match_type) pairs to exclude from search.

    existing_only

    🇻 Variable –> boolean

    If true, restricts search to existing overmaps only.

    explored

    🇻 Variable –> boolean?

    If set, filters by terrain explored status (true = explored only, false = unexplored only).

    max_results

    🇻 Variable –> integer?

    If set, limits the number of results returned.

    seen

    🇻 Variable –> boolean?

    If set, filters by terrain seen status (true = seen only, false = unseen only).

    types

    🇻 Variable –> (string, OtMatchType)[]

    Vector of (terrain_type, match_type) pairs to search for.

    add_exclude_type

    🇲 Method –> ( string, OtMatchType )

    Helper method to add a terrain type to exclude from search.

    add_type

    🇲 Method –> ( string, OtMatchType )

    Helper method to add a terrain type to search for.

    set_search_layers

    🇲 Method –> ( integer, integer )

    Set the search layer range (z-levels).

    set_search_range

    🇲 Method –> ( integer, integer )

    Set the search range in overmap tiles (min, max).

    OterId

    Bases

    No base classes.

    Constructors

    • OterId.new( )
    • OterId.new( OterId )
    • OterId.new( OterIntId )
    • OterId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> OterId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    int_id

    🇲 Method –> ( ) -> OterIntId

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> OterRaw

    str

    🇲 Method –> ( ) -> string

    OterIntId

    Bases

    No base classes.

    Constructors

    Members

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> OterRaw

    str_id

    🇲 Method –> ( ) -> OterId

    OvermapBuffer

    Global overmap buffer that manages all overmap data

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    add_grid_connection

    🇲 Method –> ( TripointAbsOmt, TripointAbsOmt ) -> boolean

    Add an electric grid connection between two positions

    electric_grid_at

    🇲 Method –> ( TripointAbsOmt ) -> TripointAbsOmt[]

    Get all overmap tiles belonging to the electric grid at the given position

    electric_grid_connectivity_at

    🇲 Method –> ( TripointAbsOmt ) -> TripointRelOmt[]

    Get all electric grid connections from the given position

    remove_grid_connection

    🇲 Method –> ( TripointAbsOmt, TripointAbsOmt ) -> boolean

    Remove an electric grid connection between two positions

    PerkId

    Bases

    No base classes.

    Constructors

    • PerkId.new( )
    • PerkId.new( PerkId )
    • PerkId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> PerkId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> PerkRaw

    str

    🇲 Method –> ( ) -> string

    PerkRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    id

    🇻 Variable –> PerkId

    get_category

    🇲 Method –> ( ) -> string

    get_description

    🇲 Method –> ( ) -> string

    get_name

    🇲 Method –> ( ) -> string

    Player

    Bases

    • Character
    • Creature

    Constructors

    No constructors.

    Members

    No members.

    PlayerActivity

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    coords

    🇻 Variable –> TripointAbsMs[]

    interruptable_with_kb

    🇻 Variable –> boolean

    moves_left

    🇻 Variable –> integer

    moves_total

    🇻 Variable –> integer

    name

    🇻 Variable –> string

    id

    🇲 Method –> ( ) -> ActivityTypeId

    id_str

    🇲 Method –> ( ) -> string

    Point

    Bases

    No base classes.

    Constructors

    • Point.new( )
    • Point.new( Point )
    • Point.new( int, int )

    Members

    x

    🇻 Variable –> integer

    y

    🇻 Variable –> integer

    abs

    🇲 Method –> ( ) -> Point

    reinterpret_as

    🇲 Method –> ( origin: string, scale: string ) -> PointCoord

    Reinterpret this raw point as a typed point coordinate without changing x or y.

    rotate

    🇲 Method –> ( integer, Point ) -> Point

    PointCoord

    A typed two-dimensional coordinate. Its origin and scale describe how to interpret x and y, and coordinate operations only combine compatible coordinate spaces.

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    x

    🇻 Variable –> integer

    y

    🇻 Variable –> integer

    origin

    🇲 Method –> ( ) -> string

    project_combine

    🇲 Method –> ( fine: any ) -> nil | PointCoord | TripointCoord

    Combines this coarse point with a remainder from project_remain. Returns PointCoord or TripointCoord depending on the inputs, or nil if the pair is incompatible.

    project_remain

    🇲 Method –> ( scale: string ) -> (PointCoord?, PointCoord?)

    Splits this point into a coarse PointCoord at the requested scale and a PointCoord remainder at this point’s original scale. Returns nil, nil if the split is not valid.

    project_remain_mmr

    🇲 Method –> ( ) -> (PointCoord?, PointCoord?)

    Shortcut for project_remain("mmr").

    project_remain_om

    🇲 Method –> ( ) -> (PointCoord?, PointCoord?)

    Shortcut for project_remain("om").

    project_remain_omt

    🇲 Method –> ( ) -> (PointCoord?, PointCoord?)

    Shortcut for project_remain("omt").

    project_remain_seg

    🇲 Method –> ( ) -> (PointCoord?, PointCoord?)

    Shortcut for project_remain("seg").

    project_remain_sm

    🇲 Method –> ( ) -> (PointCoord?, PointCoord?)

    Shortcut for project_remain("sm").

    raw

    🇲 Method –> ( ) -> Point

    reinterpret_as

    🇲 Method –> ( origin: string, scale: string ) -> PointCoord

    Reinterpret this coordinate as another point coordinate kind without changing x or y.

    rl_dist

    🇲 Method –> ( other: PointCoord ) -> integer?

    Rectilinear distance to another PointCoord with matching origin and scale. Returns nil if the argument is incompatible.

    rotate

    🇲 Method –> ( integer, Point ) -> PointCoord

    scale

    🇲 Method –> ( ) -> string

    square_dist

    🇲 Method –> ( other: PointCoord ) -> integer?

    Chebyshev distance to another PointCoord with matching origin and scale. Returns nil if the argument is incompatible.

    to

    🇲 Method –> ( scale: string ) -> PointCoord?

    Projects this coordinate to another scale, preserving its origin and point dimension. Returns nil if the conversion is not valid.

    to_mmr

    🇲 Method –> ( ) -> PointCoord?

    Shortcut for to("mmr").

    to_ms

    🇲 Method –> ( ) -> PointCoord?

    Shortcut for to("ms").

    to_om

    🇲 Method –> ( ) -> PointCoord?

    Shortcut for to("om").

    to_omt

    🇲 Method –> ( ) -> PointCoord?

    Shortcut for to("omt").

    to_seg

    🇲 Method –> ( ) -> PointCoord?

    Shortcut for to("seg").

    to_sm

    🇲 Method –> ( ) -> PointCoord?

    Shortcut for to("sm").

    to_veh

    🇲 Method –> ( ) -> PointCoord?

    Shortcut for to("veh").

    trig_dist

    🇲 Method –> ( other: PointCoord ) -> number?

    Euclidean distance to another PointCoord with matching origin and scale. Returns nil if the argument is incompatible.

    type

    🇲 Method –> ( ) -> string

    PopupInputStr

    Bases

    No base classes.

    Constructors

    • PopupInputStr.new( )

    Members

    desc

    🇲 Method –> ( string )

    desc is above input field.

    query_int

    🇲 Method –> ( ) -> integer

    Returns your input, but allows numbers only.

    query_str

    🇲 Method –> ( ) -> string

    Returns your input.

    title

    🇲 Method –> ( string )

    title is on the left of input field.

    PowerStat

    Power generation and consumption statistics for a grid

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    gen_w

    🇻 Variable –> integer

    Power generation in watts

    use_w

    🇻 Variable –> integer

    Power consumption in watts

    net_w

    🇲 Method –> ( ) -> integer

    Net power (generation - consumption) in watts

    QualityId

    Bases

    No base classes.

    Constructors

    • QualityId.new( )
    • QualityId.new( QualityId )
    • QualityId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> QualityId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> QualityRaw

    str

    🇲 Method –> ( ) -> string

    QueryPopup

    Bases

    No base classes.

    Constructors

    • QueryPopup.new( )

    Members

    allow_any_key

    🇲 Method –> ( boolean )

    Set whether to allow any key

    message

    🇲 Method –> ( any )

    message_color

    🇲 Method –> ( Color )

    query

    🇲 Method –> ( ) -> string

    Returns selected action

    query_yn

    🇲 Method –> ( ) -> string

    Returns YES or NO. If ESC pressed, returns NO.

    query_ynq

    🇲 Method –> ( ) -> string

    Returns YES, NO or QUIT. If ESC pressed, returns QUIT.

    RGBColor

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    name

    🇻 Variable –> CppVal<std_basic_string<char>()const>

    RangedData

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    aimed_crit_bonus

    🇻 Variable –> number

    aimed_crit_max_bonus

    🇻 Variable –> number

    damage

    🇻 Variable –> DamageInstance

    dispersion

    🇻 Variable –> integer

    range

    🇻 Variable –> integer

    RecipeId

    Bases

    No base classes.

    Constructors

    • RecipeId.new( )
    • RecipeId.new( RecipeId )
    • RecipeId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> RecipeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> RecipeRaw

    str

    🇲 Method –> ( ) -> string

    RecipeRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    booksets

    🇻 Variable –> table<ItypeId, integer>

    Books that teach this recipe, mapped to the skill level required to learn it from them.

    category

    🇻 Variable –> string

    difficulty

    🇻 Variable –> integer

    learn_by_disassembly

    🇻 Variable –> table<SkillId, integer>

    Skill levels required to learn this recipe by disassembling its result.

    required_skills

    🇻 Variable –> table<SkillId, integer>

    Secondary skill levels required to craft this recipe, besides skill_used at difficulty.

    skill_used

    🇻 Variable –> SkillId

    subcategory

    🇻 Variable –> string

    time

    🇻 Variable –> integer

    get_all

    🇫 Function –> ( ) -> RecipeRaw[]

    get_from_flag

    🇫 Function –> ( string ) -> RecipeRaw[]

    get_from_skill_used

    🇫 Function –> ( SkillId ) -> RecipeRaw[]

    has_flag

    🇲 Method –> ( string ) -> boolean

    recipe_id

    🇲 Method –> ( ) -> RecipeId

    result

    🇲 Method –> ( ) -> ItypeId

    result_name

    🇲 Method –> ( boolean ) -> string

    Relic

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    get_enchantments

    🇲 Method –> ( ) -> Enchantment[]

    get_recharge_scheme

    🇲 Method –> ( ) -> CppVal<relic_recharge>[]

    get_spells

    🇲 Method –> ( ) -> SpellSimple[]

    name

    🇲 Method –> ( ) -> string

    RequirementData

    Represents crafting requirements (tools, components, qualities)

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    can_make_with_inventory

    🇲 Method –> ( Inventory ) -> boolean

    Check if requirements can be made with given inventory

    get_components

    🇲 Method –> ( ) -> CppVal<item_comp>[][]

    Get list of all required components

    get_qualities

    🇲 Method –> ( ) -> CppVal<quality_requirement>[][]

    Get list of all required qualities

    get_tools

    🇲 Method –> ( ) -> CppVal<tool_comp>[][]

    Get list of all required tools

    id

    🇲 Method –> ( ) -> string

    Get the requirement ID as string

    is_blacklisted

    🇲 Method –> ( ) -> boolean

    Check if this requirement is blacklisted

    is_empty

    🇲 Method –> ( ) -> boolean

    Check if this requirement is empty

    is_null

    🇲 Method –> ( ) -> boolean

    Check if this is a null requirement

    list_all

    🇲 Method –> ( ) -> string

    Get a formatted list of all requirements

    list_missing

    🇲 Method –> ( ) -> string

    Get a formatted list of missing requirements

    Resistances

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    get_all_resist

    🇲 Method –> ( ) -> table<DamageType, number>

    Returns flat resistance values keyed by damage type. Damage types without resistance may be absent.

    get_effective_resist

    🇲 Method –> ( DamageUnit ) -> number

    get_resist

    🇲 Method –> ( DamageType ) -> number

    ScenarioId

    Bases

    No base classes.

    Constructors

    • ScenarioId.new( )
    • ScenarioId.new( ScenarioId )
    • ScenarioId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> ScenarioId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> ScenarioRaw

    str

    🇲 Method –> ( ) -> string

    ScenarioRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    forbids_bionics

    🇻 Variable –> boolean

    Returns true if the scenario forbids bionics outright.

    forbids_spells

    🇻 Variable –> boolean

    Returns true if the scenario forbids spells outright.

    has_map_extra

    🇻 Variable –> boolean

    Returns true if the scenario has a starting map extra.

    id

    🇻 Variable –> string

    String id of the scenario, e.g. “evacuee”. Useful for equality checks.

    is_blacklisted

    🇻 Variable –> boolean

    Returns true if the scenario is blacklisted.

    map_extra

    🇻 Variable –> string

    String id of the starting map extra, or an empty string if the scenario has none.

    point_cost

    🇻 Variable –> integer

    Point cost of the scenario.

    start_name

    🇻 Variable –> string

    Name of the starting situation shown during character creation.

    starting_vehicle

    🇻 Variable –> string

    String id of the starting vehicle, or an empty string if the scenario has none.

    str_id

    🇻 Variable –> ScenarioId

    allowed_bionics

    🇲 Method –> ( ) -> BionicDataId[]

    Allowed bionics, empty meaning all starting bionics are allowed.

    allowed_spells

    🇲 Method –> ( ) -> SpellTypeId[]

    Allowed spells, empty meaning all starting spells are allowed.

    allowed_start

    🇲 Method –> ( CppVal<string_id<start_location>> ) -> boolean

    Returns true if the given start location is allowed by this scenario.

    allowed_start_locations

    🇲 Method –> ( ) -> string[]

    String ids of the starting locations allowed by this scenario.

    allowed_traits

    🇲 Method –> ( ) -> MutationBranchId[]

    Allowed traits, empty meaning all starting traits are allowed.

    bionicquery

    🇲 Method –> ( BionicDataId ) -> boolean

    Returns true if the given bionic is allowed in this scenario.

    description

    🇲 Method –> ( boolean ) -> string

    Description of the scenario for the given gender (true = male).

    forbidden_bionics

    🇲 Method –> ( ) -> BionicDataId[]

    Bionics forbidden in this scenario.

    forbidden_spells

    🇲 Method –> ( ) -> SpellTypeId[]

    Spells forbidden in this scenario.

    forbidden_traits

    🇲 Method –> ( ) -> MutationBranchId[]

    Traits forbidden in this scenario.

    forced_bionics

    🇲 Method –> ( ) -> BionicDataId[]

    Bionics forced by the scenario.

    forced_spells

    🇲 Method –> ( ) -> SpellTypeId[]

    Spells forced by the scenario.

    forced_traits

    🇲 Method –> ( ) -> MutationBranchId[]

    Traits forced by the scenario, granted for free during character creation.

    get_flags

    🇲 Method –> ( ) -> string[]

    All scenario flags, e.g. “FIRE_START”.

    has_flag

    🇲 Method –> ( string ) -> boolean

    Returns true if the scenario has the given flag.

    is_forbidden_bionic

    🇲 Method –> ( BionicDataId ) -> boolean

    Returns true if the given bionic is forbidden in this scenario.

    is_forbidden_spell

    🇲 Method –> ( SpellTypeId ) -> boolean

    Returns true if the given spell is forbidden in this scenario.

    is_forbidden_trait

    🇲 Method –> ( MutationBranchId ) -> boolean

    Returns true if the given trait is forbidden in this scenario.

    is_locked_bionic

    🇲 Method –> ( BionicDataId ) -> boolean

    Returns true if the given bionic is forced by this scenario.

    is_locked_trait

    🇲 Method –> ( MutationBranchId ) -> boolean

    Returns true if the given trait is forced by this scenario.

    missions

    🇲 Method –> ( ) -> MissionTypeIdRaw[]

    Mission types assigned at the start of the game.

    name

    🇲 Method –> ( boolean ) -> string

    The scenario’s id as a plain string. Display name of the scenario for the given gender (true = male).

    perks

    🇲 Method –> ( ) -> PerkId[]

    Perks forced by the scenario.

    permitted_professions

    🇲 Method –> ( ) -> string[]

    String ids of professions permitted by this scenario.

    spellquery

    🇲 Method –> ( SpellTypeId ) -> boolean

    Returns true if the given spell is allowed in this scenario.

    surround_groups

    🇲 Method –> ( ) -> (MonsterGroupId, number)[]

    Monster groups surrounding the start: array of (mongroup_id, chance) pairs.

    traitquery

    🇲 Method –> ( MutationBranchId ) -> boolean

    Returns true if the given trait is allowed in this scenario.

    SkillId

    Bases

    No base classes.

    Constructors

    • SkillId.new( )
    • SkillId.new( SkillId )
    • SkillId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> SkillId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> SkillRaw

    str

    🇲 Method –> ( ) -> string

    SkillLevel

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    can_train

    🇲 Method –> ( ) -> boolean

    highest_level

    🇲 Method –> ( ) -> integer

    is_training

    🇲 Method –> ( ) -> boolean

    level

    🇲 Method –> ( ) -> integer

    train

    🇲 Method –> ( integer, boolean )

    SkillLevelMap

    Bases

    • Dict( SkillId, SkillLevel )

    Constructors

    No constructors.

    Members

    get_skill_level

    🇲 Method –> ( SkillId ) -> integer

    get_skill_level_object

    🇲 Method –> ( SkillId ) -> SkillLevel

    mod_skill_level

    🇲 Method –> ( SkillId, integer )

    Sound

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    from_decibel

    🇫 Function –> ( integer ) -> Sound

    to_decibel

    🇲 Method –> ( ) -> integer

    SpeciesTypeId

    Bases

    No base classes.

    Constructors

    • SpeciesTypeId.new( )
    • SpeciesTypeId.new( SpeciesTypeId )
    • SpeciesTypeId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> SpeciesTypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> SpeciesTypeRaw

    str

    🇲 Method –> ( ) -> string

    Spell

    The class used for spells that a player knows, casts, and gains experience for using. If a given spell is not supposed to be directly cast by a player, consider using SpellSimple instead.

    Bases

    No base classes.

    Constructors

    Members

    id

    🇻 Variable –> SpellTypeId

    cast

    🇲 Method –> ( Creature, TripointBubMs )

    Cast this spell, as well as any sub-spells.

    cast_single_effect

    🇲 Method –> ( Creature, TripointBubMs )

    Cast only this spell’s main effects. Generally, cast() should be used instead.

    desc

    🇲 Method –> ( ) -> string

    gain_exp

    🇲 Method –> ( integer )

    gain_levels

    🇲 Method –> ( integer )

    get_level

    🇲 Method –> ( ) -> integer

    name

    🇲 Method –> ( ) -> string

    set_exp

    🇲 Method –> ( integer )

    set_level

    🇲 Method –> ( integer )

    xp

    🇲 Method –> ( ) -> integer

    SpellSimple

    The type for basic spells. If you don’t need to track XP from casting (e.g., if a spell is intended to be cast by anything other than a player), this is likely the appropriate type. Otherwise, see the Spell type.

    Bases

    No base classes.

    Constructors

    Members

    force_target_source

    🇻 Variable –> boolean

    Whether or not the target point is locked to the source’s location.

    id

    🇻 Variable –> SpellTypeId

    level

    🇻 Variable –> integer

    trigger_once_in

    🇻 Variable –> integer

    Used for enchantments; the spell’s chance to trigger every turn.

    cast

    🇲 Method –> ( Creature, TripointBubMs, integer? )

    max_level

    🇲 Method –> ( ) -> integer

    Returns the defined maximum level of this SpellSimple instance, if defined. Otherwise, returns 0.

    prompt_cast

    🇫 Function –> ( SpellTypeId, TripointBubMs, integer? ) -> SpellSimple

    Static function: Creates and immediately casts a SimpleSpell, then returns the new spell for potential reuse. If the given tripoint is the player’s location, the spell will be locked to the player. (This does not necessarily cause friendly fire!) If an integer is specified, the spell will be cast at that level.

    SpellTypeId

    Bases

    No base classes.

    Constructors

    • SpellTypeId.new( )
    • SpellTypeId.new( SpellTypeId )
    • SpellTypeId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> SpellTypeId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> SpellTypeRaw

    str

    🇲 Method –> ( ) -> string

    SpellTypeRaw

    The ‘raw’ type for storing the information defining every spell in the game. It’s not possible to cast directly from this type; check SpellSimple and Spell.

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    aoe_increment

    🇻 Variable –> number

    base_casting_time

    🇻 Variable –> integer

    base_energy_cost

    🇻 Variable –> integer

    casting_time_increment

    🇻 Variable –> number

    damage_increment

    🇻 Variable –> number

    difficulty

    🇻 Variable –> integer

    dot_increment

    🇻 Variable –> number

    duration_increment

    🇻 Variable –> integer

    effect_name

    🇻 Variable –> string

    The name of the primary effect this spell will enact.

    effect_str

    🇻 Variable –> string

    Specifics about the effect this spell will enact.

    energy_increment

    🇻 Variable –> number

    field_chance

    🇻 Variable –> integer

    field_intensity_increment

    🇻 Variable –> number

    field_intensity_variance

    🇻 Variable –> number

    final_casting_time

    🇻 Variable –> integer

    final_energy_cost

    🇻 Variable –> integer

    id

    🇻 Variable –> SpellTypeId

    max_aoe

    🇻 Variable –> integer

    max_damage

    🇻 Variable –> integer

    max_dot

    🇻 Variable –> integer

    max_duration

    🇻 Variable –> integer

    max_field_intensity

    🇻 Variable –> integer

    max_level

    🇻 Variable –> integer

    max_range

    🇻 Variable –> integer

    min_aoe

    🇻 Variable –> integer

    min_damage

    🇻 Variable –> integer

    min_dot

    🇻 Variable –> integer

    min_duration

    🇻 Variable –> integer

    min_field_intensity

    🇻 Variable –> integer

    min_range

    🇻 Variable –> integer

    range_increment

    🇻 Variable –> number

    additional_spells

    🇲 Method –> ( ) -> SpellSimple[]

    Other spells cast by this spell.

    get_all

    🇫 Function –> ( ) -> SpellTypeRaw[]

    Returns a (long) list of every spell in the game.

    Temperature

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    from_celsius

    🇫 Function –> ( number ) -> Temperature

    from_fahrenheit

    🇫 Function –> ( number ) -> Temperature

    from_kelvin

    🇫 Function –> ( number ) -> Temperature

    to_celsius

    🇲 Method –> ( ) -> number

    to_fahrenheit

    🇲 Method –> ( ) -> number

    to_kelvin

    🇲 Method –> ( ) -> number

    TerId

    Bases

    No base classes.

    Constructors

    • TerId.new( )
    • TerId.new( TerId )
    • TerId.new( TerIntId )
    • TerId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> TerId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    int_id

    🇲 Method –> ( ) -> TerIntId

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> TerRaw

    str

    🇲 Method –> ( ) -> string

    TerIntId

    Bases

    No base classes.

    Constructors

    Members

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> TerRaw

    str_id

    🇲 Method –> ( ) -> TerId

    TerRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    close

    🇻 Variable –> TerId

    heat_radiation

    🇻 Variable –> integer

    open

    🇻 Variable –> TerId

    roof

    🇻 Variable –> TerId

    transforms_into

    🇻 Variable –> TerId

    trap_id_str

    🇻 Variable –> string

    get_coverage

    🇲 Method –> ( ) -> integer

    get_flags

    🇲 Method –> ( ) -> string[]

    get_light_emitted

    🇲 Method –> ( ) -> integer

    get_max_volume

    🇲 Method –> ( ) -> Volume

    get_movecost

    🇲 Method –> ( ) -> integer

    has_flag

    🇲 Method –> ( string ) -> boolean

    int_id

    🇲 Method –> ( ) -> TerIntId

    name

    🇲 Method –> ( ) -> string

    set_coverage

    🇲 Method –> ( integer )

    set_flag

    🇲 Method –> ( string )

    set_light_emitted

    🇲 Method –> ( integer )

    set_max_volume

    🇲 Method –> ( Volume )

    set_movecost

    🇲 Method –> ( integer )

    str_id

    🇲 Method –> ( ) -> TerId

    TimeDuration

    Represent duration between 2 fixed points in time

    Bases

    No base classes.

    Constructors

    • TimeDuration.new( )

    Members

    from_days

    🇫 Function –> ( integer ) -> TimeDuration

    from_hours

    🇫 Function –> ( integer ) -> TimeDuration

    from_minutes

    🇫 Function –> ( integer ) -> TimeDuration

    from_seconds

    🇫 Function –> ( integer ) -> TimeDuration

    from_turns

    🇫 Function –> ( integer ) -> TimeDuration

    from_weeks

    🇫 Function –> ( integer ) -> TimeDuration

    make_random

    🇲 Method –> ( TimeDuration ) -> TimeDuration

    to_days

    🇲 Method –> ( ) -> integer

    to_hours

    🇲 Method –> ( ) -> integer

    to_minutes

    🇲 Method –> ( ) -> integer

    to_seconds

    🇲 Method –> ( ) -> integer

    to_turns

    🇲 Method –> ( ) -> integer

    to_weeks

    🇲 Method –> ( ) -> integer

    TimePoint

    Library for dealing with time primitives.
    Represent fixed point in time

    Bases

    No base classes.

    Constructors

    • TimePoint.new( )

    Members

    from_turn

    🇫 Function –> ( integer ) -> TimePoint

    hour_of_day

    🇲 Method –> ( ) -> integer

    is_dawn

    🇲 Method –> ( ) -> boolean

    is_day

    🇲 Method –> ( ) -> boolean

    is_dusk

    🇲 Method –> ( ) -> boolean

    is_night

    🇲 Method –> ( ) -> boolean

    minute_of_hour

    🇲 Method –> ( ) -> integer

    moon_phase

    🇲 Method –> ( ) -> MoonPhase

    season

    🇲 Method –> ( ) -> string

    second_of_minute

    🇲 Method –> ( ) -> integer

    sunrise

    🇲 Method –> ( ) -> TimePoint

    sunset

    🇲 Method –> ( ) -> TimePoint

    to_string_time_of_day

    🇲 Method –> ( ) -> string

    to_turn

    🇲 Method –> ( ) -> integer

    TrapId

    Bases

    No base classes.

    Constructors

    • TrapId.new( )
    • TrapId.new( TrapId )
    • TrapId.new( TrapIntId )
    • TrapId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> TrapId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    int_id

    🇲 Method –> ( ) -> TrapIntId

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> TrapRaw

    str

    🇲 Method –> ( ) -> string

    TrapIntId

    Bases

    No base classes.

    Constructors

    Members

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> TrapRaw

    str_id

    🇲 Method –> ( ) -> TrapId

    Tripoint

    Bases

    No base classes.

    Constructors

    • Tripoint.new( )
    • Tripoint.new( Point, int )
    • Tripoint.new( Tripoint )
    • Tripoint.new( int, int, int )

    Members

    x

    🇻 Variable –> integer

    y

    🇻 Variable –> integer

    z

    🇻 Variable –> integer

    abs

    🇲 Method –> ( ) -> Tripoint

    reinterpret_as

    🇲 Method –> ( origin: string, scale: string ) -> TripointCoord

    Reinterpret this raw tripoint as a typed tripoint coordinate without changing x, y, or z.

    rotate_2d

    🇲 Method –> ( integer, Point ) -> Tripoint

    xy

    🇲 Method –> ( ) -> Point

    TripointCoord

    A typed three-dimensional coordinate. Its origin and scale describe how to interpret x, y, and z, and coordinate operations only combine compatible coordinate spaces.

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    x

    🇻 Variable –> integer

    y

    🇻 Variable –> integer

    z

    🇻 Variable –> integer

    origin

    🇲 Method –> ( ) -> string

    project_combine

    🇲 Method –> ( fine: any ) -> nil | PointCoord | TripointCoord

    Combines this coarse tripoint with a remainder from project_remain. Returns TripointCoord, or nil if the pair is incompatible.

    project_remain

    🇲 Method –> ( scale: string ) -> (TripointCoord?, PointCoord?)

    Splits this tripoint into a coarse TripointCoord at the requested scale and a PointCoord remainder at this tripoint’s original scale. The z value stays on the coarse tripoint. Returns nil, nil if the split is not valid.

    project_remain_mmr

    🇲 Method –> ( ) -> (TripointCoord?, PointCoord?)

    Shortcut for project_remain("mmr").

    project_remain_om

    🇲 Method –> ( ) -> (TripointCoord?, PointCoord?)

    Shortcut for project_remain("om").

    project_remain_omt

    🇲 Method –> ( ) -> (TripointCoord?, PointCoord?)

    Shortcut for project_remain("omt").

    project_remain_seg

    🇲 Method –> ( ) -> (TripointCoord?, PointCoord?)

    Shortcut for project_remain("seg").

    project_remain_sm

    🇲 Method –> ( ) -> (TripointCoord?, PointCoord?)

    Shortcut for project_remain("sm").

    raw

    🇲 Method –> ( ) -> Tripoint

    reinterpret_as

    🇲 Method –> ( origin: string, scale: string ) -> TripointCoord

    Reinterpret this coordinate as another tripoint coordinate kind without changing x, y, or z.

    rl_dist

    🇲 Method –> ( other: TripointCoord ) -> integer?

    Rectilinear distance to another TripointCoord with matching origin and scale. Returns nil if the argument is incompatible.

    rotate_2d

    🇲 Method –> ( integer, Point ) -> TripointCoord

    scale

    🇲 Method –> ( ) -> string

    square_dist

    🇲 Method –> ( other: TripointCoord ) -> integer?

    Chebyshev distance to another TripointCoord with matching origin and scale. Returns nil if the argument is incompatible.

    to

    🇲 Method –> ( scale: string ) -> TripointCoord?

    Projects this coordinate to another scale, preserving its origin and tripoint dimension. Returns nil if the conversion is not valid.

    to_mmr

    🇲 Method –> ( ) -> TripointCoord?

    Shortcut for to("mmr").

    to_ms

    🇲 Method –> ( ) -> TripointCoord?

    Shortcut for to("ms").

    to_om

    🇲 Method –> ( ) -> TripointCoord?

    Shortcut for to("om").

    to_omt

    🇲 Method –> ( ) -> TripointCoord?

    Shortcut for to("omt").

    to_seg

    🇲 Method –> ( ) -> TripointCoord?

    Shortcut for to("seg").

    to_sm

    🇲 Method –> ( ) -> TripointCoord?

    Shortcut for to("sm").

    to_veh

    🇲 Method –> ( ) -> TripointCoord?

    Shortcut for to("veh").

    trig_dist

    🇲 Method –> ( other: TripointCoord ) -> number?

    Euclidean distance to another TripointCoord with matching origin and scale. Returns nil if the argument is incompatible.

    type

    🇲 Method –> ( ) -> string

    xy

    🇲 Method –> ( ) -> PointCoord

    UiList

    Bases

    No base classes.

    Constructors

    • UiList.new( )

    Members

    entries

    🇻 Variable –> UiListEntry[]

    Entries from uilist. Remember, in lua, the first element of vector is entries[1], not entries[0].

    add

    🇲 Method –> ( integer, string )

    Adds an entry. string is its name, and int is what it returns. If int is -1, the number is decided orderly.

    add_w_col

    🇲 Method –> ( integer, string, string, string )

    Adds an entry with desc and col(third string). col is additional text on the right of the entry name.

    add_w_desc

    🇲 Method –> ( integer, string, string )

    Adds an entry with desc(second string). desc_enabled(true) is required for showing desc.

    border_color

    🇲 Method –> ( Color )

    Changes the color. Default color is c_magenta.

    desc_enabled

    🇲 Method –> ( boolean )

    Puts a lower box. Footer or entry desc appears on it.

    footer

    🇲 Method –> ( string )

    Sets footer text which is in lower box. It overwrites descs of entries unless is empty.

    hilight_color

    🇲 Method –> ( Color )

    Changes the color. Default color is h_white.

    hotkey_color

    🇲 Method –> ( Color )

    Changes the color. Default color is c_light_green.

    query

    🇲 Method –> ( ) -> integer

    Returns retval for selected entry, or a negative number on fail/cancel

    text

    🇲 Method –> ( string )

    Sets text which is in upper box.

    text_color

    🇲 Method –> ( Color )

    Changes the color. Default color is c_light_gray.

    title

    🇲 Method –> ( string )

    Sets title which is on the top line.

    title_color

    🇲 Method –> ( Color )

    Changes the color. Default color is c_green.

    UiListEntry

    This type came from UiList.

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    ctxt

    🇻 Variable –> string

    Entry text of column.

    desc

    🇻 Variable –> string

    Entry description

    enable

    🇻 Variable –> boolean

    Entry whether it’s enabled or not. Default is true.

    txt

    🇻 Variable –> string

    Entry text

    txt_color

    🇲 Method –> ( Color )

    Entry text color. Its default color is c_red_red, which makes color of the entry same as what uilist decides. So if you want to make color different, choose one except c_red_red.

    VitaminId

    Bases

    No base classes.

    Constructors

    • VitaminId.new( )
    • VitaminId.new( VitaminId )
    • VitaminId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> VitaminId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> VitaminRaw

    str

    🇲 Method –> ( ) -> string

    VitaminRaw

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    deficiency

    🇲 Method –> ( ) -> EffectTypeId

    excess

    🇲 Method –> ( ) -> EffectTypeId

    has_flag

    🇲 Method –> ( string ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    max

    🇲 Method –> ( ) -> integer

    min

    🇲 Method –> ( ) -> integer

    name

    🇲 Method –> ( ) -> string

    rate

    🇲 Method –> ( ) -> TimeDuration

    severity

    🇲 Method –> ( integer ) -> integer

    vitamin_id

    🇫 Function –> ( )

    vitamin_type

    🇲 Method –> ( ) -> VitaminType

    Volume

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    from_liter

    🇫 Function –> ( integer ) -> Volume

    from_milliliter

    🇫 Function –> ( integer ) -> Volume

    to_liter

    🇲 Method –> ( ) -> number

    to_milliliter

    🇲 Method –> ( ) -> integer

    WeaponCategoryId

    Bases

    No base classes.

    Constructors

    • WeaponCategoryId.new( )
    • WeaponCategoryId.new( WeaponCategoryId )
    • WeaponCategoryId.new( string )

    Members

    NULL_ID

    🇫 Function –> ( ) -> WeaponCategoryId

    implements_int_id

    🇫 Function –> ( ) -> boolean

    is_null

    🇲 Method –> ( ) -> boolean

    is_valid

    🇲 Method –> ( ) -> boolean

    obj

    🇲 Method –> ( ) -> WeaponCategoryRaw

    str

    🇲 Method –> ( ) -> string

    WrappedVehicle

    Bases

    No base classes.

    Constructors

    No constructors.

    Members

    charge_batteries

    🇲 Method –> ( integer ) -> integer

    Charges the onboard batteries by up to amount. Returns the charges actually added.

    drain_batteries

    🇲 Method –> ( integer ) -> integer

    Drains up to amount charges from the onboard batteries. Returns the charges actually drained.

    drain_fuel

    🇲 Method –> ( ItypeId, integer ) -> integer

    Drains up to amount charges of the given fuel type from the vehicle. Returns the charges actually drained.

    facing

    🇲 Method –> ( ) -> number

    Returns the vehicle’s facing in degrees (0 = east, 90 = north), or 0 if the handle is invalid.

    fuel_left

    🇲 Method –> ( ItypeId ) -> integer

    Returns the charges of the given fuel type left in the vehicle (e.g. ItypeId.new(“battery”)), or 0 if the handle is invalid.

    is_locked

    🇲 Method –> ( ) -> boolean

    Returns true if the vehicle is locked, false otherwise (also false if the handle is invalid).

    is_valid

    🇲 Method –> ( ) -> boolean

    Returns true if the wrapped vehicle still exists, false if the handle is invalid (e.g. the vehicle was destroyed).

    name

    🇲 Method –> ( ) -> string

    Returns the vehicle’s display name, or an empty string if the handle is invalid.

    pos

    🇲 Method –> ( ) -> TripointBubMs

    Returns the vehicle origin tile in local map-square coordinates.

    set_locked

    🇲 Method –> ( boolean )

    Locks or unlocks the vehicle. Does nothing if the handle is invalid.

    type

    🇲 Method –> ( ) -> string

    Returns the vehicle prototype id string.

    Enums

    ActionId

    Entries

    • ACTION_NULL = 0
    • ACTION_SELECT = 1
    • ACTION_SEC_SELECT = 2
    • ACTION_PAUSE = 3
    • ACTION_TIMEOUT = 4
    • ACTION_MOVE_FORTH = 5
    • ACTION_MOVE_FORTH_RIGHT = 6
    • ACTION_MOVE_RIGHT = 7
    • ACTION_MOVE_BACK_RIGHT = 8
    • ACTION_MOVE_BACK = 9
    • ACTION_MOVE_BACK_LEFT = 10
    • ACTION_MOVE_LEFT = 11
    • ACTION_MOVE_FORTH_LEFT = 12
    • ACTION_MOVE_DOWN = 13
    • ACTION_MOVE_UP = 14
    • ACTION_CYCLE_MOVE = 15
    • ACTION_RESET_MOVE = 16
    • ACTION_TOGGLE_RUN = 17
    • ACTION_TOGGLE_CROUCH = 18
    • ACTION_TOGGLE_PRONE = 19
    • ACTION_OPEN_MOVEMENT = 20
    • ACTION_TOGGLE_MAP_MEMORY = 21
    • ACTION_CENTER = 22
    • ACTION_SHIFT_N = 23
    • ACTION_SHIFT_NE = 24
    • ACTION_SHIFT_E = 25
    • ACTION_SHIFT_SE = 26
    • ACTION_SHIFT_S = 27
    • ACTION_SHIFT_SW = 28
    • ACTION_SHIFT_W = 29
    • ACTION_SHIFT_NW = 30
    • ACTION_OPEN = 31
    • ACTION_CLOSE = 32
    • ACTION_SMASH = 33
    • ACTION_EXAMINE = 34
    • ACTION_JUMP = 35
    • ACTION_PICKUP = 36
    • ACTION_PICKUP_ALL = 37
    • ACTION_PICKUP_FEET = 38
    • ACTION_GRAB = 39
    • ACTION_HAUL = 40
    • ACTION_BUTCHER = 41
    • ACTION_CHAT = 42
    • ACTION_LOOK = 43
    • ACTION_PEEK = 44
    • ACTION_LIST_ITEMS = 45
    • ACTION_ZONES = 46
    • ACTION_LOOT = 47
    • ACTION_INVENTORY = 48
    • ACTION_ADVANCEDINV = 49
    • ACTION_COMPARE = 50
    • ACTION_ORGANIZE = 51
    • ACTION_USE = 52
    • ACTION_USE_WIELDED = 53
    • ACTION_WEAR = 54
    • ACTION_TAKE_OFF = 55
    • ACTION_EAT = 56
    • ACTION_OPEN_CONSUME = 57
    • ACTION_READ = 58
    • ACTION_WIELD = 59
    • ACTION_PICK_STYLE = 60
    • ACTION_RELOAD_ITEM = 61
    • ACTION_RELOAD_WEAPON = 62
    • ACTION_RELOAD_WIELDED = 63
    • ACTION_UNLOAD = 64
    • ACTION_UNLOAD_ALL = 65
    • ACTION_MEND = 66
    • ACTION_THROW = 67
    • ACTION_FIRE = 68
    • ACTION_FIRE_BURST = 69
    • ACTION_SELECT_FIRE_MODE = 70
    • ACTION_SELECT_DEFAULT_AMMO = 71
    • ACTION_CAST_SPELL = 72
    • ACTION_CAST_LAST_SPELL = 73
    • ACTION_DROP = 74
    • ACTION_DIR_DROP = 75
    • ACTION_BIONICS = 76
    • ACTION_MUTATIONS = 77
    • ACTION_PERKS = 78
    • ACTION_SORT_ARMOR = 79
    • ACTION_AUTOATTACK = 80
    • ACTION_TOGGLE_MANUAL_COMBAT_MODE = 81
    • ACTION_WAIT = 82
    • ACTION_CRAFT = 83
    • ACTION_RECRAFT = 84
    • ACTION_LONGCRAFT = 85
    • ACTION_CONSTRUCT = 86
    • ACTION_DISASSEMBLE = 87
    • ACTION_SALVAGE = 88
    • ACTION_SLEEP = 89
    • ACTION_CONTROL_VEHICLE = 90
    • ACTION_TOGGLE_AUTO_TRAVEL_MODE = 91
    • ACTION_TOGGLE_SAFEMODE = 92
    • ACTION_TOGGLE_AUTOSAFE = 93
    • ACTION_TOGGLE_THIEF_MODE = 94
    • ACTION_IGNORE_ENEMY = 95
    • ACTION_WHITELIST_ENEMY = 96
    • ACTION_SAVE = 97
    • ACTION_QUICKSAVE = 98
    • ACTION_QUICKLOAD = 99
    • ACTION_SUICIDE = 100
    • ACTION_PL_INFO = 101
    • ACTION_MAP = 102
    • ACTION_SKY = 103
    • ACTION_MISSIONS = 104
    • ACTION_SCORES = 105
    • ACTION_FACTIONS = 106
    • ACTION_MORALE = 107
    • ACTION_MESSAGES = 108
    • ACTION_OPEN_WIKI = 109
    • ACTION_OPEN_HHG = 110
    • ACTION_HELP = 111
    • ACTION_MAIN_MENU = 112
    • ACTION_DIARY = 113
    • ACTION_KEYBINDINGS = 114
    • ACTION_OPTIONS = 115
    • ACTION_AUTOPICKUP = 116
    • ACTION_AUTONOTES = 117
    • ACTION_SAFEMODE = 118
    • ACTION_COLOR = 119
    • ACTION_WORLD_MODS = 120
    • ACTION_DISTRACTION_MANAGER = 121
    • ACTION_TOGGLE_CHARACTER_PREVIEW_CLOTHES = 122
    • ACTION_TOGGLE_FULLSCREEN = 123
    • ACTION_DEBUG = 124
    • ACTION_LUA_CONSOLE = 125
    • ACTION_LUA_RELOAD = 126
    • ACTION_DISPLAY_SCENT = 127
    • ACTION_DISPLAY_SCENT_TYPE = 128
    • ACTION_TOGGLE_DEBUG_MODE = 129
    • ACTION_ZOOM_OUT = 130
    • ACTION_ZOOM_IN = 131
    • ACTION_ACTIONMENU = 132
    • ACTION_ITEMACTION = 133
    • ACTION_TOGGLE_PIXEL_MINIMAP = 134
    • ACTION_TOGGLE_PANEL_ADM = 135
    • ACTION_PANEL_MGMT = 136
    • ACTION_RELOAD_TILESET = 137
    • ACTION_TOGGLE_AUTO_FEATURES = 138
    • ACTION_TOGGLE_AUTO_PULP_BUTCHER = 139
    • ACTION_TOGGLE_AUTO_MINING = 140
    • ACTION_TOGGLE_AUTO_FORAGING = 141
    • ACTION_TOGGLE_AUTO_PICKUP = 142
    • ACTION_DISPLAY_TEMPERATURE = 143
    • ACTION_DISPLAY_VEHICLE_AI = 144
    • ACTION_DISPLAY_VISIBILITY = 145
    • ACTION_DISPLAY_LIGHTING = 146
    • ACTION_DISPLAY_RADIATION = 147
    • ACTION_DISPLAY_TRANSPARENCY = 148
    • ACTION_DISPLAY_OUTSIDE = 149
    • ACTION_DISPLAY_SUBMAP_GRID = 150
    • ACTION_DISPLAY_SOUND_ABSORPTION = 151
    • ACTION_DISPLAY_SOUND_WALLS = 152
    • ACTION_TOGGLE_ZONE_OVERLAY = 153
    • ACTION_DISPLAY_TILES_NO_VFX = 154
    • ACTION_TOGGLE_HOUR_TIMER = 155
    • ACTION_SWAP_TO_NPC = 156

    AddictionType

    Entries

    • NONE = 0
    • CAFFEINE = 1
    • ALCOHOL = 2
    • SLEEP = 3
    • PKILLER = 4
    • SPEED = 5
    • CIG = 6
    • COKE = 7
    • CRACK = 8
    • MUTAGEN = 9
    • DIAZEPAM = 10
    • MARLOSS_R = 11
    • MARLOSS_B = 12
    • MARLOSS_Y = 13

    ArtifactCharge

    Entries

    • ARTC_NULL = 0
    • ARTC_TIME = 1
    • ARTC_SOLAR = 2
    • ARTC_PAIN = 3
    • ARTC_HP = 4
    • ARTC_FATIGUE = 5
    • ARTC_PORTAL = 6

    ArtifactChargeReq

    Entries

    • ACR_NULL = 0
    • ACR_EQUIP = 1
    • ACR_SKIN = 2
    • ACR_SLEEP = 3
    • ACR_RAD = 4
    • ACR_WET = 5
    • ACR_SKY = 6

    ArtifactEffectActive

    Entries

    • AEP_NULL = 0
    • AEP_STR_UP = 1
    • AEP_DEX_UP = 2
    • AEP_PER_UP = 3
    • AEP_INT_UP = 4
    • AEP_ALL_UP = 5
    • AEP_SPEED_UP = 6
    • AEP_PBLUE = 7
    • AEP_SNAKES = 8
    • AEP_INVISIBLE = 9
    • AEP_CLAIRVOYANCE = 10
    • AEP_SUPER_CLAIRVOYANCE = 11
    • AEP_STEALTH = 12
    • AEP_EXTINGUISH = 13
    • AEP_GLOW = 14
    • AEP_PSYSHIELD = 15
    • AEP_RESIST_ELECTRICITY = 16
    • AEP_CARRY_MORE = 17
    • AEP_SAP_LIFE = 18
    • AEP_FUN = 19
    • AEP_SPLIT = 20
    • AEP_HUNGER = 21
    • AEP_THIRST = 22
    • AEP_SMOKE = 23
    • AEP_EVIL = 24
    • AEP_SCHIZO = 25
    • AEP_RADIOACTIVE = 26
    • AEP_MUTAGENIC = 27
    • AEP_ATTENTION = 28
    • AEP_STR_DOWN = 29
    • AEP_DEX_DOWN = 30
    • AEP_PER_DOWN = 31
    • AEP_INT_DOWN = 32
    • AEP_ALL_DOWN = 33
    • AEP_SPEED_DOWN = 34
    • AEP_FORCE_TELEPORT = 35
    • AEP_MOVEMENT_NOISE = 36
    • AEP_BAD_WEATHER = 37
    • AEP_SICK = 38
    • AEP_CLAIRVOYANCE_PLUS = 39

    ArtifactEffectPassive

    Entries

    • AEA_NULL = 0
    • AEA_STORM = 1
    • AEA_FIREBALL = 2
    • AEA_ADRENALINE = 3
    • AEA_MAP = 4
    • AEA_BLOOD = 5
    • AEA_FATIGUE = 6
    • AEA_ACIDBALL = 7
    • AEA_PULSE = 8
    • AEA_HEAL = 9
    • AEA_CONFUSED = 10
    • AEA_ENTRANCE = 11
    • AEA_BUGS = 12
    • AEA_TELEPORT = 13
    • AEA_LIGHT = 14
    • AEA_GROWTH = 15
    • AEA_HURTALL = 16
    • AEA_FUN = 17
    • AEA_SPLIT = 18
    • AEA_RADIATION = 19
    • AEA_PAIN = 20
    • AEA_MUTATE = 21
    • AEA_PARALYZE = 22
    • AEA_FIRESTORM = 23
    • AEA_ATTENTION = 24
    • AEA_TELEGLOW = 25
    • AEA_NOISE = 26
    • AEA_SCREAM = 27
    • AEA_DIM = 28
    • AEA_FLASH = 29
    • AEA_VOMIT = 30
    • AEA_SHADOWS = 31
    • AEA_STAMINA_EMPTY = 32

    Attitude

    Entries

    • Hostile = 0
    • Neutral = 1
    • Friendly = 2
    • Any = 3

    BodyPart

    Entries

    • TORSO = 0
    • HEAD = 1
    • EYES = 2
    • MOUTH = 3
    • ARM_L = 4
    • ARM_R = 5
    • HAND_L = 6
    • HAND_R = 7
    • LEG_L = 8
    • LEG_R = 9
    • FOOT_L = 10
    • FOOT_R = 11

    CharacterMoveMode

    Entries

    • walk = 0
    • run = 1
    • crouch = 2
    • prone = 3

    Color

    Entries

    • c_black = 0
    • c_white = 1
    • c_light_gray = 2
    • c_dark_gray = 3
    • c_red = 4
    • c_green = 5
    • c_blue = 6
    • c_cyan = 7
    • c_magenta = 8
    • c_brown = 9
    • c_light_red = 10
    • c_light_green = 11
    • c_light_blue = 12
    • c_light_cyan = 13
    • c_pink = 14
    • c_yellow = 15
    • h_black = 16
    • h_white = 17
    • h_light_gray = 18
    • h_dark_gray = 19
    • h_red = 20
    • h_green = 21
    • h_blue = 22
    • h_cyan = 23
    • h_magenta = 24
    • h_brown = 25
    • h_light_red = 26
    • h_light_green = 27
    • h_light_blue = 28
    • h_light_cyan = 29
    • h_pink = 30
    • h_yellow = 31
    • i_black = 32
    • i_white = 33
    • i_light_gray = 34
    • i_dark_gray = 35
    • i_red = 36
    • i_green = 37
    • i_blue = 38
    • i_cyan = 39
    • i_magenta = 40
    • i_brown = 41
    • i_light_red = 42
    • i_light_green = 43
    • i_light_blue = 44
    • i_light_cyan = 45
    • i_pink = 46
    • i_yellow = 47
    • c_unset = 48
    • c_black_red = 49
    • c_white_red = 50
    • c_light_gray_red = 51
    • c_dark_gray_red = 52
    • c_red_red = 53
    • c_green_red = 54
    • c_blue_red = 55
    • c_cyan_red = 56
    • c_magenta_red = 57
    • c_brown_red = 58
    • c_light_red_red = 59
    • c_light_green_red = 60
    • c_light_blue_red = 61
    • c_light_cyan_red = 62
    • c_pink_red = 63
    • c_yellow_red = 64
    • c_black_white = 65
    • c_dark_gray_white = 66
    • c_light_gray_white = 67
    • c_white_white = 68
    • c_red_white = 69
    • c_light_red_white = 70
    • c_green_white = 71
    • c_light_green_white = 72
    • c_brown_white = 73
    • c_yellow_white = 74
    • c_blue_white = 75
    • c_light_blue_white = 76
    • c_magenta_white = 77
    • c_pink_white = 78
    • c_cyan_white = 79
    • c_light_cyan_white = 80
    • c_black_green = 81
    • c_dark_gray_green = 82
    • c_light_gray_green = 83
    • c_white_green = 84
    • c_red_green = 85
    • c_light_red_green = 86
    • c_green_green = 87
    • c_light_green_green = 88
    • c_brown_green = 89
    • c_yellow_green = 90
    • c_blue_green = 91
    • c_light_blue_green = 92
    • c_magenta_green = 93
    • c_pink_green = 94
    • c_cyan_green = 95
    • c_light_cyan_green = 96
    • c_black_yellow = 97
    • c_dark_gray_yellow = 98
    • c_light_gray_yellow = 99
    • c_white_yellow = 100
    • c_red_yellow = 101
    • c_light_red_yellow = 102
    • c_green_yellow = 103
    • c_light_green_yellow = 104
    • c_brown_yellow = 105
    • c_yellow_yellow = 106
    • c_blue_yellow = 107
    • c_light_blue_yellow = 108
    • c_magenta_yellow = 109
    • c_pink_yellow = 110
    • c_cyan_yellow = 111
    • c_light_cyan_yellow = 112
    • c_black_magenta = 113
    • c_dark_gray_magenta = 114
    • c_light_gray_magenta = 115
    • c_white_magenta = 116
    • c_red_magenta = 117
    • c_light_red_magenta = 118
    • c_green_magenta = 119
    • c_light_green_magenta = 120
    • c_brown_magenta = 121
    • c_yellow_magenta = 122
    • c_blue_magenta = 123
    • c_light_blue_magenta = 124
    • c_magenta_magenta = 125
    • c_pink_magenta = 126
    • c_cyan_magenta = 127
    • c_light_cyan_magenta = 128
    • c_black_cyan = 129
    • c_dark_gray_cyan = 130
    • c_light_gray_cyan = 131
    • c_white_cyan = 132
    • c_red_cyan = 133
    • c_light_red_cyan = 134
    • c_green_cyan = 135
    • c_light_green_cyan = 136
    • c_brown_cyan = 137
    • c_yellow_cyan = 138
    • c_blue_cyan = 139
    • c_light_blue_cyan = 140
    • c_magenta_cyan = 141
    • c_pink_cyan = 142
    • c_cyan_cyan = 143
    • c_light_cyan_cyan = 144

    DamageType

    Entries

    • DT_NULL = 0
    • DT_TRUE = 1
    • DT_BIOLOGICAL = 2
    • DT_BASH = 3
    • DT_CUT = 4
    • DT_ACID = 5
    • DT_STAB = 6
    • DT_HEAT = 7
    • DT_COLD = 8
    • DT_DARK = 9
    • DT_LIGHT = 10
    • DT_PSI = 11
    • DT_ELECTRIC = 12
    • DT_BULLET = 13

    Direction

    Entries

    • center = 0
    • west = 1
    • east = 2
    • north = 3
    • north_west = 4
    • north_east = 5
    • south = 6
    • south_west = 7
    • south_east = 8
    • below = 9
    • below_west = 10
    • below_east = 11
    • below_north = 12
    • below_north_west = 13
    • below_north_east = 14
    • below_south = 15
    • below_south_west = 16
    • below_south_east = 17
    • above = 18
    • above_west = 19
    • above_east = 20
    • above_north = 21
    • above_north_west = 22
    • above_north_east = 23
    • above_south = 24
    • above_south_west = 25
    • above_south_east = 26

    MissionGoal

    Entries

    • MGOAL_NULL = 0
    • MGOAL_GO_TO = 1
    • MGOAL_GO_TO_TYPE = 2
    • MGOAL_FIND_ITEM = 3
    • MGOAL_FIND_ANY_ITEM = 4
    • MGOAL_FIND_ITEM_GROUP = 5
    • MGOAL_FIND_MONSTER = 6
    • MGOAL_FIND_NPC = 7
    • MGOAL_ASSASSINATE = 8
    • MGOAL_KILL_MONSTER = 9
    • MGOAL_KILL_MONSTER_TYPE = 10
    • MGOAL_KILL_NEMESIS = 11
    • MGOAL_RECRUIT_NPC = 12
    • MGOAL_RECRUIT_NPC_CLASS = 13
    • MGOAL_COMPUTER_TOGGLE = 14
    • MGOAL_KILL_MONSTER_SPEC = 15
    • MGOAL_TALK_TO_NPC = 16
    • MGOAL_CONDITION = 17
    • MGOAL_KILL_MONSTERS = 18

    MissionOrigin

    Entries

    • ORIGIN_NULL = 0
    • ORIGIN_GAME_START = 1
    • ORIGIN_OPENER_NPC = 2
    • ORIGIN_ANY_NPC = 3
    • ORIGIN_SECONDARY = 4
    • ORIGIN_COMPUTER = 5

    MonsterAttitude

    Entries

    • MATT_NULL = 0
    • MATT_FRIEND = 1
    • MATT_FPASSIVE = 2
    • MATT_FLEE = 3
    • MATT_IGNORE = 4
    • MATT_FOLLOW = 5
    • MATT_ATTACK = 6
    • MATT_ZLAVE = 7
    • MATT_UNKNOWN = 8

    MonsterFactionAttitude

    Entries

    • ByMood = 0
    • Neutral = 1
    • Friendly = 2
    • Hate = 3

    MonsterFlag

    Entries

    • SEES = 0
    • HEARS = 1
    • GOODHEARING = 2
    • SMELLS = 3
    • KEENNOSE = 4
    • STUMBLES = 5
    • WARM = 6
    • NEMESIS = 7
    • NOHEAD = 8
    • HARDTOSHOOT = 9
    • GRABS = 10
    • GRAB_IMMUNE = 11
    • BASHES = 12
    • DESTROYS = 13
    • BORES = 14
    • POISON = 15
    • VENOM = 16
    • BADVENOM = 17
    • PARALYZEVENOM = 18
    • BLEED = 19
    • WEBWALK = 20
    • DIGS = 21
    • CAN_DIG = 22
    • FLIES = 23
    • AQUATIC = 24
    • SWIMS = 25
    • ATTACKMON = 26
    • ANIMAL = 27
    • PLASTIC = 28
    • SUNDEATH = 29
    • ELECTRIC = 30
    • ACIDPROOF = 31
    • ACIDTRAIL = 32
    • SHORTACIDTRAIL = 33
    • FIREPROOF = 34
    • SLUDGEPROOF = 35
    • SLUDGETRAIL = 36
    • COLDPROOF = 37
    • BIOPROOF = 38
    • DARKPROOF = 39
    • LIGHTPROOF = 40
    • PSIPROOF = 41
    • FIREY = 42
    • QUEEN = 43
    • ELECTRONIC = 44
    • FUR = 45
    • LEATHER = 46
    • WOOL = 47
    • FEATHER = 48
    • BONES = 49
    • FAT = 50
    • CONSOLE_DESPAWN = 51
    • IMMOBILE = 52
    • STATIONARY = 53
    • ID_CARD_DESPAWN = 54
    • RIDEABLE_MECH = 55
    • CARD_OVERRIDE = 56
    • MILITARY_MECH = 57
    • MECH_RECON_VISION = 58
    • MECH_DEFENSIVE = 59
    • HIT_AND_RUN = 60
    • GUILT = 61
    • PAY_BOT = 62
    • HUMAN = 63
    • NO_BREATHE = 64
    • FLAMMABLE = 65
    • REVIVES = 66
    • CHITIN = 67
    • VERMIN = 68
    • NOGIB = 69
    • LARVA = 70
    • ARTHROPOD_BLOOD = 71
    • ACID_BLOOD = 72
    • BILE_BLOOD = 73
    • ABSORBS = 74
    • ABSORBS_SPLITS = 75
    • CBM_CIV = 76
    • CBM_POWER = 77
    • CBM_SCI = 78
    • CBM_OP = 79
    • CBM_TECH = 80
    • CBM_SUBS = 81
    • UNUSED_76 = 82
    • FISHABLE = 83
    • GROUP_BASH = 84
    • SWARMS = 85
    • GROUP_MORALE = 86
    • INTERIOR_AMMO = 87
    • CLIMBS = 88
    • PACIFIST = 89
    • KEEP_DISTANCE = 90
    • PUSH_MON = 91
    • PUSH_VEH = 92
    • NIGHT_INVISIBILITY = 93
    • CAMOUFLAGE = 94
    • UNCANNY_DODGE = 95
    • REVIVES_HEALTHY = 96
    • NO_NECRO = 97
    • PATH_AVOID_DANGER_1 = 98
    • PATH_AVOID_DANGER_2 = 99
    • PATH_AVOID_FIRE = 100
    • PATH_AVOID_FALL = 101
    • NO_SLIP = 102
    • PRIORITIZE_TARGETS = 103
    • NOT_HALLUCINATION = 104
    • CANPLAY = 105
    • PET_MOUNTABLE = 106
    • PET_HARNESSABLE = 107
    • CAN_FETCH = 108
    • DOGFOOD = 109
    • DOG_WHISTLE = 110
    • MILKABLE = 111
    • SHEARABLE = 112
    • NO_BREED = 113
    • NO_FUNG_DMG = 114
    • PET_WONT_FOLLOW = 115
    • DRIPS_NAPALM = 116
    • DRIPS_GASOLINE = 117
    • ELECTRIC_FIELD = 118
    • LOUDMOVES = 119
    • CAN_OPEN_DOORS = 120
    • STUN_IMMUNE = 121
    • DROPS_AMMO = 122
    • CAN_BE_ORDERED = 123
    • SMALL_HEAD = 124
    • TINY_HEAD = 125
    • NO_HEAD_BONUS_CRIT = 126
    • HEAD_BONUS_CRIT_1 = 127
    • HEAD_BONUS_CRIT_2 = 128
    • TORSO_BONUS_CRIT_1 = 129
    • TORSO_BONUS_CRIT_2 = 130
    • PROJECTILE_RESISTANT_1 = 131
    • PROJECTILE_RESISTANT_2 = 132
    • PROJECTILE_RESISTANT_3 = 133
    • PROJECTILE_RESISTANT_4 = 134
    • VOLATILE = 135
    • CANT_CLONE = 136
    • MOUNTABLE_STAIRS = 137
    • MOUNTABLE_LADDER = 138
    • MOUNTABLE_OBSTACLES = 139
    • MOUNTABLE_DOORS = 140
    • MOUNTABLE_LEDGE = 141
    • FACTION_MEMORY = 142
    • COMBAT_MOUNT = 143
    • CANT_TRAIN = 144
    • POLICE_EYEBOT = 145
    • IRRADIATED = 146
    • NO_VEHICLE_COLLISION = 147

    MonsterSize

    Entries

    • TINY = 0
    • SMALL = 1
    • MEDIUM = 2
    • LARGE = 3
    • HUGE = 4

    MoonPhase

    Entries

    • MOON_NEW = 0
    • MOON_WAXING_CRESCENT = 1
    • MOON_HALF_MOON_WAXING = 2
    • MOON_WAXING_GIBBOUS = 3
    • MOON_FULL = 4
    • MOON_WANING_GIBBOUS = 5
    • MOON_HALF_MOON_WANING = 6
    • MOON_WANING_CRESCENT = 7

    MsgType

    Entries

    • good = 0
    • bad = 1
    • mixed = 2
    • warning = 3
    • info = 4
    • neutral = 5
    • debug = 6
    • headshot = 7
    • critical = 8
    • grazing = 9

    NpcAttitude

    Entries

    • NPCATT_NULL = 0
    • NPCATT_TALK = 1
    • NPCATT_LEGACY_1 = 2
    • NPCATT_FOLLOW = 3
    • NPCATT_LEGACY_2 = 4
    • NPCATT_LEAD = 5
    • NPCATT_WAIT = 6
    • NPCATT_LEGACY_6 = 7
    • NPCATT_MUG = 8
    • NPCATT_WAIT_FOR_LEAVE = 9
    • NPCATT_KILL = 10
    • NPCATT_FLEE = 11
    • NPCATT_LEGACY_3 = 12
    • NPCATT_HEAL = 13
    • NPCATT_LEGACY_4 = 14
    • NPCATT_LEGACY_5 = 15
    • NPCATT_ACTIVITY = 16
    • NPCATT_FLEE_TEMP = 17
    • NPCATT_RECOVER_GOODS = 18

    NpcNeed

    Entries

    • need_none = 0
    • need_ammo = 1
    • need_weapon = 2
    • need_gun = 3
    • need_food = 4
    • need_drink = 5
    • need_safety = 6

    OtMatchType

    Entries

    • EXACT = 0
    • TYPE = 1
    • PREFIX = 2
    • CONTAINS = 3

    SfxChannel

    Entries

    • daytime_outdoors_env = 0
    • nighttime_outdoors_env = 1
    • underground_env = 2
    • indoors_env = 3
    • indoors_rain_env = 4
    • outdoors_snow_env = 5
    • outdoors_flurry_env = 6
    • outdoors_thunderstorm_env = 7
    • outdoors_rain_env = 8
    • outdoors_drizzle_env = 9
    • outdoor_blizzard = 10
    • deafness_tone = 11
    • danger_extreme_theme = 12
    • danger_high_theme = 13
    • danger_medium_theme = 14
    • danger_low_theme = 15
    • stamina_75 = 16
    • stamina_50 = 17
    • stamina_35 = 18
    • idle_chainsaw = 19
    • chainsaw_theme = 20
    • player_activities = 21
    • exterior_engine_sound = 22
    • interior_engine_sound = 23
    • radio = 24

    VitaminType

    Entries

    • vitamin = 0
    • toxin = 1
    • drug = 2
    • counter = 3

    Libraries

    PointAbsMmr

    Members

    new

    🇫 Function –> ( ) -> PointAbsMmr
    🇫 Function –> ( Point ) -> PointAbsMmr
    🇫 Function –> ( integer, integer ) -> PointAbsMmr

    PointAbsMs

    Members

    new

    🇫 Function –> ( ) -> PointAbsMs
    🇫 Function –> ( Point ) -> PointAbsMs
    🇫 Function –> ( integer, integer ) -> PointAbsMs

    PointAbsOm

    Members

    new

    🇫 Function –> ( ) -> PointAbsOm
    🇫 Function –> ( Point ) -> PointAbsOm
    🇫 Function –> ( integer, integer ) -> PointAbsOm

    PointAbsOmt

    Members

    new

    🇫 Function –> ( ) -> PointAbsOmt
    🇫 Function –> ( Point ) -> PointAbsOmt
    🇫 Function –> ( integer, integer ) -> PointAbsOmt

    PointAbsSeg

    Members

    new

    🇫 Function –> ( ) -> PointAbsSeg
    🇫 Function –> ( Point ) -> PointAbsSeg
    🇫 Function –> ( integer, integer ) -> PointAbsSeg

    PointAbsSm

    Members

    new

    🇫 Function –> ( ) -> PointAbsSm
    🇫 Function –> ( Point ) -> PointAbsSm
    🇫 Function –> ( integer, integer ) -> PointAbsSm

    PointBubMs

    Members

    new

    🇫 Function –> ( ) -> PointBubMs
    🇫 Function –> ( Point ) -> PointBubMs
    🇫 Function –> ( integer, integer ) -> PointBubMs

    PointBubSm

    Members

    new

    🇫 Function –> ( ) -> PointBubSm
    🇫 Function –> ( Point ) -> PointBubSm
    🇫 Function –> ( integer, integer ) -> PointBubSm

    PointMmrMs

    Members

    new

    🇫 Function –> ( ) -> PointMmrMs
    🇫 Function –> ( Point ) -> PointMmrMs
    🇫 Function –> ( integer, integer ) -> PointMmrMs

    PointMmrOmt

    Members

    new

    🇫 Function –> ( ) -> PointMmrOmt
    🇫 Function –> ( Point ) -> PointMmrOmt
    🇫 Function –> ( integer, integer ) -> PointMmrOmt

    PointMmrSm

    Members

    new

    🇫 Function –> ( ) -> PointMmrSm
    🇫 Function –> ( Point ) -> PointMmrSm
    🇫 Function –> ( integer, integer ) -> PointMmrSm

    PointMntVeh

    Members

    new

    🇫 Function –> ( ) -> PointMntVeh
    🇫 Function –> ( Point ) -> PointMntVeh
    🇫 Function –> ( integer, integer ) -> PointMntVeh

    PointOmMmr

    Members

    new

    🇫 Function –> ( ) -> PointOmMmr
    🇫 Function –> ( Point ) -> PointOmMmr
    🇫 Function –> ( integer, integer ) -> PointOmMmr

    PointOmMs

    Members

    new

    🇫 Function –> ( ) -> PointOmMs
    🇫 Function –> ( Point ) -> PointOmMs
    🇫 Function –> ( integer, integer ) -> PointOmMs

    PointOmOmt

    Members

    new

    🇫 Function –> ( ) -> PointOmOmt
    🇫 Function –> ( Point ) -> PointOmOmt
    🇫 Function –> ( integer, integer ) -> PointOmOmt

    PointOmSeg

    Members

    new

    🇫 Function –> ( ) -> PointOmSeg
    🇫 Function –> ( Point ) -> PointOmSeg
    🇫 Function –> ( integer, integer ) -> PointOmSeg

    PointOmSm

    Members

    new

    🇫 Function –> ( ) -> PointOmSm
    🇫 Function –> ( Point ) -> PointOmSm
    🇫 Function –> ( integer, integer ) -> PointOmSm

    PointOmtMs

    Members

    new

    🇫 Function –> ( ) -> PointOmtMs
    🇫 Function –> ( Point ) -> PointOmtMs
    🇫 Function –> ( integer, integer ) -> PointOmtMs

    PointOmtSm

    Members

    new

    🇫 Function –> ( ) -> PointOmtSm
    🇫 Function –> ( Point ) -> PointOmtSm
    🇫 Function –> ( integer, integer ) -> PointOmtSm

    PointRelMmr

    Members

    new

    🇫 Function –> ( ) -> PointRelMmr
    🇫 Function –> ( Point ) -> PointRelMmr
    🇫 Function –> ( integer, integer ) -> PointRelMmr

    PointRelMs

    Members

    new

    🇫 Function –> ( ) -> PointRelMs
    🇫 Function –> ( Point ) -> PointRelMs
    🇫 Function –> ( integer, integer ) -> PointRelMs

    PointRelOm

    Members

    new

    🇫 Function –> ( ) -> PointRelOm
    🇫 Function –> ( Point ) -> PointRelOm
    🇫 Function –> ( integer, integer ) -> PointRelOm

    PointRelOmt

    Members

    new

    🇫 Function –> ( ) -> PointRelOmt
    🇫 Function –> ( Point ) -> PointRelOmt
    🇫 Function –> ( integer, integer ) -> PointRelOmt

    PointRelSeg

    Members

    new

    🇫 Function –> ( ) -> PointRelSeg
    🇫 Function –> ( Point ) -> PointRelSeg
    🇫 Function –> ( integer, integer ) -> PointRelSeg

    PointRelSm

    Members

    new

    🇫 Function –> ( ) -> PointRelSm
    🇫 Function –> ( Point ) -> PointRelSm
    🇫 Function –> ( integer, integer ) -> PointRelSm

    PointRelVeh

    Members

    new

    🇫 Function –> ( ) -> PointRelVeh
    🇫 Function –> ( Point ) -> PointRelVeh
    🇫 Function –> ( integer, integer ) -> PointRelVeh

    PointSegMmr

    Members

    new

    🇫 Function –> ( ) -> PointSegMmr
    🇫 Function –> ( Point ) -> PointSegMmr
    🇫 Function –> ( integer, integer ) -> PointSegMmr

    PointSegMs

    Members

    new

    🇫 Function –> ( ) -> PointSegMs
    🇫 Function –> ( Point ) -> PointSegMs
    🇫 Function –> ( integer, integer ) -> PointSegMs

    PointSegOmt

    Members

    new

    🇫 Function –> ( ) -> PointSegOmt
    🇫 Function –> ( Point ) -> PointSegOmt
    🇫 Function –> ( integer, integer ) -> PointSegOmt

    PointSegSm

    Members

    new

    🇫 Function –> ( ) -> PointSegSm
    🇫 Function –> ( Point ) -> PointSegSm
    🇫 Function –> ( integer, integer ) -> PointSegSm

    PointSmMs

    Members

    new

    🇫 Function –> ( ) -> PointSmMs
    🇫 Function –> ( Point ) -> PointSmMs
    🇫 Function –> ( integer, integer ) -> PointSmMs

    TripointAbsMmr

    Members

    new

    🇫 Function –> ( ) -> TripointAbsMmr
    🇫 Function –> ( Tripoint ) -> TripointAbsMmr
    🇫 Function –> ( Point, integer ) -> TripointAbsMmr
    🇫 Function –> ( PointAbsMmr, integer ) -> TripointAbsMmr
    🇫 Function –> ( integer, integer, integer ) -> TripointAbsMmr

    TripointAbsMs

    Members

    new

    🇫 Function –> ( ) -> TripointAbsMs
    🇫 Function –> ( Tripoint ) -> TripointAbsMs
    🇫 Function –> ( Point, integer ) -> TripointAbsMs
    🇫 Function –> ( PointAbsMs, integer ) -> TripointAbsMs
    🇫 Function –> ( integer, integer, integer ) -> TripointAbsMs

    TripointAbsOm

    Members

    new

    🇫 Function –> ( ) -> TripointAbsOm
    🇫 Function –> ( Tripoint ) -> TripointAbsOm
    🇫 Function –> ( Point, integer ) -> TripointAbsOm
    🇫 Function –> ( PointAbsOm, integer ) -> TripointAbsOm
    🇫 Function –> ( integer, integer, integer ) -> TripointAbsOm

    TripointAbsOmt

    Members

    new

    🇫 Function –> ( ) -> TripointAbsOmt
    🇫 Function –> ( Tripoint ) -> TripointAbsOmt
    🇫 Function –> ( Point, integer ) -> TripointAbsOmt
    🇫 Function –> ( PointAbsOmt, integer ) -> TripointAbsOmt
    🇫 Function –> ( integer, integer, integer ) -> TripointAbsOmt

    TripointAbsSeg

    Members

    new

    🇫 Function –> ( ) -> TripointAbsSeg
    🇫 Function –> ( Tripoint ) -> TripointAbsSeg
    🇫 Function –> ( Point, integer ) -> TripointAbsSeg
    🇫 Function –> ( PointAbsSeg, integer ) -> TripointAbsSeg
    🇫 Function –> ( integer, integer, integer ) -> TripointAbsSeg

    TripointAbsSm

    Members

    new

    🇫 Function –> ( ) -> TripointAbsSm
    🇫 Function –> ( Tripoint ) -> TripointAbsSm
    🇫 Function –> ( Point, integer ) -> TripointAbsSm
    🇫 Function –> ( PointAbsSm, integer ) -> TripointAbsSm
    🇫 Function –> ( integer, integer, integer ) -> TripointAbsSm

    TripointBubMs

    Members

    new

    🇫 Function –> ( ) -> TripointBubMs
    🇫 Function –> ( Tripoint ) -> TripointBubMs
    🇫 Function –> ( Point, integer ) -> TripointBubMs
    🇫 Function –> ( PointBubMs, integer ) -> TripointBubMs
    🇫 Function –> ( integer, integer, integer ) -> TripointBubMs

    TripointBubSm

    Members

    new

    🇫 Function –> ( ) -> TripointBubSm
    🇫 Function –> ( Tripoint ) -> TripointBubSm
    🇫 Function –> ( Point, integer ) -> TripointBubSm
    🇫 Function –> ( PointBubSm, integer ) -> TripointBubSm
    🇫 Function –> ( integer, integer, integer ) -> TripointBubSm

    TripointMmrMs

    Members

    new

    🇫 Function –> ( ) -> TripointMmrMs
    🇫 Function –> ( Tripoint ) -> TripointMmrMs
    🇫 Function –> ( Point, integer ) -> TripointMmrMs
    🇫 Function –> ( PointMmrMs, integer ) -> TripointMmrMs
    🇫 Function –> ( integer, integer, integer ) -> TripointMmrMs

    TripointMmrOmt

    Members

    new

    🇫 Function –> ( ) -> TripointMmrOmt
    🇫 Function –> ( Tripoint ) -> TripointMmrOmt
    🇫 Function –> ( Point, integer ) -> TripointMmrOmt
    🇫 Function –> ( PointMmrOmt, integer ) -> TripointMmrOmt
    🇫 Function –> ( integer, integer, integer ) -> TripointMmrOmt

    TripointMmrSm

    Members

    new

    🇫 Function –> ( ) -> TripointMmrSm
    🇫 Function –> ( Tripoint ) -> TripointMmrSm
    🇫 Function –> ( Point, integer ) -> TripointMmrSm
    🇫 Function –> ( PointMmrSm, integer ) -> TripointMmrSm
    🇫 Function –> ( integer, integer, integer ) -> TripointMmrSm

    TripointMntVeh

    Members

    new

    🇫 Function –> ( ) -> TripointMntVeh
    🇫 Function –> ( Tripoint ) -> TripointMntVeh
    🇫 Function –> ( Point, integer ) -> TripointMntVeh
    🇫 Function –> ( PointMntVeh, integer ) -> TripointMntVeh
    🇫 Function –> ( integer, integer, integer ) -> TripointMntVeh

    TripointOmMmr

    Members

    new

    🇫 Function –> ( ) -> TripointOmMmr
    🇫 Function –> ( Tripoint ) -> TripointOmMmr
    🇫 Function –> ( Point, integer ) -> TripointOmMmr
    🇫 Function –> ( PointOmMmr, integer ) -> TripointOmMmr
    🇫 Function –> ( integer, integer, integer ) -> TripointOmMmr

    TripointOmMs

    Members

    new

    🇫 Function –> ( ) -> TripointOmMs
    🇫 Function –> ( Tripoint ) -> TripointOmMs
    🇫 Function –> ( Point, integer ) -> TripointOmMs
    🇫 Function –> ( PointOmMs, integer ) -> TripointOmMs
    🇫 Function –> ( integer, integer, integer ) -> TripointOmMs

    TripointOmOmt

    Members

    new

    🇫 Function –> ( ) -> TripointOmOmt
    🇫 Function –> ( Tripoint ) -> TripointOmOmt
    🇫 Function –> ( Point, integer ) -> TripointOmOmt
    🇫 Function –> ( PointOmOmt, integer ) -> TripointOmOmt
    🇫 Function –> ( integer, integer, integer ) -> TripointOmOmt

    TripointOmSeg

    Members

    new

    🇫 Function –> ( ) -> TripointOmSeg
    🇫 Function –> ( Tripoint ) -> TripointOmSeg
    🇫 Function –> ( Point, integer ) -> TripointOmSeg
    🇫 Function –> ( PointOmSeg, integer ) -> TripointOmSeg
    🇫 Function –> ( integer, integer, integer ) -> TripointOmSeg

    TripointOmSm

    Members

    new

    🇫 Function –> ( ) -> TripointOmSm
    🇫 Function –> ( Tripoint ) -> TripointOmSm
    🇫 Function –> ( Point, integer ) -> TripointOmSm
    🇫 Function –> ( PointOmSm, integer ) -> TripointOmSm
    🇫 Function –> ( integer, integer, integer ) -> TripointOmSm

    TripointOmtMs

    Members

    new

    🇫 Function –> ( ) -> TripointOmtMs
    🇫 Function –> ( Tripoint ) -> TripointOmtMs
    🇫 Function –> ( Point, integer ) -> TripointOmtMs
    🇫 Function –> ( PointOmtMs, integer ) -> TripointOmtMs
    🇫 Function –> ( integer, integer, integer ) -> TripointOmtMs

    TripointOmtSm

    Members

    new

    🇫 Function –> ( ) -> TripointOmtSm
    🇫 Function –> ( Tripoint ) -> TripointOmtSm
    🇫 Function –> ( Point, integer ) -> TripointOmtSm
    🇫 Function –> ( PointOmtSm, integer ) -> TripointOmtSm
    🇫 Function –> ( integer, integer, integer ) -> TripointOmtSm

    TripointRelMmr

    Members

    new

    🇫 Function –> ( ) -> TripointRelMmr
    🇫 Function –> ( Tripoint ) -> TripointRelMmr
    🇫 Function –> ( Point, integer ) -> TripointRelMmr
    🇫 Function –> ( PointRelMmr, integer ) -> TripointRelMmr
    🇫 Function –> ( integer, integer, integer ) -> TripointRelMmr

    TripointRelMs

    Members

    new

    🇫 Function –> ( ) -> TripointRelMs
    🇫 Function –> ( Tripoint ) -> TripointRelMs
    🇫 Function –> ( Point, integer ) -> TripointRelMs
    🇫 Function –> ( PointRelMs, integer ) -> TripointRelMs
    🇫 Function –> ( integer, integer, integer ) -> TripointRelMs

    TripointRelOm

    Members

    new

    🇫 Function –> ( ) -> TripointRelOm
    🇫 Function –> ( Tripoint ) -> TripointRelOm
    🇫 Function –> ( Point, integer ) -> TripointRelOm
    🇫 Function –> ( PointRelOm, integer ) -> TripointRelOm
    🇫 Function –> ( integer, integer, integer ) -> TripointRelOm

    TripointRelOmt

    Members

    new

    🇫 Function –> ( ) -> TripointRelOmt
    🇫 Function –> ( Tripoint ) -> TripointRelOmt
    🇫 Function –> ( Point, integer ) -> TripointRelOmt
    🇫 Function –> ( PointRelOmt, integer ) -> TripointRelOmt
    🇫 Function –> ( integer, integer, integer ) -> TripointRelOmt

    TripointRelSeg

    Members

    new

    🇫 Function –> ( ) -> TripointRelSeg
    🇫 Function –> ( Tripoint ) -> TripointRelSeg
    🇫 Function –> ( Point, integer ) -> TripointRelSeg
    🇫 Function –> ( PointRelSeg, integer ) -> TripointRelSeg
    🇫 Function –> ( integer, integer, integer ) -> TripointRelSeg

    TripointRelSm

    Members

    new

    🇫 Function –> ( ) -> TripointRelSm
    🇫 Function –> ( Tripoint ) -> TripointRelSm
    🇫 Function –> ( Point, integer ) -> TripointRelSm
    🇫 Function –> ( PointRelSm, integer ) -> TripointRelSm
    🇫 Function –> ( integer, integer, integer ) -> TripointRelSm

    TripointRelVeh

    Members

    new

    🇫 Function –> ( ) -> TripointRelVeh
    🇫 Function –> ( Tripoint ) -> TripointRelVeh
    🇫 Function –> ( Point, integer ) -> TripointRelVeh
    🇫 Function –> ( PointRelVeh, integer ) -> TripointRelVeh
    🇫 Function –> ( integer, integer, integer ) -> TripointRelVeh

    TripointSegMmr

    Members

    new

    🇫 Function –> ( ) -> TripointSegMmr
    🇫 Function –> ( Tripoint ) -> TripointSegMmr
    🇫 Function –> ( Point, integer ) -> TripointSegMmr
    🇫 Function –> ( PointSegMmr, integer ) -> TripointSegMmr
    🇫 Function –> ( integer, integer, integer ) -> TripointSegMmr

    TripointSegMs

    Members

    new

    🇫 Function –> ( ) -> TripointSegMs
    🇫 Function –> ( Tripoint ) -> TripointSegMs
    🇫 Function –> ( Point, integer ) -> TripointSegMs
    🇫 Function –> ( PointSegMs, integer ) -> TripointSegMs
    🇫 Function –> ( integer, integer, integer ) -> TripointSegMs

    TripointSegOmt

    Members

    new

    🇫 Function –> ( ) -> TripointSegOmt
    🇫 Function –> ( Tripoint ) -> TripointSegOmt
    🇫 Function –> ( Point, integer ) -> TripointSegOmt
    🇫 Function –> ( PointSegOmt, integer ) -> TripointSegOmt
    🇫 Function –> ( integer, integer, integer ) -> TripointSegOmt

    TripointSegSm

    Members

    new

    🇫 Function –> ( ) -> TripointSegSm
    🇫 Function –> ( Tripoint ) -> TripointSegSm
    🇫 Function –> ( Point, integer ) -> TripointSegSm
    🇫 Function –> ( PointSegSm, integer ) -> TripointSegSm
    🇫 Function –> ( integer, integer, integer ) -> TripointSegSm

    TripointSmMs

    Members

    new

    🇫 Function –> ( ) -> TripointSmMs
    🇫 Function –> ( Tripoint ) -> TripointSmMs
    🇫 Function –> ( Point, integer ) -> TripointSmMs
    🇫 Function –> ( PointSmMs, integer ) -> TripointSmMs
    🇫 Function –> ( integer, integer, integer ) -> TripointSmMs

    ch_names

    Members

    generate

    🇫 Function –> ( boolean? ) -> string

    Generates a random full name with an optional boolean for gender. The loaded name is one of usage with optional gender. The combinations used in names files are as follows: Backer | (Female|Male|Unisex) Given | (Female|Male) // unisex names are duplicated in each group Family | Unisex Nick City World

    pick

    🇫 Function –> ( any ) -> string

    Generates a single name using any combination of search flags.

    const

    Various game constants

    Members

    OMT_MS_SIZE

    🇨 Constant –> integer = 24

    OMT_SM_SIZE

    🇨 Constant –> integer = 2

    OM_MS_SIZE

    🇨 Constant –> integer = 4320

    OM_OMT_SIZE

    🇨 Constant –> integer = 180

    OM_SM_SIZE

    🇨 Constant –> integer = 360

    SM_MS_SIZE

    🇨 Constant –> integer = 12

    coords

    Members

    overmap_terrain_tiles

    🇫 Function –> ( ) -> PointCoord[]

    Returns every map-square offset within one overmap terrain tile as PointCoord values.

    overmap_tiles

    🇫 Function –> ( ) -> PointCoord[]

    Returns every map-square offset within one overmap as PointCoord values.

    point

    🇫 Function –> ( string, string, Point ) -> PointCoord
    🇫 Function –> ( string, string, integer, integer ) -> PointCoord

    point_abs_mmr

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_abs_ms

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_abs_om

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_abs_omt

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_abs_seg

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_abs_sm

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_bub_ms

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_bub_sm

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_mmr_ms

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_mmr_omt

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_mmr_sm

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_mnt_veh

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_om_mmr

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_om_ms

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_om_omt

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_om_seg

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_om_sm

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_omt_ms

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_omt_sm

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_rel_mmr

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_rel_ms

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_rel_om

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_rel_omt

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_rel_seg

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_rel_sm

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_rel_veh

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_seg_mmr

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_seg_ms

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_seg_omt

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_seg_sm

    🇫 Function –> ( integer, integer ) -> PointCoord

    point_sm_ms

    🇫 Function –> ( integer, integer ) -> PointCoord

    project_combine

    🇫 Function –> ( coarse: any, fine: any ) -> nil | PointCoord | TripointCoord

    Combines a coarse coordinate with a remainder from project_remain. Returns PointCoord or TripointCoord depending on the inputs, or nil if the pair is incompatible.

    project_remain

    🇫 Function –> ( coord: any, scale: string ) -> (nil | PointCoord | TripointCoord, PointCoord?)

    Splits a PointCoord or TripointCoord into a coarser coordinate plus a remainder. Point input returns PointCoord, PointCoord; tripoint input returns TripointCoord, PointCoord. Returns nil, nil if the split is not valid.

    project_remain_mmr

    🇫 Function –> ( coord: any ) -> (nil | PointCoord | TripointCoord, PointCoord?)

    Shortcut for project_remain(coord, "mmr").

    project_remain_om

    🇫 Function –> ( coord: any ) -> (nil | PointCoord | TripointCoord, PointCoord?)

    Shortcut for project_remain(coord, "om").

    project_remain_omt

    🇫 Function –> ( coord: any ) -> (nil | PointCoord | TripointCoord, PointCoord?)

    Shortcut for project_remain(coord, "omt").

    project_remain_seg

    🇫 Function –> ( coord: any ) -> (nil | PointCoord | TripointCoord, PointCoord?)

    Shortcut for project_remain(coord, "seg").

    project_remain_sm

    🇫 Function –> ( coord: any ) -> (nil | PointCoord | TripointCoord, PointCoord?)

    Shortcut for project_remain(coord, "sm").

    project_to

    🇫 Function –> ( coord: any, scale: string ) -> nil | PointCoord | TripointCoord

    Projects a PointCoord or TripointCoord to another scale, preserving its origin and point dimension. Returns nil if the conversion is not valid.

    project_to_mmr

    🇫 Function –> ( coord: any ) -> nil | PointCoord | TripointCoord

    Shortcut for project_to(coord, "mmr").

    project_to_ms

    🇫 Function –> ( coord: any ) -> nil | PointCoord | TripointCoord

    Shortcut for project_to(coord, "ms").

    project_to_om

    🇫 Function –> ( coord: any ) -> nil | PointCoord | TripointCoord

    Shortcut for project_to(coord, "om").

    project_to_omt

    🇫 Function –> ( coord: any ) -> nil | PointCoord | TripointCoord

    Shortcut for project_to(coord, "omt").

    project_to_seg

    🇫 Function –> ( coord: any ) -> nil | PointCoord | TripointCoord

    Shortcut for project_to(coord, "seg").

    project_to_sm

    🇫 Function –> ( coord: any ) -> nil | PointCoord | TripointCoord

    Shortcut for project_to(coord, "sm").

    project_to_veh

    🇫 Function –> ( coord: any ) -> nil | PointCoord | TripointCoord

    Shortcut for project_to(coord, "veh").

    rl_dist

    🇫 Function –> ( lhs: Point, rhs: Point ) -> integer
    🇫 Function –> ( lhs: Tripoint, rhs: Tripoint ) -> integer
    🇫 Function –> ( lhs: PointCoord, rhs: PointCoord ) -> integer?
    🇫 Function –> ( lhs: TripointCoord, rhs: TripointCoord ) -> integer?

    Rectilinear distance between two raw coordinates, or between two typed coordinates with matching origin and scale. Returns nil if the typed coordinates are incompatible.

    square_dist

    🇫 Function –> ( lhs: Point, rhs: Point ) -> integer
    🇫 Function –> ( lhs: Tripoint, rhs: Tripoint ) -> integer
    🇫 Function –> ( lhs: PointCoord, rhs: PointCoord ) -> integer?
    🇫 Function –> ( lhs: TripointCoord, rhs: TripointCoord ) -> integer?

    Chebyshev distance between two raw coordinates, or between two typed coordinates with matching origin and scale. Returns nil if the typed coordinates are incompatible.

    submap_tiles

    🇫 Function –> ( ) -> PointCoord[]

    Returns every map-square offset within one submap as PointCoord values.

    trig_dist

    🇫 Function –> ( lhs: Point, rhs: Point ) -> number
    🇫 Function –> ( lhs: Tripoint, rhs: Tripoint ) -> number
    🇫 Function –> ( lhs: PointCoord, rhs: PointCoord ) -> number?
    🇫 Function –> ( lhs: TripointCoord, rhs: TripointCoord ) -> number?

    Euclidean distance between two raw coordinates, or between two typed coordinates with matching origin and scale. Returns nil if the typed coordinates are incompatible.

    tripoint

    🇫 Function –> ( string, string, Tripoint ) -> TripointCoord
    🇫 Function –> ( string, string, integer, integer, integer ) -> TripointCoord

    tripoint_abs_mmr

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_abs_ms

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_abs_om

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_abs_omt

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_abs_seg

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_abs_sm

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_bub_ms

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_bub_sm

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_mmr_ms

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_mmr_omt

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_mmr_sm

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_mnt_veh

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_om_mmr

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_om_ms

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_om_omt

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_om_seg

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_om_sm

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_omt_ms

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_omt_sm

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_rel_mmr

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_rel_ms

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_rel_om

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_rel_omt

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_rel_seg

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_rel_sm

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_rel_veh

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_seg_mmr

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_seg_ms

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_seg_omt

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_seg_sm

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    tripoint_sm_ms

    🇫 Function –> ( integer, integer, integer ) -> TripointCoord

    date_time

    System date and time API.

    Members

    day

    🇫 Function –> ( ) -> integer

    hour

    🇫 Function –> ( ) -> integer

    0 -> 23

    millisecond

    🇫 Function –> ( ) -> integer

    minute

    🇫 Function –> ( ) -> integer

    month

    🇫 Function –> ( ) -> integer

    second

    🇫 Function –> ( ) -> integer

    weekday

    🇫 Function –> ( ) -> integer

    Days since Saturday.

    weekday_str

    🇫 Function –> ( ) -> string

    year

    🇫 Function –> ( ) -> integer

    gapi

    Global game methods

    Members

    abs_to_bub

    🇫 Function –> ( TripointAbsMs ) -> TripointBubMs
    🇫 Function –> ( TripointAbsSm ) -> TripointBubSm

    add_msg

    🇫 Function –> ( MsgType, any )
    🇫 Function –> ( any )

    add_npc_follower

    🇫 Function –> ( Npc )

    add_on_every_x_hook

    🇫 Function –> ( TimeDuration, function )

    Registers fn to run once every interval of game time.
    fn receives no arguments. Return false from it to unregister it; any other return value keeps it registered.

    before_time_starts

    🇫 Function –> ( ) -> TimePoint

    bodytemp_cold

    🇫 Function –> ( ) -> integer

    bodytemp_hot

    🇫 Function –> ( ) -> integer

    bodytemp_norm

    🇫 Function –> ( ) -> integer

    bub_to_abs

    🇫 Function –> ( TripointBubMs ) -> TripointAbsMs
    🇫 Function –> ( TripointBubSm ) -> TripointAbsSm

    call_builtin_examine

    🇫 Function –> ( string, Player, TripointBubMs )

    Run a built-in examine action at a position.

    choose_adjacent

    🇫 Function –> ( string, boolean? ) -> TripointBubMs?

    choose_adjacent_highlight

    🇫 Function –> ( string, string, ActionId, boolean? ) -> TripointBubMs?
    🇫 Function –> ( string, string, bool, boolean? ) -> TripointBubMs?

    choose_adjacent_uilist

    🇫 Function –> ( string, string, function, function ) -> TripointBubMs?

    choose_area

    🇫 Function –> ( string, TripointBubMs, boolean ) -> (TripointBubMs, TripointBubMs)?

    choose_direction

    🇫 Function –> ( string, boolean? ) -> TripointRelMs?

    clear_all_omt_weather_overrides

    🇫 Function –> ( )

    Clear every active OMT weather override.

    clear_omt_weather_override

    🇫 Function –> ( TripointAbsOmt, integer )

    Clear weather overrides for all OMTs in a radius around center. Radius is in OMT tiles.

    create_item

    🇫 Function –> ( ItypeId, integer ) -> Detached<Item>

    Spawns a new item. Same as Item::spawn count sets the item’s charges, not the number of items: exactly one item is created. For stackable (count-by-charges) items such as ammo, count is the stack size. For non-stackable items, pass a negative value (e.g. -1), since a positive one is still applied as charges. Tools spawned with a negative value get their default charges.

    current_turn

    🇫 Function –> ( ) -> TimePoint

    delete_dimension

    🇫 Function –> ( dim_id: string ) -> boolean

    Fully saves the game, then deletes an inactive, non-primary dimension from memory and save storage.

    direction_from

    🇫 Function –> ( TripointCoord ) -> Direction

    Get direction from a relative tripoint coordinate delta.

    direction_name

    🇫 Function –> ( Direction ) -> string

    Get direction name from direction enum

    fling_creature

    🇫 Function –> ( Creature, Angle, number, boolean )

    get_all_creatures

    🇫 Function –> ( ) -> table

    Returns all active creatures as an array of Creature: the player first, then living NPCs, then living monsters.

    get_all_monsters

    🇫 Function –> ( ) -> table

    Returns all living active monsters as an array of Monster.

    get_all_npcs

    🇫 Function –> ( ) -> table

    Returns all living active NPCs as an array of Npc.

    get_avatar

    🇫 Function –> ( ) -> Avatar

    get_character_at

    🇫 Function –> ( TripointBubMs, boolean? ) -> Character
    🇫 Function –> ( Tripoint, boolean? ) -> Character

    get_creature_at

    🇫 Function –> ( TripointBubMs, boolean? ) -> Creature
    🇫 Function –> ( Tripoint, boolean? ) -> Creature

    get_current_dimension_id

    🇫 Function –> ( ) -> string

    Returns the current dimension id. Empty string means the overworld.

    get_distribution_grid_tracker

    🇫 Function –> ( ) -> DistributionGridTracker

    get_items_if

    🇫 Function –> ( table ) -> table

    Returns items on the map within a radius of a point, matching every given filter, as an array of Item.
    Items inside containers on the ground are included.
    Takes a table where each key is a filter; unknown keys show a debug message and are ignored. Available filters:

    • pos (Tripoint): Center point to search around.
    • radius (integer, optional): Search radius in tiles. Defaults to the pickup range.
    • category (string or string[]): Item category id is one of these, e.g. “food”.
    • type (ItemTypeId or ItemTypeId[]): Item type is one of these.
    • is_food (boolean): Whether the item is food.
    • flags (FlagId or FlagId[]): Item has at least one of these flags.
    • need_charges (boolean): Tool items must have charges left.
    • has_charges (table): { id = ItemTypeId, amount = integer }: item type is id and has at least amount charges.
    • addiction_type (AddictionType, string, or array of those): Comestible’s addiction type is one of these, e.g. <code>[AddictionType](#sol::AddictionType)</code>.ALCOHOL or "alcohol".
    • material (MaterialTypeId, string, or array of those): Item is made of at least one of these materials, e.g. "stone".
      The worn and wielded filters only apply to <code>[Character](#sol::Character)</code>:get_items_if and are ignored here.

    get_lua_log

    🇫 Function –> ( integer ) -> table

    Get recent Lua console log entries. Returns array of { level=string, text=string, from_user=bool }.

    get_map

    🇫 Function –> ( ) -> Map

    get_messages

    🇫 Function –> ( integer ) -> table

    Get recent player message log entries. Returns array of { time=string, text=string }.

    get_monster_at

    🇫 Function –> ( TripointBubMs, boolean? ) -> Monster
    🇫 Function –> ( Tripoint, boolean? ) -> Monster

    get_monsters_if

    🇫 Function –> ( table ) -> table

    Returns active monsters matching every given filter as an array of Monster.
    Takes a table where each key is a filter; unknown keys show a debug message and are ignored. Available filters:

    • type_ids (MonsterTypeId[]): Monster type is one of these.
    • faction_ids (MonsterFactionId[]): Monster faction is one of these.
    • species_ids (SpeciesTypeId[]): Monster has at least one of these species.
    • sees (Monster[]): At least one of these monsters can see it.
    • hostile_to (Monster[]): It is hostile to at least one of these monsters.
    • within_range_of (table): { range = number, monsters = Monster[] }. It is within range tiles of at least one of these monsters.
    • limit (integer): Stop searching once this many monsters have matched.

    get_monsters_near_omt

    🇫 Function –> ( table ) -> table

    Returns active monsters near an absolute overmap terrain tile as an array of Monster.
    Takes a table with keys:

    • center (TripointAbsOmt): Overmap terrain tile to search around.
    • radius (integer, optional): Search radius in overmap terrain tiles. Defaults to 0.
    • ignore_z (boolean, optional): If true, matches every z-level. Defaults to false.

    get_npc_at

    🇫 Function –> ( TripointBubMs, boolean? ) -> Npc
    🇫 Function –> ( Tripoint, boolean? ) -> Npc

    get_npcs_near_omt

    🇫 Function –> ( table ) -> table

    Returns active NPCs near an absolute overmap terrain tile as an array of Npc.
    Takes a table with keys:

    • center (TripointAbsOmt): Overmap terrain tile to search around.
    • radius (integer, optional): Search radius in overmap terrain tiles. Defaults to 0.
    • ignore_z (boolean, optional): If true, matches every z-level. Defaults to false.

    get_omt_weather_override

    🇫 Function –> ( TripointAbsOmt ) -> string?

    Get the current OMT weather override at a location, or nil if none is set.

    get_option

    🇫 Function –> ( string ) -> string

    get_option_bool

    🇫 Function –> ( string ) -> boolean

    get_option_float

    🇫 Function –> ( string ) -> number

    get_option_int

    🇫 Function –> ( string ) -> integer

    get_overmap_buffer

    🇫 Function –> ( ) -> OvermapBuffer

    Get the global overmap buffer

    get_player_pets

    🇫 Function –> ( ) -> table

    Returns the player’s living active pet monsters as an array of Monster.

    get_scenario

    🇫 Function –> ( ) -> ScenarioRaw

    Returns the scenario the current game started with, or nil if no game is active.

    get_simulated_npcs

    🇫 Function –> ( ) -> table

    Returns living NPCs in simulated (fully loaded, AI-eligible) submaps as an array of Npc.

    has_omt_weather_override

    🇫 Function –> ( TripointAbsOmt ) -> boolean

    Returns true if an OMT weather override exists at the given location.

    inv_map_splice

    🇫 Function –> ( table ) -> Item

    Opens an item selection menu listing the player’s inventory and nearby items that pass a filter, and returns the chosen item or nil.
    Takes a table with keys:

    • title (string): Menu title.
    • failure (string): Message shown when no item passes the filter.
    • check (function): Filter called with a table { item = Item }. Must return a boolean.
    • radius (integer, optional): Search radius for nearby items. Defaults to the pickup range.

    inv_map_splice_if

    🇫 Function –> ( table ) -> Item

    Opens an item selection menu listing the player’s inventory and nearby items that match the given filters, and returns the chosen item or nil.
    Takes a table with keys:

    • title (string): Menu title.
    • failure (string): Message shown when no item passes the filter.
    • radius (integer, optional): Search radius for nearby items. Defaults to the pickup range.
    • plus any filter key accepted by gapi.get_items_if (e.g. category, type, is_food, flags, need_charges, has_charges, addiction_type, material).
      Containers whose contents match a filter are listed as well; the returned item is then the container itself.

    light_ambient_lit

    🇫 Function –> ( ) -> number

    look_around

    🇫 Function –> ( ) -> TripointBubMs?

    map_inv_edit

    🇫 Function –> ( table )

    Runs a function editing the player’s inventory and nearby items.
    Takes a table with keys:

    • func (function): Editing function called with a table { item = Item }. Must return a boolean.
    • radius (integer, optional): Search radius for nearby items. Defaults to the pickup range.

    place_monster_around

    🇫 Function –> ( MonsterTypeId, TripointBubMs, integer ) -> Monster
    🇫 Function –> ( MonsterTypeId, Tripoint, integer ) -> Monster

    place_monster_at

    🇫 Function –> ( MonsterTypeId, TripointBubMs ) -> Monster
    🇫 Function –> ( MonsterTypeId, Tripoint ) -> Monster

    place_player_dimension_at

    🇫 Function –> ( opts: DimensionTravelOptions ) -> boolean

    Moves the player into another dimension and loads the destination around required target_ms or target_omt. Moves the player to a position in another dimension, creating the dimension if needed. Does nothing if the player is already in that dimension.
    Returns false if the options are invalid or there is no safe landing spot.
    OvermapTerrainLayout is string[][][].
    Fields of DimensionTravelOptions:

    • dimension_id (string, optional): Target dimension id. Empty string means the overworld.
    • target_ms (TripointAbsMs, optional): Absolute map-square destination. Required when target_omt is absent.
    • target_omt (TripointAbsOmt, optional): Absolute overmap-terrain destination. Required when target_ms is absent.
    • world_type (string, optional): World type for creating a new non-overworld dimension.
    • bounds_min_omt (TripointAbsOmt, optional): Inclusive pocket dimension minimum overmap-terrain bound.
    • bounds_max_omt (TripointAbsOmt, optional): Inclusive pocket dimension maximum overmap-terrain bound.
    • boundary_terrain (string, optional): Map terrain used outside pocket bounds.
    • boundary_overmap_terrain (string, optional): Overmap terrain used outside pocket bounds.
    • overmap_terrain (OvermapTerrainLayout, optional): Optional z/y/x table anchored at bounds_min_omt.
    • pregen_special_id (string, optional): Overmap special to force before loading the destination.
    • pregen_special_omt (TripointAbsOmt, optional): Overmap-terrain position for pregen_special_id; defaults to target_omt.

    place_player_local_at

    🇫 Function –> ( TripointBubMs )

    Teleports player to local coordinates within active map

    place_player_overmap_at

    🇫 Function –> ( TripointAbsOmt )

    Teleports player to absolute coordinate in overmap

    play_ambient_variant_sound

    🇫 Function –> ( string, string, integer, SfxChannel, integer, number, integer )

    play_variant_sound

    🇫 Function –> ( string, string, integer, boolean )
    🇫 Function –> ( string, string, integer, Angle, number, number, boolean )

    register_action_menu_entry

    🇫 Function –> ( table )

    Register a Lua-defined action menu entry in the in-game action menu.
    Takes a table with keys:

    • id (string): Unique entry id. Registering the same id again replaces the old entry.
    • fn (function): Called with no arguments when the entry is selected.
    • name (string, optional): Displayed text. Defaults to id.
    • category (string, optional): Submenu to show the entry in. Defaults to misc. Built-in categories are look, interact, inventory, combat, craft, info, misc and debug; back places it in the top-level menu, and any other id adds a new submenu.
    • hotkey (string, optional): Key name for the entry’s hotkey.

    remove_npc_follower

    🇫 Function –> ( Npc )

    reset_dimension

    🇫 Function –> ( dim_id: string ) -> boolean

    Fully saves the game, then deletes generated data for an inactive, non-primary dimension while keeping its loaded metadata.

    rng

    🇫 Function –> ( integer, integer ) -> integer

    send_event

    🇫 Function –> ( string )
    🇫 Function –> ( string, any )

    Sends a game event by name so statistics, achievements and the memorial keep working when the triggering logic is implemented in Lua.
    Event names and their fields are the event_type values and event_spec fields listed in src/event.h.
    The payload is a table keyed by the event’s field names (e.g. { character = who, itype = "marloss_berry" } for consumes_marloss_item), a bare Character-like object for events whose only field is character, or nil for events without fields.
    character fields accept a Character-like object, a character_id, or an integer id; bool fields take a Lua boolean; int fields take an integer; every other field takes a string (an integer is converted to its string form) that must be a valid value for the field, e.g. an existing item id.
    Unknown event names, unknown, missing or invalid fields raise Lua errors and send nothing. game_start and game_over are sent only by the game. Events can do more than feed statistics, achievements and the memorial: some subscribers have gameplay effects (for example, player_levels_spell teaches the follow-up spells that leveling a spell grants), so send an event only when the action it describes actually happened.

    set_omt_weather_override

    🇫 Function –> ( TripointAbsOmt, integer, string, TimePoint? )

    Override weather for all OMTs in a radius around center. Radius is in OMT tiles. Optionally expires at a given time_point.

    six_cardinal_directions

    🇫 Function –> ( ) -> TripointRelOmt[]

    Get the six cardinal overmap-terrain direction offsets (N, S, E, W, Up, Down).

    spawn_hallucination

    🇫 Function –> ( TripointBubMs ) -> boolean
    🇫 Function –> ( Tripoint ) -> boolean

    trait_generation

    🇫 Function –> ( ) -> integer

    Returns a counter that changes whenever the traits of a character may change: a mutation is gained or lost, or an enchantment grants or removes one.

    turn_zero

    🇫 Function –> ( ) -> TimePoint

    gdebug

    Debugging and logging API.

    Members

    clear_lua_log

    🇫 Function –> ( )

    debugmsg

    🇫 Function –> ( any )

    log_error

    🇫 Function –> ( any )

    log_info

    🇫 Function –> ( any )

    log_warn

    🇫 Function –> ( any )

    reload_lua_code

    🇫 Function –> ( )

    save_game

    🇫 Function –> ( ) -> boolean

    set_log_capacity

    🇫 Function –> ( integer )

    hooks

    Documentation for hooks

    Members

    on_character_death

    🇫 Function –> ( params: table )

    Called when a character is dead.
    The hook receives a table with keys:

    on_character_display_skill_action

    🇫 Function –> ( params: table )

    Called when a skill is confirmed on the character display (@) skill tab.
    Set params.results.handled = true to prevent the default training toggle.
    The hook receives a table with keys:

    on_character_display_skill_info

    🇫 Function –> ( params: table )

    Called when drawing skill info on the character display (@) skill tab.
    Set params.results.text to append text below the regular skill description.
    The hook receives a table with keys:

    on_character_effect

    🇫 Function –> ( params: table )

    Called when character is on the effect which has EFFECT_LUA_ON_TICK flag.
    The hook receives a table with keys:

    on_character_effect_added

    🇫 Function –> ( params: table )

    Called when character gets the effect which has EFFECT_LUA_ON_ADDED flag.
    The hook receives a table with keys:

    on_character_effect_removed

    🇫 Function –> ( params: table )

    Called when character loses the effect which has EFFECT_LUA_ON_REMOVED flag.
    The hook receives a table with keys:

    on_character_item_takeoff

    🇫 Function –> ( params: table )

    Called after a character has taken off an item.
    The hook receives a table with keys:

    on_character_item_wear

    🇫 Function –> ( params: table )

    Called after a character has put on an item.
    The hook receives a table with keys:

    on_character_reset_stats

    🇫 Function –> ( params: table )

    Called when character stat gets reset.
    The hook receives a table with keys:

    on_character_try_move

    🇫 Function –> ( params: table )

    Called after on_player_try_move or on_npc_try_move regardless of whether the specific hook vetoed.
    All registered callbacks run; if any returns false, movement is blocked.
    Return false to block the move.
    The hook receives a table with keys:

    on_character_try_takeoff

    🇫 Function –> ( params: table )

    Called when a character tries to take off a worn item.
    Return false to block taking off the item.
    Set params.results.allowed = false and params.results.message (string), then return params.results to block it with a custom message.
    Once a callback blocks, the remaining callbacks registered to this hook are not called.
    The hook receives a table with keys:

    on_character_try_wear

    🇫 Function –> ( params: table )

    Called when a character tries to wear an item.
    Return false to block wearing the item.
    Set params.results.allowed = false and params.results.message (string), then return params.results to block it with a custom message.
    Once a callback blocks, the remaining callbacks registered to this hook are not called.
    The hook receives a table with keys:

    on_character_wake_up

    🇫 Function –> ( params: table )

    Called when a character wakes up from sleep.
    The hook receives a table with keys:

    on_control_npc

    🇫 Function –> ( params: table )

    Called when the player swaps control to an npc.
    The hook receives a table with keys:

    • npc (NPC): The NPC being controlled.

    on_craft_result

    🇫 Function –> ( params: table )

    Called when a craft is completed, and when the crafting menu builds a preview of the result.
    The hook receives a table with keys:

    • crafter (Character)
    • craft (Item, nil in the crafting menu): The in-progress craft item
    • item (Item): The resulting item, or its contents if the result is a container
    • recipe (RecipeRaw)
    • batch_size (int)
    • hot_result (bool): True if the result is food and the recipe requires a heating tool (e.g. surface_heat)
    • dehydrated_result (bool): True if the result is food and the recipe requires a dehydrator or a charcoal smoker
    • crafting_menu (bool): True if called for the crafting menu preview

    on_creature_attacked_by_character

    🇫 Function –> ( params: table )

    Called after a character has attacked a creature in melee or hit it with a projectile.
    The hook receives a table with keys:

    on_creature_blocked

    🇫 Function –> ( params: table )

    Called when a character successfully blocks.
    The hook receives a table with keys:

    on_creature_do_turn

    🇫 Function –> ( params: table )

    Called every turn for each active creature, before it acts.
    This is the base hook; on_monster_do_turn and on_npc_do_turn also trigger this.
    The hook receives a table with keys:

    on_creature_dodged

    🇫 Function –> ( params: table )

    Called when a character or monster successfully dodges.
    The hook receives a table with keys:

    on_creature_loaded

    🇫 Function –> ( params: table )

    Called when any creature is loaded onto the active map.
    This is the base hook; on_monster_loaded and on_npc_loaded also trigger this.
    The hook receives a table with keys:

    on_creature_melee_attacked

    🇫 Function –> ( params: table )

    Called after a character or monster has attacked in melee.
    The hook receives a table with keys:

    on_creature_performed_technique

    🇫 Function –> ( params: table )

    Called when a character has performed a technique.
    The hook receives a table with keys:

    on_creature_spawn

    🇫 Function –> ( params: table )

    Called when any creature is spawned for the first time.
    This is the base hook; on_monster_spawn and on_npc_spawn also trigger this.
    The hook receives a table with keys:

    on_dialogue_end

    🇫 Function –> ( params: table )

    Called when the dialogue window closes.
    The hook receives a table with keys:

    • npc (NPC): The NPC speaking

    on_dialogue_option

    🇫 Function –> ( params: table )

    Called when a dialogue option is selected.
    Return a new talk_topic id to add it as the next topic.
    The hook receives a table with keys:

    • npc (NPC): The NPC speaking
    • next_topic (string): The topic that was selected

    on_dialogue_start

    🇫 Function –> ( params: table )

    Called just before the dialogue window opens and the first topic is chosen.
    Return a new talk_topic id to add it as the next topic.
    The hook receives a table with keys:

    • npc (NPC): The NPC speaking
    • next_topic (string): The topic that will be shown first

    on_elevator_try_use

    🇫 Function –> ( params: table )

    Called before the player uses elevator controls.
    All registered callbacks run; if any returns false, elevator use is blocked.
    Return false to block elevator use.
    The hook receives a table with keys:

    • player (Player)
    • pos (TripointBubMs)
    • om_terrain (string)

    on_every_x

    🇫 Function –> ( )

    Called every in-game period.
    Not registered through game.add_hook; use gapi.add_on_every_x_hook( interval, fn ) instead.
    The callback receives no arguments. Return false to unregister it.

    on_explosion_start

    🇫 Function –> ( params: table )

    Called when an explosion starts.
    The hook receives a table with keys:

    • pos (TripointBubMs)
    • damage (int)
    • radius (int)
    • fire (bool)

    on_game_load

    🇫 Function –> ( )

    Called right after game has loaded.

    on_game_save

    🇫 Function –> ( )

    Called when game is about to save.

    on_game_started

    🇫 Function –> ( )

    Called when the game has first started.

    on_make_mapgen_factory_list

    🇫 Function –> ( params: table )

    Called when checking which mapgen ids are used, during mapgen consistency checks.
    Insert mapgen ids that are only used from Lua to suppress the “not used by anything” error.
    The hook receives a table with keys:

    • results (set of string): The mapgen ids that are in use

    on_mapgen_postprocess

    🇫 Function –> ( params: table )

    Called right after mapgen has completed.
    The hook receives a table with keys:

    • map (MapgenConstructor): The OMT-local mapgen surface.
    • omt (TripointAbsOmt): The absolute overmap terrain position.
    • when (TimePoint): The current time (for time-based effects).

    on_mission_end

    🇫 Function –> ( params: table )

    Called right after mission has ended.
    The hook receives a table with keys:

    • mission_type (mission_type): The type of the mission.
    • mission (mission): The mission instance.
    • success (bool): Successful if true else failed.

    on_mission_start

    🇫 Function –> ( params: table )

    Called right after mission has started.
    The hook receives a table with keys:

    • mission_type (mission_type): The type of the mission.
    • mission (mission): The mission instance.

    on_mon_death

    🇫 Function –> ( params: table )

    Called when a monster is dead.
    The hook receives a table with keys:

    on_mon_effect

    🇫 Function –> ( params: table )

    Called when character is on the effect which has EFFECT_LUA_ON_TICK flag.
    The hook receives a table with keys:

    on_mon_effect_added

    🇫 Function –> ( params: table )

    Called when monster gets the effect which has EFFECT_LUA_ON_ADDED flag.
    The hook receives a table with keys:

    on_mon_effect_removed

    🇫 Function –> ( params: table )

    Called when monster loses the effect which has EFFECT_LUA_ON_REMOVED flag.
    The hook receives a table with keys:

    on_monster_do_turn

    🇫 Function –> ( params: table )

    Called every turn for each active monster, before it acts.
    Also triggers on_creature_do_turn.
    The hook receives a table with keys:

    on_monster_examine_menu_entry

    🇫 Function –> ( params: table )

    Called when an entry is selected in the examine menu of a pet monster.
    The hook receives a table with keys:

    • avatar (Avatar)
    • monster (Monster)
    • entry (string): The selected entry id, either built-in or a menu_id added by on_monster_get_examine_menu_entries

    on_monster_get_examine_menu_entries

    🇫 Function –> ( params: table )

    Called when building the examine menu of a pet monster.
    Return an array of tables with menu_id (string) and menu_label (string) to add menu entries.
    The hook receives a table with keys:

    on_monster_loaded

    🇫 Function –> ( params: table )

    Called when a monster is loaded onto the active map.
    Also triggers on_creature_loaded.
    The hook receives a table with keys:

    on_monster_spawn

    🇫 Function –> ( params: table )

    Called when a monster is spawned for the first time.
    Also triggers on_creature_spawn.
    Note: monsters spawned via mapgen submap spawn points will fire this hook,
    but monsters materialized from overmap monster groups may not.
    The hook receives a table with keys:

    on_monster_tame

    🇫 Function –> ( params: table )

    Called when a monster is tamed by a character.
    The hook receives a table with keys:

    on_monster_try_move

    🇫 Function –> ( params: table )

    Called when a monster attempts to move.
    All registered callbacks run; if any returns false, movement is blocked.
    Return false to block the move.
    The hook receives a table with keys:

    • monster (Monster)
    • from (TripointBubMs)
    • to (TripointBubMs)
    • force (bool): If the monster move call was forced

    on_npc_do_turn

    🇫 Function –> ( params: table )

    Called every turn for each simulated NPC, before it acts.
    Also triggers on_creature_do_turn.
    The hook receives a table with keys:

    on_npc_interaction

    🇫 Function –> ( params: table )

    Called when the player interacts with an NPC.
    The hook receives a table with keys:

    • npc (NPC): The NPC being interacted with

    on_npc_loaded

    🇫 Function –> ( params: table )

    Called when an NPC is loaded onto the active map.
    Also triggers on_creature_loaded.
    The hook receives a table with keys:

    on_npc_spawn

    🇫 Function –> ( params: table )

    Called when an NPC is spawned for the first time.
    Also triggers on_creature_spawn.
    The hook receives a table with keys:

    on_npc_try_move

    🇫 Function –> ( params: table )

    Called when an NPC attempts to move.
    All registered callbacks run; if any returns false, movement is blocked.
    Return false to block the move.
    The hook receives a table with keys:

    • npc (Npc)
    • from (TripointBubMs)
    • to (TripointBubMs)
    • movement_mode (CharacterMoveMode)
    • via_ramp (bool)
    • mounted (bool)
    • mount (Creature, if mounted)

    on_player_try_move

    🇫 Function –> ( params: table )

    Called when the player attempts to move.
    All registered callbacks run; if any returns false, movement is blocked.
    Return false to block the move.
    The hook receives a table with keys:

    on_shoot

    🇫 Function –> ( params: table )

    Called when shot(s) is fired from a gun.
    The hook receives a table with keys:

    • shooter (Character)
    • target_pos (TripointBubMs)
    • shots (int)
    • gun (item)
    • ammo (item): For RELOAD_AND_SHOOT guns like a bow. On the others, it returns nil value.

    on_spell_cast

    🇫 Function –> ( params: table )

    Called after a spell has been cast.
    The hook receives a table with keys:

    on_spell_try_cast

    🇫 Function –> ( params: table )

    Called when the player tries to cast a spell, before the casting activity starts.
    Return false to block casting.
    The hook receives a table with keys:

    on_throw

    🇫 Function –> ( params: table )

    Called when an item is thrown.
    The hook receives a table with keys:

    • thrower (Character)
    • target_pos (TripointBubMs)
    • throw_from_pos (TripointBubMs)
    • thrown (item)

    on_try_monster_interaction

    🇫 Function –> ( params: table )

    Called when the player tries to interact with a monster.
    Return false to prevent monster interaction actions from running.
    The hook receives a table with keys:

    • monster (Monster): The monster being interacted with

    on_try_npc_interaction

    🇫 Function –> ( params: table )

    Called when the player tries to interact with an NPC.
    Return false to prevent the npc interaction menu from appearing.
    The hook receives a table with keys:

    • npc (NPC): The NPC being interacted with

    on_weather_changed

    🇫 Function –> ( params: table )

    Called when the weather has changed.
    The hook receives a table with keys:

    • weather_id (string): Current weather ID
    • old_weather_id (string): Previous weather ID
    • temperature (float): Current temperature in Celsius
    • temperature_f (float): Current temperature in Fahrenheit
    • windspeed (float): Wind speed
    • winddirection (integer): Wind direction in degrees
    • humidity (float): Humidity percentage
    • pressure (float): Atmospheric pressure
    • is_sheltered (boolean): Whether player is sheltered

    on_weather_updated

    🇫 Function –> ( params: table )

    Called every 5 minutes when weather data is updated.
    The hook receives a table with keys:

    • weather_id (string): Current weather ID
    • temperature (float): Current temperature in Celsius
    • temperature_f (float): Current temperature in Fahrenheit
    • windspeed (float): Wind speed
    • winddirection (integer): Wind direction in degrees
    • humidity (float): Humidity percentage
    • pressure (float): Atmospheric pressure
    • is_sheltered (boolean): Whether player is sheltered

    locale

    Localization API.

    Members

    gettext

    🇫 Function –> ( string ) -> string

    Expects english source string, returns translated string.

    pgettext

    🇫 Function –> ( string, string ) -> string

    First is context string. Second is english source string.

    vgettext

    🇫 Function –> ( string, string, integer ) -> string

    First is english singular string, second is english plural string. Number is amount to translate for.

    vpgettext

    🇫 Function –> ( string, string, string, integer ) -> string

    First is context string. Second is english singular string. third is english plural. Number is amount to translate for.

    monster_groups

    Monster group definitions and helpers

    Members

    get_all

    🇫 Function –> ( ) -> MonsterGroupRaw[]

    Get all monster group definitions.

    get_all_ids

    🇫 Function –> ( ) -> MonsterGroupId[]

    List all monster group ids currently loaded.

    get_group

    🇫 Function –> ( MonsterGroupId ) -> MonsterGroupRaw

    Get a monster group definition by id.

    get_monsters_from_group

    🇫 Function –> ( MonsterGroupId ) -> MonsterTypeId[]

    Get the monster ids directly listed in a group (default monster first).

    monster_types

    Monster type definitions and helpers

    Members

    get_all_ids

    🇫 Function –> ( ) -> MonsterTypeId[]

    List all monster type ids currently loaded.

    overmapbuffer

    Global overmap buffer interface for finding and inspecting overmap terrain.

    Members

    add_grid_connection

    🇫 Function –> ( TripointAbsOmt, TripointAbsOmt ) -> boolean

    Add an electric grid connection between two positions. Returns true on success.

    check_ot

    🇫 Function –> ( string, OtMatchType, TripointAbsOmt ) -> boolean

    Check if the terrain at the given position matches the type and match mode. Returns boolean.

    create_horde

    🇫 Function –> ( table ) -> Mongroup

    Create a monster horde at the given absolute OMT position. Returns nil if type or pos is missing.
    Takes a table with keys:

    • type (MonsterGroupId or string): Monster group to spawn.
    • pos (TripointAbsOmt): Where to create the horde.
    • radius (integer, optional): Spread radius in submaps. Defaults to 1.
    • population (integer, optional): Number of monsters. Defaults to 100.
    • horde (boolean, optional): Whether the group moves as a horde. Defaults to true.
    • behaviour (string, optional): Horde behaviour: roam, city or nemesis. Defaults to roam.
    • diffuse (boolean, optional): If true, monster density doesn’t depend on distance from pos. Defaults to false.
    • target (TripointAbsOmt, optional): Initial movement target.

    drain_fluid_grid_liquid_charges

    🇫 Function –> ( TripointAbsOmt, ItypeId, integer ) -> integer

    Drain liquid charges from the fluid grid at the given TripointAbsOmt position. Returns the number removed.

    electric_grid_at

    🇫 Function –> ( TripointAbsOmt ) -> TripointAbsOmt[]

    Get all overmap tiles belonging to the electric grid at the given position. Returns TripointAbsOmt values.

    electric_grid_connectivity_at

    🇫 Function –> ( TripointAbsOmt ) -> TripointRelOmt[]

    Get all electric grid connections from the given position. Returns TripointRelOmt offsets.

    find_all

    🇫 Function –> ( TripointAbsOmt, OmtFindParams ) -> TripointAbsOmt[]

    Find all overmap terrain tiles matching the given parameters. Returns TripointAbsOmt values.

    find_closest

    🇫 Function –> ( TripointAbsOmt, OmtFindParams ) -> TripointAbsOmt?

    Find the closest overmap terrain tile matching the given parameters. Returns TripointAbsOmt or nil if not found.

    find_random

    🇫 Function –> ( TripointAbsOmt, OmtFindParams ) -> TripointAbsOmt?

    Find a random overmap terrain tile matching the given parameters. Returns TripointAbsOmt or nil if not found.

    fluid_grid_at

    🇫 Function –> ( TripointAbsOmt ) -> TripointAbsOmt[]

    Get all overmap tiles belonging to the fluid grid at the given TripointAbsOmt position. Returns TripointAbsOmt values.

    fluid_grid_connectivity_at

    🇫 Function –> ( TripointAbsOmt ) -> TripointRelOmt[]

    Get all fluid grid connections from the given TripointAbsOmt position. Returns TripointRelOmt offsets.

    fluid_grid_liquid_charges_at

    🇫 Function –> ( TripointAbsOmt, ItypeId ) -> integer

    Get the available charges of a liquid in the fluid grid at the given TripointAbsOmt position.

    fluid_grid_would_contaminate

    🇫 Function –> ( TripointAbsOmt, ItypeId ) -> boolean

    Check whether adding a liquid would contaminate the fluid grid at the given TripointAbsOmt position.

    get_note

    🇫 Function –> ( TripointAbsOmt ) -> string?

    Get a player note at the given position. Returns string or nil.

    has_horde

    🇫 Function –> ( TripointAbsOmt ) -> boolean

    Check if a horde is present at the given overmap tile.

    horde_count

    🇫 Function –> ( TripointAbsOmt ) -> integer

    Count hordes influencing the given overmap tile (absolute OMT coordinates).

    horde_size

    🇫 Function –> ( TripointAbsOmt ) -> integer

    Get the estimated size of the horde at the given overmap tile.

    hordes_at

    🇫 Function –> ( TripointAbsOmt ) -> Mongroup[]

    List hordes influencing the given overmap tile (absolute OMT coordinates).

    is_explored

    🇫 Function –> ( TripointAbsOmt ) -> boolean

    Check if the terrain at the given position has been explored by the player. Returns boolean.

    monster_groups_at

    🇫 Function –> ( TripointAbsOmt ) -> Mongroup[]

    List monster groups influencing the given overmap tile (absolute OMT coordinates).

    move_hordes

    🇫 Function –> ( )

    Advance horde movement across all loaded overmaps.

    remove_grid_connection

    🇫 Function –> ( TripointAbsOmt, TripointAbsOmt ) -> boolean

    Remove an electric grid connection between two positions. Returns true on success.

    reveal

    🇫 Function –> ( TripointAbsOmt, integer, function? ) -> boolean

    Reveal a square area around a TripointAbsOmt center on the overmap. Returns true if any new tiles were revealed. Optional filter callback receives oter_id and should return true to reveal that tile.

    seen

    🇫 Function –> ( TripointAbsOmt ) -> boolean

    Check if the terrain at the given position has been seen by the player. Returns boolean.

    set_note

    🇫 Function –> ( TripointAbsOmt, string? )

    Set a player note at the given position. Pass nil or empty string to clear.

    set_seen

    🇫 Function –> ( TripointAbsOmt, boolean? )

    Set the seen status of terrain at the given position.

    signal_hordes

    🇫 Function –> ( TripointAbsSm, integer )

    Signal nearby hordes toward an absolute submap position with the given strength.

    ter

    🇫 Function –> ( TripointAbsOmt ) -> OterIntId

    Get the overmap terrain type at the given position. Returns an oter_id.

    requirements

    Requirement definitions and lookup helpers.

    Members

    get

    🇫 Function –> ( string ) -> RequirementData?

    Look up requirement_data by ID string. Returns nil if not found.

    rgb_colors

    RGB Color Getters.

    Members

    get_all_named_colors

    🇫 Function –> ( ) -> CppVal<std_unordered_map<RGBColor,std_basic_string<char>>>

    Get RGBColor -> string mapping

    get_random

    🇫 Function –> ( string ) -> (RGBColor, string)

    Get random RGB Color from fuzzy match string

    try_parse

    🇫 Function –> ( string ) -> RGBColor?

    Get RGB Color from string

    sidebar

    Sidebar utility functions.

    Members

    clear_widgets

    🇫 Function –> ( )

    Clear all registered Lua sidebar widgets.

    get_layout_id

    🇫 Function –> ( ) -> string

    Returns current sidebar layout id (e.g. classic, compact, labels).

    register_widget

    🇫 Function –> ( table )

    Register a Lua sidebar widget.
    Takes a table with keys:

    • id (string): Unique widget id.
    • draw (function): draw(width, height) returns an array of lines. Each line is a string or a table { text = string, color = Color|string }. text may include color tags like <color_red>text for multi-color lines.
    • name (string, optional): Name shown in the sidebar options. Defaults to id.
    • height (integer, optional): Height in lines. Use -2 to fill the remaining space. Defaults to 1.
    • order (integer, optional): 1-based position in the sidebar.
    • default_toggle (boolean, optional): Whether the widget is enabled by default. Defaults to true.
    • redraw_every_frame (boolean, optional): Redraw on every frame instead of only on sidebar refresh. Defaults to false.
    • panel_visible (boolean or function, optional): Whether to show the widget. A function is called with no arguments and should return a boolean.
    • render (function, optional): Visibility check used when panel_visible is not a function. Called with no arguments; return false to hide the widget.

    tests_lib

    Library for testing purposes

    Members

    my_awesome_lambda_1

    🇫 Function –> ( ) -> integer

    my_awesome_lambda_2

    🇫 Function –> ( ) -> integer

    Modding with Lua

    Example mods

    There are a couple heavily-commented example mods in data/mods/ that make use of Lua API described here:

    • smart_house_remotes - Add remotes for controlling garage doors and window curtains.
    • saveload_lua_test - Mod for testing Lua save/load API.

    Ingame Lua console

    In-game Lua console is available through the debug menu or via Lua Console hotkey (unbound by default).

    It is rather simple, but is capable of keeping input history, showing output and errors from Lua scripts as well as running Lua snippets and printing the returned values.

    You can adjust console log capacity by running gdebug.set_log_capacity( num ) (default is 100 entries), or clear it by running gdebug.clear_lua_log().

    Lua hot-reload

    To speed up mod development process, BN supports Lua hot-reload functionality.

    There is no filesystem watcher, so hot-reload must be triggered manually via a corresponding Reload Lua Code hotkey (unbound by default). The hot-reload can also be triggered from console window by pressing the corresponding hotkey, or by running gdebug.reload_lua_code() command. Running the command from regular Lua scripts may have unintended consequences, use at your own risk!

    Note that not all code can be hot-reloaded, it’ll be explained in later sections.

    Game data loading

    When a world is being loaded, game does it in roughly these steps:

    1. Initializes world-related internal state, sets the world as active
    2. Loads world’s artifact item types (artifacts are hacky and will likely be removed soon in favor of relics + Lua)
    3. Retrieves list of mods used by the world
    4. Loads the mods according to the list
    5. Initializes avatar-related internal state
    6. Loads from save dir actual overmap data, avatar data and reality bubble data

    What we care about here is the mod loading stage. It has a number of sub-steps:

    1. Loading function receives list of world mods
    2. It discards the missing ones and prints debug message for each
    3. It checks remaining mods on the list, and throws error if a mod needs Lua, but the game build does NOT support Lua
    4. It also throws a warning if game’s Lua API version differs from the one used by the mod
    5. For every mod on the list that uses Lua, it runs the mod’s preload.lua script (if present)
    6. It goes over all mods in same order as in the list, and loads JSON definitions from each mod’s folder
    7. It finalizes loaded data (resolves copy-from, prepares some types with complex state for use)
    8. For every mod on the list that uses Lua, it runs the mod’s finalize.lua script (if present)
    9. It checks consistency of loaded data (validates values, warns about iffy combinations of values, etc.)
    10. (R) For every mod on the list that uses Lua, it runs the mod’s main.lua script (if present)

    As such, we only have 3 scipts to place a mod’s Lua code into: preload.lua, finalize.lua and main.lua. The differences between the 3 and their intended use cases will be explained below.

    You can use only one script, two or all three, depending on your needs.

    When executing hot-reload, the game repeats the step marked with (R). That means if you want the code you’re working on to be hot-reloadable, put it into main.lua.

    preload.lua

    This script is supposed to register event hooks and set up definitions that will then be referred by game JSON loading system (e.g. item use actions). Note that you can registers them here, and define them in some later stage (e.g. in main.lua to allow hot-reload to affect your hooks).

    finalize.lua

    This script is supposed to allow mods to modify definitions loaded from JSON after copy-from has been resolved, but there is no API for this yet.

    TODO: api for finalization

    main.lua

    This script is supposed to implement the main logic of the mod. This includes, but not limited, to:

    1. Mod runtime state
    2. Mod initialization on game start
    3. Mod save/load code, if required
    4. Implementation of hooks that were set up in preload.lua

    Lua API details

    While you can do a lot of interesting stuff with vanilla Lua, the integration imposes some limits to prevent potential bugs:

    • Loading packages (or Lua modules) is limited to data/lua/ and data/mods/<mod_id>/ directories.
    • Your current mod id is stored in game.current_mod variable
    • Your mod’s runtime state should live in game.mod_runtime[ game.current_mod ] table. You can also interface with other mods if you know their id, by accessing their runtime state in a similar way with game.mod_runtime[ that_other_mod_id ]
    • Changes to global state are not available between scripts. This is to prevent accidental collisions between function names and variable names. You still can define global variables and functions, but they will be visible to your mod only.

    Module loading with require

    The require function supports multiple import patterns for organizing your mod code:

    Relative imports

    Load modules relative to the current file:

    -- In data/mods/my_mod/main.lua
    local utils = require("./lib/utils")          -- loads lib/utils.lua
    local config = require("./config")            -- loads config.lua in same dir
    
    -- In data/mods/my_mod/lib/foo.lua
    local helper = require("./helper")            -- loads lib/helper.lua
    local parent_mod = require("../parent")       -- loads parent.lua from mod root
    

    Standard library imports

    Load shared libraries from data/lua/lib/ using lib. or bn.lib. prefix:

    -- Assuming penlight is installed in data/lua/lib/pl/
    local pl_utils = require("lib.pl.utils")      -- loads data/lua/lib/pl/utils.lua
    local pl_path = require("bn.lib.pl.path")     -- same, bn.lib. prefix also works
    

    Mod-local absolute imports

    Load modules from your mod directory using dotted notation (no prefix):

    -- In data/mods/my_mod/main.lua
    require("foo.bar.baz")  -- searches for:
                            -- 1. <mod>/foo/bar/baz.lua
                            -- 2. <mod>/foo/bar/baz/init.lua
    

    Search order

    • Relative (./, ../): Current file’s directory
    • Standard library (lib.*, bn.lib.*): data/lua/lib/ only
    • Mod-local (no prefix): Current mod directory only

    Caution

    Avoid naming mod modules with reserved prefixes (lib, bn) to prevent namespace conflicts. Use descriptive mod-specific names instead (e.g., mymod.core, utils).

    Module structure

    Modules should return a table:

    -- lib/math_helper.lua
    local M = {}
    
    M.add = function(a, b)
      return a + b
    end
    
    return M
    

    Then use in other files:

    local math_helper = require("./lib/math_helper")
    local result = math_helper.add(2, 3)
    

    Lua libraries and functions

    When script is called, it comes with some standard Lua libraries pre-loaded:

    LibraryDescription
    baseprint, assert, and other base functions
    mathall things math
    stringstring library
    tablethe table manipulator and observer functions
    packageload modules with require

    See Standard Libraries section in Lua manual for details.

    Some of the functions here are overloaded by BN, see Global overrides for details.

    Global state

    Most of necessary data and game runtime state is available through global game table. It has the following members:

    VariableDescription
    game.current_modId of mod that’s being loaded (available only when script is executed)
    game.active_modsList of active world mods, in load order
    game.mod_runtime.<mod_id>Runtime data for mods (each mod gets its own table named after its id)
    game.mod_storage.<mod_id>Per-mod storage that gets automatically saved/loaded on game save/load
    game.cata_internalFor internal game purposes, please don’t use this
    game.hooks.<hook_id>Hooks exposed to Lua scripts, will be called on corresponding events
    game.iuse.<iuse_id>Item use functions that will be recognized by the item factory and called on item use

    Game Bindings

    The game exposes various functions, constants and types to Lua. Functions and constants are organized into “libraries” for organizational purposes. Types are available globally, and may have member functions and fields.

    To see the full list of functions, constants and types, run the game with --lua-doc command line argument. This will generate documentation file lua_doc.md that will be placed in your config folder.

    Many API functions deal with positions in the game world. The game uses a typed coordinate system where every position carries both an origin (the reference frame) and a scale (the unit size). See coordinates.md for a full explanation of the typed coordinate types, arithmetic rules, and when raw Tripoint/Point values are appropriate.

    Global overrides

    Some functions have been globally overriden to improve integration with the game.

    FunctionDescription
    printPrint as INFO LUA to debug.log (overrides default Lua print)
    requireSupports relative (./foo, ../bar) and absolute (pl.utils) imports
    packageCustom searcher loads from data/lua/, data/mods/<mod_id>/ with security checks
    dofileDisabled
    loadfileDisabled
    loadDisabled
    loadstringDisabled

    TODO: alternatives for dofile and such

    Hooks

    To see the list of hooks, check hooks_doc section of the autogenerated documentation file. There, you will see the list of hook ids as well as function signatures that they expect.

    See also: hooks.md (priority ordering, new registration format, chaining).

    You can register new hooks using game.add_hook:

    -- In preload.lua
    local mod = game.mod_runtime[game.current_mod]
    
    game.add_hook("on_game_save", function(...)
      -- This is essentially a forward declaration.
      -- We declare that the hook exists, it should be called on game_save event,
      -- but we will forward all possible arguments (even if there is none) to,
      -- and return value from, the function that we'll declare later on.
      return mod.my_awesome_hook(...)
    end)
    
    -- In main.lua
    local mod = game.mod_runtime[game.current_mod]
    
    mod.my_awesome_hook = function()
      -- Do actual work herede
    end
    

    Item use function

    Item use functions use unique id to register themselves in item factory. On item activation, they receive multiple arguments that will be described in the example below.

    -- In preload.lua
    local mod = game.mod_runtime[ game.current_mod ]
    game.iuse_functions[ "SMART_HOUSE_REMOTE" ] = function(...)
      -- This is just a forward declaration,
      -- but it will allow us to use SMART_HOUSE_REMOTE iuse in JSONs.
      return mod.my_awesome_iuse_function(...)
    end
    
    -- In main.lua
    local mod = game.mod_runtime[ game.current_mod ]
    mod.my_awesome_iuse_function = function( who, item, pos )
      -- Do actual activation effect here.
      -- `who` is the character that activated the item
      -- `item` is the item itself
      -- `pos` is the position of the item (equal to character pos if character has it on them)
    end
    

    Translation functions

    To make the mod translatable to other languages, get your text via functions bound in locale library. See translation API for detailed explanation of their C++ counterparts.

    Usage examples are shown below:

    -- Simple string.
    --
    -- The "Experimental Lab" text will be extracted from this code by a script,
    -- and will be available for translators.
    -- When your Lua script runs, this function will search for translation of
    -- "Experimental Lab" string and return either translated string, 
    -- or the original string if there was no translation found.
    local location_name_translated = locale.gettext( "Experimental Lab" )
    
    -- ERROR: you must call `gettext` with a string literal.
    -- Calling it like this will make it so "Experimental Lab" is NOT extracted,
    -- and translators won't see it when they translate the text.
    local location_name_original = "Experimental Lab"
    local location_name_translated = locale.gettext( location_name_original )
    
    -- ERROR: don't alias the function under different name.
    -- Calling it like this will make it so "Experimental Lab" is NOT extracted,
    -- and translators won't see it when they translate the text.
    local gettext_alt = locale.gettext
    local location_name_translated = gettext_alt( "Experimental Lab" )
    
    -- This, however, is fine.
    local gettext = locale.gettext
    local location_name_translated = gettext( "Experimental Lab" )
    
    -- String with possible plural form.
    -- Many languages have more than 2 plural forms with complex rules related to which one to use.
    local item_display_name = locale.vgettext( "X-37 Prototype", "X-37 Prototypes", num_of_prototypes )
    
    -- String with context
    local text_1 = locale.pgettext("the one made of metal", "Spring")
    local text_2 = locale.pgettext("the one that makes water", "Spring")
    local text_3 = locale.pgettext("time of the year", "Spring")
    
    -- String with both context and plural forms.
    local item_display_name = locale.vpgettext("the one made of metal", "Spring", "Springs", num_of_springs)
    
    --[[
      When some text is tricky and requires explanation,
      it's common to place a special comment denoted with `~` to help translators.
      The comment MUST BE right above the function call.
    ]]
    
    --~ This comment is good and will be visible for translators.
    local ok = locale.gettext("Confusing text that needs explanation.")
    
    --~ ERROR: This comment is too far from gettext call and won't be extracted!
    local not_ok = locale.
                    gettext("Confusing text that needs explanation.")
    
    local not_ok = locale.gettext(
                      --~ ERROR: This comment is in wrong place and won't be extracted!
                      "Confusing text that needs explanation."
                    )
    
    --[[~
      ERROR: Multiline Lua comments can't be used as translator comments!
      This comment won't be extracted!
    ]] 
    local ok = locale.gettext("Confusing text that needs explanation.")
    
    --~ If you need a multiline translator comment,
    --~ just use 2 or more single-line comments.
    --~ They'll be concatenated and shown as a single multi-line comment.
    local ok = locale.gettext("Confusing text that needs explanation.")