diff --git a/CMakeLists.txt b/CMakeLists.txt index 1cbf9ed24..e83f20f54 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -63,7 +63,7 @@ set(DF_VERSION_MINOR "34") set(DF_VERSION_PATCH "07") set(DF_VERSION "${DF_VERSION_MAJOR}.${DF_VERSION_MINOR}.${DF_VERSION_PATCH}") -SET(DFHACK_RELEASE "r1" CACHE STRING "Current release revision.") +SET(DFHACK_RELEASE "r2" CACHE STRING "Current release revision.") set(DFHACK_VERSION "${DF_VERSION_MAJOR}.${DF_VERSION_MINOR}.${DF_VERSION_PATCH}-${DFHACK_RELEASE}") add_definitions(-DDFHACK_VERSION="${DFHACK_VERSION}") diff --git a/LUA_API.rst b/LUA_API.rst index d5af5e7a4..050714c72 100644 --- a/LUA_API.rst +++ b/LUA_API.rst @@ -209,7 +209,7 @@ Implemented features: * ``ref:insert(index,item)`` Inserts a new item at the specified index. To add at the end, - use ``#ref`` as index. + use ``#ref``, or just ``'#'`` as index. * ``ref:erase(index)`` @@ -428,6 +428,11 @@ Currently it defines the following features: If the thread owns the interactive console, shows a prompt and returns the entered string. Otherwise returns *nil, error*. + Depending on the context, this function may actually yield the + running coroutine and let the C++ code release the core suspend + lock. Using an explicit ``dfhack.with_suspend`` will prevent + this, forcing the function to block on input with lock held. + * ``dfhack.interpreter([prompt[,env[,history_filename]]])`` Starts an interactive lua interpreter, using the specified prompt @@ -449,6 +454,10 @@ Currently it defines the following features: Just like pcall, but also prints the error using printerr before returning. Intended as a convenience function. +* ``dfhack.saferesume(coroutine[,args...])`` + + Compares to coroutine.resume like dfhack.safecall vs pcall. + * ``dfhack.with_suspend(f[,args...])`` Calls ``f`` with arguments after grabbing the DF core suspend lock. @@ -799,3 +808,51 @@ Maps module * ``dfhack.maps.setBlockBurrowTile(burrow,block,x,y,enable)`` Adds or removes the tile from the burrow. Returns *false* if invalid coords. + + +Core interpreter context +======================== + +While plugins can create any number of interpreter instances, +there is one special context managed by dfhack core. It is the +only context that can receive events from DF and plugins. + +Core context specific functions: + +* ``dfhack.is_core_context`` + + Boolean value; *true* in the core context. + +* ``dfhack.onStateChange.foo = function(code)`` + + Event. Receives the same codes as plugin_onstatechange in C++. + + +Event type +---------- + +An event is just a lua table with a predefined metatable that +contains a __call metamethod. When it is invoked, it loops +through the table with next and calls all contained values. +This is intended as an extensible way to add listeners. + +This type itself is available in any context, but only the +core context has the actual events defined by C++ code. + +Features: + +* ``dfhack.event.new()`` + + Creates a new instance of an event. + +* ``event[key] = function`` + + Sets the function as one of the listeners. + + **NOTE**: The ``df.NULL`` key is reserved for the use by + the C++ owner of the event, and has some special semantics. + +* ``event(args...)`` + + Invokes all listeners contained in the event in an arbitrary + order using ``dfhack.safecall``. diff --git a/Lua API.html b/Lua API.html index 66385840b..cbf35f0eb 100644 --- a/Lua API.html +++ b/Lua API.html @@ -344,6 +344,10 @@ ul.auto-toc {
  • Maps module
  • +
  • Core interpreter context +
  • @@ -512,7 +516,7 @@ possible.

  • ref:insert(index,item)

    Inserts a new item at the specified index. To add at the end, -use #ref as index.

    +use #ref, or just '#' as index.

  • ref:erase(index)

    Removes the element at the given valid index.

    @@ -704,6 +708,10 @@ works with DFHack output infrastructure.

  • dfhack.lineedit([prompt[,history_filename]])

    If the thread owns the interactive console, shows a prompt and returns the entered string. Otherwise returns nil, error.

    +

    Depending on the context, this function may actually yield the +running coroutine and let the C++ code release the core suspend +lock. Using an explicit dfhack.with_suspend will prevent +this, forcing the function to block on input with lock held.

  • dfhack.interpreter([prompt[,env[,history_filename]]])

    Starts an interactive lua interpreter, using the specified prompt @@ -721,6 +729,9 @@ in C++, and dfhack.safecall.

    Just like pcall, but also prints the error using printerr before returning. Intended as a convenience function.

  • +
  • dfhack.saferesume(coroutine[,args...])

    +

    Compares to coroutine.resume like dfhack.safecall vs pcall.

    +
  • dfhack.with_suspend(f[,args...])

    Calls f with arguments after grabbing the DF core suspend lock. Suspending is necessary for accessing a consistent state of DF memory.

    @@ -1010,6 +1021,45 @@ Returns false in case of error.

    +
    +

    Core interpreter context

    +

    While plugins can create any number of interpreter instances, +there is one special context managed by dfhack core. It is the +only context that can receive events from DF and plugins.

    +

    Core context specific functions:

    + +
    +

    Event type

    +

    An event is just a lua table with a predefined metatable that +contains a __call metamethod. When it is invoked, it loops +through the table with next and calls all contained values. +This is intended as an extensible way to add listeners.

    +

    This type itself is available in any context, but only the +core context has the actual events defined by C++ code.

    +

    Features:

    +
      +
    • dfhack.event.new()

      +

      Creates a new instance of an event.

      +
    • +
    • event[key] = function

      +

      Sets the function as one of the listeners.

      +

      NOTE: The df.NULL key is reserved for the use by +the C++ owner of the event, and has some special semantics.

      +
    • +
    • event(args...)

      +

      Invokes all listeners contained in the event in an arbitrary +order using dfhack.safecall.

      +
    • +
    +
    +
    diff --git a/README.rst b/README.rst index 6e0031ef6..0efe194d7 100644 --- a/README.rst +++ b/README.rst @@ -45,25 +45,40 @@ Copy the files from a release archive so that: Uninstalling is basically the same, in reverse: - * On Windows, first delete SDL.dll and rename SDLreal.dll to SDL.dll. Then remove the other DFHack files + * On Windows, first delete SDL.dll and rename SDLreal.dll to SDL.dll. Then + remove the other DFHack files * On Linux, Remove the DFHack files. The stonesense plugin might require some additional libraries on Linux. -If any of the plugins or dfhack itself refuses to load, check the stderr.log file created in your DF folder. +If any of the plugins or dfhack itself refuses to load, check the stderr.log +file created in your DF folder. ============ Using DFHack ============ -DFHack basically extends what DF can do with something similar to the drop-down console found in Quake engine games. On Windows, this is a separate command line window. On linux, the terminal used to launch the dfhack script is taken over (so, make sure you start from a terminal). -Basic interaction with dfhack involves entering commands into the console. For some basic instroduction, use the 'help' command. To list all possible commands, use the 'ls' command. -Many commands have their own help or detailed description. You can use 'command help' or 'command ?' to show that. - -The command line has some nice line editing capabilities, including history that's preserved between different runs of DF (use up/down keys to go through the history). - -The second way to interact with DFHack is to bind the available commands to in-game hotkeys. The old way to do this is via the hotkey/zoom menu (normally opened with the 'h' key). Binding the commands is done by assigning a command as a hotkey name (with 'n'). - -A new and more flexible way is the keybinding command in the dfhack console. However, bindings created this way are not automatically remembered between runs of the game, so it becomes necessary to use the dfhack.init file to ensure that they are re-created every time it is loaded. +DFHack basically extends what DF can do with something similar to the drop-down +console found in Quake engine games. On Windows, this is a separate command line +window. On linux, the terminal used to launch the dfhack script is taken over +(so, make sure you start from a terminal). Basic interaction with dfhack +involves entering commands into the console. For some basic instroduction, +use the 'help' command. To list all possible commands, use the 'ls' command. +Many commands have their own help or detailed description. You can use +'command help' or 'command ?' to show that. + +The command line has some nice line editing capabilities, including history +that's preserved between different runs of DF (use up/down keys to go through +the history). + +The second way to interact with DFHack is to bind the available commands +to in-game hotkeys. The old way to do this is via the hotkey/zoom menu (normally +opened with the 'h' key). Binding the commands is done by assigning a command as +a hotkey name (with 'n'). + +A new and more flexible way is the keybinding command in the dfhack console. +However, bindings created this way are not automatically remembered between runs +of the game, so it becomes necessary to use the dfhack.init file to ensure that +they are re-created every time it is loaded. Interactive commands like 'liquids' cannot be used as hotkeys. @@ -72,23 +87,34 @@ Most of the commands come from plugins. Those reside in 'hack/plugins/'. ============================= Something doesn't work, help! ============================= -First, don't panic :) Second, dfhack keeps a few log files in DF's folder - stderr.log and stdout.log. You can look at those and possibly find out what's happening. -If you found a bug, you can either report it in the bay12 DFHack thread, the issues tracker on github, contact me (peterix@gmail.com) or visit the #dfhack IRC channel on freenode. +First, don't panic :) Second, dfhack keeps a few log files in DF's folder +- stderr.log and stdout.log. You can look at those and possibly find out what's +happening. +If you found a bug, you can either report it in the bay12 DFHack thread, +the issues tracker on github, contact me (peterix@gmail.com) or visit the +#dfhack IRC channel on freenode. ============= The init file ============= -If your DF folder contains a file named dfhack.init, its contents will be run every time you start DF. This allows setting up keybindings. An example file is provided as dfhack.init-example - you can tweak it and rename to dfhack.init if you want to use this functionality. +If your DF folder contains a file named dfhack.init, its contents will be run +every time you start DF. This allows setting up keybindings. An example file +is provided as dfhack.init-example - you can tweak it and rename to dfhack.init +if you want to use this functionality. ======== Commands ======== -Almost all the commands support using the 'help ' built-in command to retrieve further help without having to look at this document. Alternatively, some accept a 'help'/'?' option on their command line. +Almost all the commands support using the 'help ' built-in command +to retrieve further help without having to look at this document. Alternatively, +some accept a 'help'/'?' option on their command line. adv-bodyswap ============ -This allows taking control over your followers and other creatures in adventure mode. For example, you can make them pick up new arms and armor and equip them properly. +This allows taking control over your followers and other creatures in adventure +mode. For example, you can make them pick up new arms and armor and equip them +properly. Usage ----- @@ -98,25 +124,51 @@ Usage advtools ======== A package of different adventure mode tools (currently just one) + + Usage ----- -:list-equipped [all]: List armor and weapons equipped by your companions. If all is specified, also lists non-metal clothing. +:list-equipped [all]: List armor and weapons equipped by your companions. + If all is specified, also lists non-metal clothing. +:metal-detector [all-types] [non-trader]: Reveal metal armor and weapons in + shops. The options disable the checks + on item type and being in shop. changelayer =========== -Changes material of the geology layer under cursor to the specified inorganic RAW material. Can have impact on all surrounding regions, not only your embark! By default changing stone to soil and vice versa is not allowed. By default changes only the layer at the cursor position. Note that one layer can stretch across lots of z levels. By default changes only the geology which is linked to the biome under the cursor. That geology might be linked to other biomes as well, though. Mineral veins and gem clusters will stay on the map. Use 'changevein' for them. -tl;dr: You will end up with changing quite big areas in one go, especially if you use it in lower z levels. Use with care. +Changes material of the geology layer under cursor to the specified inorganic +RAW material. Can have impact on all surrounding regions, not only your embark! +By default changing stone to soil and vice versa is not allowed. By default +changes only the layer at the cursor position. Note that one layer can stretch +across lots of z levels. By default changes only the geology which is linked +to the biome under the cursor. That geology might be linked to other biomes +as well, though. Mineral veins and gem clusters will stay on the map. Use +'changevein' for them. + +tl;dr: You will end up with changing quite big areas in one go, especially if +you use it in lower z levels. Use with care. Options ------- :all_biomes: Change selected layer for all biomes on your map. - Result may be undesirable since the same layer can AND WILL be on different z-levels for different biomes. Use the tool 'probe' to get an idea how layers and biomes are distributed on your map. -:all_layers: Change all layers on your map (only for the selected biome unless 'all_biomes' is added). - Candy mountain, anyone? Will make your map quite boring, but tidy. -:force: Allow changing stone to soil and vice versa. !!THIS CAN HAVE WEIRD EFFECTS, USE WITH CARE!! - Note that soil will not be magically replaced with stone. You will, however, get a stone floor after digging so it will allow the floor to be engraved. - Note that stone will not be magically replaced with soil. You will, however, get a soil floor after digging so it could be helpful for creating farm plots on maps with no soil. + Result may be undesirable since the same layer can AND WILL + be on different z-levels for different biomes. Use the tool + 'probe' to get an idea how layers and biomes are distributed + on your map. +:all_layers: Change all layers on your map (only for the selected biome + unless 'all_biomes' is added). + Candy mountain, anyone? Will make your map quite boring, + but tidy. +:force: Allow changing stone to soil and vice versa. !!THIS CAN HAVE + WEIRD EFFECTS, USE WITH CARE!! + Note that soil will not be magically replaced with stone. + You will, however, get a stone floor after digging so it + will allow the floor to be engraved. + Note that stone will not be magically replaced with soil. + You will, however, get a soil floor after digging so it + could be helpful for creating farm plots on maps with no + soil. :verbose: Give some details about what is being changed. :trouble: Give some advice about known problems. @@ -131,13 +183,23 @@ Examples: .. note:: - * If you use changelayer and nothing happens, try to pause/unpause the game for a while and try to move the cursor to another tile. Then try again. If that doesn't help try temporarily changing some other layer, undo your changes and try again for the layer you want to change. Saving and reloading your map might also help. - * You should be fine if you only change single layers without the use of 'force'. Still it's advisable to save your game before messing with the map. - * When you force changelayer to convert soil to stone you might experience weird stuff (flashing tiles, tiles changed all over place etc). Try reverting the changes manually or even better use an older savegame. You did save your game, right? + * If you use changelayer and nothing happens, try to pause/unpause the game + for a while and try to move the cursor to another tile. Then try again. + If that doesn't help try temporarily changing some other layer, undo your + changes and try again for the layer you want to change. Saving + and reloading your map might also help. + * You should be fine if you only change single layers without the use + of 'force'. Still it's advisable to save your game before messing with + the map. + * When you force changelayer to convert soil to stone you might experience + weird stuff (flashing tiles, tiles changed all over place etc). + Try reverting the changes manually or even better use an older savegame. + You did save your game, right? changevein ========== -Changes material of the vein under cursor to the specified inorganic RAW material. +Changes material of the vein under cursor to the specified inorganic RAW +material. Example: -------- @@ -146,15 +208,23 @@ Example: changeitem ========== -Allows changing item material and base quality. By default the item currently selected in the UI will be changed (you can select items in the 'k' list or inside containers/inventory). By default change is only allowed if materials is of the same subtype (for example wood<->wood, stone<->stone etc). But since some transformations work pretty well and may be desired you can override this with 'force'. Note that some attributes will not be touched, possibly resulting in weirdness. To get an idea how the RAW id should look like, check some items with 'info'. Using 'force' might create items which are not touched by crafters/haulers. +Allows changing item material and base quality. By default the item currently +selected in the UI will be changed (you can select items in the 'k' list +or inside containers/inventory). By default change is only allowed if materials +is of the same subtype (for example wood<->wood, stone<->stone etc). But since +some transformations work pretty well and may be desired you can override this +with 'force'. Note that some attributes will not be touched, possibly resulting +in weirdness. To get an idea how the RAW id should look like, check some items +with 'info'. Using 'force' might create items which are not touched by +crafters/haulers. Options ------- -:info: Don't change anything, print some info instead. -:here: Change all items at the cursor position. Requires in-game curser. -:material, m: Change material. Must be followed by valid material RAW id. -:quality, q: Change base quality. Must be followed by number (0-5). -:force: Ignore subtypes, force change to new material. +:info: Don't change anything, print some info instead. +:here: Change all items at the cursor position. Requires in-game cursor. +:material, m: Change material. Must be followed by valid material RAW id. +:quality, q: Change base quality. Must be followed by number (0-5). +:force: Ignore subtypes, force change to new material. Examples: --------- @@ -165,46 +235,65 @@ Examples: cursecheck ========== -Checks a single map tile or the whole map/world for cursed creatures (ghosts, vampires, necromancers, werebeasts, zombies). -With an active in-game cursor only the selected tile will be observed. Without a cursor the whole map will be checked. -By default cursed creatures will be only counted in case you just want to find out if you have any of them running around in your fort. -By default dead and passive creatures (ghosts who were put to rest, killed vampires, ...) are ignored. -Undead skeletons, corpses, bodyparts and the like are all thrown into the curse category "zombie". -Anonymous zombies and resurrected body parts will show as "unnamed creature". +Checks a single map tile or the whole map/world for cursed creatures (ghosts, +vampires, necromancers, werebeasts, zombies). + +With an active in-game cursor only the selected tile will be observed. +Without a cursor the whole map will be checked. + +By default cursed creatures will be only counted in case you just want to find +out if you have any of them running around in your fort. Dead and passive +creatures (ghosts who were put to rest, killed vampires, ...) are ignored. +Undead skeletons, corpses, bodyparts and the like are all thrown into the curse +category "zombie". Anonymous zombies and resurrected body parts will show +as "unnamed creature". Options ------- -:detail: Print full name, date of birth, date of curse and some status info (some vampires might use fake identities in-game, though). -:nick: Set the type of curse as nickname (does not always show up in-game, some vamps don't like nicknames). -:all: Include dead and passive cursed creatures (can result in a quite long list after having FUN with necromancers). -:verbose: Print all curse tags (if you really want to know it all). +:detail: Print full name, date of birth, date of curse and some status + info (some vampires might use fake identities in-game, though). +:nick: Set the type of curse as nickname (does not always show up + in-game, some vamps don't like nicknames). +:all: Include dead and passive cursed creatures (can result in a quite + long list after having FUN with necromancers). +:verbose: Print all curse tags (if you really want to know it all). Examples: --------- ``cursecheck detail all`` - Give detailed info about all cursed creatures including deceased ones (no in-game cursor). + Give detailed info about all cursed creatures including deceased ones (no + in-game cursor). ``cursecheck nick`` - Give a nickname all living/active cursed creatures on the map(no in-game cursor). + Give a nickname all living/active cursed creatures on the map(no in-game + cursor). .. note:: - * If you do a full search (with the option "all") former ghosts will show up with the cursetype "unknown" because their ghostly flag is not set anymore. But if you happen to find a living/active creature with cursetype "unknown" please report that in the dfhack thread on the modding forum or per irc. This is likely to happen with mods which introduce new types of curses, for example. + * If you do a full search (with the option "all") former ghosts will show up + with the cursetype "unknown" because their ghostly flag is not set + anymore. But if you happen to find a living/active creature with cursetype + "unknown" please report that in the dfhack thread on the modding forum or + per irc. This is likely to happen with mods which introduce new types + of curses, for example. follow ====== -Makes the game view follow the currently highlighted unit after you exit from current menu/cursor mode. Handy for watching dwarves running around. Deactivated by moving the view manually. +Makes the game view follow the currently highlighted unit after you exit from +current menu/cursor mode. Handy for watching dwarves running around. Deactivated +by moving the view manually. forcepause ========== -Forces DF to pause. This is useful when your FPS drops below 1 and you lose control of the game. +Forces DF to pause. This is useful when your FPS drops below 1 and you lose +control of the game. * Activate with 'forcepause 1' * Deactivate with 'forcepause 0' nopause ======= -Disables pausing (both manual and automatic) with the exception of pause forced by 'reveal hell'. -This is nice for digging under rivers. +Disables pausing (both manual and automatic) with the exception of pause forced +by 'reveal hell'. This is nice for digging under rivers. die === @@ -229,17 +318,53 @@ Options autodump-destroy-here ===================== -Destroy items marked for dumping under cursor. Identical to autodump destroy-here, but intended for use as keybinding. +Destroy items marked for dumping under cursor. Identical to autodump +destroy-here, but intended for use as keybinding. autodump-destroy-item ===================== -Destroy the selected item. The item may be selected in the 'k' list, or inside a container. If called again before the game is resumed, cancels destroy. +Destroy the selected item. The item may be selected in the 'k' list, or inside +a container. If called again before the game is resumed, cancels destroy. + +burrow +====== +Miscellaneous burrow control. Allows manipulating burrows and automated burrow +expansion while digging. + +Options +------- +:enable feature ...: +:disable feature ...: Enable or Disable features of the plugin. +:clear-unit burrow burrow ...: +:clear-tiles burrow burrow ...: Removes all units or tiles from the burrows. +:set-units target-burrow src-burrow ...: +:add-units target-burrow src-burrow ...: +:remove-units target-burrow src-burrow ...: Adds or removes units in source + burrows to/from the target burrow. Set is equivalent to clear and add. +:set-tiles target-burrow src-burrow ...: +:add-tiles target-burrow src-burrow ...: +:remove-tiles target-burrow src-burrow ...: Adds or removes tiles in source + burrows to/from the target burrow. In place of a source burrow it is + possible to use one of the following keywords: ABOVE_GROUND, + SUBTERRANEAN, INSIDE, OUTSIDE, LIGHT, DARK, HIDDEN, REVEALED + +Features +-------- +:auto-grow: When a wall inside a burrow with a name ending in '+' is dug + out, the burrow is extended to newly-revealed adjacent walls. + This final '+' may be omitted in burrow name args of commands above. + Digging 1-wide corridors with the miner inside the burrow is SLOW. + +catsplosion +=========== +Makes cats just *multiply*. It is not a good idea to run this more than once or +twice. clean ===== -Cleans all the splatter that get scattered all over the map, items and creatures. -In an old fortress, this can significantly reduce FPS lag. It can also spoil your -!!FUN!!, so think before you use it. +Cleans all the splatter that get scattered all over the map, items and +creatures. In an old fortress, this can significantly reduce FPS lag. It can +also spoil your !!FUN!!, so think before you use it. Options ------- @@ -254,12 +379,13 @@ Extra options for 'map' spotclean ========= -Works like 'clean map snow mud', but only for the tile under the cursor. Ideal if you want to keep that bloody entrance 'clean map' would clean up. +Works like 'clean map snow mud', but only for the tile under the cursor. Ideal +if you want to keep that bloody entrance 'clean map' would clean up. cleanowned ========== -Confiscates items owned by dwarfs. -By default, owned food on the floor and rotten items are confistacted and dumped. +Confiscates items owned by dwarfs. By default, owned food on the floor +and rotten items are confistacted and dumped. Options ------- @@ -267,7 +393,8 @@ Options :scattered: confiscated and dump all items scattered on the floor :x: confiscate/dump items with wear level 'x' and more :X: confiscate/dump items with wear level 'X' and more -:dryrun: a dry run. combine with other options to see what will happen without it actually happening. +:dryrun: a dry run. combine with other options to see what will happen + without it actually happening. Example: -------- @@ -286,18 +413,6 @@ deramp (by zilpin) Removes all ramps designated for removal from the map. This is useful for replicating the old channel digging designation. It also removes any and all 'down ramps' that can remain after a cave-in (you don't have to designate anything for that to happen). -df2minecraft -============ -This generates a minecraft world out of the currently loaded fortress. -Generated worlds are placed into your DF folder, named "World #". - -.. warning:: - - * This is experimental! It *will* cause crashes. - * If it works, the process takes quite a while to complete. - * Do not use if you have any unsaved progress! - * Non-square embarks are exported wrong. It's a known bug. - dfusion ======= This is the DFusion lua plugin system by warmist/darius, running as a DFHack plugin. @@ -329,8 +444,10 @@ feature ======= Enables management of map features. -* Discovering a magma feature (magma pool, volcano, magma sea, or curious underground structure) permits magma workshops and furnaces to be built. -* Discovering a cavern layer causes plants (trees, shrubs, and grass) from that cavern to grow within your fortress. +* Discovering a magma feature (magma pool, volcano, magma sea, or curious + underground structure) permits magma workshops and furnaces to be built. +* Discovering a cavern layer causes plants (trees, shrubs, and grass) from + that cavern to grow within your fortress. Options ------- @@ -376,36 +493,53 @@ Example: fixdiplomats ============ -Up to version 0.31.12, Elves only sent Diplomats to your fortress to propose tree cutting quotas due to a bug; once that bug was fixed, Elves stopped caring about excess tree cutting. This command adds a Diplomat position to all Elven civilizations, allowing them to negotiate tree cutting quotas (and allowing you to violate them and potentially start wars) in case you haven't already modified your raws accordingly. +Up to version 0.31.12, Elves only sent Diplomats to your fortress to propose +tree cutting quotas due to a bug; once that bug was fixed, Elves stopped caring +about excess tree cutting. This command adds a Diplomat position to all Elven +civilizations, allowing them to negotiate tree cutting quotas (and allowing you +to violate them and potentially start wars) in case you haven't already modified +your raws accordingly. fixmerchants ============ -This command adds the Guild Representative position to all Human civilizations, allowing them to make trade agreements (just as they did back in 0.28.181.40d and earlier) in case you haven't already modified your raws accordingly. +This command adds the Guild Representative position to all Human civilizations, +allowing them to make trade agreements (just as they did back in 0.28.181.40d +and earlier) in case you haven't already modified your raws accordingly. fixveins ======== -Removes invalid references to mineral inclusions and restores missing ones. Use this if you broke your embark with tools like tiletypes, or if you accidentally placed a construction on top of a valuable mineral floor. +Removes invalid references to mineral inclusions and restores missing ones. +Use this if you broke your embark with tools like tiletypes, or if you +accidentally placed a construction on top of a valuable mineral floor. fixwagons ========= -Due to a bug in all releases of version 0.31, merchants no longer bring wagons with their caravans. This command re-enables them for all appropriate civilizations. +Due to a bug in all releases of version 0.31, merchants no longer bring wagons +with their caravans. This command re-enables them for all appropriate +civilizations. flows ===== -A tool for checking how many tiles contain flowing liquids. If you suspect that your magma sea leaks into HFS, you can use this tool to be sure without revealing the map. +A tool for checking how many tiles contain flowing liquids. If you suspect that +your magma sea leaks into HFS, you can use this tool to be sure without +revealing the map. getplants ========= -This tool allows plant gathering and tree cutting by RAW ID. Specify the types of trees to cut down and/or shrubs to gather by their plant names, separated by spaces. +This tool allows plant gathering and tree cutting by RAW ID. Specify the types +of trees to cut down and/or shrubs to gather by their plant names, separated +by spaces. Options ------- -:-t: Select trees only (exclude shrubs) -:-s: Select shrubs only (exclude trees) -:-c: Clear designations instead of setting them -:-x: Apply selected action to all plants except those specified (invert selection) +:-t: Select trees only (exclude shrubs) +:-s: Select shrubs only (exclude trees) +:-c: Clear designations instead of setting them +:-x: Apply selected action to all plants except those specified (invert + selection) -Specifying both -t and -s will have no effect. If no plant IDs are specified, all valid plant IDs will be listed. +Specifying both -t and -s will have no effect. If no plant IDs are specified, +all valid plant IDs will be listed. tidlers ======= @@ -420,41 +554,61 @@ job Command for general job query and manipulation. Options: - * no extra options - Print details of the current job. The job can be selected in a workshop, or the unit/jobs screen. + * no extra options - Print details of the current job. The job can be selected + in a workshop, or the unit/jobs screen. * list - Print details of all jobs in the selected workshop. - * item-material - Replace the exact material id in the job item. - * item-type - Replace the exact item type id in the job item. + * item-material - Replace the exact material + id in the job item. + * item-type - Replace the exact item type id in + the job item. job-material ============ -Alter the material of the selected job. Invoked as: job-material +Alter the material of the selected job. + +Invoked as: job-material Intended to be used as a keybinding: - * In 'q' mode, when a job is highlighted within a workshop or furnace, changes the material of the job. Only inorganic materials can be used in this mode. - * In 'b' mode, during selection of building components positions the cursor over the first available choice with the matching material. + * In 'q' mode, when a job is highlighted within a workshop or furnace, + changes the material of the job. Only inorganic materials can be used + in this mode. + * In 'b' mode, during selection of building components positions the cursor + over the first available choice with the matching material. job-duplicate ============= Duplicate the selected job in a workshop: - * In 'q' mode, when a job is highlighted within a workshop or furnace building, instantly duplicates the job. + * In 'q' mode, when a job is highlighted within a workshop or furnace building, + instantly duplicates the job. keybinding ========== -Manages DFHack keybindings. Currently it supports any combination of Ctrl/Alt/Shift with F1-F9, or A-Z. +Manages DFHack keybindings. + +Currently it supports any combination of Ctrl/Alt/Shift with F1-F9, or A-Z. Options ------- :keybinding list : List bindings active for the key combination. :keybinding clear ...: Remove bindings for the specified keys. -:keybinding add "cmdline" "cmdline"...: Add bindings for the specified key. -:keybinding set "cmdline" "cmdline"...: Clear, and then add bindings for the specified key. +:keybinding add "cmdline" "cmdline"...: Add bindings for the specified + key. +:keybinding set "cmdline" "cmdline"...: Clear, and then add bindings for + the specified key. -When multiple commands are bound to the same key combination, DFHack selects the first applicable one. Later 'add' commands, and earlier entries within one 'add' command have priority. Commands that are not specifically intended for use as a hotkey are always considered applicable. +When multiple commands are bound to the same key combination, DFHack selects +the first applicable one. Later 'add' commands, and earlier entries within one +'add' command have priority. Commands that are not specifically intended for use +as a hotkey are always considered applicable. liquids ======= -Allows adding magma, water and obsidian to the game. It replaces the normal dfhack command line and can't be used from a hotkey. Settings will be remembered as long as dfhack runs. Intended for use in combination with the command liquids-here (which can be bound to a hotkey). +Allows adding magma, water and obsidian to the game. It replaces the normal +dfhack command line and can't be used from a hotkey. Settings will be remembered +as long as dfhack runs. Intended for use in combination with the command +liquids-here (which can be bound to a hotkey). + For more information, refer to the command's internal help. .. note:: @@ -464,26 +618,30 @@ For more information, refer to the command's internal help. liquids-here ============ -Run the liquid spawner with the current/last settings made in liquids (if no settings in liquids were made it paints a point of 7/7 magma by default). +Run the liquid spawner with the current/last settings made in liquids (if no +settings in liquids were made it paints a point of 7/7 magma by default). + Intended to be used as keybinding. Requires an active in-game cursor. - + mode ==== -This command lets you see and change the game mode directly. Not all combinations are good for every situation and most of them will produce undesirable results. -There are a few good ones though. +This command lets you see and change the game mode directly. +Not all combinations are good for every situation and most of them will +produce undesirable results. There are a few good ones though. .. admonition:: Example You are in fort game mode, managing your fortress and paused. - You switch to the arena game mode, *assume control of a creature* and then switch to adventure game mode(1). + You switch to the arena game mode, *assume control of a creature* and then + switch to adventure game mode(1). You just lost a fortress and gained an adventurer. -I take no responsibility of anything that happens as a result of using this tool :P +I take no responsibility of anything that happens as a result of using this tool extirpate ========= -A tool for getting rid of trees and shrubs. By default, it only kills a tree/shrub under the cursor. -The plants are turned into ashes instantly. +A tool for getting rid of trees and shrubs. By default, it only kills +a tree/shrub under the cursor. The plants are turned into ashes instantly. Options ------- @@ -497,7 +655,8 @@ Makes all saplings present on the map grow into trees (almost) instantly. immolate ======== -Very similar to extirpate, but additionally sets the plants on fire. The fires can and *will* spread ;) +Very similar to extirpate, but additionally sets the plants on fire. The fires +can and *will* spread ;) probe ===== @@ -505,7 +664,8 @@ Can be used to determine tile properties like temperature. prospect ======== -Prints a big list of all the present minerals and plants. By default, only the visible part of the map is scanned. +Prints a big list of all the present minerals and plants. By default, only +the visible part of the map is scanned. Options ------- @@ -515,9 +675,10 @@ Options Pre-embark estimate ------------------- -If called during the embark selection screen, displays an estimate of layer stone availability. -If the 'all' option is specified, also estimates veins. The estimate is computed either -for 1 embark tile of the blinking biome, or for all tiles of the embark rectangle. +If called during the embark selection screen, displays an estimate of layer +stone availability. If the 'all' option is specified, also estimates veins. +The estimate is computed either for 1 embark tile of the blinking biome, or +for all tiles of the embark rectangle. Options ------- @@ -525,7 +686,7 @@ Options regrass ======= -Regrows all surface grass, restoring outdoor plant growth for pre-0.31.19 worlds. +Regrows grass. Not much to it ;) rename ====== @@ -534,15 +695,22 @@ Allows renaming various things. Options ------- :rename squad "name": Rename squad by index to 'name'. -:rename hotkey \"name\": Rename hotkey by index. This allows assigning longer commands to the DF hotkeys. -:rename unit "nickname": Rename a unit/creature highlighted in the DF user interface. -:rename unit-profession "custom profession": Change proffession name of the highlighted unit/creature. +:rename hotkey \"name\": Rename hotkey by index. This allows assigning + longer commands to the DF hotkeys. +:rename unit "nickname": Rename a unit/creature highlighted in the DF user + interface. +:rename unit-profession "custom profession": Change proffession name of the + highlighted unit/creature. reveal ====== -This reveals the map. By default, HFS will remain hidden so that the demons don't spawn. You can use 'reveal hell' to reveal everything. With hell revealed, you won't be able to unpause until you hide the map again. If you really want to unpause with hell revealed, use 'reveal demons'. +This reveals the map. By default, HFS will remain hidden so that the demons +don't spawn. You can use 'reveal hell' to reveal everything. With hell revealed, +you won't be able to unpause until you hide the map again. If you really want +to unpause with hell revealed, use 'reveal demons'. -Reveal also works in adventure mode, but any of its effects are negated once you move. When you use it this way, you don't need to run 'unreveal'. +Reveal also works in adventure mode, but any of its effects are negated once +you move. When you use it this way, you don't need to run 'unreveal'. unreveal ======== @@ -554,17 +722,23 @@ Switches between 'reveal' and 'unreveal'. revflood ======== -This command will hide the whole map and then reveal all the tiles that have a path to the in-game cursor. +This command will hide the whole map and then reveal all the tiles that have +a path to the in-game cursor. revforget ========= -When you use reveal, it saves information about what was/wasn't visible before revealing everything. Unreveal uses this information to hide things again. This command throws away the information. For example, use in cases where you abandoned with the fort revealed and no longer want the data. +When you use reveal, it saves information about what was/wasn't visible before +revealing everything. Unreveal uses this information to hide things again. +This command throws away the information. For example, use in cases where +you abandoned with the fort revealed and no longer want the data. lair ==== -This command allows you to mark the map as 'monster lair', preventing item scatter on abandon. When invoked as 'lair reset', it does the opposite. +This command allows you to mark the map as 'monster lair', preventing item +scatter on abandon. When invoked as 'lair reset', it does the opposite. -Unlike reveal, this command doesn't save the information about tiles - you won't be able to restore state of real monster lairs using 'lair reset'. +Unlike reveal, this command doesn't save the information about tiles - you +won't be able to restore state of real monster lairs using 'lair reset'. Options ------- @@ -573,7 +747,8 @@ Options seedwatch ========= -Tool for turning cooking of seeds and plants on/off depending on how much you have of them. +Tool for turning cooking of seeds and plants on/off depending on how much you +have of them. See 'seedwatch help' for detailed description. @@ -583,48 +758,159 @@ Shows all items needed for the currently active strange mood. copystock ========== -Copies the parameters of the currently highlighted stockpile to the custom stockpile settings and switches to custom stockpile placement mode, effectively allowing you to copy/paste stockpiles easily. +Copies the parameters of the currently highlighted stockpile to the custom +stockpile settings and switches to custom stockpile placement mode, effectively +allowing you to copy/paste stockpiles easily. ssense / stonesense =================== -An isometric visualizer that runs in a second window. This requires working graphics acceleration and at least a dual core CPU (otherwise it will slow down DF). +An isometric visualizer that runs in a second window. This requires working +graphics acceleration and at least a dual core CPU (otherwise it will slow +down DF). -All the data resides in the 'stonesense' directory. For detailed instructions, see stonesense/README.txt +All the data resides in the 'stonesense' directory. For detailed instructions, +see stonesense/README.txt Compatible with Windows > XP SP3 and most modern Linux distributions. -Older versions, support and extra graphics can be found in the bay12 forum thread: -http://www.bay12forums.com/smf/index.php?topic=43260.0 +Older versions, support and extra graphics can be found in the bay12 forum +thread: http://www.bay12forums.com/smf/index.php?topic=43260.0 Some additional resources: http://df.magmawiki.com/index.php/Utility:Stonesense/Content_repository tiletypes ========= -Can be used for painting map tiles and is a interactive command, much like liquids. -You can paint tiles by their properties - shape, general material and a few others (paint). -You can also paint only over tiles that match a set of properties (filter) +Can be used for painting map tiles and is an interactive command, much like +liquids. + +The tool works with two set of options and a brush. The brush determines which +tiles will be processed. First set of options is the filter, which can exclude +some of the tiles from the brush by looking at the tile properties. The second +set of options is the paint - this determines how the selected tiles are +changed. + +Both paint and filter can have many different properties including things like +general shape (WALL, FLOOR, etc.), general material (SOIL, STONE, MINERAL, +etc.), state of 'designated', 'hidden' and 'light' flags. + +The properties of filter and paint can be partially defined. This means that +you can for example do something like this: + +:: + + filter material STONE + filter shape FORTIFICATION + paint shape FLOOR + +This will turn all stone fortifications into floors, preserving the material. + +Or this: +:: + + filter shape FLOOR + filter material MINERAL + paint shape WALL + +Turning mineral vein floors back into walls. + +The tool also allows tweaking some tile flags: + +Or this: + +:: + + paint hidden 1 + paint hidden 0 + +This will hide previously revealed tiles (or show hidden with the 0 option). + +Any paint or filter option can be disabled entirely by using the ANY keyword: + +:: + + paint hidden ANY + paint shape ANY + filter material any + filter shape any + +You can use several different brushes for painting tiles: + * Point. (point) + * Rectangular range. (range) + * A column ranging from current cursor to the first solid tile above. (column) + * DF map block - 16x16 tiles, in a regular grid. (block) + +Example: + +:: + + range 10 10 1 + +This will change the brush to a rectangle spanning 10x10 tiles on one z-level. +The range starts at the position of the cursor and goes to the east, south and +up. For more details, see the 'help' command while using this. +tiletypes-commands +================== +Runs tiletypes commands, separated by ;. This makes it possible to change +tiletypes modes from a hotkey. + +tiletypes-here +============== +Apply the current tiletypes options at the in-game cursor position, including +the brush. Can be used from a hotkey. + +tiletypes-here-point +==================== +Apply the current tiletypes options at the in-game cursor position to a single +tile. Can be used from a hotkey. + tweak ===== Contains various tweaks for minor bugs (currently just one). Options ------- -:tweak clear-missing: Remove the missing status from the selected unit. This allows engraving slabs for ghostly, but not yet found, creatures. -:tweak clear-ghostly: Remove the ghostly status from the selected unit and mark it as dead. This allows getting rid of bugged ghosts which do not show up in the engraving slab menu at all, even after using clear-missing. It works, but is potentially very dangerous - so use with care. Probably (almost certainly) it does not have the same effects like a proper burial. You've been warned. -:tweak fixmigrant: Remove the resident/merchant flag from the selected unit. Intended to fix bugged migrants/traders who stay at the map edge and don't enter your fort. Only works for dwarves (or generally the player's race in modded games). Do NOT abuse this for 'real' caravan merchants (if you really want to kidnap them, use 'tweak makeown' instead, otherwise they will have their clothes set to forbidden etc). -:tweak makeown: Force selected unit to become a member of your fort. Can be abused to grab caravan merchants and escorts, even if they don't belong to the player's race. Foreign sentients (humans, elves) can be put to work, but you can't assign rooms to them and they don't show up in DwarfTherapist because the game treats them like pets. Grabbing draft animals from a caravan can result in weirdness (animals go insane or berserk and are not flagged as tame), but you are allowed to mark them for slaughter. Grabbing wagons results in some funny spam, then they are scuttled. +:clear-missing: Remove the missing status from the selected unit. + This allows engraving slabs for ghostly, but not yet + found, creatures. +:clear-ghostly: Remove the ghostly status from the selected unit and mark + it as dead. This allows getting rid of bugged ghosts + which do not show up in the engraving slab menu at all, + even after using clear-missing. It works, but is + potentially very dangerous - so use with care. Probably + (almost certainly) it does not have the same effects like + a proper burial. You've been warned. +:fixmigrant: Remove the resident/merchant flag from the selected unit. + Intended to fix bugged migrants/traders who stay at the + map edge and don't enter your fort. Only works for + dwarves (or generally the player's race in modded games). + Do NOT abuse this for 'real' caravan merchants (if you + really want to kidnap them, use 'tweak makeown' instead, + otherwise they will have their clothes set to forbidden etc). +:makeown: Force selected unit to become a member of your fort. + Can be abused to grab caravan merchants and escorts, even if + they don't belong to the player's race. Foreign sentients + (humans, elves) can be put to work, but you can't assign rooms + to them and they don't show up in DwarfTherapist because the + game treats them like pets. Grabbing draft animals from + a caravan can result in weirdness (animals go insane or berserk + and are not flagged as tame), but you are allowed to mark them + for slaughter. Grabbing wagons results in some funny spam, then + they are scuttled. tubefill ======== -Fills all the adamantine veins again. Veins that were empty will be filled in too, but might still trigger a demon invasion (this is a known bug). +Fills all the adamantine veins again. Veins that were empty will be filled in +too, but might still trigger a demon invasion (this is a known bug). digv ==== -Designates a whole vein for digging. Requires an active in-game cursor placed over a vein tile. With the 'x' option, it will traverse z-levels (putting stairs between the same-material tiles). +Designates a whole vein for digging. Requires an active in-game cursor placed +over a vein tile. With the 'x' option, it will traverse z-levels (putting stairs +between the same-material tiles). digvx ===== @@ -632,7 +918,11 @@ A permanent alias for 'digv x'. digl ==== -Designates layer stone for digging. Requires an active in-game cursor placed over a layer stone tile. With the 'x' option, it will traverse z-levels (putting stairs between the same-material tiles). With the 'undo' option it will remove the dig designation instead (if you realize that digging out a 50 z-level deep layer was not such a good idea after all). +Designates layer stone for digging. Requires an active in-game cursor placed +over a layer stone tile. With the 'x' option, it will traverse z-levels +(putting stairs between the same-material tiles). With the 'undo' option it +will remove the dig designation instead (if you realize that digging out a 50 +z-level deep layer was not such a good idea after all). diglx ===== @@ -745,9 +1035,9 @@ When the plugin is enabled, it protects all repeat jobs from removal. If they do disappear due to any cause, they are immediately re-added to their workshop and suspended. -In addition, when any constraints on item amounts are set, repeat jobs that produce -that kind of item are automatically suspended and resumed as the item amount -goes above or below the limit. The gap specifies how much below the limit +In addition, when any constraints on item amounts are set, repeat jobs that +produce that kind of item are automatically suspended and resumed as the item +amount goes above or below the limit. The gap specifies how much below the limit the amount has to drop before jobs are resumed; this is intended to reduce the frequency of jobs being toggled. @@ -790,12 +1080,14 @@ Make sure there are always 80-100 units of dimple dye. workflow amount POWDER_MISC//MUSHROOM_CUP_DIMPLE:MILL 100 20 - In order for this to work, you have to set the material of the PLANT input on - the Mill Plants job to MUSHROOM_CUP_DIMPLE using the 'job item-material' command. + In order for this to work, you have to set the material of the PLANT input + on the Mill Plants job to MUSHROOM_CUP_DIMPLE using the 'job item-material' + command. mapexport ========= -Export the current loaded map as a file. This will be eventually usable with visualizers. +Export the current loaded map as a file. This will be eventually usable +with visualizers. dwarfexport =========== @@ -808,13 +1100,19 @@ Helps a bit with managing activity zones (pens, pastures and pits) and cages. Options: -------- :set: Set zone or cage under cursor as default for future assigns. -:assign: Assign unit(s) to the pen or pit marked with the 'set' command. If no filters are set a unit must be selected in the in-game ui. Can also be followed by a valid zone id which will be set instead. +:assign: Assign unit(s) to the pen or pit marked with the 'set' command. + If no filters are set a unit must be selected in the in-game ui. + Can also be followed by a valid zone id which will be set + instead. :unassign: Unassign selected creature from it's zone. -:nick: Mass-assign nicknames, must be followed by the name you want to set. +:nick: Mass-assign nicknames, must be followed by the name you want + to set. :remnick: Mass-remove nicknames. :tocages: Assign unit(s) to cages inside a pasture. -:uinfo: Print info about unit(s). If no filters are set a unit must be selected in the in-game ui. -:zinfo: Print info about zone(s). If no filters are set zones under the cursor are listed. +:uinfo: Print info about unit(s). If no filters are set a unit must + be selected in the in-game ui. +:zinfo: Print info about zone(s). If no filters are set zones under + the cursor are listed. :verbose: Print some more info. :filters: Print list of valid filter options. :examples: Print some usage examples. @@ -823,20 +1121,28 @@ Options: Filters: -------- :all: Process all units (to be used with additional filters). -:count: Must be followed by a number. Process only n units (to be used with additional filters). +:count: Must be followed by a number. Process only n units (to be used + with additional filters). :unassigned: Not assigned to zone, chain or built cage. :minage: Minimum age. Must be followed by number. :maxage: Maximum age. Must be followed by number. -:race: Must be followed by a race raw id (e.g. BIRD_TURKEY, ALPACA etc). Negatable. +:race: Must be followed by a race RAW ID (e.g. BIRD_TURKEY, ALPACA, + etc). Negatable. :caged: In a built cage. Negatable. :own: From own civilization. Negatable. -:merchant: Is a merchant / belongs to a merchant. Should only be used for pitting, not for stealing animals (slaughter should work). +:merchant: Is a merchant / belongs to a merchant. Should only be used for + pitting, not for stealing animals (slaughter should work). :war: Trained war creature. Negatable. :hunting: Trained hunting creature. Negatable. :tamed: Creature is tame. Negatable. -:trained: Creature is trained. Finds war/hunting creatures as well as creatures who have a training level greater than 'domesticated'. If you want to specifically search for war/hunting creatures use 'war' or 'hunting' Negatable. -:trainablewar: Creature can be trained for war (and is not already trained for war/hunt). Negatable. -:trainablehunt: Creature can be trained for hunting (and is not already trained for war/hunt). Negatable. +:trained: Creature is trained. Finds war/hunting creatures as well as + creatures who have a training level greater than 'domesticated'. + If you want to specifically search for war/hunting creatures use + 'war' or 'hunting' Negatable. +:trainablewar: Creature can be trained for war (and is not already trained for + war/hunt). Negatable. +:trainablehunt: Creature can be trained for hunting (and is not already trained + for war/hunt). Negatable. :male: Creature is male. Negatable. :female: Creature is female. Negatable. :egglayer: Race lays eggs. Negatable. @@ -845,26 +1151,61 @@ Filters: Usage with single units ----------------------- -One convenient way to use the zone tool is to bind the command 'zone assign' to a hotkey, maybe also the command 'zone set'. Place the in-game cursor over a pen/pasture or pit, use 'zone set' to mark it. Then you can select units on the map (in 'v' or 'k' mode), in the unit list or from inside cages and use 'zone assign' to assign them to their new home. Allows pitting your own dwarves, by the way. +One convenient way to use the zone tool is to bind the command 'zone assign' to +a hotkey, maybe also the command 'zone set'. Place the in-game cursor over +a pen/pasture or pit, use 'zone set' to mark it. Then you can select units +on the map (in 'v' or 'k' mode), in the unit list or from inside cages +and use 'zone assign' to assign them to their new home. Allows pitting your +own dwarves, by the way. Usage with filters ------------------ -All filters can be used together with the 'assign' command. Restrictions: It's not possible to assign units who are inside built cages or chained because in most cases that won't be desirable anyways. It's not possible to cage owned pets because in that case the owner uncages them after a while which results in infinite hauling back and forth. Usually you should always use the filter 'own' (which implies tame) unless you want to use the zone tool for pitting hostiles. 'own' ignores own dwarves unless you specify 'race DWARF' (so it's safe to use 'assign all own' to one big pasture if you want to have all your animals at the same place). 'egglayer' and 'milkable' should be used together with 'female' unless you have a mod with egg-laying male elves who give milk or whatever. Merchants and their animals are ignored unless you specify 'merchant' (pitting them should be no problem, but stealing and pasturing their animals is not a good idea since currently they are not properly added to your own stocks; slaughtering them should work). Most filters can be negated (e.g. 'not grazer' -> race is not a grazer). +All filters can be used together with the 'assign' command. + +Restrictions: It's not possible to assign units who are inside built cages +or chained because in most cases that won't be desirable anyways. +It's not possible to cage owned pets because in that case the owner +uncages them after a while which results in infinite hauling back and forth. + +Usually you should always use the filter 'own' (which implies tame) unless you +want to use the zone tool for pitting hostiles. 'own' ignores own dwarves unless +you specify 'race DWARF' (so it's safe to use 'assign all own' to one big +pasture if you want to have all your animals at the same place). 'egglayer' and +'milkable' should be used together with 'female' unless you have a mod with +egg-laying male elves who give milk or whatever. Merchants and their animals are +ignored unless you specify 'merchant' (pitting them should be no problem, +but stealing and pasturing their animals is not a good idea since currently they +are not properly added to your own stocks; slaughtering them should work). + +Most filters can be negated (e.g. 'not grazer' -> race is not a grazer). Mass-renaming ------------- -Using the 'nick' command you can set the same nickname for multiple units. If used without 'assign', 'all' or 'count' it will rename all units in the current default target zone. Combined with 'assign', 'all' or 'count' (and further optional filters) it will rename units matching the filter conditions. +Using the 'nick' command you can set the same nickname for multiple units. +If used without 'assign', 'all' or 'count' it will rename all units in the +current default target zone. Combined with 'assign', 'all' or 'count' (and +further optional filters) it will rename units matching the filter conditions. Cage zones ---------- -Using the 'tocages' command you can assign units to a set of cages, for example a room next to your butcher shop(s). They will be spread evenly among available cages to optimize hauling to and butchering from them. For this to work you need to build cages and then place one pen/pasture activity zone above them, covering all cages you want to use. Then use 'zone set' (like with 'assign') and use 'zone tocages filter1 filter2 ...'. 'tocages' overwrites 'assign' because it would make no sense, but can be used together with 'nick' or 'remnick' and all the usual filters. +Using the 'tocages' command you can assign units to a set of cages, for example +a room next to your butcher shop(s). They will be spread evenly among available +cages to optimize hauling to and butchering from them. For this to work you need +to build cages and then place one pen/pasture activity zone above them, covering +all cages you want to use. Then use 'zone set' (like with 'assign') and use +'zone tocages filter1 filter2 ...'. 'tocages' overwrites 'assign' because it +would make no sense, but can be used together with 'nick' or 'remnick' and all +the usual filters. Examples -------- ``zone assign all own ALPACA minage 3 maxage 10`` - Assign all own alpacas who are between 3 and 10 years old to the selected pasture. + Assign all own alpacas who are between 3 and 10 years old to the selected + pasture. ``zone assign all own caged grazer nick ineedgrass`` - Assign all own grazers who are sitting in cages on stockpiles (e.g. after buying them from merchants) to the selected pasture and give them the nickname 'ineedgrass'. + Assign all own grazers who are sitting in cages on stockpiles (e.g. after + buying them from merchants) to the selected pasture and give them + the nickname 'ineedgrass'. ``zone assign all own not grazer not race CAT`` Assign all own animals who are not grazers, excluding cats. ``zone assign count 5 own female milkable`` @@ -872,48 +1213,93 @@ Examples ``zone assign all own race DWARF maxage 2`` Throw all useless kids into a pit :) ``zone nick donttouchme`` - Nicknames all units in the current default zone or cage to 'donttouchme'. Mostly intended to be used for special pastures or cages which are not marked as rooms you want to protect from autobutcher. + Nicknames all units in the current default zone or cage to 'donttouchme'. + Mostly intended to be used for special pastures or cages which are not marked + as rooms you want to protect from autobutcher. ``zone tocages count 50 own tame male not grazer`` - Stuff up to 50 owned tame male animals who are not grazers into cages built on the current default zone. + Stuff up to 50 owned tame male animals who are not grazers into cages built + on the current default zone. autonestbox =========== -Assigns unpastured female egg-layers to nestbox zones. Requires that you create pen/pasture zones above nestboxes. If the pen is bigger than 1x1 the nestbox must be in the top left corner. Only 1 unit will be assigned per pen, regardless of the size. The age of the units is currently not checked, most birds grow up quite fast. Egglayers who are also grazers will be ignored, since confining them to a 1x1 pasture is not a good idea. Only tame and domesticated own units are processed since pasturing half-trained wild egglayers could destroy your neat nestbox zones when they revert to wild. When called without options autonestbox will instantly run once. +Assigns unpastured female egg-layers to nestbox zones. Requires that you create +pen/pasture zones above nestboxes. If the pen is bigger than 1x1 the nestbox +must be in the top left corner. Only 1 unit will be assigned per pen, regardless +of the size. The age of the units is currently not checked, most birds grow up +quite fast. Egglayers who are also grazers will be ignored, since confining them +to a 1x1 pasture is not a good idea. Only tame and domesticated own units are +processed since pasturing half-trained wild egglayers could destroy your neat +nestbox zones when they revert to wild. When called without options autonestbox +will instantly run once. Options: -------- -:start: Start running every X frames (df simulation ticks). Default: X=6000, which would be every 60 seconds at 100fps. +:start: Start running every X frames (df simulation ticks). + Default: X=6000, which would be every 60 seconds at 100fps. :stop: Stop running automatically. -:sleep: Must be followed by number X. Changes the timer to sleep X frames between runs. +:sleep: Must be followed by number X. Changes the timer to sleep X + frames between runs. autobutcher =========== -Assigns lifestock for slaughter once it reaches a specific count. Requires that you add the target race(s) to a watch list. Only tame units will be processed. Named units will be completely ignored (to protect specific animals fro autobutcher you can give them nicknames with the tool 'rename unit' for single units or with 'zone nick' to mass-rename units in pastures and cages). Creatures trained for war or hunting will be ignored as well. Creatures assigned to cages will be ignored if the cage is defined as a room (to avoid butchering unnamed zoo animals). Once you have too much adults, the oldest will be butchered first. Once you have too much kids, the youngest will be butchered first. If you don't set any target count the following default will be used: 1 male kid, 5 female kids, 1 male adult, 5 female adults. +Assigns lifestock for slaughter once it reaches a specific count. Requires that +you add the target race(s) to a watch list. Only tame units will be processed. + +Named units will be completely ignored (to protect specific animals from +autobutcher you can give them nicknames with the tool 'rename unit' for single +units or with 'zone nick' to mass-rename units in pastures and cages). + +Creatures trained for war or hunting will be ignored as well. + +Creatures assigned to cages will be ignored if the cage is defined as a room +(to avoid butchering unnamed zoo animals). + +Once you have too much adults, the oldest will be butchered first. +Once you have too much kids, the youngest will be butchered first. +If you don't set any target count the following default will be used: +1 male kid, 5 female kids, 1 male adult, 5 female adults. Options: -------- -:start: Start running every X frames (df simulation ticks). Default: X=6000, which would be every 60 seconds at 100fps. +:start: Start running every X frames (df simulation ticks). + Default: X=6000, which would be every 60 seconds at 100fps. :stop: Stop running automatically. -:sleep: Must be followed by number X. Changes the timer to sleep X frames between runs. -:watch R: Start watching a race. R can be a valid race RAW id (ALPACA, BIRD_TURKEY, etc) or a list of ids seperated by spaces or the keyword 'all' which affects all races on your current watchlist. -:unwatch R: Stop watching race(s). The current target settings will be remembered. R can be a list of ids or the keyword 'all'. -:forget R: Stop watching race(s) and forget it's/their target settings. R can be a list of ids or the keyword 'all'. -:autowatch: Automatically adds all new races (animals you buy from merchants, tame yourself or get from migrants) - to the watch list using default target count. +:sleep: Must be followed by number X. Changes the timer to sleep + X frames between runs. +:watch R: Start watching a race. R can be a valid race RAW id (ALPACA, + BIRD_TURKEY, etc) or a list of ids seperated by spaces or + the keyword 'all' which affects all races on your current + watchlist. +:unwatch R: Stop watching race(s). The current target settings will be + remembered. R can be a list of ids or the keyword 'all'. +:forget R: Stop watching race(s) and forget it's/their target settings. + R can be a list of ids or the keyword 'all'. +:autowatch: Automatically adds all new races (animals you buy from merchants, + tame yourself or get from migrants) to the watch list using + default target count. :noautowatch: Stop auto-adding new races to the watchlist. :list: Print the current status and watchlist. -:list_export: Print status and watchlist in a format which can be used to import them to another savegame (see notes). +:list_export: Print status and watchlist in a format which can be used + to import them to another savegame (see notes). :target fk mk fa ma R: Set target count for specified race(s). fk = number of female kids, mk = number of male kids, fa = number of female adults, ma = number of female adults. - R can be a list of ids or the keyword 'all' or 'new'. R = 'all': change target count for all races on watchlist and set the new default for the future. R = 'new': don't touch current settings on the watchlist, only set the new default for future entries. + R can be a list of ids or the keyword 'all' or 'new'. + R = 'all': change target count for all races on watchlist + and set the new default for the future. R = 'new': don't touch + current settings on the watchlist, only set the new default + for future entries. :example: Print some usage examples. Examples: --------- -You want to keep max 7 kids (4 female, 3 male) and max 3 adults (2 female, 1 male) of the race alpaca. Once the kids grow up the oldest adults will get slaughtered. Excess kids will get slaughtered starting with the youngest to allow that the older ones grow into adults. Any unnamed cats will be slaughtered as soon as possible. +You want to keep max 7 kids (4 female, 3 male) and max 3 adults (2 female, +1 male) of the race alpaca. Once the kids grow up the oldest adults will get +slaughtered. Excess kids will get slaughtered starting with the youngest +to allow that the older ones grow into adults. Any unnamed cats will +be slaughtered as soon as possible. :: autobutcher target 4 3 2 1 ALPACA BIRD_TURKEY @@ -921,21 +1307,30 @@ You want to keep max 7 kids (4 female, 3 male) and max 3 adults (2 female, 1 mal autobutcher watch ALPACA BIRD_TURKEY CAT autobutcher start -Automatically put all new races onto the watchlist and mark unnamed tame units for slaughter as soon as they arrive in your fort. Settings already made for specific races will be left untouched. +Automatically put all new races onto the watchlist and mark unnamed tame units +for slaughter as soon as they arrive in your fort. Settings already made +for specific races will be left untouched. :: autobutcher target 0 0 0 0 new autobutcher autowatch autobutcher start -Stop watching the races alpaca and cat, but remember the target count settings so that you can use 'unwatch' without the need to enter the values again. Note: 'autobutcher unwatch all' works, but only makes sense if you want to keep the plugin running with the 'autowatch' feature or manually add some new races with 'watch'. If you simply want to stop it completely use 'autobutcher stop' instead. +Stop watching the races alpaca and cat, but remember the target count +settings so that you can use 'unwatch' without the need to enter the +values again. Note: 'autobutcher unwatch all' works, but only makes sense +if you want to keep the plugin running with the 'autowatch' feature or manually +add some new races with 'watch'. If you simply want to stop it completely use +'autobutcher stop' instead. :: autobutcher unwatch ALPACA CAT Note: ----- -Settings and watchlist are stored in the savegame, so that you can have different settings for each world. If you want to copy your watchlist to another savegame you can use the command list_export: +Settings and watchlist are stored in the savegame, so that you can have +different settings for each world. If you want to copy your watchlist to +another savegame you can use the command list_export: :: Load savegame where you made the settings. @@ -943,3 +1338,19 @@ Settings and watchlist are stored in the savegame, so that you can have differen dfhack-run autobutcher list_export > autobutcher.bat Load the savegame where you want to copy the settings to, run the batch file (from the shell): autobutcher.bat + + +autolabor +========= +Automatically manage dwarf labors. + +When enabled, autolabor periodically checks your dwarves and enables or +disables labors. It tries to keep as many dwarves as possible busy but +also tries to have dwarves specialize in specific skills. + +.. note:: + + Warning: autolabor will override any manual changes you make to labors + while it is enabled. + +For detailed usage information, see 'help autolabor'. diff --git a/Readme.html b/Readme.html index 4e1a06eb1..49ddb1984 100644 --- a/Readme.html +++ b/Readme.html @@ -318,7 +318,7 @@ ul.auto-toc {
    -

    Introduction

    +

    Introduction

    DFHack is a Dwarf Fortress memory access library and a set of basic tools that use it. Tools come in the form of plugins or (not yet) external tools. It is an attempt to unite the various ways tools @@ -326,190 +326,219 @@ access DF memory and allow for easier development of new tools.

    Contents

    -

    Getting DFHack

    +

    Getting DFHack

    The project is currently hosted on github, for both source and binaries at http://github.com/peterix/dfhack

    Releases can be downloaded from here: https://github.com/peterix/dfhack/downloads

    All new releases are announced in the bay12 thread: http://tinyurl.com/dfhack-ng

    -

    Compatibility

    +

    Compatibility

    DFHack works on Windows XP, Vista, 7 or any modern Linux distribution. OSX is not supported due to lack of developers with a Mac.

    Currently, only versions 0.34.06 and 0.34.07 are supported. If you need DFHack @@ -518,7 +547,7 @@ for older versions, look for older releases.

    It is possible to use the Windows DFHack under wine/OSX.

    -

    Installation/Removal

    +

    Installation/Removal

    Installing DFhack involves copying files into your DF folder. Copy the files from a release archive so that:

    @@ -530,41 +559,67 @@ Copy the files from a release archive so that:

    Uninstalling is basically the same, in reverse:

      -
    • On Windows, first delete SDL.dll and rename SDLreal.dll to SDL.dll. Then remove the other DFHack files
    • +
    • On Windows, first delete SDL.dll and rename SDLreal.dll to SDL.dll. Then +remove the other DFHack files
    • On Linux, Remove the DFHack files.

    The stonesense plugin might require some additional libraries on Linux.

    -

    If any of the plugins or dfhack itself refuses to load, check the stderr.log file created in your DF folder.

    +

    If any of the plugins or dfhack itself refuses to load, check the stderr.log +file created in your DF folder.

    -

    Using DFHack

    -

    DFHack basically extends what DF can do with something similar to the drop-down console found in Quake engine games. On Windows, this is a separate command line window. On linux, the terminal used to launch the dfhack script is taken over (so, make sure you start from a terminal). -Basic interaction with dfhack involves entering commands into the console. For some basic instroduction, use the 'help' command. To list all possible commands, use the 'ls' command. -Many commands have their own help or detailed description. You can use 'command help' or 'command ?' to show that.

    -

    The command line has some nice line editing capabilities, including history that's preserved between different runs of DF (use up/down keys to go through the history).

    -

    The second way to interact with DFHack is to bind the available commands to in-game hotkeys. The old way to do this is via the hotkey/zoom menu (normally opened with the 'h' key). Binding the commands is done by assigning a command as a hotkey name (with 'n').

    -

    A new and more flexible way is the keybinding command in the dfhack console. However, bindings created this way are not automatically remembered between runs of the game, so it becomes necessary to use the dfhack.init file to ensure that they are re-created every time it is loaded.

    +

    Using DFHack

    +

    DFHack basically extends what DF can do with something similar to the drop-down +console found in Quake engine games. On Windows, this is a separate command line +window. On linux, the terminal used to launch the dfhack script is taken over +(so, make sure you start from a terminal). Basic interaction with dfhack +involves entering commands into the console. For some basic instroduction, +use the 'help' command. To list all possible commands, use the 'ls' command. +Many commands have their own help or detailed description. You can use +'command help' or 'command ?' to show that.

    +

    The command line has some nice line editing capabilities, including history +that's preserved between different runs of DF (use up/down keys to go through +the history).

    +

    The second way to interact with DFHack is to bind the available commands +to in-game hotkeys. The old way to do this is via the hotkey/zoom menu (normally +opened with the 'h' key). Binding the commands is done by assigning a command as +a hotkey name (with 'n').

    +

    A new and more flexible way is the keybinding command in the dfhack console. +However, bindings created this way are not automatically remembered between runs +of the game, so it becomes necessary to use the dfhack.init file to ensure that +they are re-created every time it is loaded.

    Interactive commands like 'liquids' cannot be used as hotkeys.

    Most of the commands come from plugins. Those reside in 'hack/plugins/'.

    -

    Something doesn't work, help!

    -

    First, don't panic :) Second, dfhack keeps a few log files in DF's folder - stderr.log and stdout.log. You can look at those and possibly find out what's happening. -If you found a bug, you can either report it in the bay12 DFHack thread, the issues tracker on github, contact me (peterix@gmail.com) or visit the #dfhack IRC channel on freenode.

    +

    Something doesn't work, help!

    +

    First, don't panic :) Second, dfhack keeps a few log files in DF's folder +- stderr.log and stdout.log. You can look at those and possibly find out what's +happening. +If you found a bug, you can either report it in the bay12 DFHack thread, +the issues tracker on github, contact me (peterix@gmail.com) or visit the +#dfhack IRC channel on freenode.

    -

    The init file

    -

    If your DF folder contains a file named dfhack.init, its contents will be run every time you start DF. This allows setting up keybindings. An example file is provided as dfhack.init-example - you can tweak it and rename to dfhack.init if you want to use this functionality.

    +

    The init file

    +

    If your DF folder contains a file named dfhack.init, its contents will be run +every time you start DF. This allows setting up keybindings. An example file +is provided as dfhack.init-example - you can tweak it and rename to dfhack.init +if you want to use this functionality.

    -

    Commands

    -

    Almost all the commands support using the 'help <command-name>' built-in command to retrieve further help without having to look at this document. Alternatively, some accept a 'help'/'?' option on their command line.

    +

    Commands

    +

    Almost all the commands support using the 'help <command-name>' built-in command +to retrieve further help without having to look at this document. Alternatively, +some accept a 'help'/'?' option on their command line.

    -

    adv-bodyswap

    -

    This allows taking control over your followers and other creatures in adventure mode. For example, you can make them pick up new arms and armor and equip them properly.

    +

    adv-bodyswap

    +

    This allows taking control over your followers and other creatures in adventure +mode. For example, you can make them pick up new arms and armor and equip them +properly.

    -

    Usage

    +

    Usage

    • When viewing unit details, body-swaps into that unit.
    • @@ -574,40 +629,65 @@ If you found a bug, you can either report it in the bay12 DFHack thread, the iss
    -

    advtools

    +

    advtools

    A package of different adventure mode tools (currently just one)

    -

    Usage

    +

    Usage

    - + + + +
    list-equipped [all]:
     List armor and weapons equipped by your companions. If all is specified, also lists non-metal clothing.
     List armor and weapons equipped by your companions. +If all is specified, also lists non-metal clothing.
    metal-detector [all-types] [non-trader]:
     Reveal metal armor and weapons in +shops. The options disable the checks +on item type and being in shop.
    -

    changelayer

    -

    Changes material of the geology layer under cursor to the specified inorganic RAW material. Can have impact on all surrounding regions, not only your embark! By default changing stone to soil and vice versa is not allowed. By default changes only the layer at the cursor position. Note that one layer can stretch across lots of z levels. By default changes only the geology which is linked to the biome under the cursor. That geology might be linked to other biomes as well, though. Mineral veins and gem clusters will stay on the map. Use 'changevein' for them. -tl;dr: You will end up with changing quite big areas in one go, especially if you use it in lower z levels. Use with care.

    +

    changelayer

    +

    Changes material of the geology layer under cursor to the specified inorganic +RAW material. Can have impact on all surrounding regions, not only your embark! +By default changing stone to soil and vice versa is not allowed. By default +changes only the layer at the cursor position. Note that one layer can stretch +across lots of z levels. By default changes only the geology which is linked +to the biome under the cursor. That geology might be linked to other biomes +as well, though. Mineral veins and gem clusters will stay on the map. Use +'changevein' for them.

    +

    tl;dr: You will end up with changing quite big areas in one go, especially if +you use it in lower z levels. Use with care.

    -

    Options

    +

    Options

    - - - - +Result may be undesirable since the same layer can AND WILL +be on different z-levels for different biomes. Use the tool +'probe' to get an idea how layers and biomes are distributed +on your map. + + + + @@ -617,7 +697,7 @@ Note that stone will not be magically replaced with soil. You will, however, get
    all_biomes:Change selected layer for all biomes on your map. -Result may be undesirable since the same layer can AND WILL be on different z-levels for different biomes. Use the tool 'probe' to get an idea how layers and biomes are distributed on your map.
    all_layers:Change all layers on your map (only for the selected biome unless 'all_biomes' is added). -Candy mountain, anyone? Will make your map quite boring, but tidy.
    force:Allow changing stone to soil and vice versa. !!THIS CAN HAVE WEIRD EFFECTS, USE WITH CARE!! -Note that soil will not be magically replaced with stone. You will, however, get a stone floor after digging so it will allow the floor to be engraved. -Note that stone will not be magically replaced with soil. You will, however, get a soil floor after digging so it could be helpful for creating farm plots on maps with no soil.
    all_layers:Change all layers on your map (only for the selected biome +unless 'all_biomes' is added). +Candy mountain, anyone? Will make your map quite boring, +but tidy.
    force:Allow changing stone to soil and vice versa. !!THIS CAN HAVE +WEIRD EFFECTS, USE WITH CARE!! +Note that soil will not be magically replaced with stone. +You will, however, get a stone floor after digging so it +will allow the floor to be engraved. +Note that stone will not be magically replaced with soil. +You will, however, get a soil floor after digging so it +could be helpful for creating farm plots on maps with no +soil.
    verbose:Give some details about what is being changed.
    -

    Examples:

    +

    Examples:

    changelayer GRANITE
    Convert layer at cursor position into granite.
    @@ -629,18 +709,28 @@ Note that stone will not be magically replaced with soil. You will, however, get

    Note

      -
    • If you use changelayer and nothing happens, try to pause/unpause the game for a while and try to move the cursor to another tile. Then try again. If that doesn't help try temporarily changing some other layer, undo your changes and try again for the layer you want to change. Saving and reloading your map might also help.
    • -
    • You should be fine if you only change single layers without the use of 'force'. Still it's advisable to save your game before messing with the map.
    • -
    • When you force changelayer to convert soil to stone you might experience weird stuff (flashing tiles, tiles changed all over place etc). Try reverting the changes manually or even better use an older savegame. You did save your game, right?
    • +
    • If you use changelayer and nothing happens, try to pause/unpause the game +for a while and try to move the cursor to another tile. Then try again. +If that doesn't help try temporarily changing some other layer, undo your +changes and try again for the layer you want to change. Saving +and reloading your map might also help.
    • +
    • You should be fine if you only change single layers without the use +of 'force'. Still it's advisable to save your game before messing with +the map.
    • +
    • When you force changelayer to convert soil to stone you might experience +weird stuff (flashing tiles, tiles changed all over place etc). +Try reverting the changes manually or even better use an older savegame. +You did save your game, right?
    -

    changevein

    -

    Changes material of the vein under cursor to the specified inorganic RAW material.

    +

    changevein

    +

    Changes material of the vein under cursor to the specified inorganic RAW +material.

    -

    Example:

    +

    Example:

    changevein NATIVE_PLATINUM
    Convert vein at cursor position into platinum ore.
    @@ -648,17 +738,25 @@ Note that stone will not be magically replaced with soil. You will, however, get
    -

    changeitem

    -

    Allows changing item material and base quality. By default the item currently selected in the UI will be changed (you can select items in the 'k' list or inside containers/inventory). By default change is only allowed if materials is of the same subtype (for example wood<->wood, stone<->stone etc). But since some transformations work pretty well and may be desired you can override this with 'force'. Note that some attributes will not be touched, possibly resulting in weirdness. To get an idea how the RAW id should look like, check some items with 'info'. Using 'force' might create items which are not touched by crafters/haulers.

    +

    changeitem

    +

    Allows changing item material and base quality. By default the item currently +selected in the UI will be changed (you can select items in the 'k' list +or inside containers/inventory). By default change is only allowed if materials +is of the same subtype (for example wood<->wood, stone<->stone etc). But since +some transformations work pretty well and may be desired you can override this +with 'force'. Note that some attributes will not be touched, possibly resulting +in weirdness. To get an idea how the RAW id should look like, check some items +with 'info'. Using 'force' might create items which are not touched by +crafters/haulers.

    -

    Options

    +

    Options

    - + @@ -670,7 +768,7 @@ Note that stone will not be magically replaced with soil. You will, however, get
    info:Don't change anything, print some info instead.
    here:Change all items at the cursor position. Requires in-game curser.
    here:Change all items at the cursor position. Requires in-game cursor.
    material, m:Change material. Must be followed by valid material RAW id.
    -

    Examples:

    +

    Examples:

    changeitem m INORGANIC:GRANITE here
    Change material of all items under the cursor to granite.
    @@ -680,24 +778,31 @@ Note that stone will not be magically replaced with soil. You will, however, get
    -

    cursecheck

    -

    Checks a single map tile or the whole map/world for cursed creatures (ghosts, vampires, necromancers, werebeasts, zombies). -With an active in-game cursor only the selected tile will be observed. Without a cursor the whole map will be checked. -By default cursed creatures will be only counted in case you just want to find out if you have any of them running around in your fort. -By default dead and passive creatures (ghosts who were put to rest, killed vampires, ...) are ignored. -Undead skeletons, corpses, bodyparts and the like are all thrown into the curse category "zombie". -Anonymous zombies and resurrected body parts will show as "unnamed creature".

    +

    cursecheck

    +

    Checks a single map tile or the whole map/world for cursed creatures (ghosts, +vampires, necromancers, werebeasts, zombies).

    +

    With an active in-game cursor only the selected tile will be observed. +Without a cursor the whole map will be checked.

    +

    By default cursed creatures will be only counted in case you just want to find +out if you have any of them running around in your fort. Dead and passive +creatures (ghosts who were put to rest, killed vampires, ...) are ignored. +Undead skeletons, corpses, bodyparts and the like are all thrown into the curse +category "zombie". Anonymous zombies and resurrected body parts will show +as "unnamed creature".

    -

    Options

    +

    Options

    - + - + - + @@ -705,28 +810,38 @@ Anonymous zombies and resurrected body parts will show as "unnamed creature
    detail:Print full name, date of birth, date of curse and some status info (some vampires might use fake identities in-game, though).
    detail:Print full name, date of birth, date of curse and some status +info (some vampires might use fake identities in-game, though).
    nick:Set the type of curse as nickname (does not always show up in-game, some vamps don't like nicknames).
    nick:Set the type of curse as nickname (does not always show up +in-game, some vamps don't like nicknames).
    all:Include dead and passive cursed creatures (can result in a quite long list after having FUN with necromancers).
    all:Include dead and passive cursed creatures (can result in a quite +long list after having FUN with necromancers).
    verbose:Print all curse tags (if you really want to know it all).
    -

    Examples:

    +

    Examples:

    cursecheck detail all
    -
    Give detailed info about all cursed creatures including deceased ones (no in-game cursor).
    +
    Give detailed info about all cursed creatures including deceased ones (no +in-game cursor).
    cursecheck nick
    -
    Give a nickname all living/active cursed creatures on the map(no in-game cursor).
    +
    Give a nickname all living/active cursed creatures on the map(no in-game +cursor).

    Note

      -
    • If you do a full search (with the option "all") former ghosts will show up with the cursetype "unknown" because their ghostly flag is not set anymore. But if you happen to find a living/active creature with cursetype "unknown" please report that in the dfhack thread on the modding forum or per irc. This is likely to happen with mods which introduce new types of curses, for example.
    • +
    • If you do a full search (with the option "all") former ghosts will show up +with the cursetype "unknown" because their ghostly flag is not set +anymore. But if you happen to find a living/active creature with cursetype +"unknown" please report that in the dfhack thread on the modding forum or +per irc. This is likely to happen with mods which introduce new types +of curses, for example.
    -

    follow

    -

    Makes the game view follow the currently highlighted unit after you exit from current menu/cursor mode. Handy for watching dwarves running around. Deactivated by moving the view manually.

    +

    follow

    +

    Makes the game view follow the currently highlighted unit after you exit from +current menu/cursor mode. Handy for watching dwarves running around. Deactivated +by moving the view manually.

    -

    forcepause

    -

    Forces DF to pause. This is useful when your FPS drops below 1 and you lose control of the game.

    +

    forcepause

    +

    Forces DF to pause. This is useful when your FPS drops below 1 and you lose +control of the game.

    • Activate with 'forcepause 1'
    • @@ -735,23 +850,23 @@ Anonymous zombies and resurrected body parts will show as "unnamed creature
    -

    nopause

    -

    Disables pausing (both manual and automatic) with the exception of pause forced by 'reveal hell'. -This is nice for digging under rivers.

    +

    nopause

    +

    Disables pausing (both manual and automatic) with the exception of pause forced +by 'reveal hell'. This is nice for digging under rivers.

    -

    die

    +

    die

    Instantly kills DF without saving.

    -

    autodump

    +

    autodump

    This utility lets you quickly move all items designated to be dumped. Items are instantly moved to the cursor position, the dump flag is unset, and the forbid flag is set, as if it had been dumped normally. Be aware that any active dump item tasks still point at the item.

    Cursor must be placed on a floor tile so the items can be dumped there.

    -

    Options

    +

    Options

    @@ -771,20 +886,89 @@ Be aware that any active dump item tasks still point at the item.

    -

    autodump-destroy-here

    -

    Destroy items marked for dumping under cursor. Identical to autodump destroy-here, but intended for use as keybinding.

    +

    autodump-destroy-here

    +

    Destroy items marked for dumping under cursor. Identical to autodump +destroy-here, but intended for use as keybinding.

    -

    autodump-destroy-item

    -

    Destroy the selected item. The item may be selected in the 'k' list, or inside a container. If called again before the game is resumed, cancels destroy.

    +

    autodump-destroy-item

    +

    Destroy the selected item. The item may be selected in the 'k' list, or inside +a container. If called again before the game is resumed, cancels destroy.

    +
    +
    +

    burrow

    +

    Miscellaneous burrow control. Allows manipulating burrows and automated burrow +expansion while digging.

    +
    +++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    enable feature ...:
     
    disable feature ...:
     Enable or Disable features of the plugin.
    clear-unit burrow burrow ...:
     
    clear-tiles burrow burrow ...:
     Removes all units or tiles from the burrows.
    set-units target-burrow src-burrow ...:
     
    add-units target-burrow src-burrow ...:
     
    remove-units target-burrow src-burrow ...:
     Adds or removes units in source +burrows to/from the target burrow. Set is equivalent to clear and add.
    set-tiles target-burrow src-burrow ...:
     
    add-tiles target-burrow src-burrow ...:
     
    remove-tiles target-burrow src-burrow ...:
     Adds or removes tiles in source +burrows to/from the target burrow. In place of a source burrow it is +possible to use one of the following keywords: ABOVE_GROUND, +SUBTERRANEAN, INSIDE, OUTSIDE, LIGHT, DARK, HIDDEN, REVEALED
    +
    +
    +

    Features

    + +++ + + + +
    auto-grow:When a wall inside a burrow with a name ending in '+' is dug +out, the burrow is extended to newly-revealed adjacent walls. +This final '+' may be omitted in burrow name args of commands above. +Digging 1-wide corridors with the miner inside the burrow is SLOW.
    +
    +
    +
    +

    catsplosion

    +

    Makes cats just multiply. It is not a good idea to run this more than once or +twice.

    -

    clean

    -

    Cleans all the splatter that get scattered all over the map, items and creatures. -In an old fortress, this can significantly reduce FPS lag. It can also spoil your -!!FUN!!, so think before you use it.

    -
    -

    Options

    +

    clean

    +

    Cleans all the splatter that get scattered all over the map, items and +creatures. In an old fortress, this can significantly reduce FPS lag. It can +also spoil your !!FUN!!, so think before you use it.

    +
    +

    Options

    @@ -799,7 +983,7 @@ In an old fortress, this can significantly reduce FPS lag. It can also spoil you
    -

    Extra options for 'map'

    +

    Extra options for 'map'

    @@ -813,15 +997,16 @@ In an old fortress, this can significantly reduce FPS lag. It can also spoil you
    -

    spotclean

    -

    Works like 'clean map snow mud', but only for the tile under the cursor. Ideal if you want to keep that bloody entrance 'clean map' would clean up.

    +

    spotclean

    +

    Works like 'clean map snow mud', but only for the tile under the cursor. Ideal +if you want to keep that bloody entrance 'clean map' would clean up.

    -

    cleanowned

    -

    Confiscates items owned by dwarfs. -By default, owned food on the floor and rotten items are confistacted and dumped.

    -
    -

    Options

    +

    cleanowned

    +

    Confiscates items owned by dwarfs. By default, owned food on the floor +and rotten items are confistacted and dumped.

    +
    @@ -834,21 +1019,22 @@ By default, owned food on the floor and rotten items are confistacted and dumped - +
    X:confiscate/dump items with wear level 'X' and more
    dryrun:a dry run. combine with other options to see what will happen without it actually happening.
    dryrun:a dry run. combine with other options to see what will happen +without it actually happening.
    -
    -

    Example:

    +
    +

    Example:

    cleanowned scattered X : This will confiscate rotten and dropped food, garbage on the floors and any worn items with 'X' damage and above.

    -

    colonies

    +

    colonies

    Allows listing all the vermin colonies on the map and optionally turning them into honey bee colonies.

    -
    -

    Options

    +
    +

    Options

    @@ -860,30 +1046,16 @@ By default, owned food on the floor and rotten items are confistacted and dumped
    -

    deramp (by zilpin)

    +

    deramp (by zilpin)

    Removes all ramps designated for removal from the map. This is useful for replicating the old channel digging designation. It also removes any and all 'down ramps' that can remain after a cave-in (you don't have to designate anything for that to happen).

    -
    -

    df2minecraft

    -

    This generates a minecraft world out of the currently loaded fortress. -Generated worlds are placed into your DF folder, named "World #".

    -
    -

    Warning

    -
      -
    • This is experimental! It will cause crashes.
    • -
    • If it works, the process takes quite a while to complete.
    • -
    • Do not use if you have any unsaved progress!
    • -
    • Non-square embarks are exported wrong. It's a known bug.
    • -
    -
    -
    -

    dfusion

    +

    dfusion

    This is the DFusion lua plugin system by warmist/darius, running as a DFHack plugin.

    See the bay12 thread for details: http://www.bay12forums.com/smf/index.php?topic=69682.15

    @@ -903,11 +1075,11 @@ Generated worlds are placed into your DF folder, named "World #".

    -

    drybuckets

    +

    drybuckets

    This utility removes water from all buckets in your fortress, allowing them to be safely used for making lye.

    -

    fastdwarf

    +

    fastdwarf

    Makes your minions move at ludicrous speeds.

      @@ -917,14 +1089,16 @@ Generated worlds are placed into your DF folder, named "World #".

    -

    feature

    +

    feature

    Enables management of map features.

      -
    • Discovering a magma feature (magma pool, volcano, magma sea, or curious underground structure) permits magma workshops and furnaces to be built.
    • -
    • Discovering a cavern layer causes plants (trees, shrubs, and grass) from that cavern to grow within your fortress.
    • +
    • Discovering a magma feature (magma pool, volcano, magma sea, or curious +underground structure) permits magma workshops and furnaces to be built.
    • +
    • Discovering a cavern layer causes plants (trees, shrubs, and grass) from +that cavern to grow within your fortress.
    -
    @@ -940,10 +1114,10 @@ Generated worlds are placed into your DF folder, named "World #".

    -

    filltraffic

    +

    filltraffic

    Set traffic designations using flood-fill starting at the cursor.

    @@ -960,7 +1134,7 @@ Generated worlds are placed into your DF folder, named "World #".

    -

    Other Options:

    +

    Other Options:

    @@ -974,16 +1148,16 @@ Generated worlds are placed into your DF folder, named "World #".

    -
    -

    Example:

    +
    +

    Example:

    'filltraffic H' - When used in a room with doors, it will set traffic to HIGH in just that room.

    -

    alltraffic

    +

    alltraffic

    Set traffic designations for every single tile of the map (useful for resetting traffic designations).

    -
    -

    Traffic Type Codes:

    +
    +

    Traffic Type Codes:

    @@ -999,36 +1173,51 @@ Generated worlds are placed into your DF folder, named "World #".

    -
    -

    Example:

    +
    +

    Example:

    'alltraffic N' - Set traffic to 'normal' for all tiles.

    -

    fixdiplomats

    -

    Up to version 0.31.12, Elves only sent Diplomats to your fortress to propose tree cutting quotas due to a bug; once that bug was fixed, Elves stopped caring about excess tree cutting. This command adds a Diplomat position to all Elven civilizations, allowing them to negotiate tree cutting quotas (and allowing you to violate them and potentially start wars) in case you haven't already modified your raws accordingly.

    +

    fixdiplomats

    +

    Up to version 0.31.12, Elves only sent Diplomats to your fortress to propose +tree cutting quotas due to a bug; once that bug was fixed, Elves stopped caring +about excess tree cutting. This command adds a Diplomat position to all Elven +civilizations, allowing them to negotiate tree cutting quotas (and allowing you +to violate them and potentially start wars) in case you haven't already modified +your raws accordingly.

    -

    fixmerchants

    -

    This command adds the Guild Representative position to all Human civilizations, allowing them to make trade agreements (just as they did back in 0.28.181.40d and earlier) in case you haven't already modified your raws accordingly.

    +

    fixmerchants

    +

    This command adds the Guild Representative position to all Human civilizations, +allowing them to make trade agreements (just as they did back in 0.28.181.40d +and earlier) in case you haven't already modified your raws accordingly.

    -

    fixveins

    -

    Removes invalid references to mineral inclusions and restores missing ones. Use this if you broke your embark with tools like tiletypes, or if you accidentally placed a construction on top of a valuable mineral floor.

    +

    fixveins

    +

    Removes invalid references to mineral inclusions and restores missing ones. +Use this if you broke your embark with tools like tiletypes, or if you +accidentally placed a construction on top of a valuable mineral floor.

    -

    fixwagons

    -

    Due to a bug in all releases of version 0.31, merchants no longer bring wagons with their caravans. This command re-enables them for all appropriate civilizations.

    +

    fixwagons

    +

    Due to a bug in all releases of version 0.31, merchants no longer bring wagons +with their caravans. This command re-enables them for all appropriate +civilizations.

    -

    flows

    -

    A tool for checking how many tiles contain flowing liquids. If you suspect that your magma sea leaks into HFS, you can use this tool to be sure without revealing the map.

    +

    flows

    +

    A tool for checking how many tiles contain flowing liquids. If you suspect that +your magma sea leaks into HFS, you can use this tool to be sure without +revealing the map.

    -

    getplants

    -

    This tool allows plant gathering and tree cutting by RAW ID. Specify the types of trees to cut down and/or shrubs to gather by their plant names, separated by spaces.

    -
    -

    Options

    +

    getplants

    +

    This tool allows plant gathering and tree cutting by RAW ID. Specify the types +of trees to cut down and/or shrubs to gather by their plant names, separated +by spaces.

    +
    +

    Options

    @@ -1039,62 +1228,73 @@ Generated worlds are placed into your DF folder, named "World #".

    - +
    -c:Clear designations instead of setting them
    -x:Apply selected action to all plants except those specified (invert selection)
    -x:Apply selected action to all plants except those specified (invert +selection)
    -

    Specifying both -t and -s will have no effect. If no plant IDs are specified, all valid plant IDs will be listed.

    +

    Specifying both -t and -s will have no effect. If no plant IDs are specified, +all valid plant IDs will be listed.

    -

    tidlers

    +

    tidlers

    Toggle between all possible positions where the idlers count can be placed.

    -

    twaterlvl

    +

    twaterlvl

    Toggle between displaying/not displaying liquid depth as numbers.

    -

    job

    +

    job

    Command for general job query and manipulation.

    Options:
      -
    • no extra options - Print details of the current job. The job can be selected in a workshop, or the unit/jobs screen.
    • +
    • no extra options - Print details of the current job. The job can be selected +in a workshop, or the unit/jobs screen.
    • list - Print details of all jobs in the selected workshop.
    • -
    • item-material <item-idx> <material[:subtoken]> - Replace the exact material id in the job item.
    • -
    • item-type <item-idx> <type[:subtype]> - Replace the exact item type id in the job item.
    • +
    • item-material <item-idx> <material[:subtoken]> - Replace the exact material +id in the job item.
    • +
    • item-type <item-idx> <type[:subtype]> - Replace the exact item type id in +the job item.
    -

    job-material

    -

    Alter the material of the selected job. Invoked as: job-material <inorganic-token>

    +

    job-material

    +

    Alter the material of the selected job.

    +

    Invoked as: job-material <inorganic-token>

    Intended to be used as a keybinding:
      -
    • In 'q' mode, when a job is highlighted within a workshop or furnace, changes the material of the job. Only inorganic materials can be used in this mode.
    • -
    • In 'b' mode, during selection of building components positions the cursor over the first available choice with the matching material.
    • +
    • In 'q' mode, when a job is highlighted within a workshop or furnace, +changes the material of the job. Only inorganic materials can be used +in this mode.
    • +
    • In 'b' mode, during selection of building components positions the cursor +over the first available choice with the matching material.
    -

    job-duplicate

    +

    job-duplicate

    Duplicate the selected job in a workshop:
      -
    • In 'q' mode, when a job is highlighted within a workshop or furnace building, instantly duplicates the job.
    • +
    • In 'q' mode, when a job is highlighted within a workshop or furnace building, +instantly duplicates the job.
    -

    keybinding

    -

    Manages DFHack keybindings. Currently it supports any combination of Ctrl/Alt/Shift with F1-F9, or A-Z.

    -
    -

    Options

    +

    keybinding

    +

    Manages DFHack keybindings.

    +

    Currently it supports any combination of Ctrl/Alt/Shift with F1-F9, or A-Z.

    +
    +

    Options

    @@ -1106,20 +1306,28 @@ Generated worlds are placed into your DF folder, named "World #".

    - + - +
     Remove bindings for the specified keys.
    keybinding add <key> "cmdline" "cmdline"...:
     Add bindings for the specified key.
     Add bindings for the specified +key.
    keybinding set <key> "cmdline" "cmdline"...:
     Clear, and then add bindings for the specified key.
     Clear, and then add bindings for +the specified key.
    -

    When multiple commands are bound to the same key combination, DFHack selects the first applicable one. Later 'add' commands, and earlier entries within one 'add' command have priority. Commands that are not specifically intended for use as a hotkey are always considered applicable.

    +

    When multiple commands are bound to the same key combination, DFHack selects +the first applicable one. Later 'add' commands, and earlier entries within one +'add' command have priority. Commands that are not specifically intended for use +as a hotkey are always considered applicable.

    -

    liquids

    -

    Allows adding magma, water and obsidian to the game. It replaces the normal dfhack command line and can't be used from a hotkey. Settings will be remembered as long as dfhack runs. Intended for use in combination with the command liquids-here (which can be bound to a hotkey). -For more information, refer to the command's internal help.

    +

    liquids

    +

    Allows adding magma, water and obsidian to the game. It replaces the normal +dfhack command line and can't be used from a hotkey. Settings will be remembered +as long as dfhack runs. Intended for use in combination with the command +liquids-here (which can be bound to a hotkey).

    +

    For more information, refer to the command's internal help.

    Note

    Spawning and deleting liquids can F up pathing data and @@ -1127,28 +1335,31 @@ temperatures (creating heat traps). You've been warned.

    -

    liquids-here

    -

    Run the liquid spawner with the current/last settings made in liquids (if no settings in liquids were made it paints a point of 7/7 magma by default). -Intended to be used as keybinding. Requires an active in-game cursor.

    +

    liquids-here

    +

    Run the liquid spawner with the current/last settings made in liquids (if no +settings in liquids were made it paints a point of 7/7 magma by default).

    +

    Intended to be used as keybinding. Requires an active in-game cursor.

    -

    mode

    -

    This command lets you see and change the game mode directly. Not all combinations are good for every situation and most of them will produce undesirable results. -There are a few good ones though.

    +

    mode

    +

    This command lets you see and change the game mode directly. +Not all combinations are good for every situation and most of them will +produce undesirable results. There are a few good ones though.

    Example

    You are in fort game mode, managing your fortress and paused. -You switch to the arena game mode, assume control of a creature and then switch to adventure game mode(1). +You switch to the arena game mode, assume control of a creature and then +switch to adventure game mode(1). You just lost a fortress and gained an adventurer.

    -

    I take no responsibility of anything that happens as a result of using this tool :P

    +

    I take no responsibility of anything that happens as a result of using this tool

    -

    extirpate

    -

    A tool for getting rid of trees and shrubs. By default, it only kills a tree/shrub under the cursor. -The plants are turned into ashes instantly.

    -
    -

    Options

    +

    extirpate

    +

    A tool for getting rid of trees and shrubs. By default, it only kills +a tree/shrub under the cursor. The plants are turned into ashes instantly.

    +
    +

    Options

    @@ -1164,22 +1375,24 @@ The plants are turned into ashes instantly.

    -

    grow

    +

    grow

    Makes all saplings present on the map grow into trees (almost) instantly.

    -

    immolate

    -

    Very similar to extirpate, but additionally sets the plants on fire. The fires can and will spread ;)

    +

    immolate

    +

    Very similar to extirpate, but additionally sets the plants on fire. The fires +can and will spread ;)

    -

    probe

    +

    probe

    Can be used to determine tile properties like temperature.

    -

    prospect

    -

    Prints a big list of all the present minerals and plants. By default, only the visible part of the map is scanned.

    -
    -

    Options

    +

    prospect

    +

    Prints a big list of all the present minerals and plants. By default, only +the visible part of the map is scanned.

    +
    @@ -1194,13 +1407,14 @@ The plants are turned into ashes instantly.

    -

    Pre-embark estimate

    -

    If called during the embark selection screen, displays an estimate of layer stone availability. -If the 'all' option is specified, also estimates veins. The estimate is computed either -for 1 embark tile of the blinking biome, or for all tiles of the embark rectangle.

    +

    Pre-embark estimate

    +

    If called during the embark selection screen, displays an estimate of layer +stone availability. If the 'all' option is specified, also estimates veins. +The estimate is computed either for 1 embark tile of the blinking biome, or +for all tiles of the embark rectangle.

    -
    -

    Options

    +
    +

    Options

    @@ -1212,14 +1426,14 @@ for 1 embark tile of the blinking biome, or for all tiles of the embark rectangl
    -

    regrass

    -

    Regrows all surface grass, restoring outdoor plant growth for pre-0.31.19 worlds.

    +

    regrass

    +

    Regrows grass. Not much to it ;)

    -

    rename

    +

    rename

    Allows renaming various things.

    -
    @@ -1228,45 +1442,58 @@ for 1 embark tile of the blinking biome, or for all tiles of the embark rectangl - + - + - +
     Rename squad by index to 'name'.
    rename hotkey <index> "name":
     Rename hotkey by index. This allows assigning longer commands to the DF hotkeys.
     Rename hotkey by index. This allows assigning +longer commands to the DF hotkeys.
    rename unit "nickname":
     Rename a unit/creature highlighted in the DF user interface.
     Rename a unit/creature highlighted in the DF user +interface.
    rename unit-profession "custom profession":
     Change proffession name of the highlighted unit/creature.
     Change proffession name of the +highlighted unit/creature.
    -

    reveal

    -

    This reveals the map. By default, HFS will remain hidden so that the demons don't spawn. You can use 'reveal hell' to reveal everything. With hell revealed, you won't be able to unpause until you hide the map again. If you really want to unpause with hell revealed, use 'reveal demons'.

    -

    Reveal also works in adventure mode, but any of its effects are negated once you move. When you use it this way, you don't need to run 'unreveal'.

    +

    reveal

    +

    This reveals the map. By default, HFS will remain hidden so that the demons +don't spawn. You can use 'reveal hell' to reveal everything. With hell revealed, +you won't be able to unpause until you hide the map again. If you really want +to unpause with hell revealed, use 'reveal demons'.

    +

    Reveal also works in adventure mode, but any of its effects are negated once +you move. When you use it this way, you don't need to run 'unreveal'.

    -

    unreveal

    +

    unreveal

    Reverts the effects of 'reveal'.

    -

    revtoggle

    +

    revtoggle

    Switches between 'reveal' and 'unreveal'.

    -

    revflood

    -

    This command will hide the whole map and then reveal all the tiles that have a path to the in-game cursor.

    +

    revflood

    +

    This command will hide the whole map and then reveal all the tiles that have +a path to the in-game cursor.

    -

    revforget

    -

    When you use reveal, it saves information about what was/wasn't visible before revealing everything. Unreveal uses this information to hide things again. This command throws away the information. For example, use in cases where you abandoned with the fort revealed and no longer want the data.

    +

    revforget

    +

    When you use reveal, it saves information about what was/wasn't visible before +revealing everything. Unreveal uses this information to hide things again. +This command throws away the information. For example, use in cases where +you abandoned with the fort revealed and no longer want the data.

    -

    lair

    -

    This command allows you to mark the map as 'monster lair', preventing item scatter on abandon. When invoked as 'lair reset', it does the opposite.

    -

    Unlike reveal, this command doesn't save the information about tiles - you won't be able to restore state of real monster lairs using 'lair reset'.

    -
    -

    Options

    +

    lair

    +

    This command allows you to mark the map as 'monster lair', preventing item +scatter on abandon. When invoked as 'lair reset', it does the opposite.

    +

    Unlike reveal, this command doesn't save the information about tiles - you +won't be able to restore state of real monster lairs using 'lair reset'.

    +
    +

    Options

    @@ -1280,81 +1507,187 @@ for 1 embark tile of the blinking biome, or for all tiles of the embark rectangl
    -

    seedwatch

    -

    Tool for turning cooking of seeds and plants on/off depending on how much you have of them.

    +

    seedwatch

    +

    Tool for turning cooking of seeds and plants on/off depending on how much you +have of them.

    See 'seedwatch help' for detailed description.

    -

    showmood

    +

    showmood

    Shows all items needed for the currently active strange mood.

    -

    copystock

    -

    Copies the parameters of the currently highlighted stockpile to the custom stockpile settings and switches to custom stockpile placement mode, effectively allowing you to copy/paste stockpiles easily.

    +

    copystock

    +

    Copies the parameters of the currently highlighted stockpile to the custom +stockpile settings and switches to custom stockpile placement mode, effectively +allowing you to copy/paste stockpiles easily.

    -

    ssense / stonesense

    -

    An isometric visualizer that runs in a second window. This requires working graphics acceleration and at least a dual core CPU (otherwise it will slow down DF).

    -

    All the data resides in the 'stonesense' directory. For detailed instructions, see stonesense/README.txt

    +

    ssense / stonesense

    +

    An isometric visualizer that runs in a second window. This requires working +graphics acceleration and at least a dual core CPU (otherwise it will slow +down DF).

    +

    All the data resides in the 'stonesense' directory. For detailed instructions, +see stonesense/README.txt

    Compatible with Windows > XP SP3 and most modern Linux distributions.

    -

    Older versions, support and extra graphics can be found in the bay12 forum thread: -http://www.bay12forums.com/smf/index.php?topic=43260.0

    +

    Older versions, support and extra graphics can be found in the bay12 forum +thread: http://www.bay12forums.com/smf/index.php?topic=43260.0

    Some additional resources: http://df.magmawiki.com/index.php/Utility:Stonesense/Content_repository

    -

    tiletypes

    -

    Can be used for painting map tiles and is a interactive command, much like liquids. -You can paint tiles by their properties - shape, general material and a few others (paint). -You can also paint only over tiles that match a set of properties (filter)

    +

    tiletypes

    +

    Can be used for painting map tiles and is an interactive command, much like +liquids.

    +

    The tool works with two set of options and a brush. The brush determines which +tiles will be processed. First set of options is the filter, which can exclude +some of the tiles from the brush by looking at the tile properties. The second +set of options is the paint - this determines how the selected tiles are +changed.

    +

    Both paint and filter can have many different properties including things like +general shape (WALL, FLOOR, etc.), general material (SOIL, STONE, MINERAL, +etc.), state of 'designated', 'hidden' and 'light' flags.

    +

    The properties of filter and paint can be partially defined. This means that +you can for example do something like this:

    +
    +filter material STONE
    +filter shape FORTIFICATION
    +paint shape FLOOR
    +
    +

    This will turn all stone fortifications into floors, preserving the material.

    +

    Or this:

    +
    +filter shape FLOOR
    +filter material MINERAL
    +paint shape WALL
    +
    +

    Turning mineral vein floors back into walls.

    +

    The tool also allows tweaking some tile flags:

    +

    Or this:

    +
    +paint hidden 1
    +paint hidden 0
    +
    +

    This will hide previously revealed tiles (or show hidden with the 0 option).

    +

    Any paint or filter option can be disabled entirely by using the ANY keyword:

    +
    +paint hidden ANY
    +paint shape ANY
    +filter material any
    +filter shape any
    +
    +
    +
    You can use several different brushes for painting tiles:
    +
      +
    • Point. (point)
    • +
    • Rectangular range. (range)
    • +
    • A column ranging from current cursor to the first solid tile above. (column)
    • +
    • DF map block - 16x16 tiles, in a regular grid. (block)
    • +
    +
    +
    +

    Example:

    +
    +range 10 10 1
    +
    +

    This will change the brush to a rectangle spanning 10x10 tiles on one z-level. +The range starts at the position of the cursor and goes to the east, south and +up.

    For more details, see the 'help' command while using this.

    +
    +

    tiletypes-commands

    +

    Runs tiletypes commands, separated by ;. This makes it possible to change +tiletypes modes from a hotkey.

    +
    +
    +

    tiletypes-here

    +

    Apply the current tiletypes options at the in-game cursor position, including +the brush. Can be used from a hotkey.

    +
    +
    +

    tiletypes-here-point

    +

    Apply the current tiletypes options at the in-game cursor position to a single +tile. Can be used from a hotkey.

    +
    -

    tweak

    +

    tweak

    Contains various tweaks for minor bugs (currently just one).

    -
    - - - - - + + + + + + +
    tweak clear-missing:
     Remove the missing status from the selected unit. This allows engraving slabs for ghostly, but not yet found, creatures.
    tweak clear-ghostly:
     Remove the ghostly status from the selected unit and mark it as dead. This allows getting rid of bugged ghosts which do not show up in the engraving slab menu at all, even after using clear-missing. It works, but is potentially very dangerous - so use with care. Probably (almost certainly) it does not have the same effects like a proper burial. You've been warned.
    clear-missing:Remove the missing status from the selected unit. +This allows engraving slabs for ghostly, but not yet +found, creatures.
    clear-ghostly:Remove the ghostly status from the selected unit and mark +it as dead. This allows getting rid of bugged ghosts +which do not show up in the engraving slab menu at all, +even after using clear-missing. It works, but is +potentially very dangerous - so use with care. Probably +(almost certainly) it does not have the same effects like +a proper burial. You've been warned.
    fixmigrant:Remove the resident/merchant flag from the selected unit. +Intended to fix bugged migrants/traders who stay at the +map edge and don't enter your fort. Only works for +dwarves (or generally the player's race in modded games). +Do NOT abuse this for 'real' caravan merchants (if you +really want to kidnap them, use 'tweak makeown' instead, +otherwise they will have their clothes set to forbidden etc).
    makeown:Force selected unit to become a member of your fort. +Can be abused to grab caravan merchants and escorts, even if +they don't belong to the player's race. Foreign sentients +(humans, elves) can be put to work, but you can't assign rooms +to them and they don't show up in DwarfTherapist because the +game treats them like pets. Grabbing draft animals from +a caravan can result in weirdness (animals go insane or berserk +and are not flagged as tame), but you are allowed to mark them +for slaughter. Grabbing wagons results in some funny spam, then +they are scuttled.
    -

    tubefill

    -

    Fills all the adamantine veins again. Veins that were empty will be filled in too, but might still trigger a demon invasion (this is a known bug).

    +

    tubefill

    +

    Fills all the adamantine veins again. Veins that were empty will be filled in +too, but might still trigger a demon invasion (this is a known bug).

    -

    digv

    -

    Designates a whole vein for digging. Requires an active in-game cursor placed over a vein tile. With the 'x' option, it will traverse z-levels (putting stairs between the same-material tiles).

    +

    digv

    +

    Designates a whole vein for digging. Requires an active in-game cursor placed +over a vein tile. With the 'x' option, it will traverse z-levels (putting stairs +between the same-material tiles).

    -

    digvx

    +

    digvx

    A permanent alias for 'digv x'.

    -

    digl

    -

    Designates layer stone for digging. Requires an active in-game cursor placed over a layer stone tile. With the 'x' option, it will traverse z-levels (putting stairs between the same-material tiles). With the 'undo' option it will remove the dig designation instead (if you realize that digging out a 50 z-level deep layer was not such a good idea after all).

    +

    digl

    +

    Designates layer stone for digging. Requires an active in-game cursor placed +over a layer stone tile. With the 'x' option, it will traverse z-levels +(putting stairs between the same-material tiles). With the 'undo' option it +will remove the dig designation instead (if you realize that digging out a 50 +z-level deep layer was not such a good idea after all).

    -

    diglx

    +

    diglx

    A permanent alias for 'digl x'.

    -

    digexp

    +

    digexp

    This command can be used for exploratory mining.

    See: http://df.magmawiki.com/index.php/DF2010:Exploratory_mining

    There are two variables that can be set: pattern and filter.

    -

    Patterns:

    +

    Patterns:

    @@ -1375,7 +1708,7 @@ You can also paint only over tiles that match a set of properties (filter)

    -

    Filters:

    +

    Filters:

    @@ -1390,8 +1723,8 @@ You can also paint only over tiles that match a set of properties (filter)

    After you have a pattern set, you can use 'expdig' to apply it again.

    -
    -

    Examples:

    +
    +

    Examples:

    designate the diagonal 5 patter over all hidden tiles:
      @@ -1412,11 +1745,11 @@ You can also paint only over tiles that match a set of properties (filter)

    -

    digcircle

    +

    digcircle

    A command for easy designation of filled and hollow circles. It has several types of options.

    -

    Shape:

    +

    Shape:

    @@ -1431,7 +1764,7 @@ It has several types of options.

    -

    Action:

    +

    Action:

    @@ -1446,7 +1779,7 @@ It has several types of options.

    -

    Designation types:

    +

    Designation types:

    @@ -1468,8 +1801,8 @@ It has several types of options.

    After you have set the options, the command called with no options repeats with the last selected parameters.

    -
    -

    Examples:

    +
    +

    Examples:

    • 'digcircle filled 3' = Dig a filled circle with radius = 3.
    • 'digcircle' = Do it again.
    • @@ -1477,11 +1810,11 @@ repeats with the last selected parameters.

    -

    weather

    +

    weather

    Prints the current weather map by default.

    Also lets you change the current weather to 'clear sky', 'rainy' or 'snowing'.

    -
    @@ -1497,10 +1830,10 @@ repeats with the last selected parameters.

    -

    workflow

    +

    workflow

    Manage control of repeat jobs.

    -
    -

    Usage

    +
    +

    Usage

    workflow enable [option...], workflow disable [option...]

    If no options are specified, enables or disables the plugin. @@ -1521,18 +1854,18 @@ Otherwise, enables or disables any of the following options:

    -

    Function

    +

    Function

    When the plugin is enabled, it protects all repeat jobs from removal. If they do disappear due to any cause, they are immediately re-added to their workshop and suspended.

    -

    In addition, when any constraints on item amounts are set, repeat jobs that produce -that kind of item are automatically suspended and resumed as the item amount -goes above or below the limit. The gap specifies how much below the limit +

    In addition, when any constraints on item amounts are set, repeat jobs that +produce that kind of item are automatically suspended and resumed as the item +amount goes above or below the limit. The gap specifies how much below the limit the amount has to drop before jobs are resumed; this is intended to reduce the frequency of jobs being toggled.

    -

    Constraint examples

    +

    Constraint examples

    Keep metal bolts within 900-1000, and wood/bone within 150-200.

     workflow amount AMMO:ITEM_AMMO_BOLTS/METAL 1000 100
    @@ -1563,19 +1896,345 @@ workflow count BOULDER/CLAY 20
     
       workflow amount POWDER_MISC//MUSHROOM_CUP_DIMPLE:MILL 100 20
     
    -In order for this to work, you have to set the material of the PLANT input on
    -the Mill Plants job to MUSHROOM_CUP_DIMPLE using the 'job item-material' command.
    +In order for this to work, you have to set the material of the PLANT input
    +on the Mill Plants job to MUSHROOM_CUP_DIMPLE using the 'job item-material'
    +command.
     
    -

    mapexport

    -

    Export the current loaded map as a file. This will be eventually usable with visualizers.

    +

    mapexport

    +

    Export the current loaded map as a file. This will be eventually usable +with visualizers.

    -

    dwarfexport

    +

    dwarfexport

    Export dwarves to RuneSmith-compatible XML.

    +
    +

    zone

    +

    Helps a bit with managing activity zones (pens, pastures and pits) and cages.

    +
    +++ + + + + + + + + + + + + + + + + + + + + + + + + + +
    set:Set zone or cage under cursor as default for future assigns.
    assign:Assign unit(s) to the pen or pit marked with the 'set' command. +If no filters are set a unit must be selected in the in-game ui. +Can also be followed by a valid zone id which will be set +instead.
    unassign:Unassign selected creature from it's zone.
    nick:Mass-assign nicknames, must be followed by the name you want +to set.
    remnick:Mass-remove nicknames.
    tocages:Assign unit(s) to cages inside a pasture.
    uinfo:Print info about unit(s). If no filters are set a unit must +be selected in the in-game ui.
    zinfo:Print info about zone(s). If no filters are set zones under +the cursor are listed.
    verbose:Print some more info.
    filters:Print list of valid filter options.
    examples:Print some usage examples.
    not:Negates the next filter keyword.
    +
    +
    +

    Filters:

    + +++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    all:Process all units (to be used with additional filters).
    count:Must be followed by a number. Process only n units (to be used +with additional filters).
    unassigned:Not assigned to zone, chain or built cage.
    minage:Minimum age. Must be followed by number.
    maxage:Maximum age. Must be followed by number.
    race:Must be followed by a race RAW ID (e.g. BIRD_TURKEY, ALPACA, +etc). Negatable.
    caged:In a built cage. Negatable.
    own:From own civilization. Negatable.
    merchant:Is a merchant / belongs to a merchant. Should only be used for +pitting, not for stealing animals (slaughter should work).
    war:Trained war creature. Negatable.
    hunting:Trained hunting creature. Negatable.
    tamed:Creature is tame. Negatable.
    trained:Creature is trained. Finds war/hunting creatures as well as +creatures who have a training level greater than 'domesticated'. +If you want to specifically search for war/hunting creatures use +'war' or 'hunting' Negatable.
    trainablewar:Creature can be trained for war (and is not already trained for +war/hunt). Negatable.
    trainablehunt:Creature can be trained for hunting (and is not already trained +for war/hunt). Negatable.
    male:Creature is male. Negatable.
    female:Creature is female. Negatable.
    egglayer:Race lays eggs. Negatable.
    grazer:Race is a grazer. Negatable.
    milkable:Race is milkable. Negatable.
    +
    +
    +

    Usage with single units

    +

    One convenient way to use the zone tool is to bind the command 'zone assign' to +a hotkey, maybe also the command 'zone set'. Place the in-game cursor over +a pen/pasture or pit, use 'zone set' to mark it. Then you can select units +on the map (in 'v' or 'k' mode), in the unit list or from inside cages +and use 'zone assign' to assign them to their new home. Allows pitting your +own dwarves, by the way.

    +
    +
    +

    Usage with filters

    +

    All filters can be used together with the 'assign' command.

    +

    Restrictions: It's not possible to assign units who are inside built cages +or chained because in most cases that won't be desirable anyways. +It's not possible to cage owned pets because in that case the owner +uncages them after a while which results in infinite hauling back and forth.

    +

    Usually you should always use the filter 'own' (which implies tame) unless you +want to use the zone tool for pitting hostiles. 'own' ignores own dwarves unless +you specify 'race DWARF' (so it's safe to use 'assign all own' to one big +pasture if you want to have all your animals at the same place). 'egglayer' and +'milkable' should be used together with 'female' unless you have a mod with +egg-laying male elves who give milk or whatever. Merchants and their animals are +ignored unless you specify 'merchant' (pitting them should be no problem, +but stealing and pasturing their animals is not a good idea since currently they +are not properly added to your own stocks; slaughtering them should work).

    +

    Most filters can be negated (e.g. 'not grazer' -> race is not a grazer).

    +
    +
    +

    Mass-renaming

    +

    Using the 'nick' command you can set the same nickname for multiple units. +If used without 'assign', 'all' or 'count' it will rename all units in the +current default target zone. Combined with 'assign', 'all' or 'count' (and +further optional filters) it will rename units matching the filter conditions.

    +
    +
    +

    Cage zones

    +

    Using the 'tocages' command you can assign units to a set of cages, for example +a room next to your butcher shop(s). They will be spread evenly among available +cages to optimize hauling to and butchering from them. For this to work you need +to build cages and then place one pen/pasture activity zone above them, covering +all cages you want to use. Then use 'zone set' (like with 'assign') and use +'zone tocages filter1 filter2 ...'. 'tocages' overwrites 'assign' because it +would make no sense, but can be used together with 'nick' or 'remnick' and all +the usual filters.

    +
    +
    +

    Examples

    +
    +
    zone assign all own ALPACA minage 3 maxage 10
    +
    Assign all own alpacas who are between 3 and 10 years old to the selected +pasture.
    +
    zone assign all own caged grazer nick ineedgrass
    +
    Assign all own grazers who are sitting in cages on stockpiles (e.g. after +buying them from merchants) to the selected pasture and give them +the nickname 'ineedgrass'.
    +
    zone assign all own not grazer not race CAT
    +
    Assign all own animals who are not grazers, excluding cats.
    +
    zone assign count 5 own female milkable
    +
    Assign up to 5 own female milkable creatures to the selected pasture.
    +
    zone assign all own race DWARF maxage 2
    +
    Throw all useless kids into a pit :)
    +
    zone nick donttouchme
    +
    Nicknames all units in the current default zone or cage to 'donttouchme'. +Mostly intended to be used for special pastures or cages which are not marked +as rooms you want to protect from autobutcher.
    +
    zone tocages count 50 own tame male not grazer
    +
    Stuff up to 50 owned tame male animals who are not grazers into cages built +on the current default zone.
    +
    +
    +
    +
    +

    autonestbox

    +

    Assigns unpastured female egg-layers to nestbox zones. Requires that you create +pen/pasture zones above nestboxes. If the pen is bigger than 1x1 the nestbox +must be in the top left corner. Only 1 unit will be assigned per pen, regardless +of the size. The age of the units is currently not checked, most birds grow up +quite fast. Egglayers who are also grazers will be ignored, since confining them +to a 1x1 pasture is not a good idea. Only tame and domesticated own units are +processed since pasturing half-trained wild egglayers could destroy your neat +nestbox zones when they revert to wild. When called without options autonestbox +will instantly run once.

    +
    +

    Options:

    + +++ + + + + + + + +
    start:Start running every X frames (df simulation ticks). +Default: X=6000, which would be every 60 seconds at 100fps.
    stop:Stop running automatically.
    sleep:Must be followed by number X. Changes the timer to sleep X +frames between runs.
    +
    +
    +
    +

    autobutcher

    +

    Assigns lifestock for slaughter once it reaches a specific count. Requires that +you add the target race(s) to a watch list. Only tame units will be processed.

    +

    Named units will be completely ignored (to protect specific animals from +autobutcher you can give them nicknames with the tool 'rename unit' for single +units or with 'zone nick' to mass-rename units in pastures and cages).

    +

    Creatures trained for war or hunting will be ignored as well.

    +

    Creatures assigned to cages will be ignored if the cage is defined as a room +(to avoid butchering unnamed zoo animals).

    +

    Once you have too much adults, the oldest will be butchered first. +Once you have too much kids, the youngest will be butchered first. +If you don't set any target count the following default will be used: +1 male kid, 5 female kids, 1 male adult, 5 female adults.

    +
    +

    Options:

    + +++ + + + + + + + + + + + + + + + + + + + + + + + + + + +
    start:Start running every X frames (df simulation ticks). +Default: X=6000, which would be every 60 seconds at 100fps.
    stop:Stop running automatically.
    sleep:Must be followed by number X. Changes the timer to sleep +X frames between runs.
    watch R:Start watching a race. R can be a valid race RAW id (ALPACA, +BIRD_TURKEY, etc) or a list of ids seperated by spaces or +the keyword 'all' which affects all races on your current +watchlist.
    unwatch R:Stop watching race(s). The current target settings will be +remembered. R can be a list of ids or the keyword 'all'.
    forget R:Stop watching race(s) and forget it's/their target settings. +R can be a list of ids or the keyword 'all'.
    autowatch:Automatically adds all new races (animals you buy from merchants, +tame yourself or get from migrants) to the watch list using +default target count.
    noautowatch:Stop auto-adding new races to the watchlist.
    list:Print the current status and watchlist.
    list_export:Print status and watchlist in a format which can be used +to import them to another savegame (see notes).
    target fk mk fa ma R:
     Set target count for specified race(s). +fk = number of female kids, +mk = number of male kids, +fa = number of female adults, +ma = number of female adults. +R can be a list of ids or the keyword 'all' or 'new'. +R = 'all': change target count for all races on watchlist +and set the new default for the future. R = 'new': don't touch +current settings on the watchlist, only set the new default +for future entries.
    example:Print some usage examples.
    +
    +
    +

    Examples:

    +

    You want to keep max 7 kids (4 female, 3 male) and max 3 adults (2 female, +1 male) of the race alpaca. Once the kids grow up the oldest adults will get +slaughtered. Excess kids will get slaughtered starting with the youngest +to allow that the older ones grow into adults. Any unnamed cats will +be slaughtered as soon as possible.

    +
    +autobutcher target 4 3 2 1 ALPACA BIRD_TURKEY
    +autobutcher target 0 0 0 0 CAT
    +autobutcher watch ALPACA BIRD_TURKEY CAT
    +autobutcher start
    +
    +

    Automatically put all new races onto the watchlist and mark unnamed tame units +for slaughter as soon as they arrive in your fort. Settings already made +for specific races will be left untouched.

    +
    +autobutcher target 0 0 0 0 new
    +autobutcher autowatch
    +autobutcher start
    +
    +

    Stop watching the races alpaca and cat, but remember the target count +settings so that you can use 'unwatch' without the need to enter the +values again. Note: 'autobutcher unwatch all' works, but only makes sense +if you want to keep the plugin running with the 'autowatch' feature or manually +add some new races with 'watch'. If you simply want to stop it completely use +'autobutcher stop' instead.

    +
    +autobutcher unwatch ALPACA CAT
    +
    +
    +
    +

    Note:

    +

    Settings and watchlist are stored in the savegame, so that you can have +different settings for each world. If you want to copy your watchlist to +another savegame you can use the command list_export:

    +
    +Load savegame where you made the settings.
    +Start a CMD shell and navigate to the df directory. Type the following into the shell:
    +dfhack-run autobutcher list_export > autobutcher.bat
    +Load the savegame where you want to copy the settings to, run the batch file (from the shell):
    +autobutcher.bat
    +
    +
    +
    +
    +

    autolabor

    +

    Automatically manage dwarf labors.

    +

    When enabled, autolabor periodically checks your dwarves and enables or +disables labors. It tries to keep as many dwarves as possible busy but +also tries to have dwarves specialize in specific skills.

    +
    +

    Note

    +

    Warning: autolabor will override any manual changes you make to labors +while it is enabled.

    +
    +

    For detailed usage information, see 'help autolabor'.

    +
    diff --git a/build/generate-MSVC-all-breakfast.bat b/build/generate-MSVC-all-breakfast.bat index 08c5b03ff..1921fba6c 100644 --- a/build/generate-MSVC-all-breakfast.bat +++ b/build/generate-MSVC-all-breakfast.bat @@ -4,5 +4,6 @@ IF NOT EXIST DF_PATH.txt SET _DF_PATH=%CD%\DF mkdir VC2010 cd VC2010 echo generating a build folder -for /f "delims=" %%a in ('DATE /T') do @set myvar=breakfast-%%a +rem for /f "delims=" %%a in ('DATE /T') do @set myvar=breakfast-%BUILD_NUMBER% +set myvar=breakfast-%BUILD_NUMBER% cmake ..\.. -G"Visual Studio 10" -DDFHACK_RELEASE="%myvar%" -DCMAKE_INSTALL_PREFIX="%_DF_PATH%" -DBUILD_DEVEL=1 -DBUILD_DEV_PLUGINS=1 -DBUILD_DF2MC=1 -DBUILD_DFUSION=1 -DBUILD_STONESENSE=1 -DBUILD_SERVER=1 diff --git a/build/package-debug.bat b/build/package-debug.bat index e6149c56d..b6833f552 100644 --- a/build/package-debug.bat +++ b/build/package-debug.bat @@ -1,4 +1,6 @@ +@echo off call "%VS100COMNTOOLS%vsvars32.bat" cd VC2010 msbuild /m /p:Platform=Win32 /p:Configuration=RelWithDebInfo PACKAGE.vcxproj -cd .. \ No newline at end of file +cd .. +exit %ERRORLEVEL% \ No newline at end of file diff --git a/build/package-release.bat b/build/package-release.bat index 3cc3d4af7..99e94b0e5 100644 --- a/build/package-release.bat +++ b/build/package-release.bat @@ -1,4 +1,6 @@ +@echo off call "%VS100COMNTOOLS%vsvars32.bat" cd VC2010 msbuild /m /p:Platform=Win32 /p:Configuration=Release PACKAGE.vcxproj -cd .. \ No newline at end of file +cd .. +exit %ERRORLEVEL% \ No newline at end of file diff --git a/depends/lua/CMakeLists.txt b/depends/lua/CMakeLists.txt index 3a56aa639..b77bce6f7 100644 --- a/depends/lua/CMakeLists.txt +++ b/depends/lua/CMakeLists.txt @@ -1,7 +1,7 @@ PROJECT ( lua CXX ) CMAKE_MINIMUM_REQUIRED(VERSION 2.8) -SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-DLUA_USE_APICHECK") +SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -DLUA_USE_APICHECK") IF(WIN32) ADD_DEFINITIONS(-D_CRT_SECURE_NO_DEPRECATE ) diff --git a/depends/lua/src/ldo.c b/depends/lua/src/ldo.c index 26f9a6747..e0f13c44e 100644 --- a/depends/lua/src/ldo.c +++ b/depends/lua/src/ldo.c @@ -403,7 +403,7 @@ static void finishCcall (lua_State *L) { lua_assert(ci->u.c.k != NULL); /* must have a continuation */ lua_assert(L->nny == 0); /* finish 'luaD_call' */ - L->nCcalls--; + //L->nCcalls--; /* finish 'lua_callk' */ adjustresults(L, ci->nresults); /* call continuation function */ @@ -513,7 +513,7 @@ static void resume (lua_State *L, void *ud) { api_checknelems(L, n); firstArg = L->top - n; /* yield results come from continuation */ } - L->nCcalls--; /* finish 'luaD_call' */ + //L->nCcalls--; /* finish 'luaD_call' */ luaD_poscall(L, firstArg); /* finish 'luaD_precall' */ } unroll(L, NULL); diff --git a/library/Console-windows.cpp b/library/Console-windows.cpp index 8c507d610..d4d47303f 100644 --- a/library/Console-windows.cpp +++ b/library/Console-windows.cpp @@ -223,12 +223,13 @@ namespace DFHack size_t plen = prompt.size(); const char * buf = raw_buffer.c_str(); size_t len = raw_buffer.size(); + int cooked_cursor = raw_cursor; - while ((plen + raw_cursor) >= cols) + while ((plen + cooked_cursor) >= cols) { buf++; len--; - raw_cursor--; + cooked_cursor--; } while (plen + len > cols) { @@ -247,7 +248,7 @@ namespace DFHack output(tmp, inf.dwSize.X - (plen + len), len + plen, inf.dwCursorPosition.Y); free(tmp); } - inf.dwCursorPosition.X = (SHORT)(raw_cursor + plen); + inf.dwCursorPosition.X = (SHORT)(cooked_cursor + plen); SetConsoleCursorPosition(console_out, inf.dwCursorPosition); } diff --git a/library/Core.cpp b/library/Core.cpp index e6b9c45ff..6e1e0986a 100644 --- a/library/Core.cpp +++ b/library/Core.cpp @@ -49,6 +49,8 @@ using namespace std; #include "modules/Graphic.h" #include "modules/Windows.h" #include "RemoteServer.h" +#include "LuaTools.h" + using namespace DFHack; #include "df/ui.h" @@ -118,7 +120,7 @@ struct Core::Private } }; -void cheap_tokenise(string const& input, vector &output) +void Core::cheap_tokenise(string const& input, vector &output) { string *cur = NULL; @@ -177,7 +179,7 @@ void fHKthread(void * iodata) color_ostream_proxy out(core->getConsole()); vector args; - cheap_tokenise(stuff, args); + Core::cheap_tokenise(stuff, args); if (args.empty()) { out.printerr("Empty hotkey command.\n"); continue; @@ -218,7 +220,7 @@ static void runInteractiveCommand(Core *core, PluginManager *plug_mgr, int &clue { // cut the input into parts vector parts; - cheap_tokenise(command,parts); + Core::cheap_tokenise(command,parts); if(parts.size() == 0) { clueless_counter ++; @@ -701,6 +703,9 @@ bool Core::Init() virtual_identity::Init(this); df::global::InitGlobals(); + // initialize common lua context + Lua::Core::Init(con); + // create mutex for syncing with interactive tasks misc_data_mutex=new mutex(); cerr << "Initializing Plugins.\n"; @@ -803,6 +808,13 @@ void *Core::GetData( std::string key ) } } +bool Core::isSuspended(void) +{ + lock_guard lock(d->AccessMutex); + + return (d->df_suspend_depth > 0 && d->df_suspend_thread == this_thread::get_id()); +} + void Core::Suspend() { auto tid = this_thread::get_id(); @@ -882,10 +894,13 @@ int Core::Update() Init(); if(errorstate) return -1; + Lua::Core::Reset(con, "core init"); } color_ostream_proxy out(con); + Lua::Core::Reset(out, "DF code execution"); + if (first_update) plug_mgr->OnStateChange(out, SC_CORE_INITIALIZED); @@ -976,6 +991,8 @@ int Core::Update() assert(d->df_suspend_depth == 0); // destroy condition delete nc; + // check lua stack depth + Lua::Core::Reset(con, "suspend"); } return 0; diff --git a/library/LuaApi.cpp b/library/LuaApi.cpp index 917e44d38..5f2195760 100644 --- a/library/LuaApi.cpp +++ b/library/LuaApi.cpp @@ -74,30 +74,7 @@ distribution. using namespace DFHack; using namespace DFHack::LuaWrapper; -template -void push_pointer_vector(lua_State *state, const std::vector &pvec) -{ - lua_createtable(state,pvec.size(),0); - - for (size_t i = 0; i < pvec.size(); i++) - { - Lua::PushDFObject(state, pvec[i]); - lua_rawseti(state, -2, i+1); - } -} - -template -T *get_checked_arg(lua_State *state, int arg) -{ - luaL_checkany(state, arg); - - auto ptr = Lua::GetDFObject(state, arg); - if (!ptr) - luaL_argerror(state, arg, "invalid type"); - return ptr; -} - -int push_pos(lua_State *state, df::coord pos) +int Lua::PushPosXYZ(lua_State *state, df::coord pos) { if (!pos.isValid()) { @@ -570,9 +547,9 @@ static void OpenModule(lua_State *state, const char *mname, lua_pop(state, 1); } -#define WRAPM(module, function) { #function, df::wrap_function(module::function) } -#define WRAP(function) { #function, df::wrap_function(function) } -#define WRAPN(name, function) { #name, df::wrap_function(function) } +#define WRAPM(module, function) { #function, df::wrap_function(module::function,true) } +#define WRAP(function) { #function, df::wrap_function(function,true) } +#define WRAPN(name, function) { #name, df::wrap_function(function,true) } static const LuaWrapper::FunctionReg dfhack_module[] = { WRAPM(Translation, TranslateName), @@ -613,7 +590,7 @@ static int job_listNewlyCreated(lua_State *state) if (Job::listNewlyCreated(&pvec, &nxid)) { lua_pushinteger(state, nxid); - push_pointer_vector(state, pvec); + Lua::PushVector(state, pvec); return 2; } else @@ -642,7 +619,7 @@ static const LuaWrapper::FunctionReg dfhack_units_module[] = { static int units_getPosition(lua_State *state) { - return push_pos(state, Units::getPosition(get_checked_arg(state,1))); + return Lua::PushPosXYZ(state, Units::getPosition(Lua::CheckDFObject(state,1))); } static const luaL_Reg dfhack_units_funcs[] = { @@ -673,14 +650,14 @@ static const LuaWrapper::FunctionReg dfhack_items_module[] = { static int items_getPosition(lua_State *state) { - return push_pos(state, Items::getPosition(get_checked_arg(state,1))); + return Lua::PushPosXYZ(state, Items::getPosition(Lua::CheckDFObject(state,1))); } static int items_getContainedItems(lua_State *state) { std::vector pvec; - Items::getContainedItems(get_checked_arg(state,1),&pvec); - push_pointer_vector(state, pvec); + Items::getContainedItems(Lua::CheckDFObject(state,1),&pvec); + Lua::PushVector(state, pvec); return 1; } @@ -719,8 +696,8 @@ static const LuaWrapper::FunctionReg dfhack_maps_module[] = { static int maps_listBurrowBlocks(lua_State *state) { std::vector pvec; - Maps::listBurrowBlocks(&pvec, get_checked_arg(state,1)); - push_pointer_vector(state, pvec); + Maps::listBurrowBlocks(&pvec, Lua::CheckDFObject(state,1)); + Lua::PushVector(state, pvec); return 1; } diff --git a/library/LuaTools.cpp b/library/LuaTools.cpp index 5129ba648..469caa65f 100644 --- a/library/LuaTools.cpp +++ b/library/LuaTools.cpp @@ -58,9 +58,22 @@ distribution. #include #include +#include + using namespace DFHack; using namespace DFHack::LuaWrapper; +lua_State *DFHack::Lua::Core::State = NULL; + +inline void AssertCoreSuspend(lua_State *state) +{ + assert(!Lua::IsCoreContext(state) || DFHack::Core::getInstance().isSuspended()); +} + +/* + * Public DF object reference handling API + */ + void DFHack::Lua::PushDFObject(lua_State *state, type_identity *type, void *ptr) { push_object_internal(state, type, ptr, false); @@ -71,6 +84,40 @@ void *DFHack::Lua::GetDFObject(lua_State *state, type_identity *type, int val_in return get_object_internal(state, type, val_index, exact_type, false); } +void *DFHack::Lua::CheckDFObject(lua_State *state, type_identity *type, int val_index, bool exact_type) +{ + if (lua_type(state, val_index) == LUA_TNONE) + { + if (val_index > 0) + luaL_argerror(state, val_index, "pointer expected"); + else + luaL_error(state, "at index %d: pointer expected", val_index); + } + + if (lua_isnil(state, val_index)) + return NULL; + + void *rv = get_object_internal(state, type, val_index, exact_type, false); + + if (!rv) + { + std::string error = "invalid pointer type"; + if (type) + error += "; expected: " + type->getFullName(); + + if (val_index > 0) + luaL_argerror(state, val_index, error.c_str()); + else + luaL_error(state, "at index %d: %s", val_index, error.c_str()); + } + + return rv; +} + +/* + * Console I/O wrappers + */ + static int DFHACK_OSTREAM_TOKEN = 0; color_ostream *DFHack::Lua::GetOutput(lua_State *L) @@ -193,15 +240,14 @@ static int lua_dfhack_is_interactive(lua_State *S) return 1; } -static int lua_dfhack_lineedit(lua_State *S) +static int dfhack_lineedit_sync(lua_State *S, Console *pstream) { - const char *prompt = luaL_optstring(S, 1, ">> "); - const char *hfile = luaL_optstring(S, 2, NULL); - - Console *pstream = get_console(S); if (!pstream) return 2; + const char *prompt = luaL_optstring(S, 1, ">> "); + const char *hfile = luaL_optstring(S, 2, NULL); + DFHack::CommandHistory hist; if (hfile) hist.load(hfile); @@ -224,6 +270,51 @@ static int lua_dfhack_lineedit(lua_State *S) } } +static int DFHACK_QUERY_COROTABLE_TOKEN = 0; + +static int yield_helper(lua_State *S) +{ + return lua_yield(S, lua_gettop(S)); +} + +namespace { + int dfhack_lineedit_cont(lua_State *L, int status, int) + { + if (Lua::IsSuccess(status)) + return lua_gettop(L) - 2; + else + return dfhack_lineedit_sync(L, get_console(L)); + } +} + +static int dfhack_lineedit(lua_State *S) +{ + lua_settop(S, 2); + + Console *pstream = get_console(S); + if (!pstream) + return 2; + + lua_rawgetp(S, LUA_REGISTRYINDEX, &DFHACK_QUERY_COROTABLE_TOKEN); + lua_rawgetp(S, -1, S); + bool in_coroutine = !lua_isnil(S, -1); + lua_settop(S, 2); + + if (in_coroutine) + { + lua_pushcfunction(S, yield_helper); + lua_pushvalue(S, 1); + lua_pushvalue(S, 2); + return Lua::TailPCallK(S, 2, LUA_MULTRET, 0, 0); + } + + return dfhack_lineedit_sync(S, pstream); +} + +/* + * Exception handling + */ + static int DFHACK_EXCEPTION_META_TOKEN = 0; static void error_tostring(lua_State *L, bool keep_old = false) @@ -265,8 +356,21 @@ static void report_error(lua_State *L, color_ostream *out = NULL) lua_pop(L, 1); } -static bool convert_to_exception(lua_State *L) +static bool convert_to_exception(lua_State *L, int slevel, lua_State *thread = NULL) { + if (!thread) + thread = L; + + if (thread == L) + lua_pushthread(L); + else + { + lua_pushthread(thread); + lua_xmove(thread, L, 1); + } + + lua_swap(L); + int base = lua_gettop(L); bool force_unknown = false; @@ -277,13 +381,33 @@ static bool convert_to_exception(lua_State *L) bool is_exception = lua_rawequal(L, -1, -2); lua_settop(L, base); - // If it is an exception, return as is if (is_exception) - return false; + { + // If it is an exception from the same thread, return as is + lua_getfield(L, base, "thread"); + bool same_thread = lua_rawequal(L, -1, base-1); + lua_settop(L, base); + + if (same_thread) + { + lua_remove(L, base-1); + return false; + } - force_unknown = true; + // Create a new exception for this thread + lua_newtable(L); + luaL_where(L, 1); + lua_pushstring(L, "coroutine resume failed"); + lua_concat(L, 2); + lua_setfield(L, -2, "message"); + lua_swap(L); + lua_setfield(L, -2, "cause"); + } + else + force_unknown = true; } + // Promote non-table to table, and do some sanity checks if (!lua_istable(L, base) || force_unknown) { lua_newtable(L); @@ -313,6 +437,10 @@ static bool convert_to_exception(lua_State *L) lua_rawgetp(L, LUA_REGISTRYINDEX, &DFHACK_EXCEPTION_META_TOKEN); lua_setmetatable(L, base); + lua_swap(L); + lua_setfield(L, -2, "thread"); + luaL_traceback(L, thread, NULL, slevel); + lua_setfield(L, -2, "stacktrace"); return true; } @@ -321,13 +449,7 @@ static int dfhack_onerror(lua_State *L) luaL_checkany(L, 1); lua_settop(L, 1); - bool changed = convert_to_exception(L); - if (!changed) - return 1; - - luaL_traceback(L, L, NULL, 1); - lua_setfield(L, 1, "stacktrace"); - + convert_to_exception(L, 1); return 1; } @@ -364,14 +486,8 @@ static void push_simple_error(lua_State *L, const char *str) { lua_pushstring(L, str); - if (lua_checkstack(L, 5)) - convert_to_exception(L); - if (lua_checkstack(L, LUA_MINSTACK)) - { - luaL_traceback(L, L, NULL, 1); - lua_setfield(L, -2, "stacktrace"); - } + convert_to_exception(L, 0); } static bool do_finish_pcall(lua_State *L, bool success, int base = 1, int space = 2) @@ -387,37 +503,34 @@ static bool do_finish_pcall(lua_State *L, bool success, int base = 1, int space { lua_pushboolean(L, success); lua_replace(L, base); /* put first result in first slot */ - return true; + return success; } } -static int finish_dfhack_safecall (lua_State *L, bool success) -{ - success = do_finish_pcall(L, success); - - if (!success) - report_error(L); +namespace { + int safecall_cont(lua_State *L, int status, int) + { + bool success = do_finish_pcall(L, Lua::IsSuccess(status)); - return lua_gettop(L); -} + if (!success) + report_error(L); -static int safecall_cont (lua_State *L) -{ - int status = lua_getctx(L, NULL); - return finish_dfhack_safecall(L, (status == LUA_YIELD)); + return lua_gettop(L); + } } -static int lua_dfhack_safecall (lua_State *L) +static int dfhack_safecall (lua_State *L) { luaL_checkany(L, 1); lua_pushcfunction(L, dfhack_onerror); lua_insert(L, 1); - int status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 1, 0, safecall_cont); - return finish_dfhack_safecall(L, (status == LUA_OK)); + return Lua::TailPCallK(L, lua_gettop(L) - 2, LUA_MULTRET, 1, 0); } bool DFHack::Lua::SafeCall(color_ostream &out, lua_State *L, int nargs, int nres, bool perr) { + AssertCoreSuspend(L); + int base = lua_gettop(L) - nargs; color_ostream *cur_out = Lua::GetOutput(L); @@ -440,13 +553,180 @@ bool DFHack::Lua::SafeCall(color_ostream &out, lua_State *L, int nargs, int nres return ok; } -bool DFHack::Lua::Require(color_ostream &out, lua_State *state, - const std::string &module, bool setglobal) +// Copied from lcorolib.c, with error handling modifications +static int resume_helper(lua_State *L, lua_State *co, int narg, int nres) +{ + if (!co) { + lua_pop(L, narg); + push_simple_error(L, "coroutine expected in resume"); + return LUA_ERRRUN; + } + if (!lua_checkstack(co, narg)) { + lua_pop(L, narg); + push_simple_error(L, "too many arguments to resume"); + return LUA_ERRRUN; + } + if (lua_status(co) == LUA_OK && lua_gettop(co) == 0) { + lua_pop(L, narg); + push_simple_error(L, "cannot resume dead coroutine"); + return LUA_ERRRUN; + } + lua_xmove(L, co, narg); + int status = lua_resume(co, L, narg); + if (Lua::IsSuccess(status)) + { + int nact = lua_gettop(co); + if (nres == LUA_MULTRET) + nres = nact; + else if (nres < nact) + lua_settop(co, nact = nres); + if (!lua_checkstack(L, nres + 1)) { + lua_settop(co, 0); + push_simple_error(L, "too many results to resume"); + return LUA_ERRRUN; + } + int ttop = lua_gettop(L) + nres; + lua_xmove(co, L, nact); + lua_settop(L, ttop); + } + else + { + lua_xmove(co, L, 1); + + // A cross-thread version of dfhack_onerror + if (lua_checkstack(L, LUA_MINSTACK)) + convert_to_exception(L, 0, co); + } + return status; +} + +static int dfhack_coresume (lua_State *L) { + lua_State *co = lua_tothread(L, 1); + luaL_argcheck(L, !!co, 1, "coroutine expected"); + int r = resume_helper(L, co, lua_gettop(L) - 1, LUA_MULTRET); + bool ok = Lua::IsSuccess(r); + lua_pushboolean(L, ok); + lua_insert(L, 2); + return lua_gettop(L) - 1; +} + +static int dfhack_saferesume (lua_State *L) { + lua_State *co = lua_tothread(L, 1); + luaL_argcheck(L, !!co, 1, "coroutine expected"); + int r = resume_helper(L, co, lua_gettop(L) - 1, LUA_MULTRET); + bool ok = Lua::IsSuccess(r); + lua_pushboolean(L, ok); + lua_insert(L, 2); + if (!ok) + report_error(L); + return lua_gettop(L) - 1; +} + +static int dfhack_coauxwrap (lua_State *L) { + lua_State *co = lua_tothread(L, lua_upvalueindex(1)); + int r = resume_helper(L, co, lua_gettop(L), LUA_MULTRET); + if (Lua::IsSuccess(r)) + return lua_gettop(L); + else + return lua_error(L); +} + +static int dfhack_cowrap (lua_State *L) { + luaL_checktype(L, 1, LUA_TFUNCTION); + lua_settop(L, 1); + Lua::NewCoroutine(L); + lua_pushcclosure(L, dfhack_coauxwrap, 1); + return 1; +} + +lua_State *DFHack::Lua::NewCoroutine(lua_State *L) { + lua_State *NL = lua_newthread(L); + lua_swap(L); + lua_xmove(L, NL, 1); /* move function from L to NL */ + return NL; +} + +int DFHack::Lua::SafeResume(color_ostream &out, lua_State *from, lua_State *thread, int nargs, int nres, bool perr) { + AssertCoreSuspend(from); + + color_ostream *cur_out = Lua::GetOutput(from); + set_dfhack_output(from, &out); + + int rv = resume_helper(from, thread, nargs, nres); + + if (!Lua::IsSuccess(rv) && perr) + { + report_error(from, &out); + lua_pop(from, 1); + } + + set_dfhack_output(from, cur_out); + + return rv; +} + +int DFHack::Lua::SafeResume(color_ostream &out, lua_State *from, int nargs, int nres, bool perr) +{ + int base = lua_gettop(from) - nargs; + lua_State *thread = lua_tothread(from, base); + + int rv = SafeResume(out, from, thread, nargs, nres, perr); + + lua_remove(from, base); + return rv; +} + +/* + * Module loading + */ + +static int DFHACK_LOADED_TOKEN = 0; + +bool DFHack::Lua::PushModule(color_ostream &out, lua_State *state, const char *module) +{ + AssertCoreSuspend(state); + + // Check if it is already loaded + lua_rawgetp(state, LUA_REGISTRYINDEX, &DFHACK_LOADED_TOKEN); + lua_pushstring(state, module); + lua_rawget(state, -2); + + if (lua_toboolean(state, -1)) + { + lua_remove(state, -2); + return true; + } + + lua_pop(state, 2); lua_getglobal(state, "require"); - lua_pushstring(state, module.c_str()); + lua_pushstring(state, module); + + return Lua::SafeCall(out, state, 1, 1); +} - if (!Lua::SafeCall(out, state, 1, 1)) +bool DFHack::Lua::PushModulePublic(color_ostream &out, lua_State *state, + const char *module, const char *name) +{ + if (!PushModule(out, state, module)) + return false; + + if (!lua_istable(state, -1)) + { + lua_pop(state, 1); + return false; + } + + lua_pushstring(state, name); + lua_rawget(state, -2); + lua_remove(state, -2); + return true; +} + +bool DFHack::Lua::Require(color_ostream &out, lua_State *state, + const std::string &module, bool setglobal) +{ + if (!PushModule(out, state, module.c_str())) return false; if (setglobal) @@ -471,6 +751,8 @@ bool DFHack::Lua::SafeCallString(color_ostream &out, lua_State *state, const std int nargs, int nres, bool perr, const char *debug_tag, int env_idx) { + AssertCoreSuspend(state); + if (!debug_tag) debug_tag = code.c_str(); if (env_idx) @@ -504,129 +786,144 @@ bool DFHack::Lua::SafeCallString(color_ostream &out, lua_State *state, const std return Lua::SafeCall(out, state, nargs, nres, perr); } -bool DFHack::Lua::InterpreterLoop(color_ostream &out, lua_State *state, - const char *prompt, int env, const char *hfile) +/* + * Coroutine interactive query loop + */ + +static int resume_query_loop(color_ostream &out, + lua_State *thread, lua_State *state, int nargs, + std::string &prompt, std::string &histfile) +{ + int rv = Lua::SafeResume(out, state, thread, nargs, 2); + + if (Lua::IsSuccess(rv)) + { + prompt = ifnull(lua_tostring(state, -2), ""); + histfile = ifnull(lua_tostring(state, -1), ""); + lua_pop(state, 2); + } + + return rv; +} + +bool DFHack::Lua::RunCoreQueryLoop(color_ostream &out, lua_State *state, + bool (*init)(color_ostream&, lua_State*, void*), + void *arg) { if (!out.is_console()) return false; if (!lua_checkstack(state, 20)) return false; - if (!hfile) - hfile = "lua.history"; - if (!prompt) - prompt = "lua"; + Console &con = static_cast(out); + + lua_State *thread; + int rv; + std::string prompt; + std::string histfile; DFHack::CommandHistory hist; - hist.load(hfile); + std::string histname; - out.print("Type quit to exit interactive lua interpreter.\n"); + { + CoreSuspender suspend; - static bool print_banner = true; - if (print_banner) { - out.print("Shortcuts:\n" - " '= foo' => '_1,_2,... = foo'\n" - " '! foo' => 'print(foo)'\n" - "Both save the first result as '_'.\n"); - print_banner = false; - } + int base = lua_gettop(state); - Console &con = static_cast(out); + if (!init(out, state, arg)) + { + lua_settop(state, base); + return false; + } - // Make a proxy global environment. - lua_newtable(state); - int base = lua_gettop(state); + lua_rawgetp(state, LUA_REGISTRYINDEX, &DFHACK_QUERY_COROTABLE_TOKEN); + lua_pushvalue(state, base+1); + lua_remove(state, base+1); + thread = Lua::NewCoroutine(state); + lua_rawsetp(state, -2, thread); + lua_pop(state, 1); - lua_newtable(state); - if (env) - lua_pushvalue(state, env); - else - lua_rawgeti(state, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS); - lua_setfield(state, -2, "__index"); - lua_setmetatable(state, -2); + rv = resume_query_loop(out, thread, state, lua_gettop(state)-base, prompt, histfile); + } - // Main interactive loop - int vcnt = 1; - string curline; - string prompt_str = "[" + string(prompt) + "]# "; + while (rv == LUA_YIELD) + { + if (histfile != histname) + { + if (!histname.empty()) + hist.save(histname.c_str()); - for (;;) { - lua_settop(state, base); + hist.clear(); + histname = histfile; - con.lineedit(prompt_str,curline,hist); + if (!histname.empty()) + hist.load(histname.c_str()); + } - if (curline.empty()) - continue; - if (curline == "quit") - break; + if (prompt.empty()) + prompt = ">> "; + std::string curline; + con.lineedit(prompt,curline,hist); hist.add(curline); - char pfix = curline[0]; - - if (pfix == '=' || pfix == '!') { - curline = "return " + curline.substr(1); - - if (!Lua::SafeCallString(out, state, curline, 0, LUA_MULTRET, true, "=(interactive)", base)) - continue; - - int numret = lua_gettop(state) - base; + CoreSuspender suspend; - if (numret >= 1) - { - lua_pushvalue(state, base+1); - lua_setfield(state, base, "_"); - - if (pfix == '!') - { - lua_pushcfunction(state, lua_dfhack_println); - lua_insert(state, base+1); - SafeCall(out, state, numret, 0); - continue; - } - } + lua_pushlstring(state, curline.data(), curline.size()); + rv = resume_query_loop(out, thread, state, 1, prompt, histfile); + } + } - for (int i = 1; i <= numret; i++) - { - std::string name = stl_sprintf("_%d", vcnt++); - lua_pushvalue(state, base + i); - lua_setfield(state, base, name.c_str()); + if (!histname.empty()) + hist.save(histname.c_str()); - out.print("%s = ", name.c_str()); + { + CoreSuspender suspend; - lua_pushcfunction(state, lua_dfhack_println); - lua_pushvalue(state, base + i); - SafeCall(out, state, 1, 0); - } - } - else - { - if (!Lua::SafeCallString(out, state, curline, 0, LUA_MULTRET, true, "=(interactive)", base)) - continue; - } + lua_rawgetp(state, LUA_REGISTRYINDEX, &DFHACK_QUERY_COROTABLE_TOKEN); + lua_pushnil(state); + lua_rawsetp(state, -2, thread); + lua_pop(state, 1); } - lua_settop(state, base-1); + return (rv == LUA_OK); +} - hist.save(hfile); +namespace { + struct InterpreterArgs { + const char *prompt; + const char *hfile; + }; +} + +static bool init_interpreter(color_ostream &out, lua_State *state, void *info) +{ + auto args = (InterpreterArgs*)info; + lua_getglobal(state, "dfhack"); + lua_getfield(state, -1, "interpreter"); + lua_remove(state, -2); + lua_pushstring(state, args->prompt); + lua_pushstring(state, args->hfile); return true; } -static int lua_dfhack_interpreter(lua_State *state) +bool DFHack::Lua::InterpreterLoop(color_ostream &out, lua_State *state, + const char *prompt, const char *hfile) { - Console *pstream = get_console(state); - if (!pstream) - return 2; + if (!out.is_console()) + return false; - int argc = lua_gettop(state); + if (!hfile) + hfile = "lua.history"; + if (!prompt) + prompt = "lua"; - const char *prompt = (argc >= 1 ? lua_tostring(state, 1) : NULL); - int env = (argc >= 2 && !lua_isnil(state,2) ? 2 : 0); - const char *hfile = (argc >= 3 ? lua_tostring(state, 3) : NULL); + InterpreterArgs args; + args.prompt = prompt; + args.hfile = hfile; - lua_pushboolean(state, Lua::InterpreterLoop(*pstream, state, prompt, env, hfile)); - return 1; + return RunCoreQueryLoop(out, state, init_interpreter, &args); } static bool do_invoke_cleanup(lua_State *L, int nargs, int errorfun, bool success) @@ -648,8 +945,10 @@ static bool do_invoke_cleanup(lua_State *L, int nargs, int errorfun, bool succes return success; } -static int finish_dfhack_cleanup (lua_State *L, bool success) +int dfhack_cleanup_cont(lua_State *L, int status, int) { + bool success = Lua::IsSuccess(status); + int nargs = lua_tointeger(L, 1); bool always = lua_toboolean(L, 2); int rvbase = 4+nargs; @@ -690,12 +989,6 @@ static int finish_dfhack_cleanup (lua_State *L, bool success) return numret; } -static int dfhack_cleanup_cont (lua_State *L) -{ - int status = lua_getctx(L, NULL); - return finish_dfhack_cleanup(L, (status == LUA_YIELD)); -} - static int dfhack_call_with_finalizer (lua_State *L) { int nargs = luaL_checkint(L, 1); @@ -730,8 +1023,7 @@ static int dfhack_call_with_finalizer (lua_State *L) // Actually invoke // stack: [nargs] [always] [errorfun] [cleanup fun] [cleanup args...] |rvbase+1:| [fun] [args...] - int status = lua_pcallk(L, lua_gettop(L)-rvbase-1, LUA_MULTRET, 3, 0, dfhack_cleanup_cont); - return finish_dfhack_cleanup(L, (status == LUA_OK)); + return Lua::TailPCallK(L, lua_gettop(L)-rvbase-1, LUA_MULTRET, 3, 0); } static int lua_dfhack_with_suspend(lua_State *L) @@ -761,15 +1053,24 @@ static int dfhack_open_plugin(lua_State *L) return 0; } +bool Lua::IsCoreContext(lua_State *state) +{ + // This uses a private field of the lua state to + // evaluate the condition without accessing the lua + // stack, and thus requiring a lock on the core state. + return state && Lua::Core::State && + state->l_G == Lua::Core::State->l_G; +} + static const luaL_Reg dfhack_funcs[] = { { "print", lua_dfhack_print }, { "println", lua_dfhack_println }, { "printerr", lua_dfhack_printerr }, { "color", lua_dfhack_color }, { "is_interactive", lua_dfhack_is_interactive }, - { "lineedit", lua_dfhack_lineedit }, - { "interpreter", lua_dfhack_interpreter }, - { "safecall", lua_dfhack_safecall }, + { "lineedit", dfhack_lineedit }, + { "safecall", dfhack_safecall }, + { "saferesume", dfhack_saferesume }, { "onerror", dfhack_onerror }, { "call_with_finalizer", dfhack_call_with_finalizer }, { "with_suspend", lua_dfhack_with_suspend }, @@ -777,6 +1078,158 @@ static const luaL_Reg dfhack_funcs[] = { { NULL, NULL } }; +static const luaL_Reg dfhack_coro_funcs[] = { + { "resume", dfhack_coresume }, + { "wrap", dfhack_cowrap }, + { NULL, NULL } +}; + +/************ + * Events * + ************/ + +static int DFHACK_EVENT_META_TOKEN = 0; + +int DFHack::Lua::NewEvent(lua_State *state) +{ + lua_newtable(state); + lua_rawgetp(state, LUA_REGISTRYINDEX, &DFHACK_EVENT_META_TOKEN); + lua_setmetatable(state, -2); + return 1; +} + +static void do_invoke_event(lua_State *L, int argbase, int num_args, int errorfun) +{ + for (int i = 0; i < num_args; i++) + lua_pushvalue(L, argbase+i); + + if (lua_pcall(L, num_args, 0, errorfun) != LUA_OK) + { + report_error(L); + lua_pop(L, 1); + } +} + +static void dfhack_event_invoke(lua_State *L, int base, bool from_c) +{ + int event = base+1; + int num_args = lua_gettop(L)-event; + + int errorfun = base+2; + lua_pushcfunction(L, dfhack_onerror); + lua_insert(L, errorfun); + + int argbase = base+3; + + // stack: |base| event errorfun (args) + + if (!from_c) + { + // Invoke the NULL key first + lua_rawgetp(L, event, NULL); + + if (lua_isnil(L, -1)) + lua_pop(L, 1); + else + do_invoke_event(L, argbase, num_args, errorfun); + } + + lua_pushnil(L); + + // stack: |base| event errorfun (args) key || cb (args) + + while (lua_next(L, event)) + { + // Skip the NULL key in the main loop + if (lua_islightuserdata(L, -2) && !lua_touserdata(L, -2)) + lua_pop(L, 1); + else + do_invoke_event(L, argbase, num_args, errorfun); + } + + lua_settop(L, base); +} + +static int dfhack_event_call(lua_State *state) +{ + luaL_checktype(state, 1, LUA_TTABLE); + luaL_checkstack(state, lua_gettop(state)+2, "stack overflow in event dispatch"); + + dfhack_event_invoke(state, 0, false); + return 0; +} + +void DFHack::Lua::InvokeEvent(color_ostream &out, lua_State *state, void *key, int num_args) +{ + AssertCoreSuspend(state); + + int base = lua_gettop(state) - num_args; + + if (!lua_checkstack(state, num_args+4)) + { + out.printerr("Stack overflow in Lua::InvokeEvent"); + lua_settop(state, base); + return; + } + + lua_rawgetp(state, LUA_REGISTRYINDEX, key); + + if (!lua_istable(state, -1)) + { + if (!lua_isnil(state, -1)) + out.printerr("Invalid event object in Lua::InvokeEvent"); + lua_settop(state, base); + return; + } + + lua_insert(state, base+1); + + color_ostream *cur_out = Lua::GetOutput(state); + set_dfhack_output(state, &out); + dfhack_event_invoke(state, base, true); + set_dfhack_output(state, cur_out); +} + +void DFHack::Lua::MakeEvent(lua_State *state, void *key) +{ + lua_rawgetp(state, LUA_REGISTRYINDEX, key); + + if (lua_isnil(state, -1)) + { + lua_pop(state, 1); + NewEvent(state); + } + + lua_dup(state); + lua_rawsetp(state, LUA_REGISTRYINDEX, key); +} + +void DFHack::Lua::Notification::invoke(color_ostream &out, int nargs) +{ + assert(state); + InvokeEvent(out, state, key, nargs); +} + +void DFHack::Lua::Notification::bind(lua_State *state, void *key) +{ + this->state = state; + this->key = key; +} + +void DFHack::Lua::Notification::bind(lua_State *state, const char *name) +{ + MakeEvent(state, this); + + if (handler) + { + PushFunctionWrapper(state, 0, name, handler); + lua_rawsetp(state, -2, NULL); + } + + this->state = state; + this->key = this; +} + /************************ * Main Open function * ************************/ @@ -791,6 +1244,10 @@ lua_State *DFHack::Lua::Open(color_ostream &out, lua_State *state) luaL_openlibs(state); AttachDFGlobals(state); + // Table of query coroutines + lua_newtable(state); + lua_rawsetp(state, LUA_REGISTRYINDEX, &DFHACK_QUERY_COROTABLE_TOKEN); + // Replace the print function of the standard library lua_pushcfunction(state, lua_dfhack_println); lua_setglobal(state, "print"); @@ -798,6 +1255,9 @@ lua_State *DFHack::Lua::Open(color_ostream &out, lua_State *state) // Create the dfhack global lua_newtable(state); + lua_pushboolean(state, IsCoreContext(state)); + lua_setfield(state, -2, "is_core_context"); + // Create the metatable for exceptions lua_newtable(state); lua_pushcfunction(state, dfhack_exception_tostring); @@ -806,6 +1266,15 @@ lua_State *DFHack::Lua::Open(color_ostream &out, lua_State *state) lua_rawsetp(state, LUA_REGISTRYINDEX, &DFHACK_EXCEPTION_META_TOKEN); lua_setfield(state, -2, "exception"); + lua_newtable(state); + lua_pushcfunction(state, dfhack_event_call); + lua_setfield(state, -2, "__call"); + lua_pushcfunction(state, Lua::NewEvent); + lua_setfield(state, -2, "new"); + lua_dup(state); + lua_rawsetp(state, LUA_REGISTRYINDEX, &DFHACK_EVENT_META_TOKEN); + lua_setfield(state, -2, "event"); + // Initialize the dfhack global luaL_setfuncs(state, dfhack_funcs, 0); @@ -813,9 +1282,61 @@ lua_State *DFHack::Lua::Open(color_ostream &out, lua_State *state) lua_setglobal(state, "dfhack"); + // stash the loaded module table into our own registry key + lua_getglobal(state, "package"); + assert(lua_istable(state, -1)); + lua_getfield(state, -1, "loaded"); + assert(lua_istable(state, -1)); + lua_rawsetp(state, LUA_REGISTRYINDEX, &DFHACK_LOADED_TOKEN); + lua_pop(state, 1); + + // replace some coroutine functions + lua_getglobal(state, "coroutine"); + luaL_setfuncs(state, dfhack_coro_funcs, 0); + lua_pop(state, 1); + // load dfhack.lua Require(out, state, "dfhack"); + lua_settop(state, 0); + if (!lua_checkstack(state, 64)) + out.printerr("Could not extend initial lua stack size to 64 items.\n"); + return state; } +void DFHack::Lua::Core::onStateChange(color_ostream &out, int code) { + if (!State) return; + + Lua::Push(State, code); + Lua::InvokeEvent(out, State, (void*)onStateChange, 1); +} + +void DFHack::Lua::Core::Init(color_ostream &out) +{ + if (State) + return; + + State = luaL_newstate(); + + Lua::Open(out, State); + + // Register events + lua_getglobal(State, "dfhack"); + + MakeEvent(State, (void*)onStateChange); + lua_setfield(State, -2, "onStateChange"); + + lua_pop(State, 1); +} + +void DFHack::Lua::Core::Reset(color_ostream &out, const char *where) +{ + int top = lua_gettop(State); + + if (top != 0) + { + out.printerr("Common lua context stack top left at %d after %s.\n", top, where); + lua_settop(State, 0); + } +} diff --git a/library/LuaTypes.cpp b/library/LuaTypes.cpp index f5ba565d5..2cfe8a84e 100644 --- a/library/LuaTypes.cpp +++ b/library/LuaTypes.cpp @@ -733,8 +733,18 @@ static int lookup_container_field(lua_State *state, int field, const char *mode * Index verification: number and in range. */ static int check_container_index(lua_State *state, int len, - int fidx, int iidx, const char *mode) + int fidx, int iidx, const char *mode, + bool is_insert = false) { + if (is_insert && len >= 0) + { + if (lua_type(state, iidx) == LUA_TSTRING + && strcmp(lua_tostring(state, iidx), "#") == 0) + return len; + + len++; + } + if (!lua_isnumber(state, iidx)) field_error(state, fidx, "invalid index", mode); @@ -867,8 +877,7 @@ static int method_container_insert(lua_State *state) auto id = (container_identity*)lua_touserdata(state, UPVAL_CONTAINER_ID); int len = id->lua_item_count(state, ptr, container_identity::COUNT_LEN); - if (len >= 0) len++; - int idx = check_container_index(state, len, UPVAL_METHOD_NAME, 2, "call"); + int idx = check_container_index(state, len, UPVAL_METHOD_NAME, 2, "call", true); if (!id->lua_insert(state, UPVAL_METHOD_NAME, ptr, idx, 3)) field_error(state, UPVAL_METHOD_NAME, "not supported", "call"); @@ -1036,7 +1045,9 @@ static int meta_call_function(lua_State *state) int LuaWrapper::method_wrapper_core(lua_State *state, function_identity_base *id) { - if (lua_gettop(state) != id->getNumArgs()) + if (id->adjustArgs()) + lua_settop(state, id->getNumArgs()); + else if (lua_gettop(state) != id->getNumArgs()) field_error(state, UPVAL_METHOD_NAME, "invalid argument count", "invoke"); try { @@ -1056,10 +1067,10 @@ int LuaWrapper::method_wrapper_core(lua_State *state, function_identity_base *id } /** - * Create a closure invoking the given function, and add it to the field table. + * Push a closure invoking the given function. */ -static void AddMethodWrapper(lua_State *state, int meta_idx, int field_idx, - const char *name, function_identity_base *fun) +void LuaWrapper::PushFunctionWrapper(lua_State *state, int meta_idx, + const char *name, function_identity_base *fun) { lua_rawgetp(state, LUA_REGISTRYINDEX, &DFHACK_TYPETABLE_TOKEN); if (meta_idx) @@ -1069,7 +1080,15 @@ static void AddMethodWrapper(lua_State *state, int meta_idx, int field_idx, lua_pushfstring(state, "%s()", name); lua_pushlightuserdata(state, fun); lua_pushcclosure(state, meta_call_function, 4); +} +/** + * Create a closure invoking the given function, and add it to the field table. + */ +static void AddMethodWrapper(lua_State *state, int meta_idx, int field_idx, + const char *name, function_identity_base *fun) +{ + PushFunctionWrapper(state, meta_idx, name, fun); lua_setfield(state, field_idx, name); } diff --git a/library/PluginManager.cpp b/library/PluginManager.cpp index 4d0c06ddf..837c3e2d5 100644 --- a/library/PluginManager.cpp +++ b/library/PluginManager.cpp @@ -33,6 +33,7 @@ distribution. #include "MiscUtils.h" #include "LuaWrapper.h" +#include "LuaTools.h" using namespace DFHack; @@ -380,6 +381,7 @@ command_result Plugin::on_update(color_ostream &out) if(state == PS_LOADED && plugin_onupdate) { cr = plugin_onupdate(out); + Lua::Core::Reset(out, "plugin_onupdate"); } access->lock_sub(); return cr; @@ -392,6 +394,7 @@ command_result Plugin::on_state_change(color_ostream &out, state_change_event ev if(state == PS_LOADED && plugin_onstatechange) { cr = plugin_onstatechange(out, event); + Lua::Core::Reset(out, "plugin_onstatechange"); } access->lock_sub(); return cr; @@ -445,9 +448,7 @@ void Plugin::index_lua(DFLibrary *lib) for (; cmdlist->name; ++cmdlist) { auto &cmd = lua_commands[cmdlist->name]; - if (!cmd) cmd = new LuaCommand; - cmd->owner = this; - cmd->name = cmdlist->name; + if (!cmd) cmd = new LuaCommand(this,cmdlist->name); cmd->command = cmdlist->command; } } @@ -456,12 +457,22 @@ void Plugin::index_lua(DFLibrary *lib) for (; funlist->name; ++funlist) { auto &cmd = lua_functions[funlist->name]; - if (!cmd) cmd = new LuaFunction; - cmd->owner = this; - cmd->name = funlist->name; + if (!cmd) cmd = new LuaFunction(this,funlist->name); cmd->identity = funlist->identity; } } + if (auto evlist = (EventReg*)LookupPlugin(lib, "plugin_lua_events")) + { + for (; evlist->name; ++evlist) + { + auto &cmd = lua_events[evlist->name]; + if (!cmd) cmd = new LuaEvent(this,evlist->name); + cmd->handler.identity = evlist->event->get_handler(); + cmd->event = evlist->event; + if (cmd->active) + cmd->event->bind(Lua::Core::State, cmd); + } + } } void Plugin::reset_lua() @@ -470,6 +481,11 @@ void Plugin::reset_lua() it->second->command = NULL; for (auto it = lua_functions.begin(); it != lua_functions.end(); ++it) it->second->identity = NULL; + for (auto it = lua_events.begin(); it != lua_events.end(); ++it) + { + it->second->handler.identity = NULL; + it->second->event = NULL; + } } int Plugin::lua_cmd_wrapper(lua_State *state) @@ -513,13 +529,35 @@ void Plugin::open_lua(lua_State *state, int table) for (auto it = lua_functions.begin(); it != lua_functions.end(); ++it) { - lua_rawgetp(state, LUA_REGISTRYINDEX, &LuaWrapper::DFHACK_TYPETABLE_TOKEN); - lua_pushlightuserdata(state, NULL); - lua_pushfstring(state, "%s.%s()", name.c_str(), it->second->name.c_str()); - lua_pushlightuserdata(state, it->second); - lua_pushcclosure(state, lua_fun_wrapper, 4); + push_function(state, it->second); lua_setfield(state, table, it->first.c_str()); } + + if (Lua::IsCoreContext(state)) + { + for (auto it = lua_events.begin(); it != lua_events.end(); ++it) + { + Lua::MakeEvent(state, it->second); + + push_function(state, &it->second->handler); + lua_rawsetp(state, -2, NULL); + + it->second->active = true; + if (it->second->event) + it->second->event->bind(state, it->second); + + lua_setfield(state, table, it->first.c_str()); + } + } +} + +void Plugin::push_function(lua_State *state, LuaFunction *fn) +{ + lua_rawgetp(state, LUA_REGISTRYINDEX, &LuaWrapper::DFHACK_TYPETABLE_TOKEN); + lua_pushlightuserdata(state, NULL); + lua_pushfstring(state, "%s.%s()", name.c_str(), fn->name.c_str()); + lua_pushlightuserdata(state, fn); + lua_pushcclosure(state, lua_fun_wrapper, 4); } PluginManager::PluginManager(Core * core) @@ -603,6 +641,8 @@ void PluginManager::OnStateChange(color_ostream &out, state_change_event event) { all_plugins[i]->on_state_change(out, event); } + + Lua::Core::onStateChange(out, event); } // FIXME: doesn't check name collisions! diff --git a/library/include/Core.h b/library/include/Core.h index f8ac8e783..4f9b10c84 100644 --- a/library/include/Core.h +++ b/library/include/Core.h @@ -90,6 +90,8 @@ namespace DFHack static Core instance; return instance; } + /// check if the activity lock is owned by this thread + bool isSuspended(void); /// try to acquire the activity lock void Suspend(void); /// return activity lock @@ -135,6 +137,8 @@ namespace DFHack PluginManager *getPluginManager() { return plug_mgr; } + static void cheap_tokenise(std::string const& input, std::vector &output); + private: DFHack::Console con; diff --git a/library/include/DataFuncs.h b/library/include/DataFuncs.h index a949e784b..8b917ad70 100644 --- a/library/include/DataFuncs.h +++ b/library/include/DataFuncs.h @@ -161,15 +161,15 @@ INSTANTIATE_WRAPPERS(5, (A1,A2,A3,A4,A5), (vA1,vA2,vA3,vA4,vA5), public: typedef function_wrapper wrapper; - function_identity(T ptr) - : function_identity_base(wrapper::num_args), ptr(ptr) {}; + function_identity(T ptr, bool vararg) + : function_identity_base(wrapper::num_args, vararg), ptr(ptr) {}; virtual void invoke(lua_State *state, int base) { wrapper::execute(state, base, ptr); } }; template - inline function_identity_base *wrap_function(T ptr) { + inline function_identity_base *wrap_function(T ptr, bool vararg = false) { // bah, but didn't have any idea how to allocate statically - return new function_identity(ptr); + return new function_identity(ptr, vararg); } } \ No newline at end of file diff --git a/library/include/DataIdentity.h b/library/include/DataIdentity.h index 279400f74..a775c85b2 100644 --- a/library/include/DataIdentity.h +++ b/library/include/DataIdentity.h @@ -39,13 +39,17 @@ namespace DFHack { class DFHACK_EXPORT function_identity_base : public type_identity { int num_args; + bool vararg; public: - function_identity_base(int num_args) : type_identity(0), num_args(num_args) {}; + function_identity_base(int num_args, bool vararg = false) + : type_identity(0), num_args(num_args), vararg(vararg) {}; virtual identity_type type() { return IDTYPE_FUNCTION; } int getNumArgs() { return num_args; } + bool adjustArgs() { return vararg; } + std::string getFullName() { return "function"; } virtual void invoke(lua_State *state, int base) = 0; diff --git a/library/include/LuaTools.h b/library/include/LuaTools.h index 7e3ed1683..b2d440a6b 100644 --- a/library/include/LuaTools.h +++ b/library/include/LuaTools.h @@ -34,18 +34,33 @@ distribution. #include #include -namespace DFHack { namespace Lua { +namespace DFHack { + class function_identity_base; +} + +namespace DFHack {namespace Lua { /** * Create or initialize a lua interpreter with access to DFHack tools. */ DFHACK_EXPORT lua_State *Open(color_ostream &out, lua_State *state = NULL); /** - * Load a module using require(). + * Load a module using require(). Leaves the stack as is. */ DFHACK_EXPORT bool Require(color_ostream &out, lua_State *state, const std::string &module, bool setglobal = false); + /** + * Push the module table, loading it using require() if necessary. + */ + DFHACK_EXPORT bool PushModule(color_ostream &out, lua_State *state, const char *module); + + /** + * Push the public object name exported by the module. Uses PushModule. + */ + DFHACK_EXPORT bool PushModulePublic(color_ostream &out, lua_State *state, + const char *module, const char *name); + /** * Check if the object at the given index is NIL or NULL. */ @@ -79,6 +94,12 @@ namespace DFHack { namespace Lua { */ DFHACK_EXPORT void *GetDFObject(lua_State *state, type_identity *type, int val_index, bool exact_type = false); + /** + * Check that the value is a wrapped DF object of the given type, and if so return the pointer. + * Otherwise throw an argument type error. + */ + DFHACK_EXPORT void *CheckDFObject(lua_State *state, type_identity *type, int val_index, bool exact_type = false); + /** * Assign the value at val_index to the target of given identity using df.assign(). * Return behavior is of SafeCall below. @@ -102,6 +123,14 @@ namespace DFHack { namespace Lua { return (T*)GetDFObject(state, df::identity_traits::get(), val_index, exact_type); } + /** + * Check that the value is a wrapped DF object of the correct type, and if so return the pointer. Otherwise throw an argument type error. + */ + template + T *CheckDFObject(lua_State *state, int val_index, bool exact_type = false) { + return (T*)CheckDFObject(state, df::identity_traits::get(), val_index, exact_type); + } + /** * Assign the value at val_index to the target using df.assign(). */ @@ -110,12 +139,56 @@ namespace DFHack { namespace Lua { return AssignDFObject(out, state, df::identity_traits::get(), target, val_index, perr); } + /** + * Check if the status is a success, i.e. LUA_OK or LUA_YIELD. + */ + inline bool IsSuccess(int status) { + return (status == LUA_OK || status == LUA_YIELD); + } + + // Internal helper + template + int TailPCallK_Thunk(lua_State *state) { + int tmp; + int rv = lua_getctx(state, &tmp); + return cb(state, rv, tmp); + } + + /** + * A utility for using the restartable pcall feature more conveniently; + * specifically, the callback is called with the same kind of arguments + * in both yield and non-yield case. + */ + template + int TailPCallK(lua_State *state, int narg, int nret, int errfun, int ctx) { + int rv = lua_pcallk(state, narg, nret, errfun, ctx, &TailPCallK_Thunk); + return cb(state, rv, ctx); + } + /** * Invoke lua function via pcall. Returns true if success. * If an error is signalled, and perr is true, it is printed and popped from the stack. */ DFHACK_EXPORT bool SafeCall(color_ostream &out, lua_State *state, int nargs, int nres, bool perr = true); + /** + * Pops a function from the top of the stack, and pushes a new coroutine. + */ + DFHACK_EXPORT lua_State *NewCoroutine(lua_State *state); + + /** + * Resume the coroutine using nargs values from state from. Results or the error are moved back. + * If an error is signalled, and perr is true, it is printed and popped from the stack. + * Returns the lua_resume return value. + */ + DFHACK_EXPORT int SafeResume(color_ostream &out, lua_State *from, lua_State *thread, int nargs, int nres, bool perr = true); + + /** + * Works just like SafeCall, only expects a coroutine on the stack + * instead of a function. Returns the lua_resume return value. + */ + DFHACK_EXPORT int SafeResume(color_ostream &out, lua_State *from, int nargs, int nres, bool perr = true); + /** * Parse code from string with debug_tag and env_idx, then call it using SafeCall. * In case of error, it is either left on the stack, or printed like SafeCall does. @@ -131,8 +204,168 @@ namespace DFHack { namespace Lua { /** * Run an interactive interpreter loop if possible, or return false. + * Uses RunCoreQueryLoop internally. */ DFHACK_EXPORT bool InterpreterLoop(color_ostream &out, lua_State *state, - const char *prompt = NULL, int env = 0, const char *hfile = NULL); + const char *prompt = NULL, const char *hfile = NULL); + + /** + * Run an interactive prompt loop. All access to the lua state + * is done inside CoreSuspender, while waiting for input happens + * without the suspend lock. + */ + DFHACK_EXPORT bool RunCoreQueryLoop(color_ostream &out, lua_State *state, + bool (*init)(color_ostream&, lua_State*, void*), + void *arg); + + /** + * Push utility functions + */ +#if 0 +#define NUMBER_PUSH(type) inline void Push(lua_State *state, type value) { lua_pushnumber(state, value); } + NUMBER_PUSH(char) + NUMBER_PUSH(int8_t) NUMBER_PUSH(uint8_t) + NUMBER_PUSH(int16_t) NUMBER_PUSH(uint16_t) + NUMBER_PUSH(int32_t) NUMBER_PUSH(uint32_t) + NUMBER_PUSH(int64_t) NUMBER_PUSH(uint64_t) + NUMBER_PUSH(float) NUMBER_PUSH(double) +#undef NUMBER_PUSH +#else + template inline void Push(lua_State *state, T value) { + lua_pushnumber(state, lua_Number(value)); + } +#endif + inline void Push(lua_State *state, bool value) { + lua_pushboolean(state, value); + } + inline void Push(lua_State *state, const std::string &str) { + lua_pushlstring(state, str.data(), str.size()); + } + inline void Push(lua_State *state, df::coord &obj) { PushDFObject(state, &obj); } + inline void Push(lua_State *state, df::coord2d &obj) { PushDFObject(state, &obj); } + template inline void Push(lua_State *state, T *ptr) { + PushDFObject(state, ptr); + } + + template + void PushVector(lua_State *state, const T &pvec) + { + lua_createtable(state,pvec.size(),0); + + for (size_t i = 0; i < pvec.size(); i++) + { + Push(state, pvec[i]); + lua_rawseti(state, -2, i+1); + } + } + + DFHACK_EXPORT int PushPosXYZ(lua_State *state, df::coord pos); + + DFHACK_EXPORT bool IsCoreContext(lua_State *state); + + DFHACK_EXPORT int NewEvent(lua_State *state); + DFHACK_EXPORT void MakeEvent(lua_State *state, void *key); + DFHACK_EXPORT void InvokeEvent(color_ostream &out, lua_State *state, void *key, int num_args); + + /** + * Namespace for the common lua interpreter state. + * All accesses must be done under CoreSuspender. + */ + namespace Core { + DFHACK_EXPORT extern lua_State *State; + + // Not exported; for use by the Core class + void Init(color_ostream &out); + void Reset(color_ostream &out, const char *where); + + // Events signalled by the core + void onStateChange(color_ostream &out, int code); + + template inline void Push(T &arg) { Lua::Push(State, arg); } + template inline void Push(const T &arg) { Lua::Push(State, arg); } + template inline void PushVector(const T &arg) { Lua::PushVector(State, arg); } + + inline bool SafeCall(color_ostream &out, int nargs, int nres, bool perr = true) { + return Lua::SafeCall(out, State, nargs, nres, perr); + } + inline bool PushModule(color_ostream &out, const char *module) { + return Lua::PushModule(out, State, module); + } + inline bool PushModulePublic(color_ostream &out, const char *module, const char *name) { + return Lua::PushModulePublic(out, State, module, name); + } + } + + class DFHACK_EXPORT Notification { + lua_State *state; + void *key; + function_identity_base *handler; + + public: + Notification(function_identity_base *handler = NULL) + : state(NULL), key(NULL), handler(handler) {} + + lua_State *get_state() { return state; } + function_identity_base *get_handler() { return handler; } + + void invoke(color_ostream &out, int nargs); + + void bind(lua_State *state, const char *name); + void bind(lua_State *state, void *key); + }; }} +#define DEFINE_LUA_EVENT_0(name, handler) \ + static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ + void name(color_ostream &out) { \ + handler(out); \ + if (name##_event.get_state()) { \ + name##_event.invoke(out, 0); \ + } \ + } + +#define DEFINE_LUA_EVENT_1(name, handler, arg_type1) \ + static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ + void name(color_ostream &out, arg_type1 arg1) { \ + handler(out, arg1); \ + if (auto state = name##_event.get_state()) { \ + DFHack::Lua::Push(state, arg1); \ + name##_event.invoke(out, 1); \ + } \ + } + +#define DEFINE_LUA_EVENT_2(name, handler, arg_type1, arg_type2) \ + static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ + void name(color_ostream &out, arg_type1 arg1, arg_type2 arg2) { \ + handler(out, arg1, arg2); \ + if (auto state = name##_event.get_state()) { \ + DFHack::Lua::Push(state, arg1); \ + DFHack::Lua::Push(state, arg2); \ + name##_event.invoke(out, 2); \ + } \ + } + +#define DEFINE_LUA_EVENT_3(name, handler, arg_type1, arg_type2, arg_type3) \ + static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ + void name(color_ostream &out, arg_type1 arg1, arg_type2 arg2, arg_type3 arg3) { \ + handler(out, arg1, arg2, arg3); \ + if (auto state = name##_event.get_state()) { \ + DFHack::Lua::Push(state, arg1); \ + DFHack::Lua::Push(state, arg2); \ + DFHack::Lua::Push(state, arg3); \ + name##_event.invoke(out, 3); \ + } \ + } + +#define DEFINE_LUA_EVENT_4(name, handler, arg_type1, arg_type2, arg_type3, arg_type4) \ + static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \ + void name(color_ostream &out, arg_type1 arg1, arg_type2 arg2, arg_type3 arg3, arg_type4 arg4) { \ + handler(out, arg1, arg2, arg3, arg4); \ + if (auto state = name##_event.get_state()) { \ + DFHack::Lua::Push(state, arg1); \ + DFHack::Lua::Push(state, arg2); \ + DFHack::Lua::Push(state, arg3); \ + DFHack::Lua::Push(state, arg4); \ + name##_event.invoke(out, 4); \ + } \ + } diff --git a/library/include/LuaWrapper.h b/library/include/LuaWrapper.h index 2304b940d..97b2e6980 100644 --- a/library/include/LuaWrapper.h +++ b/library/include/LuaWrapper.h @@ -222,6 +222,12 @@ namespace DFHack { namespace LuaWrapper { */ void AttachEnumKeys(lua_State *state, int meta_idx, int ftable_idx, type_identity *ienum); + /** + * Push a closure invoking the given function. + */ + void PushFunctionWrapper(lua_State *state, int meta_idx, + const char *name, function_identity_base *fun); + /** * Wrap functions and add them to the table on the top of the stack. */ diff --git a/library/include/PluginManager.h b/library/include/PluginManager.h index 080e66e66..7f98bf422 100644 --- a/library/include/PluginManager.h +++ b/library/include/PluginManager.h @@ -51,6 +51,9 @@ namespace DFHack class virtual_identity; class RPCService; class function_identity_base; + namespace Lua { + class Notification; + } // anon type, pretty much struct DFLibrary; @@ -64,13 +67,13 @@ namespace DFHack enum state_change_event { - SC_WORLD_LOADED, - SC_WORLD_UNLOADED, - SC_MAP_LOADED, - SC_MAP_UNLOADED, - SC_VIEWSCREEN_CHANGED, - SC_CORE_INITIALIZED, - SC_BEGIN_UNLOAD + SC_WORLD_LOADED = 0, + SC_WORLD_UNLOADED = 1, + SC_MAP_LOADED = 2, + SC_MAP_UNLOADED = 3, + SC_VIEWSCREEN_CHANGED = 4, + SC_CORE_INITIALIZED = 5, + SC_BEGIN_UNLOAD = 6 }; struct DFHACK_EXPORT CommandReg { const char *name; @@ -80,6 +83,10 @@ namespace DFHack const char *name; function_identity_base *identity; }; + struct DFHACK_EXPORT EventReg { + const char *name; + Lua::Notification *event; + }; struct DFHACK_EXPORT PluginCommand { typedef command_result (*command_function)(color_ostream &out, std::vector &); @@ -178,6 +185,7 @@ namespace DFHack Plugin *owner; std::string name; int (*command)(lua_State *state); + LuaCommand(Plugin *owner, std::string name) : owner(owner), name(name) {} }; std::map lua_commands; static int lua_cmd_wrapper(lua_State *state); @@ -186,9 +194,19 @@ namespace DFHack Plugin *owner; std::string name; function_identity_base *identity; + LuaFunction(Plugin *owner, std::string name) : owner(owner), name(name) {} }; std::map lua_functions; static int lua_fun_wrapper(lua_State *state); + void push_function(lua_State *state, LuaFunction *fn); + + struct LuaEvent { + LuaFunction handler; + Lua::Notification *event; + bool active; + LuaEvent(Plugin *owner, std::string name) : handler(owner,name), active(false) {} + }; + std::map lua_events; void index_lua(DFLibrary *lib); void reset_lua(); @@ -253,7 +271,10 @@ namespace DFHack DFhackCExport const DFHack::CommandReg plugin_lua_commands[] = #define DFHACK_PLUGIN_LUA_FUNCTIONS \ DFhackCExport const DFHack::FunctionReg plugin_lua_functions[] = +#define DFHACK_PLUGIN_LUA_EVENTS \ + DFhackCExport const DFHack::EventReg plugin_lua_events[] = #define DFHACK_LUA_COMMAND(name) { #name, name } -#define DFHACK_LUA_FUNCTION(name) { #name, df::wrap_function(name) } +#define DFHACK_LUA_FUNCTION(name) { #name, df::wrap_function(name,true) } +#define DFHACK_LUA_EVENT(name) { #name, &name##_event } #define DFHACK_LUA_END { NULL, NULL } diff --git a/library/include/RemoteClient.h b/library/include/RemoteClient.h index 9eb8fb427..37aaea9b1 100644 --- a/library/include/RemoteClient.h +++ b/library/include/RemoteClient.h @@ -66,7 +66,7 @@ namespace DFHack }; struct RPCMessageHeader { - static const int MAX_MESSAGE_SIZE = 8*1048756; + static const int MAX_MESSAGE_SIZE = 8*1048576; int16_t id; int32_t size; diff --git a/library/lua/dfhack.lua b/library/lua/dfhack.lua index 7230a12aa..c7e2669c5 100644 --- a/library/lua/dfhack.lua +++ b/library/lua/dfhack.lua @@ -21,6 +21,17 @@ COLOR_LIGHTMAGENTA = 13 COLOR_YELLOW = 14 COLOR_WHITE = 15 +-- Events + +if dfhack.is_core_context then + SC_WORLD_LOADED = 0 + SC_WORLD_UNLOADED = 1 + SC_MAP_LOADED = 2 + SC_MAP_UNLOADED = 3 + SC_VIEWSCREEN_CHANGED = 4 + SC_CORE_INITIALIZED = 5 +end + -- Error handling safecall = dfhack.safecall @@ -105,6 +116,10 @@ function xyz2pos(x,y,z) end end +function dfhack.event:__tostring() + return "" +end + function dfhack.persistent:__tostring() return "" @@ -124,5 +139,83 @@ function dfhack.maps.getTileSize() return map.x_count, map.y_count, map.z_count end +-- Interactive + +local print_banner = true + +function dfhack.interpreter(prompt,hfile,env) + if not dfhack.is_interactive() then + return nil, 'not interactive' + end + + print("Type quit to exit interactive lua interpreter.") + + if print_banner then + print("Shortcuts:\n".. + " '= foo' => '_1,_2,... = foo'\n".. + " '! foo' => 'print(foo)'\n".. + "Both save the first result as '_'.") + print_banner = false + end + + local prompt_str = "["..(prompt or 'lua').."]# " + local prompt_env = {} + local t_prompt + local vcnt = 1 + + setmetatable(prompt_env, { __index = env or _G }) + local cmdlinelist={} + while true do + local cmdline = dfhack.lineedit(t_prompt or prompt_str, hfile) + + if cmdline == nil or cmdline == 'quit' then + break + elseif cmdline ~= '' then + local pfix = string.sub(cmdline,1,1) + + if pfix == '!' or pfix == '=' then + cmdline = 'return '..string.sub(cmdline,2) + end + table.insert(cmdlinelist,cmdline) + local code,err = load(table.concat(cmdlinelist,'\n'), '=(interactive)', 't', prompt_env) + + if code == nil then + if err:sub(-5)=="" then + t_prompt="[cont]" + + else + dfhack.printerr(err) + cmdlinelist={} + t_prompt=nil + end + else + + cmdlinelist={} + t_prompt=nil + + local data = table.pack(safecall(code)) + + if data[1] and data.n > 1 then + prompt_env._ = data[2] + + if pfix == '!' then + safecall(print, table.unpack(data,2,data.n)) + else + for i=2,data.n do + local varname = '_'..vcnt + prompt_env[varname] = data[i] + dfhack.print(varname..' = ') + safecall(print, data[i]) + vcnt = vcnt + 1 + end + end + end + end + end + end + + return true +end + -- Feed the table back to the require() mechanism. return dfhack diff --git a/library/xml b/library/xml index a54516705..e8036d3f1 160000 --- a/library/xml +++ b/library/xml @@ -1 +1 @@ -Subproject commit a545167050fee9eedd5e319b518d961f933154a3 +Subproject commit e8036d3f13c6be0141899baae90f605ad11d5385 diff --git a/plugins/Brushes.h b/plugins/Brushes.h index 73c3a05a9..a525d279c 100644 --- a/plugins/Brushes.h +++ b/plugins/Brushes.h @@ -6,6 +6,9 @@ class Brush public: virtual ~Brush(){}; virtual coord_vec points(MapExtras::MapCache & mc,DFHack::DFCoord start) = 0; + virtual std::string str() const { + return "unknown"; + } }; /** * generic 3D rectangle brush. you can specify the dimensions of @@ -56,6 +59,13 @@ public: return v; }; ~RectangleBrush(){}; + std::string str() const { + if (x_ == 1 && y_ == 1 && z_ == 1) { + return "point"; + } else { + return "rectangle"; + } + } private: int x_, y_, z_; int cx_, cy_, cz_; @@ -89,6 +99,9 @@ public: } return v; }; + std::string str() const { + return "block"; + } }; /** @@ -117,6 +130,9 @@ public: } return v; }; + std::string str() const { + return "column"; + } }; /** @@ -168,6 +184,9 @@ public: return v; } + std::string str() const { + return "flood"; + } private: void maybeFlood(DFCoord c, std::stack &to_flood, MapExtras::MapCache &mc) { if (mc.testCoord(c)) { @@ -176,3 +195,13 @@ private: } Core *c_; }; + +inline std::ostream &operator<<(std::ostream &stream, const Brush& brush) { + stream << brush.str(); + return stream; +} + +inline std::ostream &operator<<(std::ostream &stream, const Brush* brush) { + stream << brush->str(); + return stream; +} diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index b520c5f19..4bfb392a2 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -102,6 +102,8 @@ if (BUILD_SUPPORTED) DFHACK_PLUGIN(feature feature.cpp) DFHACK_PLUGIN(lair lair.cpp) DFHACK_PLUGIN(zone zone.cpp) + DFHACK_PLUGIN(catsplosion catsplosion.cpp) + DFHACK_PLUGIN(regrass regrass.cpp) # this one exports functions to lua DFHACK_PLUGIN(burrows burrows.cpp LINK_LIBRARIES lua) # not yet. busy with other crud again... diff --git a/plugins/Dfusion/dfusion.cpp b/plugins/Dfusion/dfusion.cpp index 0886d2a34..d8710c2db 100644 --- a/plugins/Dfusion/dfusion.cpp +++ b/plugins/Dfusion/dfusion.cpp @@ -121,6 +121,12 @@ command_result lua_run_file (color_ostream &out, std::vector ¶ } command_result lua_run (color_ostream &out, std::vector ¶meters) { + if (!parameters.empty() && parameters[0] == "--core-context") + { + Lua::InterpreterLoop(out, Lua::Core::State, "core lua"); + return CR_OK; + } + mymutex->lock(); lua::state s=lua::glua::Get(); diff --git a/plugins/burrows.cpp b/plugins/burrows.cpp index 74cb57c45..a629e30c1 100644 --- a/plugins/burrows.cpp +++ b/plugins/burrows.cpp @@ -5,6 +5,7 @@ #include "Error.h" #include "DataFuncs.h" +#include "LuaTools.h" #include "modules/Gui.h" #include "modules/Job.h" @@ -121,6 +122,8 @@ static int name_burrow_id = -1; static void handle_burrow_rename(color_ostream &out, df::burrow *burrow); +DEFINE_LUA_EVENT_1(onBurrowRename, handle_burrow_rename, df::burrow*); + static void detect_burrow_renames(color_ostream &out) { if (ui->main.mode == ui_sidebar_mode::Burrows && @@ -134,7 +137,7 @@ static void detect_burrow_renames(color_ostream &out) auto burrow = df::burrow::find(name_burrow_id); name_burrow_id = -1; if (burrow) - handle_burrow_rename(out, burrow); + onBurrowRename(out, burrow); } } @@ -151,6 +154,9 @@ static std::map diggers; static void handle_dig_complete(color_ostream &out, df::job_type job, df::coord pos, df::tiletype old_tile, df::tiletype new_tile); +DEFINE_LUA_EVENT_4(onDigComplete, handle_dig_complete, + df::job_type, df::coord, df::tiletype, df::tiletype); + static void detect_digging(color_ostream &out) { for (auto it = diggers.begin(); it != diggers.end();) @@ -172,7 +178,7 @@ static void detect_digging(color_ostream &out) if (new_tile != it->second.old_tile) { - handle_dig_complete(out, it->second.job, pos, it->second.old_tile, new_tile); + onDigComplete(out, it->second.job, pos, it->second.old_tile, new_tile); //if (worker && !worker->job.current_job) // worker->counters.think_counter = worker->counters.job_counter = 0; @@ -410,6 +416,17 @@ static void handle_dig_complete(color_ostream &out, df::job_type job, df::coord } } +static void renameBurrow(color_ostream &out, df::burrow *burrow, std::string name) +{ + CHECK_NULL_POINTER(burrow); + + // The event makes this absolutely necessary + CoreSuspender suspend; + + burrow->name = name; + onBurrowRename(out, burrow); +} + static df::burrow *findByName(color_ostream &out, std::string name, bool silent = false) { int id = -1; @@ -552,6 +569,7 @@ static bool setTilesByKeyword(df::burrow *target, std::string name, bool enable) } DFHACK_PLUGIN_LUA_FUNCTIONS { + DFHACK_LUA_FUNCTION(renameBurrow), DFHACK_LUA_FUNCTION(findByName), DFHACK_LUA_FUNCTION(copyUnits), DFHACK_LUA_FUNCTION(copyTiles), @@ -559,6 +577,12 @@ DFHACK_PLUGIN_LUA_FUNCTIONS { DFHACK_LUA_END }; +DFHACK_PLUGIN_LUA_EVENTS { + DFHACK_LUA_EVENT(onBurrowRename), + DFHACK_LUA_EVENT(onDigComplete), + DFHACK_LUA_END +}; + static command_result burrow(color_ostream &out, vector ¶meters) { CoreSuspender suspend; diff --git a/plugins/devel/catsplosion.cpp b/plugins/catsplosion.cpp similarity index 96% rename from plugins/devel/catsplosion.cpp rename to plugins/catsplosion.cpp index 3c213d0a2..179aec2fd 100644 --- a/plugins/devel/catsplosion.cpp +++ b/plugins/catsplosion.cpp @@ -35,9 +35,9 @@ DFhackCExport command_result plugin_init ( color_ostream &out, std::vector & parameters) str << ":" << amount << ":" << flowmode << ":" << setmode << "]#"; if(out.lineedit(str.str(),command,liquids_hist) == -1) return CR_FAILURE; + liquids_hist.add(command); if(command=="help" || command == "?") { diff --git a/plugins/probe.cpp b/plugins/probe.cpp index 3f4a3b6fe..4e041f180 100644 --- a/plugins/probe.cpp +++ b/plugins/probe.cpp @@ -382,12 +382,15 @@ command_result df_bprobe (color_ostream &out, vector & parameters) out.print(", subtype %i", building.subtype); break; } - if(building.origin->isRoom()) + if(building.origin->is_room) //isRoom()) out << ", is room"; else out << ", not a room"; + if(building.origin->getBuildStage()!=building.origin->getMaxBuildStage()) + out << ", in construction"; out.print("\n"); + } return CR_OK; } diff --git a/plugins/devel/regrass.cpp b/plugins/regrass.cpp similarity index 100% rename from plugins/devel/regrass.cpp rename to plugins/regrass.cpp diff --git a/plugins/rename.cpp b/plugins/rename.cpp index 7302aea60..1871d0f73 100644 --- a/plugins/rename.cpp +++ b/plugins/rename.cpp @@ -150,7 +150,7 @@ static command_result rename(color_ostream &out, vector ¶meters) if (parameters.size() != 2) return CR_WRONG_USAGE; - df::unit *unit = Gui::getSelectedUnit(out); + df::unit *unit = Gui::getSelectedUnit(out, true); if (!unit) return CR_WRONG_USAGE; @@ -161,7 +161,7 @@ static command_result rename(color_ostream &out, vector ¶meters) if (parameters.size() != 2) return CR_WRONG_USAGE; - df::unit *unit = Gui::getSelectedUnit(out); + df::unit *unit = Gui::getSelectedUnit(out, true); if (!unit) return CR_WRONG_USAGE; diff --git a/plugins/stonesense b/plugins/stonesense index d1c87ec27..15e3b726c 160000 --- a/plugins/stonesense +++ b/plugins/stonesense @@ -1 +1 @@ -Subproject commit d1c87ec273ef5c928989437379943a9a71a1d4e0 +Subproject commit 15e3b726c3e68d2985aecd95d2a33bf4550caaa1 diff --git a/plugins/tiletypes.cpp b/plugins/tiletypes.cpp index 61b4ec8e7..73ec9f963 100644 --- a/plugins/tiletypes.cpp +++ b/plugins/tiletypes.cpp @@ -1,4 +1,24 @@ +// Plugin tiletypes // +// This plugin allows fine editing of individual game tiles (expect for +// changing material subtypes). +// +// Commands: +// tiletypes - runs the interractive interpreter +// tiletypes-command - run the given command +// (intended to be mapped to a hotkey or used from dfhack-run) +// tiletypes-here - runs the execute method with the last settings from +// tiletypes(-command), including brush! +// (intended to be mapped to a hotkey) +// tiletypes-here-point - runs the execute method with the last settings from +// tiletypes(-command), except with a point brush! +// (intended to be mapped to a hotkey) +// Options (everything but tiletypes-command): +// ?, help - print some help +// +// Options (tiletypes-command): +// (anything) - run the given command + #include #include #include @@ -25,39 +45,120 @@ using namespace MapExtras; using namespace DFHack; using namespace df::enums; -//zilpin: These two functions were giving me compile errors in VS2008, so I cheated with the C style loop below, just to get it to build. -//Original code is commented out. -void tolower(std::string &str) -{ - //The C++ way... - //std::transform(str.begin(), str.end(), str.begin(), std::bind2nd(std::ptr_fun(&std::tolower ), std::locale(""))); +CommandHistory tiletypes_hist; - //The C way... - for(char *c=(char *)str.c_str(); *c; ++c) - { - *c = tolower(*c); - } +command_result df_tiletypes (color_ostream &out, vector & parameters); +command_result df_tiletypes_command (color_ostream &out, vector & parameters); +command_result df_tiletypes_here (color_ostream &out, vector & parameters); +command_result df_tiletypes_here_point (color_ostream &out, vector & parameters); + +DFHACK_PLUGIN("tiletypes"); + +DFhackCExport command_result plugin_init ( color_ostream &out, std::vector &commands) +{ + tiletypes_hist.load("tiletypes.history"); + commands.push_back(PluginCommand("tiletypes", "Paint map tiles freely, similar to liquids.", df_tiletypes, true)); + commands.push_back(PluginCommand("tiletypes-command", "Run the given commands (seperated by ' ; '; an empty command is the same as run).", df_tiletypes_command)); + commands.push_back(PluginCommand("tiletypes-here", "Use the last settings from tiletypes, including brush, at cursor location.", df_tiletypes_here)); + commands.push_back(PluginCommand("tiletypes-here-point", "Use the last settings from tiletypes, not including brush, at cursor location.", df_tiletypes_here_point)); + return CR_OK; } -void toupper(std::string &str) +DFhackCExport command_result plugin_shutdown ( color_ostream &out ) { - //std::transform(str.begin(), str.end(), str.begin(), std::bind2nd(std::ptr_fun(&std::toupper), std::locale(""))); - for(char *c=(char *)str.c_str(); *c; ++c) - { - *c = toupper(*c); - } + tiletypes_hist.save("tiletypes.history"); + return CR_OK; } -int toint(const std::string &str, int failValue = 0) +void help( color_ostream & out, std::vector &commands, int start, int end) { - std::istringstream ss(str); - int valInt; - ss >> valInt; - if (ss.fail()) + std::string option = commands.size() > start ? commands[start] : ""; + if (option.empty()) { - return failValue; + out << "Commands:" << std::endl + << " quit / q : quit" << std::endl + << " filter / f [options] : change filter options" << std::endl + << " paint / p [options] : change paint options" << std::endl + << " point / p : set point brush" << std::endl + << " range / r [w] [h] [z] : set range brush" << std::endl + << " block : set block brush" << std::endl + << " column : set column brush" << std::endl + << " run / (empty) : paint!" << std::endl + << std::endl + << "Filter/paint options:" << std::endl + << " Shape / sh / s: set tile shape information" << std::endl + << " Material / mat / m: set tile material information" << std::endl + << " Special / sp: set special tile information" << std::endl + << " Variant / var / v: set variant tile information" << std::endl + << " All / a: set the four above at the same time (no ANY support)" << std::endl + << " Designated / d: set designated flag" << std::endl + << " Hidden / h: set hidden flag" << std::endl + << " Light / l: set light flag" << std::endl + << " Subterranean / st: set subterranean flag" << std::endl + << " Skyview / sv: set skyview flag" << std::endl + << "See help [option] for more information" << std::endl; + } + else if (option == "shape" || option == "s" ||option == "sh") + { + out << "Available shapes:" << std::endl + << " ANY" << std::endl; + FOR_ENUM_ITEMS(tiletype_shape,i) + { + out << " " << ENUM_KEY_STR(tiletype_shape,i) << std::endl; + } + } + else if (option == "material"|| option == "mat" ||option == "m") + { + out << "Available materials:" << std::endl + << " ANY" << std::endl; + FOR_ENUM_ITEMS(tiletype_material,i) + { + out << " " << ENUM_KEY_STR(tiletype_material,i) << std::endl; + } + } + else if (option == "special" || option == "sp") + { + out << "Available specials:" << std::endl + << " ANY" << std::endl; + FOR_ENUM_ITEMS(tiletype_special,i) + { + out << " " << ENUM_KEY_STR(tiletype_special,i) << std::endl; + } + } + else if (option == "variant" || option == "var" || option == "v") + { + out << "Available variants:" << std::endl + << " ANY" << std::endl; + FOR_ENUM_ITEMS(tiletype_variant,i) + { + out << " " << ENUM_KEY_STR(tiletype_variant,i) << std::endl; + } + } + else if (option == "designated" || option == "d") + { + out << "Available designated flags:" << std::endl + << " ANY, 0, 1" << std::endl; + } + else if (option == "hidden" || option == "h") + { + out << "Available hidden flags:" << std::endl + << " ANY, 0, 1" << std::endl; + } + else if (option == "light" || option == "l") + { + out << "Available light flags:" << std::endl + << " ANY, 0, 1" << std::endl; + } + else if (option == "subterranean" || option == "st") + { + out << "Available subterranean flags:" << std::endl + << " ANY, 0, 1" << std::endl; + } + else if (option == "skyview" || option == "sv") + { + out << "Available skyview flags:" << std::endl + << " ANY, 0, 1" << std::endl; } - return valInt; } struct TileType @@ -217,12 +318,116 @@ std::ostream &operator<<(std::ostream &stream, const TileType &paint) return stream; } -bool processTileType(TileType &paint, const std::string &option, const std::string &value) +static TileType filter, paint; +static Brush *brush = new RectangleBrush(1,1); + +void printState(color_ostream &out) { - std::string val = value; - toupper(val); + out << "Filter: " << filter << std::endl + << "Paint: " << paint << std::endl + << "Brush: " << brush << std::endl; +} + +//zilpin: These two functions were giving me compile errors in VS2008, so I cheated with the C style loop below, just to get it to build. +//Original code is commented out. +void tolower(std::string &str) +{ + //The C++ way... + //std::transform(str.begin(), str.end(), str.begin(), std::bind2nd(std::ptr_fun(&std::tolower ), std::locale(""))); + + //The C way... + for(char *c=(char *)str.c_str(); *c; ++c) + { + *c = tolower(*c); + } +} + +void toupper(std::string &str) +{ + //std::transform(str.begin(), str.end(), str.begin(), std::bind2nd(std::ptr_fun(&std::toupper), std::locale(""))); + for(char *c=(char *)str.c_str(); *c; ++c) + { + *c = toupper(*c); + } +} + +int toint(const std::string &str, int failValue = 0) +{ + std::istringstream ss(str); int valInt; - if (val == "ANY") + ss >> valInt; + if (ss.fail()) + { + return failValue; + } + return valInt; +} + +bool tryShape(std::string value, TileType &paint) +{ + FOR_ENUM_ITEMS(tiletype_shape,i) + { + if (value == ENUM_KEY_STR(tiletype_shape,i)) + { + paint.shape = i; + return true; + } + } + return false; +} + +bool tryMaterial(std::string value, TileType &paint) +{ + FOR_ENUM_ITEMS(tiletype_material, i) + { + if (value == ENUM_KEY_STR(tiletype_material,i)) + { + paint.material = i; + return true; + } + } + return false; +} + +bool trySpecial(std::string value, TileType &paint) +{ + FOR_ENUM_ITEMS(tiletype_special, i) + { + if (value == ENUM_KEY_STR(tiletype_special,i)) + { + paint.special = i; + return true; + } + } + return false; +} + +bool tryVariant(std::string value, TileType &paint) +{ + FOR_ENUM_ITEMS(tiletype_variant, i) + { + if (value == ENUM_KEY_STR(tiletype_variant,i)) + { + paint.variant = i; + return true; + } + } + return false; +} + +bool processTileType(color_ostream & out, TileType &paint, std::vector ¶ms, int start, int end) +{ + if (params.size() < start + 2) + { + return false; + } + + int loc = start; + std::string option = params[loc++]; + std::string value = params[loc++]; + toupper(value); + int valInt; + if (value == "ANY") { valInt = -1; } @@ -241,19 +446,9 @@ bool processTileType(TileType &paint, const std::string &option, const std::stri } else { - FOR_ENUM_ITEMS(tiletype_shape,i) + if (!tryShape(value, paint)) { - if (val == ENUM_KEY_STR(tiletype_shape,i)) - { - paint.shape = i; - found = true; - break; - } - } - - if (!found) - { - std::cout << "Unknown tile shape: " << value << std::endl; + out << "Unknown tile shape: " << value << std::endl; } } } @@ -266,19 +461,9 @@ bool processTileType(TileType &paint, const std::string &option, const std::stri } else { - FOR_ENUM_ITEMS(tiletype_material, i) - { - if (val == ENUM_KEY_STR(tiletype_material,i)) - { - paint.material = i; - found = true; - break; - } - } - - if (!found) + if (!tryMaterial(value, paint)) { - std::cout << "Unknown tile material: " << value << std::endl; + out << "Unknown tile material: " << value << std::endl; } } } @@ -291,19 +476,9 @@ bool processTileType(TileType &paint, const std::string &option, const std::stri } else { - FOR_ENUM_ITEMS(tiletype_special, i) + if (!trySpecial(value, paint)) { - if (val == ENUM_KEY_STR(tiletype_special,i)) - { - paint.special = i; - found = true; - break; - } - } - - if (!found) - { - std::cout << "Unknown tile special: " << value << std::endl; + out << "Unknown tile special: " << value << std::endl; } } } @@ -316,19 +491,9 @@ bool processTileType(TileType &paint, const std::string &option, const std::stri } else { - FOR_ENUM_ITEMS(tiletype_variant, i) + if (!tryVariant(value, paint)) { - if (val == ENUM_KEY_STR(tiletype_variant,i)) - { - paint.variant = i; - found = true; - break; - } - } - - if (!found) - { - std::cout << "Unknown tile variant: " << value << std::endl; + out << "Unknown tile variant: " << value << std::endl; } } } @@ -341,7 +506,7 @@ bool processTileType(TileType &paint, const std::string &option, const std::stri } else { - std::cout << "Unknown designation flag: " << value << std::endl; + out << "Unknown designation flag: " << value << std::endl; } } else if (option == "hidden" || option == "h") @@ -353,7 +518,7 @@ bool processTileType(TileType &paint, const std::string &option, const std::stri } else { - std::cout << "Unknown hidden flag: " << value << std::endl; + out << "Unknown hidden flag: " << value << std::endl; } } else if (option == "light" || option == "l") @@ -365,7 +530,7 @@ bool processTileType(TileType &paint, const std::string &option, const std::stri } else { - std::cout << "Unknown light flag: " << value << std::endl; + out << "Unknown light flag: " << value << std::endl; } } else if (option == "subterranean" || option == "st") @@ -377,7 +542,7 @@ bool processTileType(TileType &paint, const std::string &option, const std::stri } else { - std::cout << "Unknown subterranean flag: " << value << std::endl; + out << "Unknown subterranean flag: " << value << std::endl; } } else if (option == "skyview" || option == "sv") @@ -389,380 +554,388 @@ bool processTileType(TileType &paint, const std::string &option, const std::stri } else { - std::cout << "Unknown skyview flag: " << value << std::endl; + out << "Unknown skyview flag: " << value << std::endl; + } + } + else if (option == "all" || option == "a") + { + loc--; + for (; loc < end; loc++) + { + std::string param = params[loc]; + toupper(param); + + if (!(tryShape(param, paint) || tryMaterial(param, paint) || + trySpecial(param, paint) || tryVariant(param, paint))) + { + out << "Unknown description: '" << param << "'" << std::endl; + break; + } } + + found = true; } else { - std::cout << "Unknown option: '" << option << "'" << std::endl; + out << "Unknown option: '" << option << "'" << std::endl; } return found; } -void help( std::ostream & out, const std::string &option) +command_result executePaintJob(color_ostream &out) { - if (option.empty()) + if (paint.empty()) { - out << "Commands:" << std::endl - << " quit / q : quit" << std::endl - << " filter / f [options] : change filter options" << std::endl - << " paint / p [options] : change paint options" << std::endl - << " point / p : set point brush" << std::endl - << " range / r : set range brush" << std::endl - << " block : set block brush" << std::endl - << " column : set column brush" << std::endl - << std::endl - << "Filter/paint options:" << std::endl - << " Shape / sh / s: set tile shape information" << std::endl - << " Material / mat / m: set tile material information" << std::endl - << " Special / sp: set special tile information" << std::endl - << " Variant / var / v: set variant tile information" << std::endl - << " Designated / d: set designated flag" << std::endl - << " Hidden / h: set hidden flag" << std::endl - << " Light / l: set light flag" << std::endl - << " Subterranean / st: set subterranean flag" << std::endl - << " Skyview / sv: set skyview flag" << std::endl - << "See help [option] for more information" << std::endl; + out.printerr("Set the paint first.\n"); + return CR_OK; } - else if (option == "shape" || option == "s" ||option == "sh") + + CoreSuspender suspend; + uint32_t x_max = 0, y_max = 0, z_max = 0; + int32_t x = 0, y = 0, z = 0; + + if (!Maps::IsValid()) { - out << "Available shapes:" << std::endl - << " ANY" << std::endl; - FOR_ENUM_ITEMS(tiletype_shape,i) - { - out << " " << ENUM_KEY_STR(tiletype_shape,i) << std::endl; - } + out.printerr("Map is not available!\n"); + return CR_FAILURE; } - else if (option == "material"|| option == "mat" ||option == "m") + Maps::getSize(x_max, y_max, z_max); + + if (!Gui::getCursorCoords(x,y,z)) { - out << "Available materials:" << std::endl - << " ANY" << std::endl; - FOR_ENUM_ITEMS(tiletype_material,i) - { - out << " " << ENUM_KEY_STR(tiletype_material,i) << std::endl; - } + out.printerr("Can't get cursor coords! Make sure you have a cursor active in DF.\n"); + return CR_FAILURE; } - else if (option == "special" || option == "sp") + out.print("Cursor coords: (%d, %d, %d)\n", x, y, z); + + DFHack::DFCoord cursor(x,y,z); + MapExtras::MapCache map; + coord_vec all_tiles = brush->points(map, cursor); + out.print("working...\n"); + + for (coord_vec::iterator iter = all_tiles.begin(); iter != all_tiles.end(); ++iter) { - out << "Available specials:" << std::endl - << " ANY" << std::endl; - FOR_ENUM_ITEMS(tiletype_special,i) + const df::tiletype source = map.tiletypeAt(*iter); + df::tile_designation des = map.designationAt(*iter); + + if ((filter.shape > -1 && filter.shape != tileShape(source)) + || (filter.material > -1 && filter.material != tileMaterial(source)) + || (filter.special > -1 && filter.special != tileSpecial(source)) + || (filter.variant > -1 && filter.variant != tileVariant(source)) + || (filter.dig > -1 && (filter.dig != 0) != (des.bits.dig != tile_dig_designation::No)) + ) { - out << " " << ENUM_KEY_STR(tiletype_special,i) << std::endl; + return CR_OK; } - } - else if (option == "variant" || option == "var" || option == "v") - { - out << "Available variants:" << std::endl - << " ANY" << std::endl; - FOR_ENUM_ITEMS(tiletype_variant,i) + + df::tiletype_shape shape = paint.shape; + if (shape == tiletype_shape::NONE) { - out << " " << ENUM_KEY_STR(tiletype_variant,i) << std::endl; + shape = tileShape(source); + } + + df::tiletype_material material = paint.material; + if (material == tiletype_material::NONE) + { + material = tileMaterial(source); + } + + df::tiletype_special special = paint.special; + if (special == tiletype_special::NONE) + { + special = tileSpecial(source); + } + df::tiletype_variant variant = paint.variant; + /* + * FIXME: variant should be: + * 1. If user variant: + * 2. If user variant \belongs target variants + * 3. use user variant + * 4. Else + * 5. use variant 0 + * 6. If the source variant \belongs target variants + * 7 use source variant + * 8 ElseIf num target shape/material variants > 1 + * 9. pick one randomly + * 10.Else + * 11. use variant 0 + * + * The following variant check has been disabled because it's severely limiting + * the usefullness of the tool. + */ + /* + if (variant == tiletype_variant::NONE) + { + variant = tileVariant(source); + } + */ + // Remove direction from directionless tiles + DFHack::TileDirection direction = tileDirection(source); + if (!(material == tiletype_material::RIVER || shape == tiletype_shape::BROOK_BED || shape == tiletype_shape::WALL && (material == tiletype_material::CONSTRUCTION || special == tiletype_special::SMOOTH))) + { + direction.whole = 0; + } + + df::tiletype type = DFHack::findTileType(shape, material, variant, special, direction); + // hack for empty space + if (shape == tiletype_shape::EMPTY && material == tiletype_material::AIR && variant == tiletype_variant::VAR_1 && special == tiletype_special::NORMAL && direction.whole == 0) + { + type = tiletype::OpenSpace; + } + // make sure it's not invalid + if(type != tiletype::Void) + map.setTiletypeAt(*iter, type); + + if (paint.hidden > -1) + { + des.bits.hidden = paint.hidden; + } + + if (paint.light > -1) + { + des.bits.light = paint.light; + } + + if (paint.subterranean > -1) + { + des.bits.subterranean = paint.subterranean; } + + if (paint.skyview > -1) + { + des.bits.outside = paint.skyview; + } + + // Remove liquid from walls, etc + if (type != -1 && !DFHack::FlowPassable(type)) + { + des.bits.flow_size = 0; + //des.bits.liquid_type = DFHack::liquid_water; + //des.bits.water_table = 0; + des.bits.flow_forbid = 0; + //des.bits.liquid_static = 0; + //des.bits.water_stagnant = 0; + //des.bits.water_salt = 0; + } + + map.setDesignationAt(*iter, des); } - else if (option == "designated" || option == "d") + + if (map.WriteAll()) { - out << "Available designated flags:" << std::endl - << " ANY, 0, 1" << std::endl; + out.print("OK\n"); } - else if (option == "hidden" || option == "h") + else { - out << "Available hidden flags:" << std::endl - << " ANY, 0, 1" << std::endl; + out.printerr("Something failed horribly! RUN!\n"); + return CR_FAILURE; } - else if (option == "light" || option == "l") +} + +command_result processCommand(color_ostream &out, std::vector &commands, int start, int end, bool & endLoop, bool hasConsole = false) +{ + if (commands.size() == start) { - out << "Available light flags:" << std::endl - << " ANY, 0, 1" << std::endl; + return executePaintJob(out); } - else if (option == "subterranean" || option == "st") + + std::ostringstream ss_o; + int loc = start; + + std::string command = commands[loc++]; + tolower(command); + + if (command == "help" || command == "?") { - out << "Available subterranean flags:" << std::endl - << " ANY, 0, 1" << std::endl; + help(out, commands, loc, end); } - else if (option == "skyview" || option == "sv") + else if (command == "quit" || command == "q") { - out << "Available skyview flags:" << std::endl - << " ANY, 0, 1" << std::endl; + endLoop = true; } -} + else if (command == "filter" || command == "f") + { + processTileType(out, filter, commands, loc, end); + } + else if (command == "paint" || (command == "p" && commands.size() > 1)) + { + processTileType(out, paint, commands, loc, end); + } + else if (command == "point" || command == "p") + { + delete brush; + brush = new RectangleBrush(1,1); + } + else if (command == "range" || command == "r") + { + int width = 0, height = 0, z_levels = 0; -CommandHistory tiletypes_hist; + if (commands.size() > loc + 1) + { + width = toint(commands[loc++]); + height = toint(commands[loc++]); -command_result df_tiletypes (color_ostream &out, vector & parameters); + if (commands.size() > loc) { + z_levels = toint(commands[loc++]); + } + } -DFHACK_PLUGIN("tiletypes"); + if (width < 1 || height < 1) { + if (hasConsole) { + Console &con = static_cast(out); + CommandHistory hist; -DFhackCExport command_result plugin_init ( color_ostream &out, std::vector &commands) -{ - tiletypes_hist.load("tiletypes.history"); - commands.push_back(PluginCommand("tiletypes", "Paint map tiles freely, similar to liquids.", df_tiletypes, true)); - return CR_OK; -} + ss_o << "Set range width <" << width << "> "; + con.lineedit(ss_o.str(),command,hist); + width = command == "" ? width : toint(command); + + ss_o.str(""); + ss_o << "Set range height <" << height << "> "; + con.lineedit(ss_o.str(),command,hist); + height = command == "" ? height : toint(command); + + ss_o.str(""); + ss_o << "Set range z-levels <" << z_levels << "> "; + con.lineedit(ss_o.str(),command,hist); + z_levels = command == "" ? z_levels : toint(command); + } else { + return CR_WRONG_USAGE; + } + } + + if (width < 1) width = 1; + if (height < 1) height = 1; + if (z_levels < 1) z_levels = 1; + + delete brush; + brush = new RectangleBrush(width, height, z_levels, 0, 0, 0); + } + else if (command == "block") + { + delete brush; + brush = new BlockBrush(); + } + else if (command == "column") + { + delete brush; + brush = new ColumnBrush(); + } + else if (command == "run" || command.empty()) + { + executePaintJob(out); + } -DFhackCExport command_result plugin_shutdown ( color_ostream &out ) -{ - tiletypes_hist.save("tiletypes.history"); return CR_OK; } -command_result df_tiletypes (color_ostream &out, vector & parameters) +command_result df_tiletypes (color_ostream &out_, vector & parameters) { - uint32_t x_max = 0, y_max = 0, z_max = 0; - int32_t x = 0, y = 0, z = 0; - for(size_t i = 0; i < parameters.size();i++) { if(parameters[i] == "help" || parameters[i] == "?") { - out.print("This tool allows painting tiles types with a brush, using an optional filter.\n" - "The tool is interactive, similarly to the liquids tool.\n" - "Further help is available inside.\n" + out_.print("This tool allows painting tiles types with a brush, using an optional filter.\n" + "The tool is interactive, similarly to the liquids tool.\n" + "Further help is available inside.\n" ); return CR_OK; } } - if(!out.is_console()) + if(!out_.is_console()) return CR_FAILURE; - Console &con = static_cast(out); + Console &out = static_cast(out_); - TileType filter, paint; - Brush *brush = new RectangleBrush(1,1); + std::vector commands; bool end = false; - std::string brushname = "point"; - int width = 1, height = 1, z_levels = 1; - con << "Welcome to the tiletype tool.\nType 'help' or '?' for a list of available commands, 'q' to quit.\nPress return after a command to confirm." << std::endl; - con.printerr("THIS TOOL CAN BE DANGEROUS. YOU'VE BEEN WARNED.\n"); + out << "Welcome to the tiletype tool.\nType 'help' or '?' for a list of available commands, 'q' to quit.\nPress return after a command to confirm." << std::endl; + out.printerr("THIS TOOL CAN BE DANGEROUS. YOU'VE BEEN WARNED.\n"); while (!end) { - con << "Filter: " << filter << std::endl - << "Paint: " << paint << std::endl - << "Brush: " << brushname << std::endl; + printState(out); std::string input = ""; - std::string command = ""; - std::string option = ""; - std::string value = ""; - con.lineedit("tiletypes> ",input,tiletypes_hist); + if (out.lineedit("tiletypes> ",input,tiletypes_hist) == -1) + return CR_FAILURE; tiletypes_hist.add(input); - std::istringstream ss(input); - ss >> command >> option >> value; - tolower(command); - tolower(option); - if (command == "help" || command == "?") - { - help(con,option); - } - else if (command == "quit" || command == "q") - { - end = true; - } - else if (command == "filter" || command == "f") - { - processTileType(filter, option, value); - } - else if (command == "paint" || (command == "p" && !option.empty())) - { - processTileType(paint, option, value); - } - else if (command == "point" || command == "p") + commands.clear(); + Core::cheap_tokenise(input, commands); + + command_result ret = processCommand(out, commands, 0, commands.size(), end, true); + + if (ret != CR_OK) { - delete brush; - brushname = "point"; - brush = new RectangleBrush(1,1); + return ret; } - else if (command == "range" || command == "r") - { - std::stringstream ss; - CommandHistory hist; - ss << "Set range width <" << width << "> "; - con.lineedit(ss.str(),command,hist); - width = command == "" ? width : toint(command); - if (width < 1) width = 1; - - ss.str(""); - ss << "Set range height <" << height << "> "; - con.lineedit(ss.str(),command,hist); - height = command == "" ? height : toint(command); - if (height < 1) height = 1; + } + return CR_OK; +} - ss.str(""); - ss << "Set range z-levels <" << z_levels << "> "; - con.lineedit(ss.str(),command,hist); - z_levels = command == "" ? z_levels : toint(command); - if (z_levels < 1) z_levels = 1; +command_result df_tiletypes_command (color_ostream &out, vector & parameters) +{ + bool dummy; + int start = 0, end = 0; - delete brush; - if (width == 1 && height == 1 && z_levels == 1) - { - brushname = "point"; - } - else - { - brushname = "range"; + parameters.push_back(";"); + for (size_t i = 0; i < parameters.size();i++) + { + if (parameters[i] == ";") { + command_result rv = processCommand(out, parameters, start, end, dummy); + if (rv != CR_OK) { + return rv; } - brush = new RectangleBrush(width, height, z_levels, 0, 0, 0); + end++; + start = end; + } else { + end++; } - else if (command == "block") - { - delete brush; - brushname = "block"; - brush = new BlockBrush(); - } - else if (command == "column") + } + + return CR_OK; +} + +command_result df_tiletypes_here (color_ostream &out, vector & parameters) +{ + for(size_t i = 0; i < parameters.size();i++) + { + if(parameters[i] == "help" || parameters[i] == "?") { - delete brush; - brushname = "column"; - brush = new ColumnBrush(); + out << "This command is supposed to be mapped to a hotkey." << endl; + out << "It will use the current/last parameters set in tiletypes (including brush settings!)." << endl; + return CR_OK; } - else if (command.empty()) - { - if (paint.empty()) - { - con.printerr("Set the paint first.\n"); - continue; - } + } - CoreSuspender suspend; + out.print("Run tiletypes-here with these parameters: "); + printState(out); - if (!Maps::IsValid()) - { - con.printerr("Map is not available!\n"); - return CR_FAILURE; - } - Maps::getSize(x_max, y_max, z_max); + return executePaintJob(out); +} - if (!Gui::getCursorCoords(x,y,z)) - { - con.printerr("Can't get cursor coords! Make sure you have a cursor active in DF.\n"); - return CR_FAILURE; - } - con.print("Cursor coords: (%d, %d, %d)\n",x,y,z); +command_result df_tiletypes_here_point (color_ostream &out, vector & parameters) +{ + for(size_t i = 0; i < parameters.size();i++) + { + if(parameters[i] == "help" || parameters[i] == "?") + { + out << "This command is supposed to be mapped to a hotkey." << endl; + out << "It will use the current/last parameters set in tiletypes (except with a point brush)." << endl; + return CR_OK; + } + } - DFHack::DFCoord cursor(x,y,z); - MapExtras::MapCache map; - coord_vec all_tiles = brush->points(map, cursor); - con.print("working...\n"); + Brush *old = brush; + brush = new RectangleBrush(1, 1); - for (coord_vec::iterator iter = all_tiles.begin(); iter != all_tiles.end(); ++iter) - { - const df::tiletype source = map.tiletypeAt(*iter); - df::tile_designation des = map.designationAt(*iter); - - if ((filter.shape > -1 && filter.shape != tileShape(source)) - || (filter.material > -1 && filter.material != tileMaterial(source)) - || (filter.special > -1 && filter.special != tileSpecial(source)) - || (filter.variant > -1 && filter.variant != tileVariant(source)) - || (filter.dig > -1 && (filter.dig != 0) != (des.bits.dig != tile_dig_designation::No)) - ) - { - continue; - } - - df::tiletype_shape shape = paint.shape; - if (shape == tiletype_shape::NONE) - { - shape = tileShape(source); - } - - df::tiletype_material material = paint.material; - if (material == tiletype_material::NONE) - { - material = tileMaterial(source); - } - - df::tiletype_special special = paint.special; - if (special == tiletype_special::NONE) - { - special = tileSpecial(source); - } - df::tiletype_variant variant = paint.variant; - /* - * FIXME: variant should be: - * 1. If user variant: - * 2. If user variant \belongs target variants - * 3. use user variant - * 4. Else - * 5. use variant 0 - * 6. If the source variant \belongs target variants - * 7 use source variant - * 8 ElseIf num target shape/material variants > 1 - * 9. pick one randomly - * 10.Else - * 11. use variant 0 - * - * The following variant check has been disabled because it's severely limiting - * the usefullness of the tool. - */ - /* - if (variant == tiletype_variant::NONE) - { - variant = tileVariant(source); - } - */ - // Remove direction from directionless tiles - DFHack::TileDirection direction = tileDirection(source); - if (!(material == tiletype_material::RIVER || shape == tiletype_shape::BROOK_BED || shape == tiletype_shape::WALL && (material == tiletype_material::CONSTRUCTION || special == tiletype_special::SMOOTH))) { - direction.whole = 0; - } - - df::tiletype type = DFHack::findTileType(shape, material, variant, special, direction); - // hack for empty space - if (shape == tiletype_shape::EMPTY && material == tiletype_material::AIR && variant == tiletype_variant::VAR_1 && special == tiletype_special::NORMAL && direction.whole == 0) { - type = tiletype::OpenSpace; - } - // make sure it's not invalid - if(type != tiletype::Void) - map.setTiletypeAt(*iter, type); - - if (paint.hidden > -1) - { - des.bits.hidden = paint.hidden; - } - - if (paint.light > -1) - { - des.bits.light = paint.light; - } - - if (paint.subterranean > -1) - { - des.bits.subterranean = paint.subterranean; - } - - if (paint.skyview > -1) - { - des.bits.outside = paint.skyview; - } - - // Remove liquid from walls, etc - if (type != -1 && !DFHack::FlowPassable(type)) - { - des.bits.flow_size = 0; - //des.bits.liquid_type = DFHack::liquid_water; - //des.bits.water_table = 0; - des.bits.flow_forbid = 0; - //des.bits.liquid_static = 0; - //des.bits.water_stagnant = 0; - //des.bits.water_salt = 0; - } - - map.setDesignationAt(*iter, des); - } + out.print("Run tiletypes-here with these parameters: "); + printState(out); - if (map.WriteAll()) - { - con.print("OK\n"); - } - else - { - con.printerr("Something failed horribly! RUN!\n"); - } - } - } - return CR_OK; + command_result rv = executePaintJob(out); + + delete brush; + brush = old; + return rv; } diff --git a/plugins/tweak.cpp b/plugins/tweak.cpp index 31969bde7..2daa9063b 100644 --- a/plugins/tweak.cpp +++ b/plugins/tweak.cpp @@ -56,10 +56,17 @@ DFhackCExport command_result plugin_init (color_ostream &out, std::vector ¶meters) if (cmd == "clear-missing") { - df::unit *unit = getSelectedUnit(out); + df::unit *unit = getSelectedUnit(out, true); if (!unit) return CR_FAILURE; @@ -157,7 +164,7 @@ static command_result tweak(color_ostream &out, vector ¶meters) } else if (cmd == "clear-ghostly") { - df::unit *unit = getSelectedUnit(out); + df::unit *unit = getSelectedUnit(out, true); if (!unit) return CR_FAILURE; @@ -176,13 +183,9 @@ static command_result tweak(color_ostream &out, vector ¶meters) } else if (cmd == "fixmigrant") { - df::unit *unit = getSelectedUnit(out); - + df::unit *unit = getSelectedUnit(out, true); if (!unit) - { - out << "No unit selected!" << endl; return CR_FAILURE; - } if(unit->race != df::global::ui->race_id) { @@ -213,12 +216,10 @@ static command_result tweak(color_ostream &out, vector ¶meters) { // force a unit into your fort, regardless of civ or race // allows to "steal" caravan guards etc - df::unit *unit = getSelectedUnit(out); + df::unit *unit = getSelectedUnit(out, true); if (!unit) - { - out << "No unit selected!" << endl; return CR_FAILURE; - } + if (unit->flags2.bits.resident) unit->flags2.bits.resident = 0; if(unit->flags1.bits.merchant) diff --git a/plugins/zone.cpp b/plugins/zone.cpp index 968fda72f..ee6abf327 100644 --- a/plugins/zone.cpp +++ b/plugins/zone.cpp @@ -897,6 +897,10 @@ int32_t findCageAtCursor() building->z == cursor->z)) continue; + // don't set id if cage is not constructed yet + if(building->getBuildStage()!=building->getMaxBuildStage()) + break; + if(isCage(building)) { foundID = building->id; @@ -1065,10 +1069,10 @@ bool isInBuiltCageRoom(df::unit* unit) { df::building* building = world->buildings.all[b]; - // !!! for whatever reason isRoom() returns true if a cage is not a room - // !!! and false if it was defined as a room/zoo ingame - // !!! (seems not general behaviour, activity zones return false, for example) - if(building->isRoom()) + // !!! building->isRoom() returns true if the building can be made a room but currently isn't + // !!! except for coffins/tombs which always return false + // !!! using the bool is_room however gives the correct state/value + if(!building->is_room) continue; if(building->getType() == building_type::Cage) @@ -1122,6 +1126,10 @@ df::building * getBuiltCageAtPos(df::coord pos) && building->y1 == pos.y && building->z == pos.z ) { + // don't set pointer if not constructed yet + if(building->getBuildStage()!=building->getMaxBuildStage()) + break; + cage = building; break; } @@ -1594,11 +1602,6 @@ void zoneInfo(color_ostream & out, df::building* building, bool verbose) else out << "not active"; - //if(building->isRoom()) - // out <<", room"; - //else - // out << ", not a room"; - if(civ->zone_flags.bits.pen_pasture) out << ", pen/pasture"; else if (civ->zone_flags.bits.pit_pond) @@ -1655,16 +1658,7 @@ void cageInfo(color_ostream & out, df::building* building, bool verbose) << " z:" << building->z << endl; - //if(building->isRoom()) - // out <<", bldg room"; - //else - // out << ", bldg not a room"; - df::building_cagest * cage = (df::building_cagest*) building; - //if(cage->isRoom()) - // out <<", cage is room"; - //else - // out << ", cage is not a room"; int32_t creaturecount = cage->assigned_creature.size(); out << "Creatures in this cage: " << creaturecount << endl; @@ -2277,8 +2271,8 @@ command_result df_zone (color_ostream &out, vector & parameters) // find building under cursor if (!all && !(building->x1 <= cursor->x && cursor->x <= building->x2 && - building->y1 <= cursor->y && cursor->y <= building->y2 && - building->z == cursor->z)) + building->y1 <= cursor->y && cursor->y <= building->y2 && + building->z == cursor->z)) continue; zoneInfo(out, building, verbose); @@ -2465,12 +2459,9 @@ command_result df_zone (color_ostream &out, vector & parameters) else { // must have unit selected - df::unit *unit = getSelectedUnit(out); + df::unit *unit = getSelectedUnit(out, true); if (!unit) - { - out << "No unit selected." << endl; return CR_WRONG_USAGE; - } if(unit_info) { @@ -2503,18 +2494,16 @@ command_result df_zone (color_ostream &out, vector & parameters) if(building_unassign) { // must have unit selected - df::unit *unit = getSelectedUnit(out); + df::unit *unit = getSelectedUnit(out, true); if (!unit) - { - out << "No unit selected." << endl; return CR_WRONG_USAGE; - } // remove assignment reference from unit and old zone if(unassignUnitFromBuilding(unit)) out << "Unit unassigned." << endl; else out << "Unit is not assigned to an activity zone!" << endl; + return CR_OK; }