Merge remote-tracking branch 'q/master'

develop
Kelly Martin 2012-08-30 09:25:26 -05:00
commit a8158cb19a
91 changed files with 7536 additions and 1855 deletions

6
.gitignore vendored

@ -50,12 +50,6 @@ dfhack/python/PyDFHack.egg-info
dfhack/python/build
dfhack/python/dist
# Ruby binding binaries
plugins/ruby/libruby*
plugins/ruby/msvcrtruby*.tar.gz
plugins/ruby/ruby-autogen.rb
plugins/ruby/ruby-autogen.rb.rule
# CPack stuff
build/CPack*Config.cmake

@ -111,6 +111,9 @@ IF(UNIX)
SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-g -Wall -Wno-unused-variable")
SET(CMAKE_CXX_FLAGS "-fvisibility=hidden -m32 -march=i686 -mtune=generic -std=c++0x")
SET(CMAKE_C_FLAGS "-fvisibility=hidden -m32 -march=i686 -mtune=generic")
ELSEIF(MSVC)
# for msvc, tell it to always use 8-byte pointers to member functions to avoid confusion
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /vmg /vmm")
ENDIF()
# use shared libraries for protobuf

@ -724,15 +724,20 @@ can be omitted.
Gui module
----------
* ``dfhack.gui.getCurViewscreen()``
* ``dfhack.gui.getCurViewscreen([skip_dismissed])``
Returns the viewscreen that is current in the core.
Returns the topmost viewscreen. If ``skip_dismissed`` is *true*,
ignores screens already marked to be removed.
* ``dfhack.gui.getFocusString(viewscreen)``
Returns a string representation of the current focus position
in the ui. The string has a "screen/foo/bar/baz..." format.
* ``dfhack.gui.getCurFocus([skip_dismissed])``
Returns the focus string of the current viewscreen.
* ``dfhack.gui.getSelectedWorkshopJob([silent])``
When a job is selected in *'q'* mode, returns the job, else
@ -875,6 +880,15 @@ Units module
Retrieves the profession name for the given race/caste using raws.
* ``dfhack.units.getProfessionColor(unit[,ignore_noble])``
Retrieves the color associated with the profession, using noble assignments
or raws. The ``ignore_noble`` boolean disables the use of noble positions.
* ``dfhack.units.getCasteProfessionColor(race,caste,prof_id)``
Retrieves the profession color for the given race/caste using raws.
Items module
------------
@ -1027,6 +1041,11 @@ Burrows module
Buildings module
----------------
* ``dfhack.buildings.setOwner(item,unit)``
Replaces the owner of the building. If unit is *nil*, removes ownership.
Returns *false* in case of error.
* ``dfhack.buildings.getSize(building)``
Returns *width, height, centerx, centery*.
@ -1204,6 +1223,165 @@ Constructions module
Returns *true, was_only_planned* if removed; or *false* if none found.
Screen API
----------
The screen module implements support for drawing to the tiled screen of the game.
Note that drawing only has any effect when done from callbacks, so it can only
be feasibly used in the core context.
Basic painting functions:
* ``dfhack.screen.getWindowSize()``
Returns *width, height* of the screen.
* ``dfhack.screen.getMousePos()``
Returns *x,y* of the tile the mouse is over.
* ``dfhack.screen.inGraphicsMode()``
Checks if [GRAPHICS:YES] was specified in init.
* ``dfhack.screen.paintTile(pen,x,y[,char,tile])``
Paints a tile using given parameters. Pen is a table with following possible fields:
``ch``
Provides the ordinary tile character, as either a 1-character string or a number.
Can be overridden with the ``char`` function parameter.
``fg``
Foreground color for the ordinary tile. Defaults to COLOR_GREY (7).
``bg``
Background color for the ordinary tile. Defaults to COLOR_BLACK (0).
``bold``
Bright/bold text flag. If *nil*, computed based on (fg & 8); fg is masked to 3 bits.
Otherwise should be *true/false*.
``tile``
Graphical tile id. Ignored unless [GRAPHICS:YES] was in init.txt.
``tile_color = true``
Specifies that the tile should be shaded with *fg/bg*.
``tile_fg, tile_bg``
If specified, overrides *tile_color* and supplies shading colors directly.
Returns *false* if coordinates out of bounds, or other error.
* ``dfhack.screen.paintString(pen,x,y,text)``
Paints the string starting at *x,y*. Uses the string characters
in sequence to override the ``ch`` field of pen.
Returns *true* if painting at least one character succeeded.
* ``dfhack.screen.fillRect(pen,x1,y1,x2,y2)``
Fills the rectangle specified by the coordinates with the given pen.
Returns *true* if painting at least one character succeeded.
* ``dfhack.screen.findGraphicsTile(pagename,x,y)``
Finds a tile from a graphics set (i.e. the raws used for creatures),
if in graphics mode and loaded.
Returns: *tile, tile_grayscale*, or *nil* if not found.
The values can then be used for the *tile* field of *pen* structures.
* ``dfhack.screen.clear()``
Fills the screen with blank background.
* ``dfhack.screen.invalidate()``
Requests repaint of the screen by setting a flag. Unlike other
functions in this section, this may be used at any time.
In order to actually be able to paint to the screen, it is necessary
to create and register a viewscreen (basically a modal dialog) with
the game.
**NOTE**: As a matter of policy, in order to avoid user confusion, all
interface screens added by dfhack should bear the "DFHack" signature.
Screens are managed with the following functions:
* ``dfhack.screen.show(screen[,below])``
Displays the given screen, possibly placing it below a different one.
The screen must not be already shown. Returns *true* if success.
* ``dfhack.screen.dismiss(screen[,to_first])``
Marks the screen to be removed when the game enters its event loop.
If ``to_first`` is *true*, all screens up to the first one will be deleted.
* ``dfhack.screen.isDismissed(screen)``
Checks if the screen is already marked for removal.
Apart from a native viewscreen object, these functions accept a table
as a screen. In this case, ``show`` creates a new native viewscreen
that delegates all processing to methods stored in that table.
**NOTE**: Lua-implemented screens are only supported in the core context.
Supported callbacks and fields are:
* ``screen._native``
Initialized by ``show`` with a reference to the backing viewscreen
object, and removed again when the object is deleted.
* ``function screen:onShow()``
Called by ``dfhack.screen.show`` if successful.
* ``function screen:onDismiss()``
Called by ``dfhack.screen.dismiss`` if successful.
* ``function screen:onDestroy()``
Called from the destructor when the viewscreen is deleted.
* ``function screen:onResize(w, h)``
Called before ``onRender`` or ``onIdle`` when the window size has changed.
* ``function screen:onRender()``
Called when the viewscreen should paint itself. This is the only context
where the above painting functions work correctly.
If omitted, the screen is cleared; otherwise it should do that itself.
In order to make a see-through dialog, call ``self._native.parent:render()``.
* ``function screen:onIdle()``
Called every frame when the screen is on top of the stack.
* ``function screen:onHelp()``
Called when the help keybinding is activated (usually '?').
* ``function screen:onInput(keys)``
Called when keyboard or mouse events are available.
If any keys are pressed, the keys argument is a table mapping them to *true*.
Note that this refers to logical keybingings computed from real keys via
options; if multiple interpretations exist, the table will contain multiple keys.
The table also may contain special keys:
``_STRING``
Maps to an integer in range 0-255. Duplicates a separate "STRING_A???" code for convenience.
``_MOUSE_L, _MOUSE_R``
If the left or right mouse button is pressed.
If this method is omitted, the screen is dismissed on receival of the ``LEAVESCREEN`` key.
Internal API
------------
@ -1235,6 +1413,12 @@ and are only documented here for completeness:
Returns a sequence of tables describing virtual memory ranges of the process.
* ``dfhack.internal.patchMemory(dest,src,count)``
Like memmove below, but works even if dest is read-only memory, e.g. code.
If destination overlaps a completely invalid memory region, or another error
occurs, returns false.
* ``dfhack.internal.memmove(dest,src,count)``
Wraps the standard memmove function. Accepts both numbers and refs as pointers.
@ -1296,8 +1480,8 @@ 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
An event is a native object transparently wrapping a lua table,
and implementing 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.
@ -1312,10 +1496,18 @@ Features:
* ``event[key] = function``
Sets the function as one of the listeners.
Sets the function as one of the listeners. Assign *nil* to remove it.
**NOTE**: The ``df.NULL`` key is reserved for the use by
the C++ owner of the event, and has some special semantics.
the C++ owner of the event; it is an error to try setting it.
* ``#event``
Returns the number of non-nil listeners.
* ``pairs(event)``
Iterates over all listeners in the table.
* ``event(args...)``

@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.9: http://docutils.sourceforge.net/" />
<meta name="generator" content="Docutils 0.8.1: http://docutils.sourceforge.net/" />
<title>DFHack Lua API</title>
<style type="text/css">
@ -351,27 +351,28 @@ ul.auto-toc {
<li><a class="reference internal" href="#burrows-module" id="id23">Burrows module</a></li>
<li><a class="reference internal" href="#buildings-module" id="id24">Buildings module</a></li>
<li><a class="reference internal" href="#constructions-module" id="id25">Constructions module</a></li>
<li><a class="reference internal" href="#internal-api" id="id26">Internal API</a></li>
<li><a class="reference internal" href="#screen-api" id="id26">Screen API</a></li>
<li><a class="reference internal" href="#internal-api" id="id27">Internal API</a></li>
</ul>
</li>
<li><a class="reference internal" href="#core-interpreter-context" id="id27">Core interpreter context</a><ul>
<li><a class="reference internal" href="#event-type" id="id28">Event type</a></li>
<li><a class="reference internal" href="#core-interpreter-context" id="id28">Core interpreter context</a><ul>
<li><a class="reference internal" href="#event-type" id="id29">Event type</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#lua-modules" id="id29">Lua Modules</a><ul>
<li><a class="reference internal" href="#global-environment" id="id30">Global environment</a></li>
<li><a class="reference internal" href="#utils" id="id31">utils</a></li>
<li><a class="reference internal" href="#dumper" id="id32">dumper</a></li>
<li><a class="reference internal" href="#lua-modules" id="id30">Lua Modules</a><ul>
<li><a class="reference internal" href="#global-environment" id="id31">Global environment</a></li>
<li><a class="reference internal" href="#utils" id="id32">utils</a></li>
<li><a class="reference internal" href="#dumper" id="id33">dumper</a></li>
</ul>
</li>
<li><a class="reference internal" href="#plugins" id="id33">Plugins</a><ul>
<li><a class="reference internal" href="#burrows" id="id34">burrows</a></li>
<li><a class="reference internal" href="#sort" id="id35">sort</a></li>
<li><a class="reference internal" href="#plugins" id="id34">Plugins</a><ul>
<li><a class="reference internal" href="#burrows" id="id35">burrows</a></li>
<li><a class="reference internal" href="#sort" id="id36">sort</a></li>
</ul>
</li>
<li><a class="reference internal" href="#scripts" id="id36">Scripts</a></li>
<li><a class="reference internal" href="#scripts" id="id37">Scripts</a></li>
</ul>
</div>
<p>The current version of DFHack has extensive support for
@ -986,13 +987,17 @@ can be omitted.</p>
<div class="section" id="gui-module">
<h3><a class="toc-backref" href="#id18">Gui module</a></h3>
<ul>
<li><p class="first"><tt class="docutils literal">dfhack.gui.getCurViewscreen()</tt></p>
<p>Returns the viewscreen that is current in the core.</p>
<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.getCurViewscreen([skip_dismissed])</span></tt></p>
<p>Returns the topmost viewscreen. If <tt class="docutils literal">skip_dismissed</tt> is <em>true</em>,
ignores screens already marked to be removed.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.gui.getFocusString(viewscreen)</tt></p>
<p>Returns a string representation of the current focus position
in the ui. The string has a &quot;screen/foo/bar/baz...&quot; format.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.getCurFocus([skip_dismissed])</span></tt></p>
<p>Returns the focus string of the current viewscreen.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.gui.getSelectedWorkshopJob([silent])</span></tt></p>
<p>When a job is selected in <em>'q'</em> mode, returns the job, else
prints error unless silent and returns <em>nil</em>.</p>
@ -1108,6 +1113,13 @@ or raws. The <tt class="docutils literal">ignore_noble</tt> boolean disables the
<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.units.getCasteProfessionName(race,caste,prof_id[,plural])</span></tt></p>
<p>Retrieves the profession name for the given race/caste using raws.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.units.getProfessionColor(unit[,ignore_noble])</span></tt></p>
<p>Retrieves the color associated with the profession, using noble assignments
or raws. The <tt class="docutils literal">ignore_noble</tt> boolean disables the use of noble positions.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.units.getCasteProfessionColor(race,caste,prof_id)</tt></p>
<p>Retrieves the profession color for the given race/caste using raws.</p>
</li>
</ul>
</div>
<div class="section" id="items-module">
@ -1232,6 +1244,10 @@ burrows, or the presence of invaders.</p>
<div class="section" id="buildings-module">
<h3><a class="toc-backref" href="#id24">Buildings module</a></h3>
<ul>
<li><p class="first"><tt class="docutils literal">dfhack.buildings.setOwner(item,unit)</tt></p>
<p>Replaces the owner of the building. If unit is <em>nil</em>, removes ownership.
Returns <em>false</em> in case of error.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.buildings.getSize(building)</tt></p>
<p>Returns <em>width, height, centerx, centery</em>.</p>
</li>
@ -1385,8 +1401,147 @@ Returns <em>true, was_only_planned</em> if removed; or <em>false</em> if none fo
</li>
</ul>
</div>
<div class="section" id="screen-api">
<h3><a class="toc-backref" href="#id26">Screen API</a></h3>
<p>The screen module implements support for drawing to the tiled screen of the game.
Note that drawing only has any effect when done from callbacks, so it can only
be feasibly used in the core context.</p>
<p>Basic painting functions:</p>
<ul>
<li><p class="first"><tt class="docutils literal">dfhack.screen.getWindowSize()</tt></p>
<p>Returns <em>width, height</em> of the screen.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.getMousePos()</tt></p>
<p>Returns <em>x,y</em> of the tile the mouse is over.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.inGraphicsMode()</tt></p>
<p>Checks if [GRAPHICS:YES] was specified in init.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.screen.paintTile(pen,x,y[,char,tile])</span></tt></p>
<p>Paints a tile using given parameters. Pen is a table with following possible fields:</p>
<dl class="docutils">
<dt><tt class="docutils literal">ch</tt></dt>
<dd><p class="first last">Provides the ordinary tile character, as either a 1-character string or a number.
Can be overridden with the <tt class="docutils literal">char</tt> function parameter.</p>
</dd>
<dt><tt class="docutils literal">fg</tt></dt>
<dd><p class="first last">Foreground color for the ordinary tile. Defaults to COLOR_GREY (7).</p>
</dd>
<dt><tt class="docutils literal">bg</tt></dt>
<dd><p class="first last">Background color for the ordinary tile. Defaults to COLOR_BLACK (0).</p>
</dd>
<dt><tt class="docutils literal">bold</tt></dt>
<dd><p class="first last">Bright/bold text flag. If <em>nil</em>, computed based on (fg &amp; 8); fg is masked to 3 bits.
Otherwise should be <em>true/false</em>.</p>
</dd>
<dt><tt class="docutils literal">tile</tt></dt>
<dd><p class="first last">Graphical tile id. Ignored unless [GRAPHICS:YES] was in init.txt.</p>
</dd>
<dt><tt class="docutils literal">tile_color = true</tt></dt>
<dd><p class="first last">Specifies that the tile should be shaded with <em>fg/bg</em>.</p>
</dd>
<dt><tt class="docutils literal">tile_fg, tile_bg</tt></dt>
<dd><p class="first last">If specified, overrides <em>tile_color</em> and supplies shading colors directly.</p>
</dd>
</dl>
<p>Returns <em>false</em> if coordinates out of bounds, or other error.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.paintString(pen,x,y,text)</tt></p>
<p>Paints the string starting at <em>x,y</em>. Uses the string characters
in sequence to override the <tt class="docutils literal">ch</tt> field of pen.</p>
<p>Returns <em>true</em> if painting at least one character succeeded.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.fillRect(pen,x1,y1,x2,y2)</tt></p>
<p>Fills the rectangle specified by the coordinates with the given pen.
Returns <em>true</em> if painting at least one character succeeded.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.findGraphicsTile(pagename,x,y)</tt></p>
<p>Finds a tile from a graphics set (i.e. the raws used for creatures),
if in graphics mode and loaded.</p>
<p>Returns: <em>tile, tile_grayscale</em>, or <em>nil</em> if not found.
The values can then be used for the <em>tile</em> field of <em>pen</em> structures.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.clear()</tt></p>
<p>Fills the screen with blank background.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.invalidate()</tt></p>
<p>Requests repaint of the screen by setting a flag. Unlike other
functions in this section, this may be used at any time.</p>
</li>
</ul>
<p>In order to actually be able to paint to the screen, it is necessary
to create and register a viewscreen (basically a modal dialog) with
the game.</p>
<p><strong>NOTE</strong>: As a matter of policy, in order to avoid user confusion, all
interface screens added by dfhack should bear the &quot;DFHack&quot; signature.</p>
<p>Screens are managed with the following functions:</p>
<ul>
<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.screen.show(screen[,below])</span></tt></p>
<p>Displays the given screen, possibly placing it below a different one.
The screen must not be already shown. Returns <em>true</em> if success.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">dfhack.screen.dismiss(screen[,to_first])</span></tt></p>
<p>Marks the screen to be removed when the game enters its event loop.
If <tt class="docutils literal">to_first</tt> is <em>true</em>, all screens up to the first one will be deleted.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.screen.isDismissed(screen)</tt></p>
<p>Checks if the screen is already marked for removal.</p>
</li>
</ul>
<p>Apart from a native viewscreen object, these functions accept a table
as a screen. In this case, <tt class="docutils literal">show</tt> creates a new native viewscreen
that delegates all processing to methods stored in that table.</p>
<p><strong>NOTE</strong>: Lua-implemented screens are only supported in the core context.</p>
<p>Supported callbacks and fields are:</p>
<ul>
<li><p class="first"><tt class="docutils literal">screen._native</tt></p>
<p>Initialized by <tt class="docutils literal">show</tt> with a reference to the backing viewscreen
object, and removed again when the object is deleted.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onShow()</tt></p>
<p>Called by <tt class="docutils literal">dfhack.screen.show</tt> if successful.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onDismiss()</tt></p>
<p>Called by <tt class="docutils literal">dfhack.screen.dismiss</tt> if successful.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onDestroy()</tt></p>
<p>Called from the destructor when the viewscreen is deleted.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onResize(w, h)</tt></p>
<p>Called before <tt class="docutils literal">onRender</tt> or <tt class="docutils literal">onIdle</tt> when the window size has changed.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onRender()</tt></p>
<p>Called when the viewscreen should paint itself. This is the only context
where the above painting functions work correctly.</p>
<p>If omitted, the screen is cleared; otherwise it should do that itself.
In order to make a see-through dialog, call <tt class="docutils literal">self._native.parent:render()</tt>.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onIdle()</tt></p>
<p>Called every frame when the screen is on top of the stack.</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onHelp()</tt></p>
<p>Called when the help keybinding is activated (usually '?').</p>
</li>
<li><p class="first"><tt class="docutils literal">function screen:onInput(keys)</tt></p>
<p>Called when keyboard or mouse events are available.
If any keys are pressed, the keys argument is a table mapping them to <em>true</em>.
Note that this refers to logical keybingings computed from real keys via
options; if multiple interpretations exist, the table will contain multiple keys.</p>
<p>The table also may contain special keys:</p>
<dl class="docutils">
<dt><tt class="docutils literal">_STRING</tt></dt>
<dd><p class="first last">Maps to an integer in range 0-255. Duplicates a separate &quot;STRING_A???&quot; code for convenience.</p>
</dd>
<dt><tt class="docutils literal">_MOUSE_L, _MOUSE_R</tt></dt>
<dd><p class="first last">If the left or right mouse button is pressed.</p>
</dd>
</dl>
<p>If this method is omitted, the screen is dismissed on receival of the <tt class="docutils literal">LEAVESCREEN</tt> key.</p>
</li>
</ul>
</div>
<div class="section" id="internal-api">
<h3><a class="toc-backref" href="#id26">Internal API</a></h3>
<h3><a class="toc-backref" href="#id27">Internal API</a></h3>
<p>These functions are intended for the use by dfhack developers,
and are only documented here for completeness:</p>
<ul>
@ -1409,6 +1564,11 @@ global environment, persistent between calls to the script.</p>
<li><p class="first"><tt class="docutils literal">dfhack.internal.getMemRanges()</tt></p>
<p>Returns a sequence of tables describing virtual memory ranges of the process.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.internal.patchMemory(dest,src,count)</tt></p>
<p>Like memmove below, but works even if dest is read-only memory, e.g. code.
If destination overlaps a completely invalid memory region, or another error
occurs, returns false.</p>
</li>
<li><p class="first"><tt class="docutils literal">dfhack.internal.memmove(dest,src,count)</tt></p>
<p>Wraps the standard memmove function. Accepts both numbers and refs as pointers.</p>
</li>
@ -1429,7 +1589,7 @@ Returns: <em>found_index</em>, or <em>nil</em> if end reached.</p>
</div>
</div>
<div class="section" id="core-interpreter-context">
<h2><a class="toc-backref" href="#id27">Core interpreter context</a></h2>
<h2><a class="toc-backref" href="#id28">Core interpreter context</a></h2>
<p>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.</p>
@ -1460,9 +1620,9 @@ Using <tt class="docutils literal">timeout_active(id,nil)</tt> cancels the timer
</li>
</ul>
<div class="section" id="event-type">
<h3><a class="toc-backref" href="#id28">Event type</a></h3>
<p>An event is just a lua table with a predefined metatable that
contains a __call metamethod. When it is invoked, it loops
<h3><a class="toc-backref" href="#id29">Event type</a></h3>
<p>An event is a native object transparently wrapping a lua table,
and implementing 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.</p>
<p>This type itself is available in any context, but only the
@ -1473,9 +1633,15 @@ core context has the actual events defined by C++ code.</p>
<p>Creates a new instance of an event.</p>
</li>
<li><p class="first"><tt class="docutils literal">event[key] = function</tt></p>
<p>Sets the function as one of the listeners.</p>
<p>Sets the function as one of the listeners. Assign <em>nil</em> to remove it.</p>
<p><strong>NOTE</strong>: The <tt class="docutils literal">df.NULL</tt> key is reserved for the use by
the C++ owner of the event, and has some special semantics.</p>
the C++ owner of the event; it is an error to try setting it.</p>
</li>
<li><p class="first"><tt class="docutils literal">#event</tt></p>
<p>Returns the number of non-nil listeners.</p>
</li>
<li><p class="first"><tt class="docutils literal">pairs(event)</tt></p>
<p>Iterates over all listeners in the table.</p>
</li>
<li><p class="first"><tt class="docutils literal"><span class="pre">event(args...)</span></tt></p>
<p>Invokes all listeners contained in the event in an arbitrary
@ -1486,7 +1652,7 @@ order using <tt class="docutils literal">dfhack.safecall</tt>.</p>
</div>
</div>
<div class="section" id="lua-modules">
<h1><a class="toc-backref" href="#id29">Lua Modules</a></h1>
<h1><a class="toc-backref" href="#id30">Lua Modules</a></h1>
<p>DFHack sets up the lua interpreter so that the built-in <tt class="docutils literal">require</tt>
function can be used to load shared lua code from hack/lua/.
The <tt class="docutils literal">dfhack</tt> namespace reference itself may be obtained via
@ -1515,7 +1681,7 @@ in this document.</p>
</li>
</ul>
<div class="section" id="global-environment">
<h2><a class="toc-backref" href="#id30">Global environment</a></h2>
<h2><a class="toc-backref" href="#id31">Global environment</a></h2>
<p>A number of variables and functions are provided in the base global
environment by the mandatory init file dfhack.lua:</p>
<ul>
@ -1556,7 +1722,7 @@ Returns <em>nil</em> if any of obj or indices is <em>nil</em>, or a numeric inde
</ul>
</div>
<div class="section" id="utils">
<h2><a class="toc-backref" href="#id31">utils</a></h2>
<h2><a class="toc-backref" href="#id32">utils</a></h2>
<ul>
<li><p class="first"><tt class="docutils literal">utils.compare(a,b)</tt></p>
<p>Comparator function; returns <em>-1</em> if a&lt;b, <em>1</em> if a&gt;b, <em>0</em> otherwise.</p>
@ -1669,7 +1835,7 @@ throws an error.</p>
</ul>
</div>
<div class="section" id="dumper">
<h2><a class="toc-backref" href="#id32">dumper</a></h2>
<h2><a class="toc-backref" href="#id33">dumper</a></h2>
<p>A third-party lua table dumper module from
<a class="reference external" href="http://lua-users.org/wiki/DataDumper">http://lua-users.org/wiki/DataDumper</a>. Defines one
function:</p>
@ -1683,14 +1849,14 @@ the other arguments see the original documentation link above.</p>
</div>
</div>
<div class="section" id="plugins">
<h1><a class="toc-backref" href="#id33">Plugins</a></h1>
<h1><a class="toc-backref" href="#id34">Plugins</a></h1>
<p>DFHack plugins may export native functions and events
to lua contexts. They are automatically imported by
<tt class="docutils literal"><span class="pre">mkmodule('plugins.&lt;name&gt;')</span></tt>; this means that a lua
module file is still necessary for <tt class="docutils literal">require</tt> to read.</p>
<p>The following plugins have lua support.</p>
<div class="section" id="burrows">
<h2><a class="toc-backref" href="#id34">burrows</a></h2>
<h2><a class="toc-backref" href="#id35">burrows</a></h2>
<p>Implements extended burrow manipulations.</p>
<p>Events:</p>
<ul>
@ -1728,13 +1894,13 @@ set is the same as used by the command line.</p>
<p>The lua module file also re-exports functions from <tt class="docutils literal">dfhack.burrows</tt>.</p>
</div>
<div class="section" id="sort">
<h2><a class="toc-backref" href="#id35">sort</a></h2>
<h2><a class="toc-backref" href="#id36">sort</a></h2>
<p>Does not export any native functions as of now. Instead, it
calls lua code to perform the actual ordering of list items.</p>
</div>
</div>
<div class="section" id="scripts">
<h1><a class="toc-backref" href="#id36">Scripts</a></h1>
<h1><a class="toc-backref" href="#id37">Scripts</a></h1>
<p>Any files with the .lua extension placed into hack/scripts/*
are automatically used by the DFHack core as commands. The
matching command name consists of the name of the file sans

@ -1401,18 +1401,30 @@ Kills any unit of a given race.
With no argument, lists the available races.
With the special argument 'him', targets only the selected creature.
Any non-dead non-caged unit of the specified race gets its ``blood_count``
set to 0, which means immediate death at the next game tick. May not work
on vampires and other weird creatures.
set to 0, which means immediate death at the next game tick. For creatures
such as vampires, also set animal.vanish_countdown to 2.
An alternate mode is selected by adding a 2nd argument to the command,
``magma``. In this case, a column of 7/7 magma is generated on top of the
targets until they die (Warning: do not call on magma-safe creatures. Also,
using this mode for birds is not recommanded.)
Will target any unit on a revealed tile of the map, including ambushers.
Targets any unit on a revealed tile of the map, including ambushers. Ex:
Ex:
::
slayrace gob
To kill a single creature in the same way, you can use the following line,
after selecting the unit with the 'v' cursor:
To kill a single creature, select the unit with the 'v' cursor and:
::
slayrace him
To purify all elves on the map with fire (may have side-effects):
::
rb_eval df.unit_find.body.blood_count = 0
slayrace elve magma
magmasource

@ -1 +1 @@
Subproject commit c85e9fb35d3510c5dcc367056cda3237d77a7add
Subproject commit d0b2d0750dc2d529a152eba4f3f519f69ff7eab0

@ -72,13 +72,13 @@ ELSE()
SET(HASH_SET_CLASS hash_set)
ENDIF()
CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/config.h.in" "${CMAKE_CURRENT_SOURCE_DIR}/config.h")
CONFIGURE_FILE("${CMAKE_CURRENT_SOURCE_DIR}/config.h.in" "${CMAKE_CURRENT_BINARY_DIR}/config.h")
SET(LIBPROTOBUF_LITE_HDRS
google/protobuf/io/coded_stream.h
google/protobuf/io/coded_stream_inl.h
google/protobuf/stubs/common.h
config.h
${CMAKE_CURRENT_BINARY_DIR}/config.h
google/protobuf/extension_set.h
google/protobuf/generated_message_util.h
google/protobuf/stubs/hash.h
@ -207,6 +207,7 @@ ENDIF()
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(PROTOBUF_INCLUDE_DIRS ${CMAKE_CURRENT_SOURCE_DIR})
INCLUDE_DIRECTORIES(${ZLIB_INCLUDE_DIRS})
include_directories(${CMAKE_CURRENT_BINARY_DIR})
# Protobuf shared libraries

@ -42,3 +42,19 @@ keybinding add Shift-I "job-material CINNABAR"
keybinding add Shift-B "job-material COBALTITE"
keybinding add Shift-O "job-material OBSIDIAN"
keybinding add Shift-G "job-material GLASS_GREEN"
# browse linked mechanisms
keybinding add Ctrl-M@dwarfmode/QueryBuilding/Some gui/mechanisms
# browse rooms of same owner
keybinding add Alt-R@dwarfmode/QueryBuilding/Some gui/room-list.work
# interface for the liquids plugin
keybinding add Alt-L@dwarfmode/LookAround gui/liquids
###################
# UI logic tweaks #
###################
# stabilize the cursor of dwarfmode when switching menus
tweak stable-cursor

@ -27,6 +27,7 @@ include/Core.h
include/ColorText.h
include/DataDefs.h
include/DataIdentity.h
include/VTableInterpose.h
include/LuaWrapper.h
include/LuaTools.h
include/Error.h
@ -53,6 +54,7 @@ SET(MAIN_SOURCES
Core.cpp
ColorText.cpp
DataDefs.cpp
VTableInterpose.cpp
LuaWrapper.cpp
LuaTypes.cpp
LuaTools.cpp
@ -117,6 +119,7 @@ include/modules/Maps.h
include/modules/MapCache.h
include/modules/Materials.h
include/modules/Notes.h
include/modules/Screen.h
include/modules/Translation.h
include/modules/Vegetation.h
include/modules/Vermin.h
@ -137,6 +140,7 @@ modules/kitchen.cpp
modules/Maps.cpp
modules/Materials.cpp
modules/Notes.cpp
modules/Screen.cpp
modules/Translation.cpp
modules/Vegetation.cpp
modules/Vermin.cpp

@ -275,7 +275,7 @@ namespace DFHack
/// Reset color to default
void reset_color(void)
{
color(Console::COLOR_RESET);
color(COLOR_RESET);
if(!rawmode)
fflush(dfout_C);
}

@ -62,7 +62,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// George Vulov for MacOSX
#ifndef __LINUX__
#define TEMP_FAILURE_RETRY(expr) \
#define TMP_FAILURE_RETRY(expr) \
({ long int _res; \
do _res = (long int) (expr); \
while (_res == -1L && errno == EINTR); \
@ -155,7 +155,7 @@ namespace DFHack
FD_ZERO(&descriptor_set);
FD_SET(STDIN_FILENO, &descriptor_set);
FD_SET(exit_pipe[0], &descriptor_set);
int ret = TEMP_FAILURE_RETRY(
int ret = TMP_FAILURE_RETRY(
select (FD_SETSIZE,&descriptor_set, NULL, NULL, NULL)
);
if(ret == -1)
@ -165,7 +165,7 @@ namespace DFHack
if (FD_ISSET(STDIN_FILENO, &descriptor_set))
{
// read byte from stdin
ret = TEMP_FAILURE_RETRY(
ret = TMP_FAILURE_RETRY(
read(STDIN_FILENO, &out, 1)
);
if(ret == -1)
@ -245,7 +245,8 @@ namespace DFHack
if(rawmode)
{
const char * clr = "\033c\033[3J\033[H";
::write(STDIN_FILENO,clr,strlen(clr));
if (::write(STDIN_FILENO,clr,strlen(clr)) == -1)
;
}
else
{
@ -269,13 +270,14 @@ namespace DFHack
{
const char * colstr = getANSIColor(index);
int lstr = strlen(colstr);
::write(STDIN_FILENO,colstr,lstr);
if (::write(STDIN_FILENO,colstr,lstr) == -1)
;
}
}
/// Reset color to default
void reset_color(void)
{
color(Console::COLOR_RESET);
color(COLOR_RESET);
if(!rawmode)
fflush(dfout_C);
}
@ -656,7 +658,8 @@ bool Console::init(bool sharing)
inited = false;
return false;
}
freopen("stdout.log", "w", stdout);
if (!freopen("stdout.log", "w", stdout))
;
d = new Private();
// make our own weird streams so our IO isn't redirected
d->dfout_C = fopen("/dev/tty", "w");
@ -664,7 +667,8 @@ bool Console::init(bool sharing)
clear();
d->supported_terminal = !isUnsupportedTerm() && isatty(STDIN_FILENO);
// init the exit mechanism
pipe(d->exit_pipe);
if (pipe(d->exit_pipe) == -1)
;
FD_ZERO(&d->descriptor_set);
FD_SET(STDIN_FILENO, &d->descriptor_set);
FD_SET(d->exit_pipe[0], &d->descriptor_set);

@ -179,7 +179,7 @@ namespace DFHack
void color(int index)
{
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, index == color_ostream::COLOR_RESET ? default_attributes : index);
SetConsoleTextAttribute(hConsole, index == COLOR_RESET ? default_attributes : index);
}
void reset_color( void )

@ -219,28 +219,30 @@ static std::string getScriptHelp(std::string path, std::string helpprefix)
return "No help available.";
}
static std::map<string,string> listScripts(PluginManager *plug_mgr, std::string path)
static void listScripts(PluginManager *plug_mgr, std::map<string,string> &pset, std::string path, bool all, std::string prefix = "")
{
std::vector<string> files;
getdir(path, files);
std::map<string,string> pset;
for (size_t i = 0; i < files.size(); i++)
{
if (hasEnding(files[i], ".lua"))
{
std::string help = getScriptHelp(path + files[i], "-- ");
pset[files[i].substr(0, files[i].size()-4)] = help;
pset[prefix + files[i].substr(0, files[i].size()-4)] = help;
}
else if (plug_mgr->eval_ruby && hasEnding(files[i], ".rb"))
{
std::string help = getScriptHelp(path + files[i], "# ");
pset[files[i].substr(0, files[i].size()-3)] = help;
pset[prefix + files[i].substr(0, files[i].size()-3)] = help;
}
else if (all && !files[i].empty() && files[i][0] != '.')
{
listScripts(plug_mgr, pset, path+files[i]+"/", all, prefix+files[i]+"/");
}
}
return pset;
}
static bool fileExists(std::string path)
@ -335,7 +337,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve
con.print("Basic commands:\n"
" help|?|man - This text.\n"
" help COMMAND - Usage help for the given command.\n"
" ls|dir [PLUGIN] - List available commands. Optionally for single plugin.\n"
" ls|dir [-a] [PLUGIN] - List available commands. Optionally for single plugin.\n"
" cls - Clear the console.\n"
" fpause - Force DF to pause.\n"
" die - Force DF to close immediately\n"
@ -358,7 +360,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve
continue;
if (pcmd.isHotkeyCommand())
con.color(Console::COLOR_CYAN);
con.color(COLOR_CYAN);
con.print("%s: %s\n",pcmd.name.c_str(), pcmd.description.c_str());
con.reset_color();
if (!pcmd.usage.empty())
@ -469,6 +471,12 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve
}
else if(first == "ls" || first == "dir")
{
bool all = false;
if (parts.size() && parts[0] == "-a")
{
all = true;
vector_erase_at(parts, 0);
}
if(parts.size())
{
string & plugname = parts[0];
@ -481,7 +489,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve
{
const PluginCommand & pcmd = (plug->operator[](j));
if (pcmd.isHotkeyCommand())
con.color(Console::COLOR_CYAN);
con.color(COLOR_CYAN);
con.print(" %-22s - %s\n",pcmd.name.c_str(), pcmd.description.c_str());
con.reset_color();
}
@ -491,7 +499,7 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve
con.print(
"builtin:\n"
" help|?|man - This text or help specific to a plugin.\n"
" ls [PLUGIN] - List available commands. Optionally for single plugin.\n"
" ls [-a] [PLUGIN] - List available commands. Optionally for single plugin.\n"
" cls - Clear the console.\n"
" fpause - Force DF to pause.\n"
" die - Force DF to close immediately\n"
@ -519,11 +527,12 @@ command_result Core::runCommand(color_ostream &con, const std::string &first, ve
for(auto iter = out.begin();iter != out.end();iter++)
{
if ((*iter).recolor)
con.color(Console::COLOR_CYAN);
con.color(COLOR_CYAN);
con.print(" %-22s- %s\n",(*iter).name.c_str(), (*iter).description.c_str());
con.reset_color();
}
auto scripts = listScripts(plug_mgr, getHackPath() + "scripts/");
std::map<string, string> scripts;
listScripts(plug_mgr, scripts, getHackPath() + "scripts/", all);
if (!scripts.empty())
{
con.print("\nscripts:\n");
@ -1027,35 +1036,41 @@ int Core::TileUpdate()
return true;
}
// should always be from simulation thread!
int Core::Update()
int Core::ClaimSuspend(bool force_base)
{
if(errorstate)
return -1;
auto tid = this_thread::get_id();
lock_guard<mutex> lock(d->AccessMutex);
// Pretend this thread has suspended the core in the usual way
if (force_base || d->df_suspend_depth <= 0)
{
lock_guard<mutex> lock(d->AccessMutex);
assert(d->df_suspend_depth == 0);
d->df_suspend_thread = this_thread::get_id();
d->df_suspend_depth = 1000;
}
// Initialize the core
bool first_update = false;
if(!started)
d->df_suspend_thread = tid;
d->df_suspend_depth = 1000000;
return 1000000;
}
else
{
first_update = true;
Init();
if(errorstate)
return -1;
Lua::Core::Reset(con, "core init");
assert(d->df_suspend_thread == tid);
return ++d->df_suspend_depth;
}
}
color_ostream_proxy out(con);
void Core::DisclaimSuspend(int level)
{
auto tid = this_thread::get_id();
lock_guard<mutex> lock(d->AccessMutex);
assert(d->df_suspend_depth == level && d->df_suspend_thread == tid);
if (level == 1000000)
d->df_suspend_depth = 0;
else
--d->df_suspend_depth;
}
void Core::doUpdate(color_ostream &out, bool first_update)
{
Lua::Core::Reset(out, "DF code execution");
if (first_update)
@ -1129,15 +1144,36 @@ int Core::Update()
// Execute per-frame handlers
onUpdate(out);
// Release the fake suspend lock
out << std::flush;
}
// should always be from simulation thread!
int Core::Update()
{
if(errorstate)
return -1;
color_ostream_proxy out(con);
// Pretend this thread has suspended the core in the usual way,
// and run various processing hooks.
{
lock_guard<mutex> lock(d->AccessMutex);
CoreSuspendClaimer suspend(true);
assert(d->df_suspend_depth == 1000);
d->df_suspend_depth = 0;
}
// Initialize the core
bool first_update = false;
out << std::flush;
if(!started)
{
first_update = true;
Init();
if(errorstate)
return -1;
Lua::Core::Reset(con, "core init");
}
doUpdate(out, first_update);
}
// wake waiting tools
// do not allow more tools to join in while we process stuff here
@ -1158,7 +1194,7 @@ int Core::Update()
// destroy condition
delete nc;
// check lua stack depth
Lua::Core::Reset(con, "suspend");
Lua::Core::Reset(out, "suspend");
}
return 0;
@ -1198,6 +1234,7 @@ int Core::Shutdown ( void )
if(errorstate)
return true;
errorstate = 1;
CoreSuspendClaimer suspend;
if(plug_mgr)
{
delete plug_mgr;
@ -1232,7 +1269,7 @@ bool Core::ncurses_wgetch(int in, int & out)
// FIXME: copypasta, push into a method!
if(df::global::ui && df::global::gview)
{
df::viewscreen * ws = Gui::GetCurrentScreen();
df::viewscreen * ws = Gui::getCurViewscreen();
if (strict_virtual_cast<df::viewscreen_dwarfmodest>(ws) &&
df::global::ui->main.mode != ui_sidebar_mode::Hotkeys &&
df::global::ui->main.hotkeys[idx].cmd == df::ui_hotkey::T_cmd::None)
@ -1548,6 +1585,56 @@ void ClassNameCheck::getKnownClassNames(std::vector<std::string> &names)
names.push_back(*it);
}
bool Process::patchMemory(void *target, const void* src, size_t count)
{
uint8_t *sptr = (uint8_t*)target;
uint8_t *eptr = sptr + count;
// Find the valid memory ranges
std::vector<t_memrange> ranges;
getMemRanges(ranges);
unsigned start = 0;
while (start < ranges.size() && ranges[start].end <= sptr)
start++;
if (start >= ranges.size() || ranges[start].start > sptr)
return false;
unsigned end = start+1;
while (end < ranges.size() && ranges[end].start < eptr)
{
if (ranges[end].start != ranges[end-1].end)
return false;
end++;
}
if (ranges[end-1].end < eptr)
return false;
// Verify current permissions
for (unsigned i = start; i < end; i++)
if (!ranges[i].valid || !(ranges[i].read || ranges[i].execute) || ranges[i].shared)
return false;
// Apply writable permissions & update
bool ok = true;
for (unsigned i = start; i < end && ok; i++)
{
t_memrange perms = ranges[i];
perms.write = perms.read = true;
if (!setPermisions(perms, perms))
ok = false;
}
if (ok)
memmove(target, src, count);
for (unsigned i = start; i < end && ok; i++)
setPermisions(ranges[i], ranges[i]);
return ok;
}
/*******************************************************************************
M O D U L E S
*******************************************************************************/

@ -35,6 +35,7 @@ distribution.
// must be last due to MS stupidity
#include "DataDefs.h"
#include "DataIdentity.h"
#include "VTableInterpose.h"
#include "MiscUtils.h"
@ -214,6 +215,15 @@ virtual_identity::virtual_identity(size_t size, TAllocateFn alloc,
{
}
virtual_identity::~virtual_identity()
{
// Remove interpose entries, so that they don't try accessing this object later
for (auto it = interpose_list.begin(); it != interpose_list.end(); ++it)
if (it->second)
it->second->on_host_delete(this);
interpose_list.clear();
}
/* Vtable name to identity lookup. */
static std::map<std::string, virtual_identity*> name_lookup;

@ -39,6 +39,7 @@ distribution.
#include "modules/World.h"
#include "modules/Gui.h"
#include "modules/Screen.h"
#include "modules/Job.h"
#include "modules/Translation.h"
#include "modules/Units.h"
@ -76,6 +77,7 @@ distribution.
#include "df/job_material_category.h"
#include "df/burrow.h"
#include "df/building_civzonest.h"
#include "df/region_map_entry.h"
#include <lua.h>
#include <lauxlib.h>
@ -84,6 +86,8 @@ distribution.
using namespace DFHack;
using namespace DFHack::LuaWrapper;
using Screen::Pen;
void dfhack_printerr(lua_State *S, const std::string &str);
void Lua::Push(lua_State *state, const Units::NoblePosition &pos)
@ -179,6 +183,68 @@ static df::coord CheckCoordXYZ(lua_State *state, int base, bool vararg = false)
return p;
}
template<class T>
static bool get_int_field(lua_State *L, T *pf, int idx, const char *name, int defval)
{
lua_getfield(L, idx, name);
bool nil = lua_isnil(L, -1);
if (nil) *pf = T(defval);
else if (lua_isnumber(L, -1)) *pf = T(lua_tointeger(L, -1));
else luaL_error(L, "Field %s is not a number.", name);
lua_pop(L, 1);
return !nil;
}
static bool get_char_field(lua_State *L, char *pf, int idx, const char *name, char defval)
{
lua_getfield(L, idx, name);
if (lua_type(L, -1) == LUA_TSTRING)
{
*pf = lua_tostring(L, -1)[0];
lua_pop(L, 1);
return true;
}
else
{
lua_pop(L, 1);
return get_int_field(L, pf, idx, name, defval);
}
}
static void decode_pen(lua_State *L, Pen &pen, int idx)
{
idx = lua_absindex(L, idx);
get_char_field(L, &pen.ch, idx, "ch", 0);
get_int_field(L, &pen.fg, idx, "fg", 7);
get_int_field(L, &pen.bg, idx, "bg", 0);
lua_getfield(L, idx, "bold");
if (lua_isnil(L, -1))
{
pen.bold = (pen.fg & 8) != 0;
pen.fg &= 7;
}
else pen.bold = lua_toboolean(L, -1);
lua_pop(L, 1);
get_int_field(L, &pen.tile, idx, "tile", 0);
bool tcolor = get_int_field(L, &pen.tile_fg, idx, "tile_fg", 7);
tcolor = get_int_field(L, &pen.tile_bg, idx, "tile_bg", 0) || tcolor;
if (tcolor)
pen.tile_mode = Pen::TileColor;
else
{
lua_getfield(L, idx, "tile_color");
pen.tile_mode = (lua_toboolean(L, -1) ? Pen::CharColor : Pen::AsIs);
lua_pop(L, 1);
}
}
/**************************************************
* Per-world persistent configuration storage API *
**************************************************/
@ -684,6 +750,7 @@ static const LuaWrapper::FunctionReg dfhack_module[] = {
static const LuaWrapper::FunctionReg dfhack_gui_module[] = {
WRAPM(Gui, getCurViewscreen),
WRAPM(Gui, getFocusString),
WRAPM(Gui, getCurFocus),
WRAPM(Gui, getSelectedWorkshopJob),
WRAPM(Gui, getSelectedJob),
WRAPM(Gui, getSelectedUnit),
@ -749,6 +816,8 @@ static const LuaWrapper::FunctionReg dfhack_units_module[] = {
WRAPM(Units, getAge),
WRAPM(Units, getProfessionName),
WRAPM(Units, getCasteProfessionName),
WRAPM(Units, getProfessionColor),
WRAPM(Units, getCasteProfessionColor),
{ NULL, NULL }
};
@ -863,8 +932,7 @@ static int maps_getRegionBiome(lua_State *L)
static int maps_getTileBiomeRgn(lua_State *L)
{
auto pos = CheckCoordXYZ(L, 1, true);
Lua::PushPosXY(L, Maps::getTileBiomeRgn(pos));
return 1;
return Lua::PushPosXY(L, Maps::getTileBiomeRgn(pos));
}
static const luaL_Reg dfhack_maps_funcs[] = {
@ -919,6 +987,7 @@ static bool buildings_containsTile(df::building *bld, int x, int y, bool room) {
}
static const LuaWrapper::FunctionReg dfhack_buildings_module[] = {
WRAPM(Buildings, setOwner),
WRAPM(Buildings, allocInstance),
WRAPM(Buildings, checkFreeTiles),
WRAPM(Buildings, countExtentTiles),
@ -1019,6 +1088,164 @@ static const luaL_Reg dfhack_constructions_funcs[] = {
{ NULL, NULL }
};
/***** Screen module *****/
static const LuaWrapper::FunctionReg dfhack_screen_module[] = {
WRAPM(Screen, inGraphicsMode),
WRAPM(Screen, clear),
WRAPM(Screen, invalidate),
{ NULL, NULL }
};
static int screen_getMousePos(lua_State *L)
{
auto pos = Screen::getMousePos();
lua_pushinteger(L, pos.x);
lua_pushinteger(L, pos.y);
return 2;
}
static int screen_getWindowSize(lua_State *L)
{
auto pos = Screen::getWindowSize();
lua_pushinteger(L, pos.x);
lua_pushinteger(L, pos.y);
return 2;
}
static int screen_paintTile(lua_State *L)
{
Pen pen;
decode_pen(L, pen, 1);
int x = luaL_checkint(L, 2);
int y = luaL_checkint(L, 3);
if (lua_gettop(L) >= 4 && !lua_isnil(L, 4))
{
if (lua_type(L, 4) == LUA_TSTRING)
pen.ch = lua_tostring(L, 4)[0];
else
pen.ch = luaL_checkint(L, 4);
}
if (lua_gettop(L) >= 5 && !lua_isnil(L, 5))
pen.tile = luaL_checkint(L, 5);
lua_pushboolean(L, Screen::paintTile(pen, x, y));
return 1;
}
static int screen_paintString(lua_State *L)
{
Pen pen;
decode_pen(L, pen, 1);
int x = luaL_checkint(L, 2);
int y = luaL_checkint(L, 3);
const char *text = luaL_checkstring(L, 4);
lua_pushboolean(L, Screen::paintString(pen, x, y, text));
return 1;
}
static int screen_fillRect(lua_State *L)
{
Pen pen;
decode_pen(L, pen, 1);
int x1 = luaL_checkint(L, 2);
int y1 = luaL_checkint(L, 3);
int x2 = luaL_checkint(L, 4);
int y2 = luaL_checkint(L, 5);
lua_pushboolean(L, Screen::fillRect(pen, x1, y1, x2, y2));
return 1;
}
static int screen_findGraphicsTile(lua_State *L)
{
auto str = luaL_checkstring(L, 1);
int x = luaL_checkint(L, 2);
int y = luaL_checkint(L, 3);
int tile, tile_gs;
if (Screen::findGraphicsTile(str, x, y, &tile, &tile_gs))
{
lua_pushinteger(L, tile);
lua_pushinteger(L, tile_gs);
return 2;
}
else
{
lua_pushnil(L);
return 1;
}
}
namespace {
int screen_show(lua_State *L)
{
df::viewscreen *before = NULL;
if (lua_gettop(L) >= 2)
before = Lua::CheckDFObject<df::viewscreen>(L, 2);
df::viewscreen *screen = dfhack_lua_viewscreen::get_pointer(L, 1, true);
bool ok = Screen::show(screen, before);
// If it is a table, get_pointer created a new object. Don't leak it.
if (!ok && lua_istable(L, 1))
delete screen;
lua_pushboolean(L, ok);
return 1;
}
static int screen_dismiss(lua_State *L)
{
df::viewscreen *screen = dfhack_lua_viewscreen::get_pointer(L, 1, false);
Screen::dismiss(screen);
return 0;
}
static int screen_isDismissed(lua_State *L)
{
df::viewscreen *screen = dfhack_lua_viewscreen::get_pointer(L, 1, false);
lua_pushboolean(L, Screen::isDismissed(screen));
return 1;
}
static int screen_doSimulateInput(lua_State *L)
{
auto screen = Lua::CheckDFObject<df::viewscreen>(L, 1);
luaL_checktype(L, 2, LUA_TTABLE);
if (!screen)
luaL_argerror(L, 1, "NULL screen");
int sz = lua_rawlen(L, 2);
std::set<df::interface_key> keys;
for (int j = 1; j <= sz; j++)
{
lua_rawgeti(L, 2, j);
keys.insert((df::interface_key)lua_tointeger(L, -1));
lua_pop(L, 1);
}
screen->feed(&keys);
return 0;
}
}
static const luaL_Reg dfhack_screen_funcs[] = {
{ "getMousePos", screen_getMousePos },
{ "getWindowSize", screen_getWindowSize },
{ "paintTile", screen_paintTile },
{ "paintString", screen_paintString },
{ "fillRect", screen_fillRect },
{ "findGraphicsTile", screen_findGraphicsTile },
{ "show", &Lua::CallWithCatchWrapper<screen_show> },
{ "dismiss", screen_dismiss },
{ "isDismissed", screen_isDismissed },
{ "_doSimulateInput", screen_doSimulateInput },
{ NULL, NULL }
};
/***** Internal module *****/
static void *checkaddr(lua_State *L, int idx, bool allow_null = false)
@ -1124,6 +1351,17 @@ static int internal_getMemRanges(lua_State *L)
return 1;
}
static int internal_patchMemory(lua_State *L)
{
void *dest = checkaddr(L, 1);
void *src = checkaddr(L, 2);
int size = luaL_checkint(L, 3);
if (size < 0) luaL_argerror(L, 1, "negative size");
bool ok = Core::getInstance().p->patchMemory(dest, src, size);
lua_pushboolean(L, ok);
return 1;
}
static int internal_memmove(lua_State *L)
{
void *dest = checkaddr(L, 1);
@ -1214,6 +1452,7 @@ static const luaL_Reg dfhack_internal_funcs[] = {
{ "setAddress", internal_setAddress },
{ "getVTable", internal_getVTable },
{ "getMemRanges", internal_getMemRanges },
{ "patchMemory", internal_patchMemory },
{ "memmove", internal_memmove },
{ "memcmp", internal_memcmp },
{ "memscan", internal_memscan },
@ -1240,5 +1479,6 @@ void OpenDFHackApi(lua_State *state)
OpenModule(state, "burrows", dfhack_burrows_module, dfhack_burrows_funcs);
OpenModule(state, "buildings", dfhack_buildings_module, dfhack_buildings_funcs);
OpenModule(state, "constructions", dfhack_constructions_module);
OpenModule(state, "screen", dfhack_screen_module, dfhack_screen_funcs);
OpenModule(state, "internal", dfhack_internal_module, dfhack_internal_funcs);
}

@ -68,6 +68,11 @@ lua_State *DFHack::Lua::Core::State = NULL;
void dfhack_printerr(lua_State *S, const std::string &str);
inline bool is_null_userdata(lua_State *L, int idx)
{
return lua_islightuserdata(L, idx) && !lua_touserdata(L, idx);
}
inline void AssertCoreSuspend(lua_State *state)
{
assert(!Lua::IsCoreContext(state) || DFHack::Core::getInstance().isSuspended());
@ -252,7 +257,7 @@ static int lua_dfhack_color(lua_State *S)
{
int cv = luaL_optint(S, 1, -1);
if (cv < -1 || cv > color_ostream::COLOR_MAX)
if (cv < -1 || cv > COLOR_MAX)
luaL_argerror(S, 1, "invalid color value");
color_ostream *out = Lua::GetOutput(S);
@ -1244,14 +1249,123 @@ static const luaL_Reg dfhack_coro_funcs[] = {
static int DFHACK_EVENT_META_TOKEN = 0;
int DFHack::Lua::NewEvent(lua_State *state)
namespace {
struct EventObject {
int item_count;
Lua::Event::Owner *owner;
};
}
void DFHack::Lua::Event::New(lua_State *state, Owner *owner)
{
lua_newtable(state);
auto obj = (EventObject *)lua_newuserdata(state, sizeof(EventObject));
obj->item_count = 0;
obj->owner = owner;
lua_rawgetp(state, LUA_REGISTRYINDEX, &DFHACK_EVENT_META_TOKEN);
lua_setmetatable(state, -2);
lua_newtable(state);
lua_setuservalue(state, -2);
}
void DFHack::Lua::Event::SetPrivateCallback(lua_State *L, int event)
{
lua_getuservalue(L, event);
lua_swap(L);
lua_rawsetp(L, -2, NULL);
lua_pop(L, 1);
}
static int dfhack_event_new(lua_State *L)
{
Lua::Event::New(L);
return 1;
}
static int dfhack_event_len(lua_State *L)
{
luaL_checktype(L, 1, LUA_TUSERDATA);
auto obj = (EventObject *)lua_touserdata(L, 1);
lua_pushinteger(L, obj->item_count);
return 1;
}
static int dfhack_event_tostring(lua_State *L)
{
luaL_checktype(L, 1, LUA_TUSERDATA);
auto obj = (EventObject *)lua_touserdata(L, 1);
lua_pushfstring(L, "<event: %d listeners>", obj->item_count);
return 1;
}
static int dfhack_event_index(lua_State *L)
{
luaL_checktype(L, 1, LUA_TUSERDATA);
lua_getuservalue(L, 1);
lua_pushvalue(L, 2);
lua_rawget(L, -2);
return 1;
}
static int dfhack_event_next(lua_State *L)
{
luaL_checktype(L, 1, LUA_TUSERDATA);
lua_getuservalue(L, 1);
lua_pushvalue(L, 2);
while (lua_next(L, -2))
{
if (is_null_userdata(L, -2))
lua_pop(L, 1);
else
return 2;
}
lua_pushnil(L);
return 1;
}
static int dfhack_event_pairs(lua_State *L)
{
luaL_checktype(L, 1, LUA_TUSERDATA);
lua_pushcfunction(L, dfhack_event_next);
lua_pushvalue(L, 1);
lua_pushnil(L);
return 3;
}
static int dfhack_event_newindex(lua_State *L)
{
luaL_checktype(L, 1, LUA_TUSERDATA);
if (is_null_userdata(L, 2))
luaL_argerror(L, 2, "Key NULL is reserved in events.");
lua_settop(L, 3);
lua_getuservalue(L, 1);
bool new_nil = lua_isnil(L, 3);
lua_pushvalue(L, 2);
lua_rawget(L, 4);
bool old_nil = lua_isnil(L, -1);
lua_settop(L, 4);
lua_pushvalue(L, 2);
lua_pushvalue(L, 3);
lua_rawset(L, 4);
int delta = 0;
if (old_nil && !new_nil) delta = 1;
else if (new_nil && !old_nil) delta = -1;
if (delta != 0)
{
auto obj = (EventObject *)lua_touserdata(L, 1);
obj->item_count += delta;
if (obj->owner)
obj->owner->on_count_changed(obj->item_count, delta);
}
return 0;
}
static void do_invoke_event(lua_State *L, int argbase, int num_args, int errorfun)
{
for (int i = 0; i < num_args; i++)
@ -1292,7 +1406,7 @@ static void dfhack_event_invoke(lua_State *L, int base, bool from_c)
while (lua_next(L, event))
{
// Skip the NULL key in the main loop
if (lua_islightuserdata(L, -2) && !lua_touserdata(L, -2))
if (is_null_userdata(L, -2))
lua_pop(L, 1);
else
do_invoke_event(L, argbase, num_args, errorfun);
@ -1303,14 +1417,20 @@ static void dfhack_event_invoke(lua_State *L, int base, bool from_c)
static int dfhack_event_call(lua_State *state)
{
luaL_checktype(state, 1, LUA_TTABLE);
luaL_checktype(state, 1, LUA_TUSERDATA);
luaL_checkstack(state, lua_gettop(state)+2, "stack overflow in event dispatch");
auto obj = (EventObject *)lua_touserdata(state, 1);
if (obj->owner)
obj->owner->on_invoked(state, lua_gettop(state)-1, false);
lua_getuservalue(state, 1);
lua_replace(state, 1);
dfhack_event_invoke(state, 0, false);
return 0;
}
void DFHack::Lua::InvokeEvent(color_ostream &out, lua_State *state, void *key, int num_args)
void DFHack::Lua::Event::Invoke(color_ostream &out, lua_State *state, void *key, int num_args)
{
AssertCoreSuspend(state);
@ -1325,7 +1445,7 @@ void DFHack::Lua::InvokeEvent(color_ostream &out, lua_State *state, void *key, i
lua_rawgetp(state, LUA_REGISTRYINDEX, key);
if (!lua_istable(state, -1))
if (!lua_isuserdata(state, -1))
{
if (!lua_isnil(state, -1))
out.printerr("Invalid event object in Lua::InvokeEvent");
@ -1333,22 +1453,29 @@ void DFHack::Lua::InvokeEvent(color_ostream &out, lua_State *state, void *key, i
return;
}
auto obj = (EventObject *)lua_touserdata(state, -1);
lua_insert(state, base+1);
if (obj->owner)
obj->owner->on_invoked(state, num_args, true);
lua_getuservalue(state, base+1);
lua_replace(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)
void DFHack::Lua::Event::Make(lua_State *state, void *key, Owner *owner)
{
lua_rawgetp(state, LUA_REGISTRYINDEX, key);
if (lua_isnil(state, -1))
{
lua_pop(state, 1);
NewEvent(state);
New(state, owner);
}
lua_dup(state);
@ -1358,7 +1485,7 @@ void DFHack::Lua::MakeEvent(lua_State *state, void *key)
void DFHack::Lua::Notification::invoke(color_ostream &out, int nargs)
{
assert(state);
InvokeEvent(out, state, key, nargs);
Event::Invoke(out, state, key, nargs);
}
void DFHack::Lua::Notification::bind(lua_State *state, void *key)
@ -1369,12 +1496,12 @@ void DFHack::Lua::Notification::bind(lua_State *state, void *key)
void DFHack::Lua::Notification::bind(lua_State *state, const char *name)
{
MakeEvent(state, this);
Event::Make(state, this);
if (handler)
{
PushFunctionWrapper(state, 0, name, handler);
lua_rawsetp(state, -2, NULL);
Event::SetPrivateCallback(state, -2);
}
this->state = state;
@ -1435,11 +1562,26 @@ lua_State *DFHack::Lua::Open(color_ostream &out, lua_State *state)
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_pushcfunction(state, dfhack_event_len);
lua_setfield(state, -2, "__len");
lua_pushcfunction(state, dfhack_event_tostring);
lua_setfield(state, -2, "__tostring");
lua_pushcfunction(state, dfhack_event_index);
lua_setfield(state, -2, "__index");
lua_pushcfunction(state, dfhack_event_newindex);
lua_setfield(state, -2, "__newindex");
lua_pushcfunction(state, dfhack_event_pairs);
lua_setfield(state, -2, "__pairs");
lua_dup(state);
lua_rawsetp(state, LUA_REGISTRYINDEX, &DFHACK_EVENT_META_TOKEN);
lua_setfield(state, -2, "event");
lua_newtable(state);
lua_pushcfunction(state, dfhack_event_new);
lua_setfield(state, -2, "new");
lua_dup(state);
lua_setfield(state, -3, "__metatable");
lua_setfield(state, -3, "event");
lua_pop(state, 1);
// Initialize the dfhack global
luaL_setfuncs(state, dfhack_funcs, 0);
@ -1599,7 +1741,7 @@ void DFHack::Lua::Core::onStateChange(color_ostream &out, int code) {
}
Lua::Push(State, code);
Lua::InvokeEvent(out, State, (void*)onStateChange, 1);
Lua::Event::Invoke(out, State, (void*)onStateChange, 1);
}
static void run_timers(color_ostream &out, lua_State *L,
@ -1653,7 +1795,7 @@ void DFHack::Lua::Core::Init(color_ostream &out)
// Register events
lua_rawgetp(State, LUA_REGISTRYINDEX, &DFHACK_DFHACK_TOKEN);
MakeEvent(State, (void*)onStateChange);
Event::Make(State, (void*)onStateChange);
lua_setfield(State, -2, "onStateChange");
lua_pushcfunction(State, dfhack_timeout);

@ -37,6 +37,7 @@ distribution.
#include "DataDefs.h"
#include "DataIdentity.h"
#include "LuaWrapper.h"
#include "LuaTools.h"
#include "DataFuncs.h"
#include "MiscUtils.h"
@ -285,6 +286,9 @@ void container_identity::lua_item_read(lua_State *state, int fname_idx, void *pt
void container_identity::lua_item_write(lua_State *state, int fname_idx, void *ptr, int idx, int val_index)
{
if (is_readonly())
field_error(state, fname_idx, "container is read-only", "write");
auto id = (type_identity*)lua_touserdata(state, UPVAL_ITEM_ID);
void *pitem = item_pointer(id, ptr, idx);
id->lua_write(state, fname_idx, pitem, val_index);
@ -1064,6 +1068,27 @@ int LuaWrapper::method_wrapper_core(lua_State *state, function_identity_base *id
return 1;
}
int Lua::CallWithCatch(lua_State *state, int (*fn)(lua_State*), const char *context)
{
if (!context)
context = "native code";
try {
return fn(state);
}
catch (Error::NullPointer &e) {
const char *vn = e.varname();
return luaL_error(state, "%s: NULL pointer: %s", context, vn ? vn : "?");
}
catch (Error::InvalidArgument &e) {
const char *vn = e.expr();
return luaL_error(state, "%s: Invalid argument; expected: %s", context, vn ? vn : "?");
}
catch (std::exception &e) {
return luaL_error(state, "%s: C++ exception: %s", context, e.what());
}
}
/**
* Push a closure invoking the given function.
*/

@ -108,6 +108,50 @@ struct Plugin::RefAutoinc
~RefAutoinc(){ lock->lock_sub(); };
};
struct Plugin::LuaCommand {
Plugin *owner;
std::string name;
int (*command)(lua_State *state);
LuaCommand(Plugin *owner, std::string name)
: owner(owner), name(name), command(NULL) {}
};
struct Plugin::LuaFunction {
Plugin *owner;
std::string name;
function_identity_base *identity;
bool silent;
LuaFunction(Plugin *owner, std::string name)
: owner(owner), name(name), identity(NULL), silent(false) {}
};
struct Plugin::LuaEvent : public Lua::Event::Owner {
LuaFunction handler;
Lua::Notification *event;
bool active;
int count;
LuaEvent(Plugin *owner, std::string name)
: handler(owner,name), event(NULL), active(false), count(0)
{
handler.silent = true;
}
void on_count_changed(int new_cnt, int delta) {
RefAutoinc lock(handler.owner->access);
count = new_cnt;
if (event)
event->on_count_changed(new_cnt, delta);
}
void on_invoked(lua_State *state, int nargs, bool from_c) {
RefAutoinc lock(handler.owner->access);
if (event)
event->on_invoked(state, nargs, from_c);
}
};
Plugin::Plugin(Core * core, const std::string & filepath, const std::string & _filename, PluginManager * pm)
{
filename = filepath;
@ -142,19 +186,26 @@ Plugin::~Plugin()
bool Plugin::load(color_ostream &con)
{
RefAutolock lock(access);
if(state == PS_BROKEN)
{
return false;
}
else if(state == PS_LOADED)
{
return true;
RefAutolock lock(access);
if(state == PS_LOADED)
{
return true;
}
else if(state != PS_UNLOADED)
{
return false;
}
state = PS_LOADING;
}
// enter suspend
CoreSuspender suspend;
// open the library, etc
DFLibrary * plug = OpenPlugin(filename.c_str());
if(!plug)
{
con.printerr("Can't load plugin %s\n", filename.c_str());
RefAutolock lock(access);
state = PS_BROKEN;
return false;
}
@ -164,6 +215,7 @@ bool Plugin::load(color_ostream &con)
{
con.printerr("Plugin %s has no name or version.\n", filename.c_str());
ClosePlugin(plug);
RefAutolock lock(access);
state = PS_BROKEN;
return false;
}
@ -172,9 +224,11 @@ bool Plugin::load(color_ostream &con)
con.printerr("Plugin %s was not built for this version of DFHack.\n"
"Plugin: %s, DFHack: %s\n", *plug_name, *plug_version, DFHACK_VERSION);
ClosePlugin(plug);
RefAutolock lock(access);
state = PS_BROKEN;
return false;
}
RefAutolock lock(access);
plugin_init = (command_result (*)(color_ostream &, std::vector <PluginCommand> &)) LookupPlugin(plug, "plugin_init");
if(!plugin_init)
{
@ -226,6 +280,11 @@ bool Plugin::unload(color_ostream &con)
}
// wait for all calls to finish
access->wait();
state = PS_UNLOADING;
access->unlock();
// enter suspend
CoreSuspender suspend;
access->lock();
// notify plugin about shutdown, if it has a shutdown function
command_result cr = CR_OK;
if(plugin_shutdown)
@ -439,7 +498,11 @@ void Plugin::index_lua(DFLibrary *lib)
cmd->handler.identity = evlist->event->get_handler();
cmd->event = evlist->event;
if (cmd->active)
{
cmd->event->bind(Lua::Core::State, cmd);
if (cmd->count > 0)
cmd->event->on_count_changed(cmd->count, 0);
}
}
}
}
@ -467,7 +530,7 @@ int Plugin::lua_cmd_wrapper(lua_State *state)
luaL_error(state, "plugin command %s() has been unloaded",
(cmd->owner->name+"."+cmd->name).c_str());
return cmd->command(state);
return Lua::CallWithCatch(state, cmd->command, cmd->name.c_str());
}
int Plugin::lua_fun_wrapper(lua_State *state)
@ -477,8 +540,13 @@ int Plugin::lua_fun_wrapper(lua_State *state)
RefAutoinc lock(cmd->owner->access);
if (!cmd->identity)
{
if (cmd->silent)
return 0;
luaL_error(state, "plugin function %s() has been unloaded",
(cmd->owner->name+"."+cmd->name).c_str());
}
return LuaWrapper::method_wrapper_core(state, cmd->identity);
}
@ -506,14 +574,14 @@ void Plugin::open_lua(lua_State *state, int table)
{
for (auto it = lua_events.begin(); it != lua_events.end(); ++it)
{
Lua::MakeEvent(state, it->second);
Lua::Event::Make(state, it->second, it->second);
push_function(state, &it->second->handler);
lua_rawsetp(state, -2, NULL);
Lua::Event::SetPrivateCallback(state, -2);
it->second->active = true;
if (it->second->event)
it->second->event->bind(state, it->second);
it->second->event->bind(Lua::Core::State, it->second);
lua_setfield(state, table, it->first.c_str());
}

@ -0,0 +1,457 @@
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "Internal.h"
#include <string>
#include <vector>
#include <map>
#include "MemAccess.h"
#include "Core.h"
#include "VersionInfo.h"
#include "VTableInterpose.h"
#include "MiscUtils.h"
using namespace DFHack;
/*
* Code for accessing method pointers directly. Very compiler-specific.
*/
#if defined(_MSC_VER)
struct MSVC_MPTR {
void *method;
intptr_t this_shift;
};
bool DFHack::is_vmethod_pointer_(void *pptr)
{
auto pobj = (MSVC_MPTR*)pptr;
if (!pobj->method) return false;
// MSVC implements pointers to vmethods via thunks.
// This expects that they all follow a very specific pattern.
auto pval = (unsigned*)pobj->method;
switch (pval[0]) {
case 0x20FF018BU: // mov eax, [ecx]; jmp [eax]
case 0x60FF018BU: // mov eax, [ecx]; jmp [eax+0x??]
case 0xA0FF018BU: // mov eax, [ecx]; jmp [eax+0x????????]
return true;
default:
return false;
}
}
int DFHack::vmethod_pointer_to_idx_(void *pptr)
{
auto pobj = (MSVC_MPTR*)pptr;
if (!pobj->method || pobj->this_shift != 0) return -1;
auto pval = (unsigned*)pobj->method;
switch (pval[0]) {
case 0x20FF018BU: // mov eax, [ecx]; jmp [eax]
return 0;
case 0x60FF018BU: // mov eax, [ecx]; jmp [eax+0x??]
return ((int8_t)pval[1])/sizeof(void*);
case 0xA0FF018BU: // mov eax, [ecx]; jmp [eax+0x????????]
return ((int32_t)pval[1])/sizeof(void*);
default:
return -1;
}
}
void* DFHack::method_pointer_to_addr_(void *pptr)
{
if (is_vmethod_pointer_(pptr)) return NULL;
auto pobj = (MSVC_MPTR*)pptr;
return pobj->method;
}
void DFHack::addr_to_method_pointer_(void *pptr, void *addr)
{
auto pobj = (MSVC_MPTR*)pptr;
pobj->method = addr;
pobj->this_shift = 0;
}
#elif defined(__GXX_ABI_VERSION)
struct GCC_MPTR {
intptr_t method;
intptr_t this_shift;
};
bool DFHack::is_vmethod_pointer_(void *pptr)
{
auto pobj = (GCC_MPTR*)pptr;
return (pobj->method & 1) != 0;
}
int DFHack::vmethod_pointer_to_idx_(void *pptr)
{
auto pobj = (GCC_MPTR*)pptr;
if ((pobj->method & 1) == 0 || pobj->this_shift != 0)
return -1;
return (pobj->method-1)/sizeof(void*);
}
void* DFHack::method_pointer_to_addr_(void *pptr)
{
auto pobj = (GCC_MPTR*)pptr;
if ((pobj->method & 1) != 0 || pobj->this_shift != 0)
return NULL;
return (void*)pobj->method;
}
void DFHack::addr_to_method_pointer_(void *pptr, void *addr)
{
auto pobj = (GCC_MPTR*)pptr;
pobj->method = (intptr_t)addr;
pobj->this_shift = 0;
}
#else
#error Unknown compiler type
#endif
void *virtual_identity::get_vmethod_ptr(int idx)
{
assert(idx >= 0);
void **vtable = (void**)vtable_ptr;
if (!vtable) return NULL;
return vtable[idx];
}
bool virtual_identity::set_vmethod_ptr(int idx, void *ptr)
{
assert(idx >= 0);
void **vtable = (void**)vtable_ptr;
if (!vtable) return NULL;
return Core::getInstance().p->patchMemory(&vtable[idx], &ptr, sizeof(void*));
}
/*
VMethod interposing data structures.
In order to properly support adding and removing hooks,
it is necessary to track them. This is what this class
is for. The task is further complicated by propagating
hooks to child classes that use exactly the same original
vmethod implementation.
Every applied link contains in the saved_chain field a
pointer to the next vmethod body that should be called
by the hook the link represents. This is the actual
control flow structure that needs to be maintained.
There also are connections between link objects themselves,
which constitute the bookkeeping for doing that. Finally,
every link is associated with a fixed virtual_identity host,
which represents the point in the class hierarchy where
the hook is applied.
When there are no subclasses (i.e. only one host), the
structures look like this:
+--------------+ +------------+
| link1 |-next------->| link2 |-next=NULL
|s_c: original |<-------prev-|s_c: $link1 |<--+
+--------------+ +------------+ |
|
host->interpose_list[vmethod_idx] ------+
vtable: $link2
The original vtable entry is stored in the saved_chain of the
first link. The interpose_list map points to the last one.
The hooks are called in order: link2 -> link1 -> original.
When there are subclasses that use the same vmethod, but don't
hook it, the topmost link gets a set of the child_hosts, and
the hosts have the link added to their interpose_list:
+--------------+ +----------------+
| link0 @host0 |<--+-interpose_list-| host1 |
| |-child_hosts-+----->| vtable: $link |
+--------------+ | | +----------------+
| |
| | +----------------+
+-interpose_list-| host2 |
+----->| vtable: $link |
+----------------+
When a child defines its own hook, the child_hosts link is
severed and replaced with a child_next pointer to the new
hook. The hook still points back the chain with prev.
All child links to subclasses of host2 are migrated from
link1 to link2.
+--------------+-next=NULL +--------------+-next=NULL
| link1 @host1 |-child_next------->| link2 @host2 |-child_*--->subclasses
| |<-------------prev-|s_c: $link1 |
+--------------+<-------+ +--------------+<-------+
| |
+--------------+ | +--------------+ |
| host1 |-i_list-+ | host2 |-i_list-+
|vtable: $link1| |vtable: $link2|
+--------------+ +--------------+
*/
void VMethodInterposeLinkBase::set_chain(void *chain)
{
saved_chain = chain;
addr_to_method_pointer_(chain_mptr, chain);
}
VMethodInterposeLinkBase::VMethodInterposeLinkBase(virtual_identity *host, int vmethod_idx, void *interpose_method, void *chain_mptr)
: host(host), vmethod_idx(vmethod_idx), interpose_method(interpose_method), chain_mptr(chain_mptr),
applied(false), saved_chain(NULL), next(NULL), prev(NULL)
{
if (vmethod_idx < 0 || interpose_method == NULL)
{
fprintf(stderr, "Bad VMethodInterposeLinkBase arguments: %d %08x\n",
vmethod_idx, unsigned(interpose_method));
fflush(stderr);
abort();
}
}
VMethodInterposeLinkBase::~VMethodInterposeLinkBase()
{
if (is_applied())
remove();
}
VMethodInterposeLinkBase *VMethodInterposeLinkBase::get_first_interpose(virtual_identity *id)
{
auto item = id->interpose_list[vmethod_idx];
if (!item)
return NULL;
if (item->host != id)
return NULL;
while (item->prev && item->prev->host == id)
item = item->prev;
return item;
}
void VMethodInterposeLinkBase::find_child_hosts(virtual_identity *cur, void *vmptr)
{
auto &children = cur->getChildren();
for (size_t i = 0; i < children.size(); i++)
{
auto child = static_cast<virtual_identity*>(children[i]);
auto base = get_first_interpose(child);
if (base)
{
assert(base->prev == NULL);
if (base->saved_chain != vmptr)
continue;
child_next.insert(base);
}
else
{
void *cptr = child->get_vmethod_ptr(vmethod_idx);
if (cptr != vmptr)
continue;
child_hosts.insert(child);
find_child_hosts(child, vmptr);
}
}
}
void VMethodInterposeLinkBase::on_host_delete(virtual_identity *from)
{
if (from == host)
{
// When in own host, fully delete
remove();
}
else
{
// Otherwise, drop the link to that child:
assert(child_hosts.count(from) != 0 &&
from->interpose_list[vmethod_idx] == this);
// Find and restore the original vmethod ptr
auto last = this;
while (last->prev) last = last->prev;
from->set_vmethod_ptr(vmethod_idx, last->saved_chain);
// Unlink the chains
child_hosts.erase(from);
from->interpose_list[vmethod_idx] = NULL;
}
}
bool VMethodInterposeLinkBase::apply()
{
if (is_applied())
return true;
if (!host->vtable_ptr)
return false;
// Retrieve the current vtable entry
void *old_ptr = host->get_vmethod_ptr(vmethod_idx);
VMethodInterposeLinkBase *old_link = host->interpose_list[vmethod_idx];
assert(old_ptr != NULL && (!old_link || old_link->interpose_method == old_ptr));
// Apply the new method ptr
set_chain(old_ptr);
if (!host->set_vmethod_ptr(vmethod_idx, interpose_method))
{
set_chain(NULL);
return false;
}
// Push the current link into the home host
applied = true;
host->interpose_list[vmethod_idx] = this;
prev = old_link;
child_hosts.clear();
child_next.clear();
if (old_link && old_link->host == host)
{
// If the old link is home, just push into the plain chain
assert(old_link->next == NULL);
old_link->next = this;
// Child links belong to the topmost local entry
child_hosts.swap(old_link->child_hosts);
child_next.swap(old_link->child_next);
}
else
{
// If creating a new local chain, find children with same vmethod
find_child_hosts(host, old_ptr);
if (old_link)
{
// Enter the child chain set
assert(old_link->child_hosts.count(host));
old_link->child_hosts.erase(host);
old_link->child_next.insert(this);
// Subtract our own children from the parent's sets
for (auto it = child_next.begin(); it != child_next.end(); ++it)
old_link->child_next.erase(*it);
for (auto it = child_hosts.begin(); it != child_hosts.end(); ++it)
old_link->child_hosts.erase(*it);
}
}
// Chain subclass hooks
for (auto it = child_next.begin(); it != child_next.end(); ++it)
{
auto nlink = *it;
assert(nlink->saved_chain == old_ptr && nlink->prev == old_link);
nlink->set_chain(interpose_method);
nlink->prev = this;
}
// Chain passive subclass hosts
for (auto it = child_hosts.begin(); it != child_hosts.end(); ++it)
{
auto nhost = *it;
assert(nhost->interpose_list[vmethod_idx] == old_link);
nhost->set_vmethod_ptr(vmethod_idx, interpose_method);
nhost->interpose_list[vmethod_idx] = this;
}
return true;
}
void VMethodInterposeLinkBase::remove()
{
if (!is_applied())
return;
// Remove the link from prev to this
if (prev)
{
if (prev->host == host)
prev->next = next;
else
{
prev->child_next.erase(this);
if (next)
prev->child_next.insert(next);
}
}
if (next)
{
next->set_chain(saved_chain);
next->prev = prev;
assert(child_next.empty() && child_hosts.empty());
}
else
{
// Remove from the list in the identity and vtable
host->interpose_list[vmethod_idx] = prev;
host->set_vmethod_ptr(vmethod_idx, saved_chain);
for (auto it = child_next.begin(); it != child_next.end(); ++it)
{
auto nlink = *it;
assert(nlink->saved_chain == interpose_method && nlink->prev == this);
nlink->set_chain(saved_chain);
nlink->prev = prev;
if (prev)
prev->child_next.insert(nlink);
}
for (auto it = child_hosts.begin(); it != child_hosts.end(); ++it)
{
auto nhost = *it;
assert(nhost->interpose_list[vmethod_idx] == this);
nhost->interpose_list[vmethod_idx] = prev;
nhost->set_vmethod_ptr(vmethod_idx, saved_chain);
if (prev)
prev->child_hosts.insert(nhost);
}
}
applied = false;
prev = next = NULL;
child_next.clear();
child_hosts.clear();
set_chain(NULL);
}

@ -41,30 +41,32 @@ namespace dfproto
namespace DFHack
{
enum color_value
{
COLOR_RESET = -1,
COLOR_BLACK = 0,
COLOR_BLUE,
COLOR_GREEN,
COLOR_CYAN,
COLOR_RED,
COLOR_MAGENTA,
COLOR_BROWN,
COLOR_GREY,
COLOR_DARKGREY,
COLOR_LIGHTBLUE,
COLOR_LIGHTGREEN,
COLOR_LIGHTCYAN,
COLOR_LIGHTRED,
COLOR_LIGHTMAGENTA,
COLOR_YELLOW,
COLOR_WHITE,
COLOR_MAX = COLOR_WHITE
};
class DFHACK_EXPORT color_ostream : public std::ostream
{
public:
enum color_value
{
COLOR_RESET = -1,
COLOR_BLACK = 0,
COLOR_BLUE,
COLOR_GREEN,
COLOR_CYAN,
COLOR_RED,
COLOR_MAGENTA,
COLOR_BROWN,
COLOR_GREY,
COLOR_DARKGREY,
COLOR_LIGHTBLUE,
COLOR_LIGHTGREEN,
COLOR_LIGHTCYAN,
COLOR_LIGHTRED,
COLOR_LIGHTMAGENTA,
COLOR_YELLOW,
COLOR_WHITE,
COLOR_MAX = COLOR_WHITE
};
typedef DFHack::color_value color_value;
private:
color_value cur_color;

@ -174,6 +174,10 @@ namespace DFHack
struct Private;
Private *d;
friend class CoreSuspendClaimer;
int ClaimSuspend(bool force_base);
void DisclaimSuspend(int level);
bool Init();
int Update (void);
int TileUpdate (void);
@ -181,6 +185,7 @@ namespace DFHack
int DFH_SDL_Event(SDL::Event* event);
bool ncurses_wgetch(int in, int & out);
void doUpdate(color_ostream &out, bool first_update);
void onUpdate(color_ostream &out);
void onStateChange(color_ostream &out, state_change_event event);
@ -249,4 +254,20 @@ namespace DFHack
CoreSuspender(Core *core) : core(core) { core->Suspend(); }
~CoreSuspender() { core->Resume(); }
};
/** Claims the current thread already has the suspend lock.
* Strictly for use in callbacks from DF.
*/
class CoreSuspendClaimer {
Core *core;
int level;
public:
CoreSuspendClaimer(bool base = false) : core(&Core::getInstance()) {
level = core->ClaimSuspend(base);
}
CoreSuspendClaimer(Core *core, bool base = false) : core(core) {
level = core->ClaimSuspend(base);
}
~CoreSuspendClaimer() { core->DisclaimSuspend(level); }
};
}

@ -28,6 +28,7 @@ distribution.
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include "Core.h"
#include "BitArray.h"
@ -292,6 +293,8 @@ namespace DFHack
typedef virtual_class *virtual_ptr;
#endif
class DFHACK_EXPORT VMethodInterposeLinkBase;
class DFHACK_EXPORT virtual_identity : public struct_identity {
static std::map<void*, virtual_identity*> known;
@ -299,6 +302,9 @@ namespace DFHack
void *vtable_ptr;
friend class VMethodInterposeLinkBase;
std::map<int,VMethodInterposeLinkBase*> interpose_list;
protected:
virtual void doInit(Core *core);
@ -306,10 +312,14 @@ namespace DFHack
bool can_allocate() { return struct_identity::can_allocate() && (vtable_ptr != NULL); }
void *get_vmethod_ptr(int index);
bool set_vmethod_ptr(int index, void *ptr);
public:
virtual_identity(size_t size, TAllocateFn alloc,
const char *dfhack_name, const char *original_name,
virtual_identity *parent, const struct_field_info *fields);
~virtual_identity();
virtual identity_type type() { return IDTYPE_CLASS; }
@ -337,6 +347,8 @@ namespace DFHack
: (this == get(instance_ptr));
}
template<class P> static P get_vmethod_ptr(P selector);
public:
bool can_instantiate() { return can_allocate(); }
virtual_ptr instantiate() { return can_instantiate() ? (virtual_ptr)do_allocate() : NULL; }

@ -75,28 +75,31 @@ namespace df {
cur_lua_ostream_argument name(state);
#define INSTANTIATE_RETURN_TYPE(FArgs) \
template<FW_TARGSC class RT> struct return_type<RT (*) FArgs> { typedef RT type; }; \
template<FW_TARGSC class RT, class CT> struct return_type<RT (CT::*) FArgs> { typedef RT type; };
template<FW_TARGSC class RT> struct return_type<RT (*) FArgs> { \
typedef RT type; \
static const bool is_method = false; \
}; \
template<FW_TARGSC class RT, class CT> struct return_type<RT (CT::*) FArgs> { \
typedef RT type; \
typedef CT class_type; \
static const bool is_method = true; \
};
#define INSTANTIATE_WRAPPERS(Count, FArgs, Args, Loads) \
template<FW_TARGS> struct function_wrapper<void (*) FArgs, true> { \
static const bool is_method = false; \
static const int num_args = Count; \
static void execute(lua_State *state, int base, void (*cb) FArgs) { Loads; INVOKE_VOID(cb Args); } \
}; \
template<FW_TARGSC class RT> struct function_wrapper<RT (*) FArgs, false> { \
static const bool is_method = false; \
static const int num_args = Count; \
static void execute(lua_State *state, int base, RT (*cb) FArgs) { Loads; INVOKE_RV(cb Args); } \
}; \
template<FW_TARGSC class CT> struct function_wrapper<void (CT::*) FArgs, true> { \
static const bool is_method = true; \
static const int num_args = Count+1; \
static void execute(lua_State *state, int base, void (CT::*cb) FArgs) { \
LOAD_CLASS() Loads; INVOKE_VOID((self->*cb) Args); } \
}; \
template<FW_TARGSC class RT, class CT> struct function_wrapper<RT (CT::*) FArgs, false> { \
static const bool is_method = true; \
static const int num_args = Count+1; \
static void execute(lua_State *state, int base, RT (CT::*cb) FArgs) { \
LOAD_CLASS(); Loads; INVOKE_RV((self->*cb) Args); } \

@ -115,6 +115,8 @@ namespace DFHack
virtual void lua_item_read(lua_State *state, int fname_idx, void *ptr, int idx);
virtual void lua_item_write(lua_State *state, int fname_idx, void *ptr, int idx, int val_index);
virtual bool is_readonly() { return false; }
virtual bool resize(void *ptr, int size) { return false; }
virtual bool erase(void *ptr, int index) { return false; }
virtual bool insert(void *ptr, int index, void *pitem) { return false; }
@ -343,6 +345,33 @@ namespace df
}
};
template<class T>
class ro_stl_container_identity : public container_identity {
const char *name;
public:
ro_stl_container_identity(const char *name, type_identity *item, enum_identity *ienum = NULL)
: container_identity(sizeof(T), &allocator_fn<T>, item, ienum), name(name)
{}
std::string getFullName(type_identity *item) {
return name + container_identity::getFullName(item);
}
virtual bool is_readonly() { return true; }
virtual bool resize(void *ptr, int size) { return false; }
virtual bool erase(void *ptr, int size) { return false; }
virtual bool insert(void *ptr, int idx, void *item) { return false; }
protected:
virtual int item_count(void *ptr, CountMode) { return ((T*)ptr)->size(); }
virtual void *item_pointer(type_identity *item, void *ptr, int idx) {
auto iter = (*(T*)ptr).begin();
for (; idx > 0; idx--) ++iter;
return (void*)&*iter;
}
};
class bit_array_identity : public bit_container_identity {
public:
/*
@ -517,6 +546,10 @@ namespace df
static container_identity *get();
};
template<class T> struct identity_traits<std::set<T> > {
static container_identity *get();
};
template<> struct identity_traits<BitArray<int> > {
static bit_array_identity identity;
static bit_container_identity *get() { return &identity; }
@ -579,6 +612,13 @@ namespace df
return &identity;
}
template<class T>
inline container_identity *identity_traits<std::set<T> >::get() {
typedef std::set<T> container;
static ro_stl_container_identity<container> identity("set", identity_traits<T>::get());
return &identity;
}
template<class T>
inline bit_container_identity *identity_traits<BitArray<T> >::get() {
static bit_array_identity identity(identity_traits<T>::get());

@ -191,6 +191,16 @@ namespace DFHack {namespace Lua {
return cb(state, rv, ctx);
}
/**
* Call through to the function with try/catch for C++ exceptions.
*/
DFHACK_EXPORT int CallWithCatch(lua_State *, int (*fn)(lua_State*), const char *context = NULL);
template<int (*cb)(lua_State*)>
int CallWithCatchWrapper(lua_State *state) {
return CallWithCatch(state, cb);
}
/**
* 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.
@ -300,9 +310,18 @@ namespace DFHack {namespace Lua {
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 Event {
struct DFHACK_EXPORT Owner {
virtual ~Owner() {}
virtual void on_count_changed(int new_cnt, int delta) {}
virtual void on_invoked(lua_State *state, int nargs, bool from_c) {}
};
DFHACK_EXPORT void New(lua_State *state, Owner *owner = NULL);
DFHACK_EXPORT void Make(lua_State *state, void *key, Owner *owner = NULL);
DFHACK_EXPORT void SetPrivateCallback(lua_State *state, int ev_idx);
DFHACK_EXPORT void Invoke(color_ostream &out, lua_State *state, void *key, int num_args);
}
class StackUnwinder {
lua_State *state;
@ -355,18 +374,24 @@ namespace DFHack {namespace Lua {
}
}
class DFHACK_EXPORT Notification {
class DFHACK_EXPORT Notification : public Event::Owner {
lua_State *state;
void *key;
function_identity_base *handler;
int count;
public:
Notification(function_identity_base *handler = NULL)
: state(NULL), key(NULL), handler(handler) {}
: state(NULL), key(NULL), handler(handler), count(0) {}
int get_listener_count() { return count; }
lua_State *get_state() { return state; }
function_identity_base *get_handler() { return handler; }
lua_State *state_if_count() { return (count > 0) ? state : NULL; }
void on_count_changed(int new_cnt, int) { count = new_cnt; }
void invoke(color_ostream &out, int nargs);
void bind(lua_State *state, const char *name);
@ -378,7 +403,7 @@ namespace DFHack {namespace Lua {
static DFHack::Lua::Notification name##_event(df::wrap_function(handler, true)); \
void name(color_ostream &out) { \
handler(out); \
if (name##_event.get_state()) { \
if (name##_event.state_if_count()) { \
name##_event.invoke(out, 0); \
} \
}
@ -387,7 +412,7 @@ namespace DFHack {namespace Lua {
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()) { \
if (auto state = name##_event.state_if_count()) { \
DFHack::Lua::Push(state, arg1); \
name##_event.invoke(out, 1); \
} \
@ -397,7 +422,7 @@ namespace DFHack {namespace Lua {
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()) { \
if (auto state = name##_event.state_if_count()) { \
DFHack::Lua::Push(state, arg1); \
DFHack::Lua::Push(state, arg2); \
name##_event.invoke(out, 2); \
@ -408,7 +433,7 @@ namespace DFHack {namespace Lua {
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()) { \
if (auto state = name##_event.state_if_count()) { \
DFHack::Lua::Push(state, arg1); \
DFHack::Lua::Push(state, arg2); \
DFHack::Lua::Push(state, arg3); \
@ -420,7 +445,7 @@ namespace DFHack {namespace Lua {
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()) { \
if (auto state = name##_event.state_if_count()) { \
DFHack::Lua::Push(state, arg1); \
DFHack::Lua::Push(state, arg2); \
DFHack::Lua::Push(state, arg3); \
@ -433,7 +458,7 @@ namespace DFHack {namespace Lua {
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, arg_type5 arg5) { \
handler(out, arg1, arg2, arg3, arg4, arg5); \
if (auto state = name##_event.get_state()) { \
if (auto state = name##_event.state_if_count()) { \
DFHack::Lua::Push(state, arg1); \
DFHack::Lua::Push(state, arg2); \
DFHack::Lua::Push(state, arg3); \

@ -283,6 +283,9 @@ namespace DFHack
/// modify permisions of memory range
bool setPermisions(const t_memrange & range,const t_memrange &trgrange);
/// write a possibly read-only memory area
bool patchMemory(void *target, const void* src, size_t count);
private:
VersionInfo * my_descriptor;
PlatformSpecific *d;

@ -128,7 +128,9 @@ namespace DFHack
{
PS_UNLOADED,
PS_LOADED,
PS_BROKEN
PS_BROKEN,
PS_LOADING,
PS_UNLOADING
};
friend class PluginManager;
friend class RPCService;
@ -173,31 +175,16 @@ namespace DFHack
PluginManager * parent;
plugin_state state;
struct LuaCommand {
Plugin *owner;
std::string name;
int (*command)(lua_State *state);
LuaCommand(Plugin *owner, std::string name) : owner(owner), name(name) {}
};
struct LuaCommand;
std::map<std::string, LuaCommand*> lua_commands;
static int lua_cmd_wrapper(lua_State *state);
struct LuaFunction {
Plugin *owner;
std::string name;
function_identity_base *identity;
LuaFunction(Plugin *owner, std::string name) : owner(owner), name(name) {}
};
struct LuaFunction;
std::map<std::string, LuaFunction*> 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) {}
};
struct LuaEvent;
std::map<std::string, LuaEvent*> lua_events;
void index_lua(DFLibrary *lib);

@ -0,0 +1,183 @@
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include "DataFuncs.h"
namespace DFHack
{
template<bool> struct StaticAssert;
template<> struct StaticAssert<true> {};
#define STATIC_ASSERT(condition) { StaticAssert<(condition)>(); }
/* Wrapping around compiler-specific representation of pointers to methods. */
#if defined(_MSC_VER)
#define METHOD_POINTER_SIZE (sizeof(void*)*2)
#elif defined(__GXX_ABI_VERSION)
#define METHOD_POINTER_SIZE (sizeof(void*)*2)
#else
#error Unknown compiler type
#endif
#define ASSERT_METHOD_POINTER(type) \
STATIC_ASSERT(df::return_type<type>::is_method && sizeof(type)==METHOD_POINTER_SIZE);
DFHACK_EXPORT bool is_vmethod_pointer_(void*);
DFHACK_EXPORT int vmethod_pointer_to_idx_(void*);
DFHACK_EXPORT void* method_pointer_to_addr_(void*);
DFHACK_EXPORT void addr_to_method_pointer_(void*,void*);
template<class T> bool is_vmethod_pointer(T ptr) {
ASSERT_METHOD_POINTER(T);
return is_vmethod_pointer_(&ptr);
}
template<class T> int vmethod_pointer_to_idx(T ptr) {
ASSERT_METHOD_POINTER(T);
return vmethod_pointer_to_idx_(&ptr);
}
template<class T> void *method_pointer_to_addr(T ptr) {
ASSERT_METHOD_POINTER(T);
return method_pointer_to_addr_(&ptr);
}
template<class T> T addr_to_method_pointer(void *addr) {
ASSERT_METHOD_POINTER(T);
T rv;
addr_to_method_pointer_(&rv, addr);
return rv;
}
/* Access to vmethod pointers from the vtable. */
template<class P>
P virtual_identity::get_vmethod_ptr(P selector)
{
typedef typename df::return_type<P>::class_type host_class;
virtual_identity &identity = host_class::_identity;
int idx = vmethod_pointer_to_idx(selector);
return addr_to_method_pointer<P>(identity.get_vmethod_ptr(idx));
}
/* VMethod interpose API.
This API allows replacing an entry in the original vtable
with code defined by DFHack, while retaining ability to
call the original code. The API can be safely used from
plugins, and multiple hooks for the same vmethod are
automatically chained in undefined order.
Usage:
struct my_hack : df::someclass {
typedef df::someclass interpose_base;
DEFINE_VMETHOD_INTERPOSE(void, foo, (int arg)) {
// If needed by the code, claim the suspend lock.
// DO NOT USE THE USUAL CoreSuspender, OR IT WILL DEADLOCK!
// CoreSuspendClaimer suspend;
...
INTERPOSE_NEXT(foo)(arg) // call the original
...
}
};
IMPLEMENT_VMETHOD_INTERPOSE(my_hack, foo);
void init() {
if (!INTERPOSE_HOOK(my_hack, foo).apply())
error();
}
void shutdown() {
INTERPOSE_HOOK(my_hack, foo).remove();
}
*/
#define DEFINE_VMETHOD_INTERPOSE(rtype, name, args) \
typedef rtype (interpose_base::*interpose_ptr_##name)args; \
static DFHack::VMethodInterposeLink<interpose_base,interpose_ptr_##name> interpose_##name; \
rtype interpose_fn_##name args
#define IMPLEMENT_VMETHOD_INTERPOSE(class,name) \
DFHack::VMethodInterposeLink<class::interpose_base,class::interpose_ptr_##name> \
class::interpose_##name(&class::interpose_base::name, &class::interpose_fn_##name);
#define INTERPOSE_NEXT(name) (this->*interpose_##name.chain)
#define INTERPOSE_HOOK(class, name) (class::interpose_##name)
class DFHACK_EXPORT VMethodInterposeLinkBase {
/*
These link objects try to:
1) Allow multiple hooks into the same vmethod
2) Auto-remove hooks when a plugin is unloaded.
*/
friend class virtual_identity;
virtual_identity *host; // Class with the vtable
int vmethod_idx;
void *interpose_method; // Pointer to the code of the interposing method
void *chain_mptr; // Pointer to the chain field below
bool applied;
void *saved_chain; // Previous pointer to the code
VMethodInterposeLinkBase *next, *prev; // Other hooks for the same method
// inherited vtable members
std::set<virtual_identity*> child_hosts;
std::set<VMethodInterposeLinkBase*> child_next;
void set_chain(void *chain);
void on_host_delete(virtual_identity *host);
VMethodInterposeLinkBase *get_first_interpose(virtual_identity *id);
void find_child_hosts(virtual_identity *cur, void *vmptr);
public:
VMethodInterposeLinkBase(virtual_identity *host, int vmethod_idx, void *interpose_method, void *chain_mptr);
~VMethodInterposeLinkBase();
bool is_applied() { return applied; }
bool apply();
void remove();
};
template<class Base, class Ptr>
class VMethodInterposeLink : public VMethodInterposeLinkBase {
public:
Ptr chain;
operator Ptr () { return chain; }
template<class Ptr2>
VMethodInterposeLink(Ptr target, Ptr2 src)
: VMethodInterposeLinkBase(
&Base::_identity,
vmethod_pointer_to_idx(target),
method_pointer_to_addr(src),
&chain
)
{ src = target; /* check compatibility */ }
};
}

@ -92,6 +92,11 @@ DFHACK_EXPORT bool Read (const uint32_t index, t_building & building);
*/
DFHACK_EXPORT bool ReadCustomWorkshopTypes(std::map <uint32_t, std::string> & btypes);
/**
* Sets the owner unit for the building.
*/
DFHACK_EXPORT bool setOwner(df::building *building, df::unit *owner);
/**
* Find the building located at the specified tile.
* Does not work on civzones.

@ -55,8 +55,6 @@ namespace DFHack
*/
namespace Gui
{
inline df::viewscreen *getCurViewscreen() { return Core::getTopViewscreen(); }
DFHACK_EXPORT std::string getFocusString(df::viewscreen *top);
// Full-screen item details view
@ -99,6 +97,9 @@ namespace DFHack
/*
* Cursor and window coords
*/
DFHACK_EXPORT df::coord getViewportPos();
DFHACK_EXPORT df::coord getCursorPos();
DFHACK_EXPORT bool getViewCoords (int32_t &x, int32_t &y, int32_t &z);
DFHACK_EXPORT bool setViewCoords (const int32_t x, const int32_t y, const int32_t z);
@ -113,7 +114,11 @@ namespace DFHack
* Gui screens
*/
/// Get the current top-level view-screen
DFHACK_EXPORT df::viewscreen * GetCurrentScreen();
DFHACK_EXPORT df::viewscreen *getCurViewscreen(bool skip_dismissed = false);
inline std::string getCurFocus(bool skip_dismissed = false) {
return getFocusString(getCurViewscreen(skip_dismissed));
}
/// get the size of the window buffer
DFHACK_EXPORT bool getWindowSize(int32_t & width, int32_t & height);

@ -258,7 +258,7 @@ inline df::tile_occupancy *getTileOccupancy(df::coord pos) {
/**
* Returns biome info about the specified world region.
*/
DFHACK_EXPORT df::world_data::T_region_map *getRegionBiome(df::coord2d rgn_pos);
DFHACK_EXPORT df::region_map_entry *getRegionBiome(df::coord2d rgn_pos);
/**
* Returns biome world region coordinates for the given tile within given block.

@ -0,0 +1,176 @@
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include "Export.h"
#include "Module.h"
#include "BitArray.h"
#include "ColorText.h"
#include <string>
#include "DataDefs.h"
#include "df/graphic.h"
#include "df/viewscreen.h"
/**
* \defgroup grp_screen utilities for painting to the screen
* @ingroup grp_screen
*/
namespace DFHack
{
class Core;
/**
* The Screen module
* \ingroup grp_modules
* \ingroup grp_screen
*/
namespace Screen
{
/// Data structure describing all properties a screen tile can have
struct Pen {
// Ordinary text symbol
char ch;
int8_t fg, bg;
bool bold;
// Graphics tile
int tile;
enum TileMode {
AsIs, // Tile colors used without modification
CharColor, // The fg/bg pair is used
TileColor // The fields below are used
} tile_mode;
int8_t tile_fg, tile_bg;
Pen(char ch = 0, int8_t fg = 7, int8_t bg = 0, int tile = 0, bool color_tile = false)
: ch(ch), fg(fg&7), bg(bg), bold(!!(fg&8)),
tile(tile), tile_mode(color_tile ? CharColor : AsIs), tile_fg(0), tile_bg(0)
{}
Pen(char ch, int8_t fg, int8_t bg, bool bold, int tile = 0, bool color_tile = false)
: ch(ch), fg(fg), bg(bg), bold(bold),
tile(tile), tile_mode(color_tile ? CharColor : AsIs), tile_fg(0), tile_bg(0)
{}
Pen(char ch, int8_t fg, int8_t bg, int tile, int8_t tile_fg, int8_t tile_bg)
: ch(ch), fg(fg&7), bg(bg), bold(!!(fg&8)),
tile(tile), tile_mode(TileColor), tile_fg(tile_fg), tile_bg(tile_bg)
{}
Pen(char ch, int8_t fg, int8_t bg, bool bold, int tile, int8_t tile_fg, int8_t tile_bg)
: ch(ch), fg(fg), bg(bg), bold(bold),
tile(tile), tile_mode(TileColor), tile_fg(tile_fg), tile_bg(tile_bg)
{}
};
DFHACK_EXPORT df::coord2d getMousePos();
DFHACK_EXPORT df::coord2d getWindowSize();
/// Returns the state of [GRAPHICS:YES/NO]
DFHACK_EXPORT bool inGraphicsMode();
/// Paint one screen tile with the given pen
DFHACK_EXPORT bool paintTile(const Pen &pen, int x, int y);
/// Paint a string onto the screen. Ignores ch and tile of pen.
DFHACK_EXPORT bool paintString(const Pen &pen, int x, int y, const std::string &text);
/// Fills a rectangle with one pen. Possibly more efficient than a loop over paintTile.
DFHACK_EXPORT bool fillRect(const Pen &pen, int x1, int y1, int x2, int y2);
/// Draws a standard dark gray window border with a title string
DFHACK_EXPORT bool drawBorder(const std::string &title);
/// Wipes the screen to full black
DFHACK_EXPORT bool clear();
/// Requests repaint
DFHACK_EXPORT bool invalidate();
/// Find a loaded graphics tile from graphics raws.
DFHACK_EXPORT bool findGraphicsTile(const std::string &page, int x, int y, int *ptile, int *pgs = NULL);
// Push and remove viewscreens
DFHACK_EXPORT bool show(df::viewscreen *screen, df::viewscreen *before = NULL);
DFHACK_EXPORT void dismiss(df::viewscreen *screen, bool to_first = false);
DFHACK_EXPORT bool isDismissed(df::viewscreen *screen);
}
class DFHACK_EXPORT dfhack_viewscreen : public df::viewscreen {
df::coord2d last_size;
void check_resize();
protected:
bool text_input_mode;
public:
dfhack_viewscreen();
virtual ~dfhack_viewscreen();
static bool is_instance(df::viewscreen *screen);
virtual void logic();
virtual void render();
virtual int8_t movies_okay() { return 1; }
virtual bool key_conflict(df::interface_key key);
virtual bool is_lua_screen() { return false; }
virtual std::string getFocusString() = 0;
virtual void onShow() {};
virtual void onDismiss() {};
};
class DFHACK_EXPORT dfhack_lua_viewscreen : public dfhack_viewscreen {
std::string focus;
void update_focus(lua_State *L, int idx);
bool safe_call_lua(int (*pf)(lua_State *), int args, int rvs);
static dfhack_lua_viewscreen *get_self(lua_State *L);
static int do_destroy(lua_State *L);
static int do_render(lua_State *L);
static int do_notify(lua_State *L);
static int do_input(lua_State *L);
public:
dfhack_lua_viewscreen(lua_State *L, int table_idx);
virtual ~dfhack_lua_viewscreen();
static df::viewscreen *get_pointer(lua_State *L, int idx, bool make);
virtual bool is_lua_screen() { return true; }
virtual std::string getFocusString() { return focus; }
virtual void render();
virtual void logic();
virtual void help();
virtual void resize(int w, int h);
virtual void feed(std::set<df::interface_key> *keys);
virtual void onShow();
virtual void onDismiss();
};
}

@ -226,6 +226,9 @@ DFHACK_EXPORT bool getNoblePositions(std::vector<NoblePosition> *pvec, df::unit
DFHACK_EXPORT std::string getProfessionName(df::unit *unit, bool ignore_noble = false, bool plural = false);
DFHACK_EXPORT std::string getCasteProfessionName(int race, int caste, df::profession pid, bool plural = false);
DFHACK_EXPORT int8_t getProfessionColor(df::unit *unit, bool ignore_noble = false);
DFHACK_EXPORT int8_t getCasteProfessionColor(int race, int caste, df::profession pid);
}
}
#endif

@ -102,11 +102,39 @@ function reload(module)
dofile(path)
end
-- Trivial classes
function rawset_default(target,source)
for k,v in pairs(source) do
if rawget(target,k) == nil then
rawset(target,k,v)
end
end
end
function defclass(class,parent)
class = class or {}
rawset_default(class, { __index = class })
if parent then
setmetatable(class, parent)
else
rawset_default(class, { init_fields = rawset_default })
end
return class
end
function mkinstance(class,table)
table = table or {}
setmetatable(table, class)
return table
end
-- Misc functions
function printall(table)
if type(table) == 'table' or df.isvalid(table) == 'ref' then
for k,v in pairs(table) do
local ok,f,t,k = pcall(pairs,table)
if ok then
for k,v in f,t,k do
print(string.format("%-23s\t = %s",tostring(k),tostring(v)))
end
end
@ -135,14 +163,6 @@ function xyz2pos(x,y,z)
end
end
function rawset_default(target,source)
for k,v in pairs(source) do
if rawget(target,k) == nil then
rawset(target,k,v)
end
end
end
function safe_index(obj,idx,...)
if obj == nil or idx == nil then
return nil
@ -160,10 +180,6 @@ end
-- String conversions
function dfhack.event:__tostring()
return "<event>"
end
function dfhack.persistent:__tostring()
return "<persistent "..self.entry_id..":"..self.key.."=\""
..self.value.."\":"..table.concat(self.ints,",")..">"

@ -0,0 +1,403 @@
-- Viewscreen implementation utility collection.
local _ENV = mkmodule('gui')
local dscreen = dfhack.screen
USE_GRAPHICS = dscreen.inGraphicsMode()
CLEAR_PEN = {ch=32,fg=0,bg=0}
function simulateInput(screen,...)
local keys = {}
local function push_key(arg)
local kv = arg
if type(arg) == 'string' then
kv = df.interface_key[arg]
if kv == nil then
error('Invalid keycode: '..arg)
end
end
if type(kv) == 'number' then
keys[#keys+1] = kv
end
end
for i = 1,select('#',...) do
local arg = select(i,...)
if arg ~= nil then
local t = type(arg)
if type(arg) == 'table' then
for k,v in pairs(arg) do
if v == true then
push_key(k)
else
push_key(v)
end
end
else
push_key(arg)
end
end
end
dscreen._doSimulateInput(screen, keys)
end
function mkdims_xy(x1,y1,x2,y2)
return { x1=x1, y1=y1, x2=x2, y2=y2, width=x2-x1+1, height=y2-y1+1 }
end
function mkdims_wh(x1,y1,w,h)
return { x1=x1, y1=y1, x2=x1+w-1, y2=y1+h-1, width=w, height=h }
end
function inset(rect,dx1,dy1,dx2,dy2)
return mkdims_xy(
rect.x1+dx1, rect.y1+dy1,
rect.x2-(dx2 or dx1), rect.y2-(dy2 or dy1)
)
end
function is_in_rect(rect,x,y)
return x and y and x >= rect.x1 and x <= rect.x2 and y >= rect.y1 and y <= rect.y2
end
local function to_pen(default, pen, bg, bold)
if pen == nil then
return default or {}
elseif type(pen) ~= 'table' then
return {fg=pen,bg=bg,bold=bold}
else
return pen
end
end
----------------------------
-- Clipped painter object --
----------------------------
Painter = defclass(Painter, nil)
function Painter.new(rect, pen)
rect = rect or mkdims_wh(0,0,dscreen.getWindowSize())
local self = {
x1 = rect.x1, clip_x1 = rect.x1,
y1 = rect.y1, clip_y1 = rect.y1,
x2 = rect.x2, clip_x2 = rect.x2,
y2 = rect.y2, clip_y2 = rect.y2,
width = rect.x2-rect.x1+1,
height = rect.y2-rect.y1+1,
cur_pen = to_pen(nil, pen or COLOR_GREY)
}
return mkinstance(Painter, self):seek(0,0)
end
function Painter:isValidPos()
return self.x >= self.clip_x1 and self.x <= self.clip_x2
and self.y >= self.clip_y1 and self.y <= self.clip_y2
end
function Painter:viewport(x,y,w,h)
local x1,y1 = self.x1+x, self.y1+y
local x2,y2 = x1+w-1, y1+h-1
local vp = {
-- Logical viewport
x1 = x1, y1 = y1, x2 = x2, y2 = y2,
width = w, height = h,
-- Actual clipping rect
clip_x1 = math.max(self.clip_x1, x1),
clip_y1 = math.max(self.clip_y1, y1),
clip_x2 = math.min(self.clip_x2, x2),
clip_y2 = math.min(self.clip_y2, y2),
-- Pen
cur_pen = self.cur_pen
}
return mkinstance(Painter, vp):seek(0,0)
end
function Painter:localX()
return self.x - self.x1
end
function Painter:localY()
return self.y - self.y1
end
function Painter:seek(x,y)
if x then self.x = self.x1 + x end
if y then self.y = self.y1 + y end
return self
end
function Painter:advance(dx,dy)
if dx then self.x = self.x + dx end
if dy then self.y = self.y + dy end
return self
end
function Painter:newline(dx)
self.y = self.y + 1
self.x = self.x1 + (dx or 0)
return self
end
function Painter:pen(pen,...)
self.cur_pen = to_pen(self.cur_pen, pen, ...)
return self
end
function Painter:color(fg,bold,bg)
self.cur_pen = copyall(self.cur_pen)
self.cur_pen.fg = fg
self.cur_pen.bold = bold
if bg then self.cur_pen.bg = bg end
return self
end
function Painter:clear()
dscreen.fillRect(CLEAR_PEN, self.clip_x1, self.clip_y1, self.clip_x2, self.clip_y2)
return self
end
function Painter:fill(x1,y1,x2,y2,pen,bg,bold)
if type(x1) == 'table' then
x1, y1, x2, y2, pen, bg, bold = x1.x1, x1.y1, x1.x2, x1.y2, y1, x2, y2
end
x1 = math.max(x1,self.clip_x1)
y1 = math.max(y1,self.clip_y1)
x2 = math.min(x2,self.clip_x2)
y2 = math.min(y2,self.clip_y2)
dscreen.fillRect(to_pen(self.cur_pen,pen,bg,bold),x1,y1,x2,y2)
return self
end
function Painter:char(char,pen,...)
if self:isValidPos() then
dscreen.paintTile(to_pen(self.cur_pen, pen, ...), self.x, self.y, char)
end
return self:advance(1, nil)
end
function Painter:tile(char,tile,pen,...)
if self:isValidPos() then
dscreen.paintTile(to_pen(self.cur_pen, pen, ...), self.x, self.y, char, tile)
end
return self:advance(1, nil)
end
function Painter:string(text,pen,...)
if self.y >= self.clip_y1 and self.y <= self.clip_y2 then
local dx = 0
if self.x < self.clip_x1 then
dx = self.clip_x1 - self.x
end
local len = #text
if self.x + len - 1 > self.clip_x2 then
len = self.clip_x2 - self.x + 1
end
if len > dx then
dscreen.paintString(
to_pen(self.cur_pen, pen, ...),
self.x+dx, self.y,
string.sub(text,dx+1,len)
)
end
end
return self:advance(#text, nil)
end
------------------------
-- Base screen object --
------------------------
Screen = defclass(Screen)
Screen.text_input_mode = false
function Screen:init()
self:updateLayout()
return self
end
Screen.isDismissed = dscreen.isDismissed
function Screen:isShown()
return self._native ~= nil
end
function Screen:isActive()
return self:isShown() and not self:isDismissed()
end
function Screen:invalidate()
dscreen.invalidate()
end
function Screen:getWindowSize()
return dscreen.getWindowSize()
end
function Screen:getMousePos()
return dscreen.getMousePos()
end
function Screen:renderParent()
if self._native and self._native.parent then
self._native.parent:render()
else
dscreen.clear()
end
end
function Screen:sendInputToParent(...)
if self._native and self._native.parent then
simulateInput(self._native.parent, ...)
end
end
function Screen:show(below)
if self._native then
error("This screen is already on display")
end
self:onAboutToShow(below)
if not dscreen.show(self, below) then
error('Could not show screen')
end
end
function Screen:onAboutToShow()
end
function Screen:onShow()
self:updateLayout()
end
function Screen:dismiss()
if self._native then
dscreen.dismiss(self)
end
end
function Screen:onDismiss()
end
function Screen:onDestroy()
end
function Screen:onResize(w,h)
self:updateLayout()
end
function Screen:updateLayout()
end
------------------------
-- Framed screen object --
------------------------
-- Plain grey-colored frame.
GREY_FRAME = {
frame_pen = { ch = ' ', fg = COLOR_BLACK, bg = COLOR_GREY },
title_pen = { fg = COLOR_BLACK, bg = COLOR_WHITE },
signature_pen = { fg = COLOR_BLACK, bg = COLOR_GREY },
}
-- The usual boundary used by the DF screens. Often has fancy pattern in tilesets.
BOUNDARY_FRAME = {
frame_pen = { ch = 0xDB, fg = COLOR_DARKGREY, bg = COLOR_BLACK },
title_pen = { fg = COLOR_BLACK, bg = COLOR_GREY },
signature_pen = { fg = COLOR_BLACK, bg = COLOR_DARKGREY },
}
GREY_LINE_FRAME = {
frame_pen = { ch = 206, fg = COLOR_GREY, bg = COLOR_BLACK },
h_frame_pen = { ch = 205, fg = COLOR_GREY, bg = COLOR_BLACK },
v_frame_pen = { ch = 186, fg = COLOR_GREY, bg = COLOR_BLACK },
lt_frame_pen = { ch = 201, fg = COLOR_GREY, bg = COLOR_BLACK },
lb_frame_pen = { ch = 200, fg = COLOR_GREY, bg = COLOR_BLACK },
rt_frame_pen = { ch = 187, fg = COLOR_GREY, bg = COLOR_BLACK },
rb_frame_pen = { ch = 188, fg = COLOR_GREY, bg = COLOR_BLACK },
title_pen = { fg = COLOR_BLACK, bg = COLOR_GREY },
signature_pen = { fg = COLOR_DARKGREY, bg = COLOR_BLACK },
}
function paint_frame(x1,y1,x2,y2,style,title)
local pen = style.frame_pen
dscreen.paintTile(style.lt_frame_pen or pen, x1, y1)
dscreen.paintTile(style.rt_frame_pen or pen, x2, y1)
dscreen.paintTile(style.lb_frame_pen or pen, x1, y2)
dscreen.paintTile(style.rb_frame_pen or pen, x2, y2)
dscreen.fillRect(style.t_frame_pen or style.h_frame_pen or pen,x1+1,y1,x2-1,y1)
dscreen.fillRect(style.b_frame_pen or style.h_frame_pen or pen,x1+1,y2,x2-1,y2)
dscreen.fillRect(style.l_frame_pen or style.v_frame_pen or pen,x1,y1+1,x1,y2-1)
dscreen.fillRect(style.r_frame_pen or style.v_frame_pen or pen,x2,y1+1,x2,y2-1)
dscreen.paintString(style.signature_pen or style.title_pen or pen,x2-7,y2,"DFHack")
if title then
local x = math.max(0,math.floor((x2-x1-3-#title)/2)) + x1
local tstr = ' '..title..' '
if #tstr > x2-x1-1 then
tstr = string.sub(tstr,1,x2-x1-1)
end
dscreen.paintString(style.title_pen or pen, x, y1, tstr)
end
end
FramedScreen = defclass(FramedScreen, Screen)
FramedScreen.frame_style = BOUNDARY_FRAME
local function hint_coord(gap,hint)
if hint and hint > 0 then
return math.min(hint,gap)
elseif hint and hint < 0 then
return math.max(0,gap-hint)
else
return math.floor(gap/2)
end
end
function FramedScreen:updateFrameSize()
local sw, sh = dscreen.getWindowSize()
local iw, ih = sw-2, sh-2
local width = math.min(self.frame_width or iw, iw)
local height = math.min(self.frame_height or ih, ih)
local gw, gh = iw-width, ih-height
local x1, y1 = hint_coord(gw,self.frame_xhint), hint_coord(gh,self.frame_yhint)
self.frame_rect = mkdims_wh(x1+1,y1+1,width,height)
self.frame_opaque = (gw == 0 and gh == 0)
end
function FramedScreen:updateLayout()
self:updateFrameSize()
end
function FramedScreen:getWindowSize()
local rect = self.frame_rect
return rect.width, rect.height
end
function FramedScreen:getMousePos()
local rect = self.frame_rect
local x,y = dscreen.getMousePos()
if is_in_rect(rect,x,y) then
return x-rect.x1, y-rect.y1
end
end
function FramedScreen:onRender()
local rect = self.frame_rect
local x1,y1,x2,y2 = rect.x1-1, rect.y1-1, rect.x2+1, rect.y2+1
if self.frame_opaque then
dscreen.clear()
else
self:renderParent()
dscreen.fillRect(CLEAR_PEN,x1,y1,x2,y2)
end
paint_frame(x1,y1,x2,y2,self.frame_style,self.frame_title)
self:onRenderBody(Painter.new(rect))
end
function FramedScreen:onRenderBody(dc)
end
return _ENV

@ -0,0 +1,327 @@
-- Support for messing with the dwarfmode screen
local _ENV = mkmodule('gui.dwarfmode')
local gui = require('gui')
local utils = require('utils')
local dscreen = dfhack.screen
local g_cursor = df.global.cursor
local g_sel_rect = df.global.selection_rect
local world_map = df.global.world.map
AREA_MAP_WIDTH = 23
MENU_WIDTH = 30
function getPanelLayout()
local sw, sh = dscreen.getWindowSize()
local view_height = sh-2
local view_rb = sw-1
local area_x2 = sw-AREA_MAP_WIDTH-2
local menu_x2 = sw-MENU_WIDTH-2
local menu_x1 = area_x2-MENU_WIDTH-1
local area_pos = df.global.ui_area_map_width
local menu_pos = df.global.ui_menu_width
local rv = {}
if area_pos < 3 then
rv.area_map = gui.mkdims_xy(area_x2+1,1,view_rb-1,view_height)
view_rb = area_x2
end
if menu_pos < area_pos or df.global.ui.main.mode ~= 0 then
if menu_pos >= area_pos then
rv.menu_forced = true
menu_pos = area_pos-1
end
local menu_x = menu_x2
if menu_pos < 2 then menu_x = menu_x1 end
rv.menu = gui.mkdims_xy(menu_x+1,1,view_rb-1,view_height)
view_rb = menu_x
end
rv.area_pos = area_pos
rv.menu_pos = menu_pos
rv.map = gui.mkdims_xy(1,1,view_rb-1,view_height)
return rv
end
function getCursorPos()
if g_cursor ~= -30000 then
return copyall(g_cursor)
end
end
function setCursorPos(cursor)
df.global.cursor = cursor
end
function clearCursorPos()
df.global.cursor = xyz2pos(nil)
end
function getSelection()
local p1, p2
if g_sel_rect.start_x ~= -30000 then
p1 = xyz2pos(g_sel_rect.start_x, g_sel_rect.start_y, g_sel_rect.start_z)
end
if g_sel_rect.end_x ~= -30000 then
p2 = xyz2pos(g_sel_rect.end_x, g_sel_rect.end_y, g_sel_rect.end_z)
end
return p1, p2
end
function setSelectionStart(pos)
g_sel_rect.start_x = pos.x
g_sel_rect.start_y = pos.y
g_sel_rect.start_z = pos.z
end
function setSelectionEnd(pos)
g_sel_rect.end_x = pos.x
g_sel_rect.end_y = pos.y
g_sel_rect.end_z = pos.z
end
function clearSelection()
g_sel_rect.start_x = -30000
g_sel_rect.start_y = -30000
g_sel_rect.start_z = -30000
g_sel_rect.end_x = -30000
g_sel_rect.end_y = -30000
g_sel_rect.end_z = -30000
end
function getSelectionRange(p1, p2)
local r1 = xyz2pos(
math.min(p1.x, p2.x), math.min(p1.y, p2.y), math.min(p1.z, p2.z)
)
local r2 = xyz2pos(
math.max(p1.x, p2.x), math.max(p1.y, p2.y), math.max(p1.z, p2.z)
)
local sz = xyz2pos(
r2.x - r1.x + 1, r2.y - r1.y + 1, r2.z - r1.z + 1
)
return r1, sz, r2
end
Viewport = defclass(Viewport)
function Viewport.make(map,x,y,z)
local self = gui.mkdims_wh(x,y,map.width,map.height)
self.z = z
return mkinstance(Viewport, self)
end
function Viewport.get(layout)
return Viewport.make(
(layout or getPanelLayout()).map,
df.global.window_x,
df.global.window_y,
df.global.window_z
)
end
function Viewport:resize(layout)
return Viewport.make(
(layout or getPanelLayout()).map,
self.x1, self.y1, self.z
)
end
function Viewport:set()
local vp = self:clip()
df.global.window_x = vp.x1
df.global.window_y = vp.y1
df.global.window_z = vp.z
return vp
end
function Viewport:clip(x,y,z)
return self:make(
math.max(0, math.min(x or self.x1, world_map.x_count-self.width)),
math.max(0, math.min(y or self.y1, world_map.y_count-self.height)),
math.max(0, math.min(z or self.z, world_map.z_count-1))
)
end
function Viewport:isVisibleXY(target,gap)
gap = gap or 0
return math.max(target.x-gap,0) >= self.x1
and math.min(target.x+gap,world_map.x_count-1) <= self.x2
and math.max(target.y-gap,0) >= self.y1
and math.min(target.y+gap,world_map.y_count-1) <= self.y2
end
function Viewport:isVisible(target,gap)
gap = gap or 0
return self:isVisibleXY(target,gap) and target.z == self.z
end
function Viewport:centerOn(target)
return self:clip(
target.x - math.floor(self.width/2),
target.y - math.floor(self.height/2),
target.z
)
end
function Viewport:scrollTo(target,gap)
gap = math.max(0, gap or 5)
if gap*2 >= math.min(self.width, self.height) then
gap = math.floor(math.min(self.width, self.height)/2)
end
local x = math.min(self.x1, target.x-gap)
x = math.max(x, target.x+gap+1-self.width)
local y = math.min(self.y1, target.y-gap)
y = math.max(y, target.y+gap+1-self.height)
return self:clip(x, y, target.z)
end
function Viewport:reveal(target,gap,max_scroll,scroll_gap,scroll_z)
gap = math.max(0, gap or 5)
if self:isVisible(target, gap) then
return self
end
max_scroll = math.max(0, max_scroll or 5)
if self:isVisibleXY(target, -max_scroll)
and (scroll_z or target.z == self.z) then
return self:scrollTo(target, scroll_gap or gap)
else
return self:centerOn(target)
end
end
MOVEMENT_KEYS = {
CURSOR_UP = { 0, -1, 0 }, CURSOR_DOWN = { 0, 1, 0 },
CURSOR_LEFT = { -1, 0, 0 }, CURSOR_RIGHT = { 1, 0, 0 },
CURSOR_UPLEFT = { -1, -1, 0 }, CURSOR_UPRIGHT = { 1, -1, 0 },
CURSOR_DOWNLEFT = { -1, 1, 0 }, CURSOR_DOWNRIGHT = { 1, 1, 0 },
CURSOR_UP_FAST = { 0, -1, 0, true }, CURSOR_DOWN_FAST = { 0, 1, 0, true },
CURSOR_LEFT_FAST = { -1, 0, 0, true }, CURSOR_RIGHT_FAST = { 1, 0, 0, true },
CURSOR_UPLEFT_FAST = { -1, -1, 0, true }, CURSOR_UPRIGHT_FAST = { 1, -1, 0, true },
CURSOR_DOWNLEFT_FAST = { -1, 1, 0, true }, CURSOR_DOWNRIGHT_FAST = { 1, 1, 0, true },
CURSOR_UP_Z = { 0, 0, 1 }, CURSOR_DOWN_Z = { 0, 0, -1 },
CURSOR_UP_Z_AUX = { 0, 0, 1 }, CURSOR_DOWN_Z_AUX = { 0, 0, -1 },
}
function Viewport:scrollByKey(key)
local info = MOVEMENT_KEYS[key]
if info then
local delta = 10
if info[4] then delta = 20 end
return self:clip(
self.x1 + delta*info[1],
self.y1 + delta*info[2],
self.z + info[3]
)
else
return self
end
end
DwarfOverlay = defclass(DwarfOverlay, gui.Screen)
function DwarfOverlay:updateLayout()
self.df_layout = getPanelLayout()
end
function DwarfOverlay:getViewport(old_vp)
if old_vp then
return old_vp:resize(self.df_layout)
else
return Viewport.get(self.df_layout)
end
end
function DwarfOverlay:moveCursorTo(cursor,viewport)
setCursorPos(cursor)
self:getViewport(viewport):reveal(cursor, 5, 0, 10):set()
end
function DwarfOverlay:selectBuilding(building,cursor,viewport)
cursor = cursor or utils.getBuildingCenter(building)
df.global.world.selected_building = building
self:moveCursorTo(cursor, viewport)
end
function DwarfOverlay:propagateMoveKeys(keys)
for code,_ in pairs(MOVEMENT_KEYS) do
if keys[code] then
self:sendInputToParent(code)
return code
end
end
end
function DwarfOverlay:simulateViewScroll(keys, anchor, no_clip_cursor)
local layout = self.df_layout
local cursor = getCursorPos()
anchor = anchor or cursor
if anchor and keys.A_MOVE_SAME_SQUARE then
self:getViewport():centerOn(anchor):set()
return 'A_MOVE_SAME_SQUARE'
end
for code,_ in pairs(MOVEMENT_KEYS) do
if keys[code] then
local vp = self:getViewport():scrollByKey(code)
if (cursor and not no_clip_cursor) or no_clip_cursor == false then
vp = vp:reveal(anchor,4,20,4,true)
end
vp:set()
return code
end
end
end
function DwarfOverlay:onAboutToShow(below)
local screen = dfhack.gui.getCurViewscreen()
if below then screen = below.parent end
if not df.viewscreen_dwarfmodest:is_instance(screen) then
error("This screen requires the main dwarfmode view")
end
end
MenuOverlay = defclass(MenuOverlay, DwarfOverlay)
function MenuOverlay:updateLayout()
DwarfOverlay.updateLayout(self)
self.frame_rect = self.df_layout.menu
end
MenuOverlay.getWindowSize = gui.FramedScreen.getWindowSize
MenuOverlay.getMousePos = gui.FramedScreen.getMousePos
function MenuOverlay:onAboutToShow(below)
DwarfOverlay.onAboutToShow(self,below)
self:updateLayout()
if not self.df_layout.menu then
error("The menu panel of dwarfmode is not visible")
end
end
function MenuOverlay:onRender()
self:renderParent()
local menu = self.df_layout.menu
if menu then
-- Paint signature on the frame.
dscreen.paintString(
{fg=COLOR_BLACK,bg=COLOR_DARKGREY},
menu.x1+1, menu.y2+1, "DFHack"
)
self:onRenderBody(gui.Painter.new(menu))
end
end
return _ENV

@ -361,6 +361,26 @@ function insert_or_update(vector,item,field,cmp)
return added,cur,pos
end
-- Calls a method with a string temporary
function call_with_string(obj,methodname,...)
return dfhack.with_temp_object(
df.new "string",
function(str,obj,methodname,...)
obj[methodname](obj,str,...)
return str.value
end,
obj,methodname,...
)
end
function getBuildingName(building)
return call_with_string(building, 'getName')
end
function getBuildingCenter(building)
return xyz2pos(building.centerx, building.centery, building.z)
end
-- Ask a yes-no question
function prompt_yes_no(msg,default)
local prompt = msg

@ -49,6 +49,7 @@ using namespace DFHack;
#include "df/ui_look_list.h"
#include "df/d_init.h"
#include "df/item.h"
#include "df/unit.h"
#include "df/job.h"
#include "df/job_item.h"
#include "df/general_ref_building_holderst.h"
@ -177,6 +178,44 @@ bool Buildings::ReadCustomWorkshopTypes(map <uint32_t, string> & btypes)
return true;
}
bool Buildings::setOwner(df::building *bld, df::unit *unit)
{
CHECK_NULL_POINTER(bld);
if (!bld->is_room)
return false;
if (bld->owner == unit)
return true;
if (bld->owner)
{
auto &blist = bld->owner->owned_buildings;
vector_erase_at(blist, linear_index(blist, bld));
if (auto spouse = df::unit::find(bld->owner->relations.spouse_id))
{
auto &blist = spouse->owned_buildings;
vector_erase_at(blist, linear_index(blist, bld));
}
}
bld->owner = unit;
if (unit)
{
unit->owned_buildings.push_back(bld);
if (auto spouse = df::unit::find(unit->relations.spouse_id))
{
auto &blist = spouse->owned_buildings;
if (bld->canUseSpouseRoom() && linear_index(blist, bld) < 0)
blist.push_back(bld);
}
}
return true;
}
df::building *Buildings::findAtTile(df::coord pos)
{
auto occ = Maps::getTileOccupancy(pos);
@ -991,7 +1030,7 @@ bool Buildings::deconstruct(df::building *bld)
// Assume: no parties.
unlinkRooms(bld);
// Assume: not unit destroy target
vector_erase_at(ui->unk8.unk10, linear_index(ui->unk8.unk10, bld));
vector_erase_at(ui->tax_collection.rooms, linear_index(ui->tax_collection.rooms, bld));
// Assume: not used in punishment
// Assume: not used in non-own jobs
// Assume: does not affect pathfinding

@ -42,6 +42,7 @@ using namespace std;
using namespace DFHack;
#include "modules/Job.h"
#include "modules/Screen.h"
#include "DataDefs.h"
#include "df/world.h"
@ -466,6 +467,11 @@ std::string Gui::getFocusString(df::viewscreen *top)
return name;
}
else if (dfhack_viewscreen::is_instance(top))
{
auto name = static_cast<dfhack_viewscreen*>(top)->getFocusString();
return name.empty() ? "dfhack" : "dfhack/"+name;
}
else
{
Core &core = Core::getInstance();
@ -977,17 +983,36 @@ void Gui::showPopupAnnouncement(std::string message, int color, bool bright)
world->status.popups.push_back(popup);
}
df::viewscreen * Gui::GetCurrentScreen()
df::viewscreen *Gui::getCurViewscreen(bool skip_dismissed)
{
df::viewscreen * ws = &gview->view;
while(ws)
while (ws && ws->child)
ws = ws->child;
if (skip_dismissed)
{
if(ws->child)
ws = ws->child;
else
return ws;
while (ws && Screen::isDismissed(ws) && ws->parent)
ws = ws->parent;
}
return 0;
return ws;
}
df::coord Gui::getViewportPos()
{
if (!df::global::window_x || !df::global::window_y || !df::global::window_z)
return df::coord(0,0,0);
return df::coord(*df::global::window_x, *df::global::window_y, *df::global::window_z);
}
df::coord Gui::getCursorPos()
{
using df::global::cursor;
if (!cursor)
return df::coord();
return df::coord(cursor->x, cursor->y, cursor->z);
}
bool Gui::getViewCoords (int32_t &x, int32_t &y, int32_t &z)

@ -189,7 +189,7 @@ void DFHack::Job::printJobDetails(color_ostream &out, df::job *job)
{
CHECK_NULL_POINTER(job);
out.color(job->flags.bits.suspend ? Console::COLOR_DARKGREY : Console::COLOR_GREY);
out.color(job->flags.bits.suspend ? COLOR_DARKGREY : COLOR_GREY);
out << "Job " << job->id << ": " << ENUM_KEY_STR(job_type,job->job_type);
if (job->flags.whole)
out << " (" << bitfield_to_string(job->flags) << ")";

@ -57,6 +57,7 @@ using namespace std;
#include "df/builtin_mats.h"
#include "df/block_square_event_grassst.h"
#include "df/z_level_flags.h"
#include "df/region_map_entry.h"
using namespace DFHack;
using namespace df::enums;
@ -166,7 +167,7 @@ df::tile_occupancy *Maps::getTileOccupancy(int32_t x, int32_t y, int32_t z)
return block ? &block->occupancy[x&15][y&15] : NULL;
}
df::world_data::T_region_map *Maps::getRegionBiome(df::coord2d rgn_pos)
df::region_map_entry *Maps::getRegionBiome(df::coord2d rgn_pos)
{
auto data = world->world_data;
if (!data)

@ -0,0 +1,604 @@
/*
https://github.com/peterix/dfhack
Copyright (c) 2009-2011 Petr Mrázek (peterix@gmail.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "Internal.h"
#include <string>
#include <vector>
#include <map>
using namespace std;
#include "modules/Screen.h"
#include "MemAccess.h"
#include "VersionInfo.h"
#include "Types.h"
#include "Error.h"
#include "ModuleFactory.h"
#include "Core.h"
#include "PluginManager.h"
#include "LuaTools.h"
#include "MiscUtils.h"
using namespace DFHack;
#include "DataDefs.h"
#include "df/init.h"
#include "df/texture_handler.h"
#include "df/tile_page.h"
#include "df/interfacest.h"
#include "df/enabler.h"
using namespace df::enums;
using df::global::init;
using df::global::gps;
using df::global::texture;
using df::global::gview;
using df::global::enabler;
using Screen::Pen;
/*
* Screen painting API.
*/
df::coord2d Screen::getMousePos()
{
if (!gps || (enabler && !enabler->tracking_on))
return df::coord2d(-1, -1);
return df::coord2d(gps->mouse_x, gps->mouse_y);
}
df::coord2d Screen::getWindowSize()
{
if (!gps) return df::coord2d(80, 25);
return df::coord2d(gps->dimx, gps->dimy);
}
bool Screen::inGraphicsMode()
{
return init && init->display.flag.is_set(init_display_flags::USE_GRAPHICS);
}
static void doSetTile(const Pen &pen, int index)
{
auto screen = gps->screen + index*4;
screen[0] = uint8_t(pen.ch);
screen[1] = uint8_t(pen.fg) & 15;
screen[2] = uint8_t(pen.bg) & 15;
screen[3] = uint8_t(pen.bold) & 1;
gps->screentexpos[index] = pen.tile;
gps->screentexpos_addcolor[index] = (pen.tile_mode == Screen::Pen::CharColor);
gps->screentexpos_grayscale[index] = (pen.tile_mode == Screen::Pen::TileColor);
gps->screentexpos_cf[index] = pen.tile_fg;
gps->screentexpos_cbr[index] = pen.tile_bg;
}
bool Screen::paintTile(const Pen &pen, int x, int y)
{
if (!gps) return false;
int dimx = gps->dimx, dimy = gps->dimy;
if (x < 0 || x >= dimx || y < 0 || y >= dimy) return false;
doSetTile(pen, x*dimy + y);
return true;
}
bool Screen::paintString(const Pen &pen, int x, int y, const std::string &text)
{
if (!gps || y < 0 || y >= gps->dimy) return false;
Pen tmp(pen);
bool ok = false;
for (size_t i = -std::min(0,x); i < text.size(); i++)
{
if (x + i >= size_t(gps->dimx))
break;
tmp.ch = text[i];
tmp.tile = (pen.tile ? pen.tile + uint8_t(text[i]) : 0);
paintTile(tmp, x+i, y);
ok = true;
}
return ok;
}
bool Screen::fillRect(const Pen &pen, int x1, int y1, int x2, int y2)
{
if (!gps) return false;
if (x1 < 0) x1 = 0;
if (y1 < 0) y1 = 0;
if (x2 >= gps->dimx) x2 = gps->dimx-1;
if (y2 >= gps->dimy) y2 = gps->dimy-1;
if (x1 > x2 || y1 > y2) return false;
for (int x = x1; x <= x2; x++)
{
int index = x*gps->dimy;
for (int y = y1; y <= y2; y++)
doSetTile(pen, index+y);
}
return true;
}
bool Screen::drawBorder(const std::string &title)
{
if (!gps) return false;
int dimx = gps->dimx, dimy = gps->dimy;
Pen border(0xDB, 8);
Pen text(0, 0, 7);
Pen signature(0, 0, 8);
for (int x = 0; x < dimx; x++)
{
doSetTile(border, x * dimy + 0);
doSetTile(border, x * dimy + dimy - 1);
}
for (int y = 0; y < dimy; y++)
{
doSetTile(border, 0 * dimy + y);
doSetTile(border, (dimx - 1) * dimy + y);
}
paintString(signature, dimx-8, dimy-1, "DFHack");
return paintString(text, (dimx - title.length()) / 2, 0, title);
}
bool Screen::clear()
{
if (!gps) return false;
return fillRect(Pen(' ',0,0,false), 0, 0, gps->dimx-1, gps->dimy-1);
}
bool Screen::invalidate()
{
if (!enabler) return false;
enabler->flag.bits.render = true;
return true;
}
bool Screen::findGraphicsTile(const std::string &pagename, int x, int y, int *ptile, int *pgs)
{
if (!gps || !texture || x < 0 || y < 0) return false;
for (size_t i = 0; i < texture->page.size(); i++)
{
auto page = texture->page[i];
if (!page->loaded || page->token != pagename) continue;
if (x >= page->page_dim_x || y >= page->page_dim_y)
break;
int idx = y*page->page_dim_x + x;
if (size_t(idx) >= page->texpos.size())
break;
if (ptile) *ptile = page->texpos[idx];
if (pgs) *pgs = page->texpos_gs[idx];
return true;
}
return false;
}
bool Screen::show(df::viewscreen *screen, df::viewscreen *before)
{
CHECK_NULL_POINTER(screen);
CHECK_INVALID_ARGUMENT(!screen->parent && !screen->child);
if (!gps || !gview) return false;
df::viewscreen *parent = &gview->view;
while (parent && parent->child != before)
parent = parent->child;
if (!parent) return false;
gps->force_full_display_count += 2;
screen->child = parent->child;
screen->parent = parent;
parent->child = screen;
if (screen->child)
screen->child->parent = screen;
if (dfhack_viewscreen::is_instance(screen))
static_cast<dfhack_viewscreen*>(screen)->onShow();
return true;
}
void Screen::dismiss(df::viewscreen *screen, bool to_first)
{
CHECK_NULL_POINTER(screen);
if (screen->breakdown_level != interface_breakdown_types::NONE)
return;
if (to_first)
screen->breakdown_level = interface_breakdown_types::TOFIRST;
else
screen->breakdown_level = interface_breakdown_types::STOPSCREEN;
if (dfhack_viewscreen::is_instance(screen))
static_cast<dfhack_viewscreen*>(screen)->onDismiss();
}
bool Screen::isDismissed(df::viewscreen *screen)
{
CHECK_NULL_POINTER(screen);
return screen->breakdown_level != interface_breakdown_types::NONE;
}
/*
* Base DFHack viewscreen.
*/
static std::set<df::viewscreen*> dfhack_screens;
dfhack_viewscreen::dfhack_viewscreen() : text_input_mode(false)
{
dfhack_screens.insert(this);
last_size = Screen::getWindowSize();
}
dfhack_viewscreen::~dfhack_viewscreen()
{
dfhack_screens.erase(this);
}
bool dfhack_viewscreen::is_instance(df::viewscreen *screen)
{
return dfhack_screens.count(screen) != 0;
}
void dfhack_viewscreen::check_resize()
{
auto size = Screen::getWindowSize();
if (size != last_size)
{
last_size = size;
resize(size.x, size.y);
}
}
void dfhack_viewscreen::logic()
{
check_resize();
// Various stuff works poorly unless always repainting
Screen::invalidate();
}
void dfhack_viewscreen::render()
{
check_resize();
}
bool dfhack_viewscreen::key_conflict(df::interface_key key)
{
if (key == interface_key::OPTIONS)
return true;
if (text_input_mode)
{
if (key == interface_key::HELP || key == interface_key::MOVIES)
return true;
}
return false;
}
/*
* Lua-backed viewscreen.
*/
static int DFHACK_LUA_VS_TOKEN = 0;
df::viewscreen *dfhack_lua_viewscreen::get_pointer(lua_State *L, int idx, bool make)
{
df::viewscreen *screen;
if (lua_istable(L, idx))
{
if (!Lua::IsCoreContext(L))
luaL_error(L, "only the core context can create lua screens");
lua_rawgetp(L, idx, &DFHACK_LUA_VS_TOKEN);
if (!lua_isnil(L, -1))
{
if (make)
luaL_error(L, "this screen is already on display");
screen = (df::viewscreen*)lua_touserdata(L, -1);
}
else
{
if (!make)
luaL_error(L, "this screen is not on display");
screen = new dfhack_lua_viewscreen(L, idx);
}
lua_pop(L, 1);
}
else
screen = Lua::CheckDFObject<df::viewscreen>(L, idx);
return screen;
}
bool dfhack_lua_viewscreen::safe_call_lua(int (*pf)(lua_State *), int args, int rvs)
{
CoreSuspendClaimer suspend;
color_ostream_proxy out(Core::getInstance().getConsole());
auto L = Lua::Core::State;
lua_pushcfunction(L, pf);
if (args > 0) lua_insert(L, -args-1);
lua_pushlightuserdata(L, this);
if (args > 0) lua_insert(L, -args-1);
return Lua::Core::SafeCall(out, args+1, rvs);
}
dfhack_lua_viewscreen *dfhack_lua_viewscreen::get_self(lua_State *L)
{
auto self = (dfhack_lua_viewscreen*)lua_touserdata(L, 1);
lua_rawgetp(L, LUA_REGISTRYINDEX, self);
if (!lua_istable(L, -1)) return NULL;
return self;
}
int dfhack_lua_viewscreen::do_destroy(lua_State *L)
{
auto self = get_self(L);
if (!self) return 0;
lua_pushnil(L);
lua_rawsetp(L, LUA_REGISTRYINDEX, self);
lua_pushnil(L);
lua_rawsetp(L, -2, &DFHACK_LUA_VS_TOKEN);
lua_pushnil(L);
lua_setfield(L, -2, "_native");
lua_getfield(L, -1, "onDestroy");
if (lua_isnil(L, -1))
return 0;
lua_pushvalue(L, -2);
lua_call(L, 1, 0);
return 0;
}
void dfhack_lua_viewscreen::update_focus(lua_State *L, int idx)
{
lua_getfield(L, idx, "text_input_mode");
text_input_mode = lua_toboolean(L, -1);
lua_pop(L, 1);
lua_getfield(L, idx, "focus_path");
auto str = lua_tostring(L, -1);
if (!str) str = "";
focus = str;
lua_pop(L, 1);
if (focus.empty())
focus = "lua";
else
focus = "lua/"+focus;
}
int dfhack_lua_viewscreen::do_render(lua_State *L)
{
auto self = get_self(L);
if (!self) return 0;
lua_getfield(L, -1, "onRender");
if (lua_isnil(L, -1))
{
Screen::clear();
return 0;
}
lua_pushvalue(L, -2);
lua_call(L, 1, 0);
return 0;
}
int dfhack_lua_viewscreen::do_notify(lua_State *L)
{
int args = lua_gettop(L);
auto self = get_self(L);
if (!self) return 0;
lua_pushvalue(L, 2);
lua_gettable(L, -2);
if (lua_isnil(L, -1))
return 0;
// self field args table fn -> table fn table args
lua_replace(L, 1);
lua_copy(L, -1, 2);
lua_insert(L, 1);
lua_call(L, args-1, 1);
self->update_focus(L, 1);
return 1;
}
int dfhack_lua_viewscreen::do_input(lua_State *L)
{
auto self = get_self(L);
if (!self) return 0;
auto keys = (std::set<df::interface_key>*)lua_touserdata(L, 2);
lua_getfield(L, -1, "onInput");
if (lua_isnil(L, -1))
{
if (keys->count(interface_key::LEAVESCREEN))
Screen::dismiss(self);
return 0;
}
lua_pushvalue(L, -2);
lua_createtable(L, 0, keys->size()+3);
for (auto it = keys->begin(); it != keys->end(); ++it)
{
auto key = *it;
if (auto name = enum_item_raw_key(key))
lua_pushstring(L, name);
else
lua_pushinteger(L, key);
lua_pushboolean(L, true);
lua_rawset(L, -3);
if (key >= interface_key::STRING_A000 &&
key <= interface_key::STRING_A255)
{
lua_pushinteger(L, key - interface_key::STRING_A000);
lua_setfield(L, -2, "_STRING");
}
}
if (enabler && enabler->tracking_on)
{
if (enabler->mouse_lbut) {
lua_pushboolean(L, true);
lua_setfield(L, -2, "_MOUSE_L");
}
if (enabler->mouse_rbut) {
lua_pushboolean(L, true);
lua_setfield(L, -2, "_MOUSE_R");
}
}
lua_call(L, 2, 0);
self->update_focus(L, -1);
return 0;
}
dfhack_lua_viewscreen::dfhack_lua_viewscreen(lua_State *L, int table_idx)
{
assert(Lua::IsCoreContext(L));
Lua::PushDFObject(L, (df::viewscreen*)this);
lua_setfield(L, table_idx, "_native");
lua_pushlightuserdata(L, this);
lua_rawsetp(L, table_idx, &DFHACK_LUA_VS_TOKEN);
lua_pushvalue(L, table_idx);
lua_rawsetp(L, LUA_REGISTRYINDEX, this);
update_focus(L, table_idx);
}
dfhack_lua_viewscreen::~dfhack_lua_viewscreen()
{
safe_call_lua(do_destroy, 0, 0);
}
void dfhack_lua_viewscreen::render()
{
if (Screen::isDismissed(this)) return;
dfhack_viewscreen::render();
safe_call_lua(do_render, 0, 0);
}
void dfhack_lua_viewscreen::logic()
{
if (Screen::isDismissed(this)) return;
dfhack_viewscreen::logic();
lua_pushstring(Lua::Core::State, "onIdle");
safe_call_lua(do_notify, 1, 0);
}
void dfhack_lua_viewscreen::help()
{
if (Screen::isDismissed(this)) return;
lua_pushstring(Lua::Core::State, "onHelp");
safe_call_lua(do_notify, 1, 0);
}
void dfhack_lua_viewscreen::resize(int w, int h)
{
if (Screen::isDismissed(this)) return;
auto L = Lua::Core::State;
lua_pushstring(L, "onResize");
lua_pushinteger(L, w);
lua_pushinteger(L, h);
safe_call_lua(do_notify, 3, 0);
}
void dfhack_lua_viewscreen::feed(std::set<df::interface_key> *keys)
{
if (Screen::isDismissed(this)) return;
lua_pushlightuserdata(Lua::Core::State, keys);
safe_call_lua(do_input, 1, 0);
}
void dfhack_lua_viewscreen::onShow()
{
lua_pushstring(Lua::Core::State, "onShow");
safe_call_lua(do_notify, 1, 0);
}
void dfhack_lua_viewscreen::onDismiss()
{
lua_pushstring(Lua::Core::State, "onDismiss");
safe_call_lua(do_notify, 1, 0);
}

@ -948,3 +948,40 @@ std::string DFHack::Units::getCasteProfessionName(int race, int casteid, df::pro
return Translation::capitalize(prof, true);
}
int8_t DFHack::Units::getProfessionColor(df::unit *unit, bool ignore_noble)
{
std::vector<NoblePosition> np;
if (!ignore_noble && getNoblePositions(&np, unit))
{
if (np[0].position->flags.is_set(entity_position_flags::COLOR))
return np[0].position->color[0] + np[0].position->color[2] * 8;
}
return getCasteProfessionColor(unit->race, unit->caste, unit->profession);
}
int8_t DFHack::Units::getCasteProfessionColor(int race, int casteid, df::profession pid)
{
// make sure it's an actual profession
if (pid < 0 || !is_valid_enum_item(pid))
return 3;
// If it's not a Peasant, it's hardcoded
if (pid != profession::STANDARD)
return ENUM_ATTR(profession, color, pid);
if (auto creature = df::creature_raw::find(race))
{
if (auto caste = vector_get(creature->caste, casteid))
{
if (caste->flags.is_set(caste_raw_flags::CASTE_COLOR))
return caste->caste_color[0] + caste->caste_color[2] * 8;
}
return creature->color[0] + creature->color[2] * 8;
}
// default to dwarven peasant color
return 3;
}

@ -1 +1 @@
Subproject commit 3663b22e25a6772b9f2765caaff81914c131c1cc
Subproject commit 328a8dbdc7d9e1e838798abf79861cc18a387e3f

@ -81,7 +81,7 @@ if (BUILD_SUPPORTED)
DFHACK_PLUGIN(weather weather.cpp)
DFHACK_PLUGIN(colonies colonies.cpp)
DFHACK_PLUGIN(mode mode.cpp)
DFHACK_PLUGIN(liquids liquids.cpp Brushes.h)
DFHACK_PLUGIN(liquids liquids.cpp Brushes.h LINK_LIBRARIES lua)
DFHACK_PLUGIN(tiletypes tiletypes.cpp Brushes.h)
DFHACK_PLUGIN(tubefill tubefill.cpp)
DFHACK_PLUGIN(autodump autodump.cpp)
@ -110,6 +110,7 @@ if (BUILD_SUPPORTED)
DFHACK_PLUGIN(catsplosion catsplosion.cpp)
DFHACK_PLUGIN(regrass regrass.cpp)
DFHACK_PLUGIN(forceequip forceequip.cpp)
DFHACK_PLUGIN(manipulator manipulator.cpp)
# this one exports functions to lua
DFHACK_PLUGIN(burrows burrows.cpp LINK_LIBRARIES lua)
DFHACK_PLUGIN(sort sort.cpp LINK_LIBRARIES lua)

@ -1,5 +1,4 @@
#include "Core.h"
#include "Console.h"
#include "Export.h"
#include "PluginManager.h"
#include "MemAccess.h"
@ -12,7 +11,6 @@
#include "luamain.h"
#include "lua_Console.h"
#include "lua_Process.h"
#include "lua_Hexsearch.h"
#include "lua_Misc.h"
@ -50,7 +48,6 @@ DFhackCExport command_result plugin_init (color_ostream &out, std::vector <Plugi
//maybe remake it to run automaticaly
Lua::Open(out, st);
lua::RegisterConsole(st);
lua::RegisterProcess(st);
lua::RegisterHexsearch(st);
lua::RegisterMisc(st);

@ -1,13 +0,0 @@
#ifndef LUA_CONSOLE_H
#define LUA_CONSOLE_H
#include <Console.h>
#include "luamain.h"
namespace lua
{
void RegisterConsole(lua::state &st);
}
#endif

@ -8,7 +8,7 @@ DOUBLE=5
FLOAT=6
getline=function (inp)
return Console.lineedit(inp or "")
return dfhack.lineedit(inp or "")
end
io.stdin=nil

@ -127,7 +127,7 @@ function EditDF()
tbl[i]={k,getTypename(v)}
i=i+1
end
number=Console.lineedit("select item to edit (q to quit):")
number=dfhack.lineedit("select item to edit (q to quit):")
if number and tonumber(number) then
local entry=tbl[tonumber(number)]
if entry==nil then

@ -1,7 +1,3 @@
Console.print = dfhack.print
Console.println = dfhack.println
Console.printerr = dfhack.printerr
function err(msg) --make local maybe...
print(msg)
print(debug.traceback())
@ -30,13 +26,13 @@ function loadall(t1) --loads all non interactive plugin parts, so that later the
end
end
function mainmenu(t1)
--Console.clear()
while true do
print("No. Name Desc")
for k,v in pairs(t1) do
print(string.format("%3d %15s %s",k,v[1],v[2]))
end
local q=Console.lineedit("Select plugin to run (q to quit):")
local q=dfhack.lineedit("Select plugin to run (q to quit):")
if q=='q' then return end
q=tonumber(q)
if q~=nil then
@ -92,7 +88,7 @@ local f,err=load(table.concat(args,' '))
if f then
f()
else
Console.printerr(err)
dfhack.printerr(err)
end
if not INIT then

@ -1,131 +0,0 @@
#include "LuaTools.h"
#include "lua_Console.h"
#include <sstream>
//TODO error management. Using lua error? or something other?
static DFHack::color_ostream* GetConsolePtr(lua::state &st)
{
return DFHack::Lua::GetOutput(st);
}
static int lua_Console_clear(lua_State *S)
{
lua::state st(S);
DFHack::color_ostream* c=GetConsolePtr(st);
c->clear();
return 0;
}
static int lua_Console_gotoxy(lua_State *S)
{
lua::state st(S);
DFHack::color_ostream* c=GetConsolePtr(st);
if(c->is_console())
{
DFHack::Console* con=static_cast<DFHack::Console*>(c);
con->gotoxy(st.as<int>(1,1),st.as<int>(1,2));
}
return 0;
}
static int lua_Console_color(lua_State *S)
{
lua::state st(S);
DFHack::color_ostream* c=GetConsolePtr(st);
c->color( static_cast<DFHack::Console::color_value>(st.as<int>(-1,1)) );
return 0;
}
static int lua_Console_reset_color(lua_State *S)
{
lua::state st(S);
DFHack::color_ostream* c=GetConsolePtr(st);
c->reset_color();
return 0;
}
static int lua_Console_cursor(lua_State *S)
{
lua::state st(S);
DFHack::color_ostream* c=GetConsolePtr(st);
if(c->is_console())
{
DFHack::Console* con=static_cast<DFHack::Console*>(c);
con->cursor(st.as<bool>(1));
}
return 0;
}
static int lua_Console_msleep(lua_State *S)
{
lua::state st(S);
DFHack::color_ostream* c=GetConsolePtr(st);
if(c->is_console())
{
DFHack::Console* con=static_cast<DFHack::Console*>(c);
con->msleep(st.as<unsigned>(1));
}
return 0;
}
static int lua_Console_get_columns(lua_State *S)
{
lua::state st(S);
DFHack::color_ostream* c=GetConsolePtr(st);
if(c->is_console())
{
DFHack::Console* con=static_cast<DFHack::Console*>(c);
st.push(con->get_columns());
}
return 1;
}
static int lua_Console_get_rows(lua_State *S)
{
lua::state st(S);
DFHack::color_ostream* c=GetConsolePtr(st);
if(c->is_console())
{
DFHack::Console* con=static_cast<DFHack::Console*>(c);
st.push(con->get_rows());
}
return 1;
}
static int lua_Console_lineedit(lua_State *S)
{
lua::state st(S);
DFHack::color_ostream* c=GetConsolePtr(st);
if(c->is_console())
{
DFHack::Console* con=static_cast<DFHack::Console*>(c);
string ret;
DFHack::CommandHistory hist;
int i=con->lineedit(st.as<string>(1),ret,hist);
st.push(ret);
st.push(i);
return 2;// dunno if len is needed...
}
else
return 0;
}
const luaL_Reg lua_console_func[]=
{
{"clear",lua_Console_clear},
{"gotoxy",lua_Console_gotoxy},
{"color",lua_Console_color},
{"reset_color",lua_Console_reset_color},
{"cursor",lua_Console_cursor},
{"msleep",lua_Console_msleep},
{"get_columns",lua_Console_get_columns},
{"get_rows",lua_Console_get_rows},
{"lineedit",lua_Console_lineedit},
{NULL,NULL}
};
void lua::RegisterConsole(lua::state &st)
{
st.getglobal("Console");
if(st.is<lua::nil>())
{
st.pop();
st.newtable();
}
lua::RegFunctionsLocal(st, lua_console_func);
//TODO add color consts
st.setglobal("Console");
}

@ -462,7 +462,7 @@ void joinCounts(std::map<df::coord, int> &counts)
static void printCompanionHeader(color_ostream &out, size_t i, df::unit *unit)
{
out.color(Console::COLOR_GREY);
out.color(COLOR_GREY);
if (i < 28)
out << char('a'+i);

File diff suppressed because it is too large Load Diff

@ -19,6 +19,7 @@
#include "df/world_data.h"
#include "df/world_geo_biome.h"
#include "df/world_geo_layer.h"
#include "df/region_map_entry.h"
using namespace DFHack;
using namespace df::enums;

@ -114,6 +114,28 @@ command_result cleanunits (color_ostream &out)
return CR_OK;
}
command_result cleanplants (color_ostream &out)
{
// Invoked from clean(), already suspended
int cleaned_plants = 0, cleaned_total = 0;
for (size_t i = 0; i < world->plants.all.size(); i++)
{
df::plant *plant = world->plants.all[i];
if (plant->contaminants.size())
{
for (size_t j = 0; j < plant->contaminants.size(); j++)
delete plant->contaminants[j];
cleaned_plants++;
cleaned_total += plant->contaminants.size();
plant->contaminants.clear();
}
}
if (cleaned_total)
out.print("Removed %d contaminants from %d plants.\n", cleaned_total, cleaned_plants);
return CR_OK;
}
command_result spotclean (color_ostream &out, vector <string> & parameters)
{
// HOTKEY COMMAND: CORE ALREADY SUSPENDED
@ -153,6 +175,7 @@ command_result clean (color_ostream &out, vector <string> & parameters)
bool mud = false;
bool units = false;
bool items = false;
bool plants = false;
for(size_t i = 0; i < parameters.size();i++)
{
if(parameters[i] == "map")
@ -161,11 +184,14 @@ command_result clean (color_ostream &out, vector <string> & parameters)
units = true;
else if(parameters[i] == "items")
items = true;
else if(parameters[i] == "plants")
plants = true;
else if(parameters[i] == "all")
{
map = true;
items = true;
units = true;
plants = true;
}
else if(parameters[i] == "snow")
snow = true;
@ -174,7 +200,7 @@ command_result clean (color_ostream &out, vector <string> & parameters)
else
return CR_WRONG_USAGE;
}
if(!map && !units && !items)
if(!map && !units && !items && !plants)
return CR_WRONG_USAGE;
CoreSuspender suspend;
@ -185,6 +211,8 @@ command_result clean (color_ostream &out, vector <string> & parameters)
cleanunits(out);
if(items)
cleanitems(out);
if(plants)
cleanplants(out);
return CR_OK;
}
@ -198,6 +226,7 @@ DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <Plug
" map - clean the map tiles\n"
" items - clean all items\n"
" units - clean all creatures\n"
" plants - clean all plants\n"
" all - clean everything.\n"
"More options for 'map':\n"
" snow - also remove snow\n"

@ -17,3 +17,7 @@ DFHACK_PLUGIN(stockcheck stockcheck.cpp)
DFHACK_PLUGIN(stripcaged stripcaged.cpp)
DFHACK_PLUGIN(rprobe rprobe.cpp)
DFHACK_PLUGIN(nestboxes nestboxes.cpp)
DFHACK_PLUGIN(vshook vshook.cpp)
IF(UNIX)
DFHACK_PLUGIN(ref-index ref-index.cpp)
ENDIF()

@ -257,7 +257,7 @@ command_result kittens (color_ostream &out, vector <string> & parameters)
};
con.cursor(false);
con.clear();
Console::color_value color = Console::COLOR_BLUE;
Console::color_value color = COLOR_BLUE;
while(1)
{
if(shutdown_flag)
@ -282,7 +282,7 @@ command_result kittens (color_ostream &out, vector <string> & parameters)
con.flush();
con.msleep(60);
((int&)color) ++;
if(color > Console::COLOR_MAX)
color = Console::COLOR_BLUE;
if(color > COLOR_MAX)
color = COLOR_BLUE;
}
}

@ -73,7 +73,7 @@ void outputHex(uint8_t *buf,uint8_t *lbuf,size_t len,size_t start,color_ostream
con.reset_color();
if(isAddr((uint32_t *)(buf+j+i),ranges))
con.color(Console::COLOR_LIGHTRED); //coloring in the middle does not work
con.color(COLOR_LIGHTRED); //coloring in the middle does not work
//TODO make something better?
}
if(lbuf[j+i]!=buf[j+i])

@ -0,0 +1,149 @@
#include "Core.h"
#include <Console.h>
#include <Export.h>
#include <PluginManager.h>
#include <modules/Gui.h>
#include <modules/Screen.h>
#include <vector>
#include <cstdio>
#include <stack>
#include <string>
#include <cmath>
#include <VTableInterpose.h>
#include "df/item.h"
#include "df/unit.h"
#include "df/world.h"
#include "df/general_ref_item.h"
#include "df/general_ref_unit.h"
using std::vector;
using std::string;
using std::stack;
using namespace DFHack;
using df::global::gps;
DFHACK_PLUGIN("ref-index");
#define global_id id
template<class T>
T get_from_global_id_vector(int32_t id, const std::vector<T> &vect, int32_t *cache)
{
size_t size = vect.size();
int32_t start=0;
int32_t end=(int32_t)size-1;
// Check the cached location. If it is a match, this provides O(1) lookup.
// Otherwise it works like one binsearch iteration.
if (size_t(*cache) < size)
{
T cptr = vect[*cache];
if (cptr->global_id == id)
return cptr;
if (cptr->global_id < id)
start = *cache+1;
else
end = *cache-1;
}
// Regular binsearch. The end check provides O(1) caching for missing item.
if (start <= end && vect[end]->global_id >= id)
{
do {
int32_t mid=(start+end)>>1;
T cptr=vect[mid];
if(cptr->global_id==id)
{
*cache = mid;
return cptr;
}
else if(cptr->global_id>id)end=mid-1;
else start=mid+1;
} while(start<=end);
}
*cache = end+1;
return NULL;
}
template<class T> T *find_object(int32_t id, int32_t *cache);
template<> df::item *find_object<df::item>(int32_t id, int32_t *cache) {
return get_from_global_id_vector(id, df::global::world->items.all, cache);
}
template<> df::unit *find_object<df::unit>(int32_t id, int32_t *cache) {
return get_from_global_id_vector(id, df::global::world->units.all, cache);
}
template<class T>
struct CachedRef {
int32_t id;
int32_t cache;
CachedRef(int32_t id = -1) : id(id), cache(-1) {}
T *target() { return find_object<T>(id, &cache); }
};
#ifdef LINUX_BUILD
struct item_hook : df::general_ref_item {
typedef df::general_ref_item interpose_base;
DEFINE_VMETHOD_INTERPOSE(df::item*, getItem, ())
{
// HUGE HACK: ASSUMES THERE ARE 4 USABLE BYTES AFTER THE OBJECT
// This actually is true with glibc allocator due to granularity.
return find_object<df::item>(item_id, 1+&item_id);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(item_hook, getItem);
struct unit_hook : df::general_ref_unit {
typedef df::general_ref_unit interpose_base;
DEFINE_VMETHOD_INTERPOSE(df::unit*, getUnit, ())
{
// HUGE HACK: ASSUMES THERE ARE 4 USABLE BYTES AFTER THE OBJECT
// This actually is true with glibc allocator due to granularity.
return find_object<df::unit>(unit_id, 1+&unit_id);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(unit_hook, getUnit);
command_result hook_refs(color_ostream &out, vector <string> & parameters)
{
auto &hook = INTERPOSE_HOOK(item_hook, getItem);
if (hook.is_applied())
{
hook.remove();
INTERPOSE_HOOK(unit_hook, getUnit).remove();
}
else
{
hook.apply();
INTERPOSE_HOOK(unit_hook, getUnit).apply();
}
if (hook.is_applied())
out.print("Hook is applied.\n");
else
out.print("Hook is not applied.\n");
return CR_OK;
}
#endif
DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands)
{
#ifdef LINUX_BUILD
commands.push_back(PluginCommand("hook-refs","Inject O(1) cached lookup into general refs.",hook_refs));
#endif
return CR_OK;
}
DFhackCExport command_result plugin_shutdown ( color_ostream &out )
{
return CR_OK;
}

@ -27,6 +27,7 @@ using namespace std;
#include "df/world_region_details.h"
#include "df/world_geo_biome.h"
#include "df/world_geo_layer.h"
#include "df/region_map_entry.h"
#include "df/inclusion_type.h"
#include "df/viewscreen_choose_start_sitest.h"
@ -79,7 +80,7 @@ command_result rprobe (color_ostream &out, vector <string> & parameters)
if (parameters.size() == 2)
{
if (parameters[0] == "wet")
if (parameters[0] == "rai")
set_field = 0;
else if (parameters[0] == "veg")
set_field = 1;
@ -87,7 +88,7 @@ command_result rprobe (color_ostream &out, vector <string> & parameters)
set_field = 2;
else if (parameters[0] == "evi")
set_field = 3;
else if (parameters[0] == "hil")
else if (parameters[0] == "dra")
set_field = 4;
else if (parameters[0] == "sav")
set_field = 5;
@ -113,11 +114,11 @@ command_result rprobe (color_ostream &out, vector <string> & parameters)
{
coord2d rg = screen->biome_rgn[i];
df::world_data::T_region_map* rd = &data->region_map[rg.x][rg.y];
auto rd = &data->region_map[rg.x][rg.y];
if (set && i == to_set) {
if (set_field == 0)
rd->wetness = set_val;
rd->rainfall = set_val;
else if (set_field == 1)
rd->vegetation = set_val;
else if (set_field == 2)
@ -125,11 +126,11 @@ command_result rprobe (color_ostream &out, vector <string> & parameters)
else if (set_field == 3)
rd->evilness = set_val;
else if (set_field == 4)
rd->hilliness = set_val;
rd->drainage = set_val;
else if (set_field == 5)
rd->savagery = set_val;
else if (set_field == 6)
rd->saltiness = set_val;
rd->salinity = set_val;
}
out << i << ": x = " << rg.x << ", y = " << rg.y;
@ -140,13 +141,13 @@ command_result rprobe (color_ostream &out, vector <string> & parameters)
" landmass_id: " << rd->landmass_id <<
" flags: " << hex << rd->flags.as_int() << dec << endl;
out <<
"wet: " << rd->wetness << " " <<
"rai: " << rd->rainfall << " " <<
"veg: " << rd->vegetation << " " <<
"tem: " << rd->temperature << " " <<
"evi: " << rd->evilness << " " <<
"hil: " << rd->hilliness << " " <<
"dra: " << rd->drainage << " " <<
"sav: " << rd->savagery << " " <<
"sal: " << rd->saltiness;
"sal: " << rd->salinity;
int32_t *p = (int32_t *)rd;
int c = sizeof(*rd) / sizeof(int32_t);

@ -0,0 +1,55 @@
#include "Core.h"
#include <Console.h>
#include <Export.h>
#include <PluginManager.h>
#include <modules/Gui.h>
#include <modules/Screen.h>
#include <vector>
#include <cstdio>
#include <stack>
#include <string>
#include <cmath>
#include <VTableInterpose.h>
#include "df/graphic.h"
#include "df/viewscreen_titlest.h"
using std::vector;
using std::string;
using std::stack;
using namespace DFHack;
using df::global::gps;
DFHACK_PLUGIN("vshook");
struct title_hook : df::viewscreen_titlest {
typedef df::viewscreen_titlest interpose_base;
DEFINE_VMETHOD_INTERPOSE(void, render, ())
{
INTERPOSE_NEXT(render)();
Screen::Pen pen(' ',COLOR_WHITE,COLOR_BLACK);
Screen::paintString(pen,0,0,"DFHack " DFHACK_VERSION);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(title_hook, render);
DFhackCExport command_result plugin_init ( color_ostream &out, std::vector <PluginCommand> &commands)
{
if (gps)
{
if (!INTERPOSE_HOOK(title_hook, render).apply())
out.printerr("Could not interpose viewscreen_titlest::render\n");
}
return CR_OK;
}
DFhackCExport command_result plugin_shutdown ( color_ostream &out )
{
INTERPOSE_HOOK(title_hook, render).remove();
return CR_OK;
}

@ -27,6 +27,7 @@
#include <set>
#include <cstdlib>
#include <sstream>
#include <memory>
using std::vector;
using std::string;
using std::endl;
@ -41,6 +42,7 @@ using std::set;
#include "modules/Gui.h"
#include "TileTypes.h"
#include "modules/MapCache.h"
#include "LuaTools.h"
#include "Brushes.h"
using namespace MapExtras;
using namespace DFHack;
@ -50,7 +52,6 @@ CommandHistory liquids_hist;
command_result df_liquids (color_ostream &out, vector <string> & parameters);
command_result df_liquids_here (color_ostream &out, vector <string> & parameters);
command_result df_liquids_execute (color_ostream &out);
DFHACK_PLUGIN("liquids");
@ -74,13 +75,79 @@ DFhackCExport command_result plugin_shutdown ( color_ostream &out )
return CR_OK;
}
// static stuff to be remembered between sessions
static string brushname = "point";
static string mode="magma";
static string flowmode="f+";
static string _setmode ="s.";
static unsigned int amount = 7;
static int width = 1, height = 1, z_levels = 1;
enum BrushType {
B_POINT, B_RANGE, B_BLOCK, B_COLUMN, B_FLOOD
};
static const char *brush_name[] = {
"point", "range", "block", "column", "flood", NULL
};
enum PaintMode {
P_WATER, P_MAGMA, P_OBSIDIAN, P_OBSIDIAN_FLOOR,
P_RIVER_SOURCE, P_FLOW_BITS, P_WCLEAN
};
static const char *paint_mode_name[] = {
"water", "magma", "obsidian", "obsidian_floor",
"riversource", "flowbits", "wclean", NULL
};
enum ModifyMode {
M_INC, M_KEEP, M_DEC
};
static const char *modify_mode_name[] = {
"+", ".", "-", NULL
};
enum PermaflowMode {
PF_KEEP, PF_NONE,
PF_NORTH, PF_SOUTH, PF_EAST, PF_WEST,
PF_NORTHEAST, PF_NORTHWEST, PF_SOUTHEAST, PF_SOUTHWEST
};
static const char *permaflow_name[] = {
".", "-", "N", "S", "E", "W",
"NE", "NW", "SE", "SW", NULL
};
#define X(name) tile_liquid_flow_dir::name
static const df::tile_liquid_flow_dir permaflow_id[] = {
X(none), X(none), X(north), X(south), X(east), X(west),
X(northeast), X(northwest), X(southeast), X(southwest)
};
#undef X
struct OperationMode {
BrushType brush;
PaintMode paint;
ModifyMode flowmode;
ModifyMode setmode;
PermaflowMode permaflow;
unsigned int amount;
df::coord size;
OperationMode() :
brush(B_POINT), paint(P_MAGMA),
flowmode(M_INC), setmode(M_KEEP), permaflow(PF_KEEP), amount(7),
size(1,1,1)
{}
} cur_mode;
command_result df_liquids_execute(color_ostream &out);
command_result df_liquids_execute(color_ostream &out, OperationMode &mode, df::coord pos);
static void print_prompt(std::ostream &str, OperationMode &cur_mode)
{
str <<"[" << paint_mode_name[cur_mode.paint] << ":" << brush_name[cur_mode.brush];
if (cur_mode.brush == B_RANGE)
str << "(w" << cur_mode.size.x << ":h" << cur_mode.size.y << ":z" << cur_mode.size.z << ")";
str << ":" << cur_mode.amount << ":f" << modify_mode_name[cur_mode.flowmode]
<< ":s" << modify_mode_name[cur_mode.setmode]
<< ":pf" << permaflow_name[cur_mode.permaflow]
<< "]";
}
command_result df_liquids (color_ostream &out_, vector <string> & parameters)
{
@ -117,10 +184,8 @@ command_result df_liquids (color_ostream &out_, vector <string> & parameters)
string input = "";
std::stringstream str;
str <<"[" << mode << ":" << brushname;
if (brushname == "range")
str << "(w" << width << ":h" << height << ":z" << z_levels << ")";
str << ":" << amount << ":" << flowmode << ":" << _setmode << "]#";
print_prompt(str, cur_mode);
str << "# ";
if(out.lineedit(str.str(),input,liquids_hist) == -1)
return CR_FAILURE;
liquids_hist.add(input);
@ -147,6 +212,10 @@ command_result df_liquids (color_ostream &out_, vector <string> & parameters)
<< "f+ - make the spawned liquid flow" << endl
<< "f. - don't change flow state (read state in flow mode)" << endl
<< "f- - make the spawned liquid static" << endl
<< "Permaflow (only for water):" << endl
<< "pf. - don't change permaflow state" << endl
<< "pf- - make the spawned liquid static" << endl
<< "pf[NS][EW] - make the spawned liquid permanently flow" << endl
<< "0-7 - set liquid amount" << endl
<< "Brush:" << endl
<< "point - single tile [p]" << endl
@ -168,38 +237,39 @@ command_result df_liquids (color_ostream &out_, vector <string> & parameters)
}
else if(command == "m")
{
mode = "magma";
cur_mode.paint = P_MAGMA;
}
else if(command == "o")
{
mode = "obsidian";
cur_mode.paint = P_OBSIDIAN;
}
else if(command == "of")
{
mode = "obsidian_floor";
cur_mode.paint = P_OBSIDIAN_FLOOR;
}
else if(command == "w")
{
mode = "water";
cur_mode.paint = P_WATER;
}
else if(command == "f")
{
mode = "flowbits";
cur_mode.paint = P_FLOW_BITS;
}
else if(command == "rs")
{
mode = "riversource";
cur_mode.paint = P_RIVER_SOURCE;
}
else if(command == "wclean")
{
mode = "wclean";
cur_mode.paint = P_WCLEAN;
}
else if(command == "point" || command == "p")
{
brushname = "point";
cur_mode.brush = B_POINT;
}
else if(command == "range" || command == "r")
{
int width, height, z_levels;
command_result res = parseRectangle(out, commands, 1, commands.size(),
width, height, z_levels);
if (res != CR_OK)
@ -209,24 +279,26 @@ command_result df_liquids (color_ostream &out_, vector <string> & parameters)
if (width == 1 && height == 1 && z_levels == 1)
{
brushname = "point";
cur_mode.brush = B_POINT;
cur_mode.size = df::coord(1, 1, 1);
}
else
{
brushname = "range";
cur_mode.brush = B_RANGE;
cur_mode.size = df::coord(width, height, z_levels);
}
}
else if(command == "block")
{
brushname = "block";
cur_mode.brush = B_BLOCK;
}
else if(command == "column")
{
brushname = "column";
cur_mode.brush = B_COLUMN;
}
else if(command == "flood")
{
brushname = "flood";
cur_mode.brush = B_FLOOD;
}
else if(command == "q")
{
@ -234,45 +306,59 @@ command_result df_liquids (color_ostream &out_, vector <string> & parameters)
}
else if(command == "f+")
{
flowmode = "f+";
cur_mode.flowmode = M_INC;
}
else if(command == "f-")
{
flowmode = "f-";
cur_mode.flowmode = M_DEC;
}
else if(command == "f.")
{
flowmode = "f.";
cur_mode.flowmode = M_KEEP;
}
else if(command == "s+")
{
_setmode = "s+";
cur_mode.setmode = M_INC;
}
else if(command == "s-")
{
_setmode = "s-";
cur_mode.setmode = M_DEC;
}
else if(command == "s.")
{
_setmode = "s.";
cur_mode.setmode = M_KEEP;
}
else if (command.size() > 2 && memcmp(command.c_str(), "pf", 2) == 0)
{
auto *tail = command.c_str()+2;
for (int pm = PF_KEEP; pm <= PF_SOUTHWEST; pm++)
{
if (strcmp(tail, permaflow_name[pm]) != 0)
continue;
cur_mode.permaflow = PermaflowMode(pm);
tail = NULL;
break;
}
if (tail)
out << command << " : invalid permaflow mode" << endl;
}
// blah blah, bad code, bite me.
else if(command == "0")
amount = 0;
cur_mode.amount = 0;
else if(command == "1")
amount = 1;
cur_mode.amount = 1;
else if(command == "2")
amount = 2;
cur_mode.amount = 2;
else if(command == "3")
amount = 3;
cur_mode.amount = 3;
else if(command == "4")
amount = 4;
cur_mode.amount = 4;
else if(command == "5")
amount = 5;
cur_mode.amount = 5;
else if(command == "6")
amount = 6;
cur_mode.amount = 6;
else if(command == "7")
amount = 7;
cur_mode.amount = 7;
else if(command.empty())
{
df_liquids_execute(out);
@ -298,78 +384,75 @@ command_result df_liquids_here (color_ostream &out, vector <string> & parameters
}
out.print("Run liquids-here with these parameters: ");
out << "[" << mode << ":" << brushname;
if (brushname == "range")
out << "(w" << width << ":h" << height << ":z" << z_levels << ")";
out << ":" << amount << ":" << flowmode << ":" << _setmode << "]\n";
print_prompt(out, cur_mode);
out << endl;
return df_liquids_execute(out);
}
command_result df_liquids_execute(color_ostream &out)
{
// create brush type depending on old parameters
Brush * brush;
CoreSuspender suspend;
if (brushname == "point")
auto cursor = Gui::getCursorPos();
if (!cursor.isValid())
{
brush = new RectangleBrush(1,1,1,0,0,0);
//width = 1;
//height = 1;
//z_levels = 1;
out.printerr("Can't get cursor coords! Make sure you have a cursor active in DF.\n");
return CR_WRONG_USAGE;
}
else if (brushname == "range")
{
brush = new RectangleBrush(width,height,z_levels,0,0,0);
}
else if(brushname == "block")
auto rv = df_liquids_execute(out, cur_mode, cursor);
if (rv == CR_OK)
out << "OK" << endl;
return rv;
}
command_result df_liquids_execute(color_ostream &out, OperationMode &cur_mode, df::coord cursor)
{
// create brush type depending on old parameters
Brush *brush;
switch (cur_mode.brush)
{
case B_POINT:
brush = new RectangleBrush(1,1,1,0,0,0);
break;
case B_RANGE:
brush = new RectangleBrush(cur_mode.size.x,cur_mode.size.y,cur_mode.size.z,0,0,0);
break;
case B_BLOCK:
brush = new BlockBrush();
}
else if(brushname == "column")
{
break;
case B_COLUMN:
brush = new ColumnBrush();
}
else if(brushname == "flood")
{
break;
case B_FLOOD:
brush = new FloodBrush(&Core::getInstance());
}
else
{
break;
default:
// this should never happen!
out << "Old brushtype is invalid! Resetting to point brush.\n";
brushname = "point";
width = 1;
height = 1;
z_levels = 1;
brush = new RectangleBrush(width,height,z_levels,0,0,0);
cur_mode.brush = B_POINT;
brush = new RectangleBrush(1,1,1,0,0,0);
}
CoreSuspender suspend;
std::auto_ptr<Brush> brush_ref(brush);
do
if (!Maps::IsValid())
{
if (!Maps::IsValid())
{
out << "Can't see any DF map loaded." << endl;
break;;
}
int32_t x,y,z;
if(!Gui::getCursorCoords(x,y,z))
{
out << "Can't get cursor coords! Make sure you have a cursor active in DF." << endl;
break;
}
out << "cursor coords: " << x << "/" << y << "/" << z << endl;
MapCache mcache;
DFHack::DFCoord cursor(x,y,z);
coord_vec all_tiles = brush->points(mcache,cursor);
out << "working..." << endl;
out << "Can't see any DF map loaded." << endl;
return CR_FAILURE;
}
// Force the game to recompute its walkability cache
df::global::world->reindex_pathfinding = true;
MapCache mcache;
coord_vec all_tiles = brush->points(mcache,cursor);
if(mode == "obsidian")
// Force the game to recompute its walkability cache
df::global::world->reindex_pathfinding = true;
switch (cur_mode.paint)
{
case P_OBSIDIAN:
{
coord_vec::iterator iter = all_tiles.begin();
while (iter != all_tiles.end())
@ -383,8 +466,9 @@ command_result df_liquids_execute(color_ostream &out)
mcache.setDesignationAt(*iter, des);
iter ++;
}
break;
}
if(mode == "obsidian_floor")
case P_OBSIDIAN_FLOOR:
{
coord_vec::iterator iter = all_tiles.begin();
while (iter != all_tiles.end())
@ -392,8 +476,9 @@ command_result df_liquids_execute(color_ostream &out)
mcache.setTiletypeAt(*iter, findRandomVariant(tiletype::LavaFloor1));
iter ++;
}
break;
}
else if(mode == "riversource")
case P_RIVER_SOURCE:
{
coord_vec::iterator iter = all_tiles.begin();
while (iter != all_tiles.end())
@ -413,8 +498,9 @@ command_result df_liquids_execute(color_ostream &out)
iter++;
}
break;
}
else if(mode=="wclean")
case P_WCLEAN:
{
coord_vec::iterator iter = all_tiles.begin();
while (iter != all_tiles.end())
@ -426,8 +512,11 @@ command_result df_liquids_execute(color_ostream &out)
mcache.setDesignationAt(current,des);
iter++;
}
break;
}
else if(mode== "magma" || mode== "water" || mode == "flowbits")
case P_MAGMA:
case P_WATER:
case P_FLOW_BITS:
{
set <Block *> seen_blocks;
coord_vec::iterator iter = all_tiles.begin();
@ -442,6 +531,7 @@ command_result df_liquids_execute(color_ostream &out)
iter ++;
continue;
}
auto raw_block = block->getRaw();
df::tile_designation des = mcache.designationAt(current);
df::tiletype tt = mcache.tiletypeAt(current);
// don't put liquids into places where they don't belong...
@ -450,30 +540,29 @@ command_result df_liquids_execute(color_ostream &out)
iter++;
continue;
}
if(mode != "flowbits")
if(cur_mode.paint != P_FLOW_BITS)
{
unsigned old_amount = des.bits.flow_size;
unsigned new_amount = old_amount;
df::tile_liquid old_liquid = des.bits.liquid_type;
df::tile_liquid new_liquid = old_liquid;
// Compute new liquid type and amount
if(_setmode == "s.")
{
new_amount = amount;
}
else if(_setmode == "s+")
{
if(old_amount < amount)
new_amount = amount;
}
else if(_setmode == "s-")
switch (cur_mode.setmode)
{
if (old_amount > amount)
new_amount = amount;
case M_KEEP:
new_amount = cur_mode.amount;
break;
case M_INC:
if(old_amount < cur_mode.amount)
new_amount = cur_mode.amount;
break;
case M_DEC:
if (old_amount > cur_mode.amount)
new_amount = cur_mode.amount;
}
if (mode == "magma")
if (cur_mode.paint == P_MAGMA)
new_liquid = tile_liquid::Magma;
else if (mode == "water")
else if (cur_mode.paint == P_WATER)
new_liquid = tile_liquid::Water;
// Store new amount and type
des.bits.flow_size = new_amount;
@ -502,40 +591,77 @@ command_result df_liquids_execute(color_ostream &out)
// request flow engine updates
block->enableBlockUpdates(new_amount != old_amount, new_liquid != old_liquid);
}
if (cur_mode.permaflow != PF_KEEP && raw_block)
{
auto &flow = raw_block->liquid_flow[current.x&15][current.y&15];
flow.bits.perm_flow_dir = permaflow_id[cur_mode.permaflow];
flow.bits.temp_flow_timer = 0;
}
seen_blocks.insert(block);
iter++;
}
set <Block *>::iterator biter = seen_blocks.begin();
while (biter != seen_blocks.end())
{
if(flowmode == "f+")
switch (cur_mode.flowmode)
{
case M_INC:
(*biter)->enableBlockUpdates(true);
}
else if(flowmode == "f-")
{
break;
case M_DEC:
if (auto block = (*biter)->getRaw())
{
block->flags.bits.update_liquid = false;
block->flags.bits.update_liquid_twice = false;
}
}
else
{
auto bflags = (*biter)->BlockFlags();
out << "flow bit 1 = " << bflags.bits.update_liquid << endl;
out << "flow bit 2 = " << bflags.bits.update_liquid_twice << endl;
break;
case M_KEEP:
{
auto bflags = (*biter)->BlockFlags();
out << "flow bit 1 = " << bflags.bits.update_liquid << endl;
out << "flow bit 2 = " << bflags.bits.update_liquid_twice << endl;
}
}
biter ++;
}
break;
}
if(mcache.WriteAll())
out << "OK" << endl;
else
out << "Something failed horribly! RUN!" << endl;
} while (0);
}
if(!mcache.WriteAll())
{
out << "Something failed horribly! RUN!" << endl;
return CR_FAILURE;
}
// cleanup
delete brush;
return CR_OK;
}
static int paint(lua_State *L)
{
df::coord pos;
OperationMode mode;
lua_settop(L, 8);
Lua::CheckDFAssign(L, &pos, 1);
if (!pos.isValid())
luaL_argerror(L, 1, "invalid cursor position");
mode.brush = (BrushType)luaL_checkoption(L, 2, NULL, brush_name);
mode.paint = (PaintMode)luaL_checkoption(L, 3, NULL, paint_mode_name);
mode.amount = luaL_optint(L, 4, 7);
if (mode.amount < 0 || mode.amount > 7)
luaL_argerror(L, 4, "invalid liquid amount");
if (!lua_isnil(L, 5))
Lua::CheckDFAssign(L, &mode.size, 5);
mode.setmode = (ModifyMode)luaL_checkoption(L, 6, ".", modify_mode_name);
mode.flowmode = (ModifyMode)luaL_checkoption(L, 7, "+", modify_mode_name);
mode.permaflow = (PermaflowMode)luaL_checkoption(L, 8, ".", permaflow_name);
lua_pushboolean(L, df_liquids_execute(*Lua::GetOutput(L), mode, pos));
return 1;
}
DFHACK_PLUGIN_LUA_COMMANDS {
DFHACK_LUA_COMMAND(paint),
DFHACK_LUA_END
};

@ -0,0 +1,11 @@
local _ENV = mkmodule('plugins.liquids')
--[[
Native functions:
* paint(pos,brush,paint,amount,size,setmode,flowmode)
--]]
return _ENV

@ -0,0 +1,783 @@
// Dwarf Manipulator - a Therapist-style labor editor
#include "Core.h"
#include <Console.h>
#include <Export.h>
#include <PluginManager.h>
#include <MiscUtils.h>
#include <modules/Screen.h>
#include <modules/Translation.h>
#include <modules/Units.h>
#include <vector>
#include <string>
#include <set>
#include <algorithm>
#include <VTableInterpose.h>
#include "df/world.h"
#include "df/ui.h"
#include "df/graphic.h"
#include "df/enabler.h"
#include "df/viewscreen_unitlistst.h"
#include "df/interface_key.h"
#include "df/unit.h"
#include "df/unit_soul.h"
#include "df/unit_skill.h"
#include "df/creature_raw.h"
#include "df/caste_raw.h"
using std::set;
using std::vector;
using std::string;
using namespace DFHack;
using namespace df::enums;
using df::global::world;
using df::global::ui;
using df::global::gps;
using df::global::enabler;
DFHACK_PLUGIN("manipulator");
struct SkillLevel
{
const char *name;
int points;
char abbrev;
};
#define NUM_SKILL_LEVELS (sizeof(skill_levels) / sizeof(SkillLevel))
// The various skill rankings. Zero skill is hardcoded to "Not" and '-'.
const SkillLevel skill_levels[] = {
{"Dabbling", 500, '0'},
{"Novice", 600, '1'},
{"Adequate", 700, '2'},
{"Competent", 800, '3'},
{"Skilled", 900, '4'},
{"Proficient", 1000, '5'},
{"Talented", 1100, '6'},
{"Adept", 1200, '7'},
{"Expert", 1300, '8'},
{"Professional",1400, '9'},
{"Accomplished",1500, 'A'},
{"Great", 1600, 'B'},
{"Master", 1700, 'C'},
{"High Master", 1800, 'D'},
{"Grand Master",1900, 'E'},
{"Legendary", 2000, 'U'},
{"Legendary+1", 2100, 'V'},
{"Legendary+2", 2200, 'W'},
{"Legendary+3", 2300, 'X'},
{"Legendary+4", 2400, 'Y'},
{"Legendary+5", 0, 'Z'}
};
struct SkillColumn
{
df::profession profession;
df::unit_labor labor;
df::job_skill skill;
char label[3];
bool special; // specified labor is mutually exclusive with all other special labors
};
#define NUM_COLUMNS (sizeof(columns) / sizeof(SkillColumn))
// All of the skill/labor columns we want to display. Includes profession (for color), labor, skill, and 2 character label
const SkillColumn columns[] = {
// Mining
{profession::MINER, unit_labor::MINE, job_skill::MINING, "Mi", true},
// Woodworking
{profession::WOODWORKER, unit_labor::CARPENTER, job_skill::CARPENTRY, "Ca"},
{profession::WOODWORKER, unit_labor::BOWYER, job_skill::BOWYER, "Bw"},
{profession::WOODWORKER, unit_labor::CUTWOOD, job_skill::WOODCUTTING, "WC", true},
// Stoneworking
{profession::STONEWORKER, unit_labor::MASON, job_skill::MASONRY, "Ma"},
{profession::STONEWORKER, unit_labor::DETAIL, job_skill::DETAILSTONE, "En"},
// Hunting/Related
{profession::RANGER, unit_labor::ANIMALTRAIN, job_skill::ANIMALTRAIN, "Tn"},
{profession::RANGER, unit_labor::ANIMALCARE, job_skill::ANIMALCARE, "Ca"},
{profession::RANGER, unit_labor::HUNT, job_skill::SNEAK, "Hu", true},
{profession::RANGER, unit_labor::TRAPPER, job_skill::TRAPPING, "Tr"},
{profession::RANGER, unit_labor::DISSECT_VERMIN, job_skill::DISSECT_VERMIN, "Di"},
// Healthcare
{profession::DOCTOR, unit_labor::DIAGNOSE, job_skill::DIAGNOSE, "Di"},
{profession::DOCTOR, unit_labor::SURGERY, job_skill::SURGERY, "Su"},
{profession::DOCTOR, unit_labor::BONE_SETTING, job_skill::SET_BONE, "Bo"},
{profession::DOCTOR, unit_labor::SUTURING, job_skill::SUTURE, "St"},
{profession::DOCTOR, unit_labor::DRESSING_WOUNDS, job_skill::DRESS_WOUNDS, "Dr"},
{profession::DOCTOR, unit_labor::FEED_WATER_CIVILIANS, job_skill::NONE, "Fd"},
{profession::DOCTOR, unit_labor::RECOVER_WOUNDED, job_skill::NONE, "Re"},
// Farming/Related
{profession::FARMER, unit_labor::BUTCHER, job_skill::BUTCHER, "Bu"},
{profession::FARMER, unit_labor::TANNER, job_skill::TANNER, "Ta"},
{profession::FARMER, unit_labor::PLANT, job_skill::PLANT, "Gr"},
{profession::FARMER, unit_labor::DYER, job_skill::DYER, "Dy"},
{profession::FARMER, unit_labor::SOAP_MAKER, job_skill::SOAP_MAKING, "So"},
{profession::FARMER, unit_labor::BURN_WOOD, job_skill::WOOD_BURNING, "WB"},
{profession::FARMER, unit_labor::POTASH_MAKING, job_skill::POTASH_MAKING, "Po"},
{profession::FARMER, unit_labor::LYE_MAKING, job_skill::LYE_MAKING, "Ly"},
{profession::FARMER, unit_labor::MILLER, job_skill::MILLING, "Ml"},
{profession::FARMER, unit_labor::BREWER, job_skill::BREWING, "Br"},
{profession::FARMER, unit_labor::HERBALIST, job_skill::HERBALISM, "He"},
{profession::FARMER, unit_labor::PROCESS_PLANT, job_skill::PROCESSPLANTS, "Th"},
{profession::FARMER, unit_labor::MAKE_CHEESE, job_skill::CHEESEMAKING, "Ch"},
{profession::FARMER, unit_labor::MILK, job_skill::MILK, "Mk"},
{profession::FARMER, unit_labor::SHEARER, job_skill::SHEARING, "Sh"},
{profession::FARMER, unit_labor::SPINNER, job_skill::SPINNING, "Sp"},
{profession::FARMER, unit_labor::COOK, job_skill::COOK, "Co"},
{profession::FARMER, unit_labor::PRESSING, job_skill::PRESSING, "Pr"},
{profession::FARMER, unit_labor::BEEKEEPING, job_skill::BEEKEEPING, "Be"},
// Fishing/Related
{profession::FISHERMAN, unit_labor::FISH, job_skill::FISH, "Fi"},
{profession::FISHERMAN, unit_labor::CLEAN_FISH, job_skill::PROCESSFISH, "Cl"},
{profession::FISHERMAN, unit_labor::DISSECT_FISH, job_skill::DISSECT_FISH, "Di"},
// Metalsmithing
{profession::METALSMITH, unit_labor::SMELT, job_skill::SMELT, "Fu"},
{profession::METALSMITH, unit_labor::FORGE_WEAPON, job_skill::FORGE_WEAPON, "We"},
{profession::METALSMITH, unit_labor::FORGE_ARMOR, job_skill::FORGE_ARMOR, "Ar"},
{profession::METALSMITH, unit_labor::FORGE_FURNITURE, job_skill::FORGE_FURNITURE, "Bl"},
{profession::METALSMITH, unit_labor::METAL_CRAFT, job_skill::METALCRAFT, "Cr"},
// Jewelry
{profession::JEWELER, unit_labor::CUT_GEM, job_skill::CUTGEM, "Cu"},
{profession::JEWELER, unit_labor::ENCRUST_GEM, job_skill::ENCRUSTGEM, "Se"},
// Crafts
{profession::CRAFTSMAN, unit_labor::LEATHER, job_skill::LEATHERWORK, "Le"},
{profession::CRAFTSMAN, unit_labor::WOOD_CRAFT, job_skill::WOODCRAFT, "Wo"},
{profession::CRAFTSMAN, unit_labor::STONE_CRAFT, job_skill::STONECRAFT, "St"},
{profession::CRAFTSMAN, unit_labor::BONE_CARVE, job_skill::BONECARVE, "Bo"},
{profession::CRAFTSMAN, unit_labor::GLASSMAKER, job_skill::GLASSMAKER, "Gl"},
{profession::CRAFTSMAN, unit_labor::WEAVER, job_skill::WEAVING, "We"},
{profession::CRAFTSMAN, unit_labor::CLOTHESMAKER, job_skill::CLOTHESMAKING, "Cl"},
{profession::CRAFTSMAN, unit_labor::EXTRACT_STRAND, job_skill::EXTRACT_STRAND, "Ad"},
{profession::CRAFTSMAN, unit_labor::POTTERY, job_skill::POTTERY, "Po"},
{profession::CRAFTSMAN, unit_labor::GLAZING, job_skill::GLAZING, "Gl"},
{profession::CRAFTSMAN, unit_labor::WAX_WORKING, job_skill::WAX_WORKING, "Wx"},
// Engineering
{profession::ENGINEER, unit_labor::SIEGECRAFT, job_skill::SIEGECRAFT, "En"},
{profession::ENGINEER, unit_labor::SIEGEOPERATE, job_skill::SIEGEOPERATE, "Op"},
{profession::ENGINEER, unit_labor::MECHANIC, job_skill::MECHANICS, "Me"},
{profession::ENGINEER, unit_labor::OPERATE_PUMP, job_skill::OPERATE_PUMP, "Pu"},
// Hauling
{profession::STANDARD, unit_labor::HAUL_STONE, job_skill::NONE, "St"},
{profession::STANDARD, unit_labor::HAUL_WOOD, job_skill::NONE, "Wo"},
{profession::STANDARD, unit_labor::HAUL_ITEM, job_skill::NONE, "It"},
{profession::STANDARD, unit_labor::HAUL_BODY, job_skill::NONE, "Bu"},
{profession::STANDARD, unit_labor::HAUL_FOOD, job_skill::NONE, "Fo"},
{profession::STANDARD, unit_labor::HAUL_REFUSE, job_skill::NONE, "Re"},
{profession::STANDARD, unit_labor::HAUL_FURNITURE, job_skill::NONE, "Fu"},
{profession::STANDARD, unit_labor::HAUL_ANIMAL, job_skill::NONE, "An"},
{profession::STANDARD, unit_labor::PUSH_HAUL_VEHICLE, job_skill::NONE, "Ve"},
// Other Jobs
{profession::CHILD, unit_labor::ARCHITECT, job_skill::DESIGNBUILDING, "Ar"},
{profession::CHILD, unit_labor::ALCHEMIST, job_skill::ALCHEMY, "Al"},
{profession::CHILD, unit_labor::CLEAN, job_skill::NONE, "Cl"},
// Military
{profession::WRESTLER, unit_labor::NONE, job_skill::WRESTLING, "Wr"},
{profession::WRESTLER, unit_labor::NONE, job_skill::AXE, "Ax"},
{profession::WRESTLER, unit_labor::NONE, job_skill::SWORD, "Sw"},
{profession::WRESTLER, unit_labor::NONE, job_skill::MACE, "Mc"},
{profession::WRESTLER, unit_labor::NONE, job_skill::HAMMER, "Ha"},
{profession::WRESTLER, unit_labor::NONE, job_skill::SPEAR, "Sp"},
{profession::WRESTLER, unit_labor::NONE, job_skill::DAGGER, "Kn"},
{profession::WRESTLER, unit_labor::NONE, job_skill::CROSSBOW, "Cb"},
{profession::WRESTLER, unit_labor::NONE, job_skill::BOW, "Bo"},
{profession::WRESTLER, unit_labor::NONE, job_skill::BLOWGUN, "Bl"},
{profession::WRESTLER, unit_labor::NONE, job_skill::PIKE, "Pk"},
{profession::WRESTLER, unit_labor::NONE, job_skill::WHIP, "La"},
{profession::WRESTLER, unit_labor::NONE, job_skill::ARMOR, "Ar"},
{profession::WRESTLER, unit_labor::NONE, job_skill::SHIELD, "Sh"},
{profession::WRESTLER, unit_labor::NONE, job_skill::BITE, "Bi"},
{profession::WRESTLER, unit_labor::NONE, job_skill::GRASP_STRIKE, "St"},
{profession::WRESTLER, unit_labor::NONE, job_skill::STANCE_STRIKE, "Ki"},
{profession::WRESTLER, unit_labor::NONE, job_skill::DODGING, "Do"},
{profession::WRESTLER, unit_labor::NONE, job_skill::MISC_WEAPON, "Mi"},
{profession::WRESTLER, unit_labor::NONE, job_skill::MELEE_COMBAT, "Fg"},
{profession::WRESTLER, unit_labor::NONE, job_skill::RANGED_COMBAT, "Ac"},
{profession::RECRUIT, unit_labor::NONE, job_skill::LEADERSHIP, "Ld"},
{profession::RECRUIT, unit_labor::NONE, job_skill::TEACHING, "Te"},
{profession::RECRUIT, unit_labor::NONE, job_skill::KNOWLEDGE_ACQUISITION, "St"},
{profession::RECRUIT, unit_labor::NONE, job_skill::DISCIPLINE, "Di"},
{profession::RECRUIT, unit_labor::NONE, job_skill::CONCENTRATION, "Co"},
{profession::RECRUIT, unit_labor::NONE, job_skill::SITUATIONAL_AWARENESS, "Ob"},
{profession::RECRUIT, unit_labor::NONE, job_skill::COORDINATION, "Cr"},
{profession::RECRUIT, unit_labor::NONE, job_skill::BALANCE, "Ba"},
// Social
{profession::STANDARD, unit_labor::NONE, job_skill::PERSUASION, "Pe"},
{profession::STANDARD, unit_labor::NONE, job_skill::NEGOTIATION, "Ne"},
{profession::STANDARD, unit_labor::NONE, job_skill::JUDGING_INTENT, "Ju"},
{profession::STANDARD, unit_labor::NONE, job_skill::LYING, "Li"},
{profession::STANDARD, unit_labor::NONE, job_skill::INTIMIDATION, "In"},
{profession::STANDARD, unit_labor::NONE, job_skill::CONVERSATION, "Cn"},
{profession::STANDARD, unit_labor::NONE, job_skill::COMEDY, "Cm"},
{profession::STANDARD, unit_labor::NONE, job_skill::FLATTERY, "Fl"},
{profession::STANDARD, unit_labor::NONE, job_skill::CONSOLE, "Cs"},
{profession::STANDARD, unit_labor::NONE, job_skill::PACIFY, "Pc"},
// Noble
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::APPRAISAL, "Ap"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::ORGANIZATION, "Or"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::RECORD_KEEPING, "RK"},
// Miscellaneous
{profession::STANDARD, unit_labor::NONE, job_skill::THROW, "Th"},
{profession::STANDARD, unit_labor::NONE, job_skill::CRUTCH_WALK, "CW"},
{profession::STANDARD, unit_labor::NONE, job_skill::SWIMMING, "Sw"},
{profession::STANDARD, unit_labor::NONE, job_skill::KNAPPING, "Kn"},
{profession::DRUNK, unit_labor::NONE, job_skill::WRITING, "Wr"},
{profession::DRUNK, unit_labor::NONE, job_skill::PROSE, "Pr"},
{profession::DRUNK, unit_labor::NONE, job_skill::POETRY, "Po"},
{profession::DRUNK, unit_labor::NONE, job_skill::READING, "Rd"},
{profession::DRUNK, unit_labor::NONE, job_skill::SPEAKING, "Sp"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::MILITARY_TACTICS, "MT"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::TRACKING, "Tr"},
{profession::ADMINISTRATOR, unit_labor::NONE, job_skill::MAGIC_NATURE, "Dr"},
};
struct UnitInfo
{
df::unit *unit;
bool allowEdit;
string name;
string transname;
string profession;
int8_t color;
};
enum altsort_mode {
ALTSORT_NAME,
ALTSORT_PROFESSION,
ALTSORT_MAX
};
bool descending;
df::job_skill sort_skill;
df::unit_labor sort_labor;
bool sortByName (const UnitInfo *d1, const UnitInfo *d2)
{
if (descending)
return (d1->name > d2->name);
else
return (d1->name < d2->name);
}
bool sortByProfession (const UnitInfo *d1, const UnitInfo *d2)
{
if (descending)
return (d1->profession > d2->profession);
else
return (d1->profession < d2->profession);
}
bool sortBySkill (const UnitInfo *d1, const UnitInfo *d2)
{
if (sort_skill != job_skill::NONE)
{
df::unit_skill *s1 = binsearch_in_vector<df::unit_skill,df::enum_field<df::job_skill,int16_t>>(d1->unit->status.current_soul->skills, &df::unit_skill::id, sort_skill);
df::unit_skill *s2 = binsearch_in_vector<df::unit_skill,df::enum_field<df::job_skill,int16_t>>(d2->unit->status.current_soul->skills, &df::unit_skill::id, sort_skill);
int l1 = s1 ? s1->rating : 0;
int l2 = s2 ? s2->rating : 0;
int e1 = s1 ? s1->experience : 0;
int e2 = s2 ? s2->experience : 0;
if (descending)
{
if (l1 != l2)
return l1 > l2;
if (e1 != e2)
return e1 > e2;
}
else
{
if (l1 != l2)
return l1 < l2;
if (e1 != e2)
return e1 < e2;
}
}
if (sort_labor != unit_labor::NONE)
{
if (descending)
return d1->unit->status.labors[sort_labor] > d2->unit->status.labors[sort_labor];
else
return d1->unit->status.labors[sort_labor] < d2->unit->status.labors[sort_labor];
}
return sortByName(d1, d2);
}
class viewscreen_unitlaborsst : public dfhack_viewscreen {
public:
void feed(set<df::interface_key> *events);
void render();
void resize(int w, int h) { calcSize(); }
void help() { }
std::string getFocusString() { return "unitlabors"; }
viewscreen_unitlaborsst(vector<df::unit*> &src);
~viewscreen_unitlaborsst() { };
protected:
vector<UnitInfo *> units;
altsort_mode altsort;
int first_row, sel_row;
int first_column, sel_column;
int height, name_width, prof_width, labors_width;
void calcSize ();
};
viewscreen_unitlaborsst::viewscreen_unitlaborsst(vector<df::unit*> &src)
{
for (size_t i = 0; i < src.size(); i++)
{
UnitInfo *cur = new UnitInfo;
df::unit *unit = src[i];
cur->unit = unit;
cur->allowEdit = true;
if (unit->race != ui->race_id)
cur->allowEdit = false;
if (unit->civ_id != ui->civ_id)
cur->allowEdit = false;
if (unit->flags1.bits.dead)
cur->allowEdit = false;
if (!ENUM_ATTR(profession, can_assign_labor, unit->profession))
cur->allowEdit = false;
cur->name = Translation::TranslateName(&unit->name, false);
cur->transname = Translation::TranslateName(&unit->name, true);
cur->profession = Units::getProfessionName(unit);
cur->color = Units::getProfessionColor(unit);
units.push_back(cur);
}
std::sort(units.begin(), units.end(), sortByName);
altsort = ALTSORT_NAME;
first_row = sel_row = 0;
first_column = sel_column = 0;
calcSize();
}
void viewscreen_unitlaborsst::calcSize()
{
height = gps->dimy - 10;
if (height > units.size())
height = units.size();
name_width = prof_width = labors_width = 0;
for (int i = 4; i < gps->dimx; i++)
{
// 20% for Name, 20% for Profession, 60% for Labors
switch ((i - 4) % 5)
{
case 0: case 2: case 4:
labors_width++;
break;
case 1:
name_width++;
break;
case 3:
prof_width++;
break;
}
}
while (labors_width > NUM_COLUMNS)
{
if (labors_width & 1)
name_width++;
else
prof_width++;
labors_width--;
}
// don't adjust scroll position immediately after the window opened
if (units.size() == 0)
return;
// if the window grows vertically, scroll upward to eliminate blank rows from the bottom
if (first_row > units.size() - height)
first_row = units.size() - height;
// if it shrinks vertically, scroll downward to keep the cursor visible
if (first_row < sel_row - height + 1)
first_row = sel_row - height + 1;
// if the window grows horizontally, scroll to the left to eliminate blank columns from the right
if (first_column > NUM_COLUMNS - labors_width)
first_column = NUM_COLUMNS - labors_width;
// if it shrinks horizontally, scroll to the right to keep the cursor visible
if (first_column < sel_column - labors_width + 1)
first_column = sel_column - labors_width + 1;
}
void viewscreen_unitlaborsst::feed(set<df::interface_key> *events)
{
if (events->count(interface_key::LEAVESCREEN))
{
events->clear();
Screen::dismiss(this);
return;
}
if (!units.size())
return;
if (events->count(interface_key::CURSOR_UP) || events->count(interface_key::CURSOR_UPLEFT) || events->count(interface_key::CURSOR_UPRIGHT))
sel_row--;
if (events->count(interface_key::CURSOR_UP_FAST) || events->count(interface_key::CURSOR_UPLEFT_FAST) || events->count(interface_key::CURSOR_UPRIGHT_FAST))
sel_row -= 10;
if (events->count(interface_key::CURSOR_DOWN) || events->count(interface_key::CURSOR_DOWNLEFT) || events->count(interface_key::CURSOR_DOWNRIGHT))
sel_row++;
if (events->count(interface_key::CURSOR_DOWN_FAST) || events->count(interface_key::CURSOR_DOWNLEFT_FAST) || events->count(interface_key::CURSOR_DOWNRIGHT_FAST))
sel_row += 10;
if (sel_row < 0)
sel_row = 0;
if (sel_row > units.size() - 1)
sel_row = units.size() - 1;
if (sel_row < first_row)
first_row = sel_row;
if (first_row < sel_row - height + 1)
first_row = sel_row - height + 1;
if (events->count(interface_key::CURSOR_LEFT) || events->count(interface_key::CURSOR_UPLEFT) || events->count(interface_key::CURSOR_DOWNLEFT))
sel_column--;
if (events->count(interface_key::CURSOR_LEFT_FAST) || events->count(interface_key::CURSOR_UPLEFT_FAST) || events->count(interface_key::CURSOR_DOWNLEFT_FAST))
sel_column -= 10;
if (events->count(interface_key::CURSOR_RIGHT) || events->count(interface_key::CURSOR_UPRIGHT) || events->count(interface_key::CURSOR_DOWNRIGHT))
sel_column++;
if (events->count(interface_key::CURSOR_RIGHT_FAST) || events->count(interface_key::CURSOR_UPRIGHT_FAST) || events->count(interface_key::CURSOR_DOWNRIGHT_FAST))
sel_column += 10;
if ((sel_column != 0) && events->count(interface_key::CURSOR_UP_Z))
{
// go to beginning of current column group; if already at the beginning, go to the beginning of the previous one
sel_column--;
df::profession cur = columns[sel_column].profession;
while ((sel_column > 0) && columns[sel_column - 1].profession == cur)
sel_column--;
}
if ((sel_column != NUM_COLUMNS - 1) && events->count(interface_key::CURSOR_DOWN_Z))
{
// go to end of current column group; if already at the end, go to the end of the next one
sel_column++;
df::profession cur = columns[sel_column].profession;
while ((sel_column < NUM_COLUMNS - 1) && columns[sel_column + 1].profession == cur)
sel_column++;
}
if (sel_column < 0)
sel_column = 0;
if (sel_column > NUM_COLUMNS - 1)
sel_column = NUM_COLUMNS - 1;
if (sel_column < first_column)
first_column = sel_column;
if (first_column < sel_column - labors_width + 1)
first_column = sel_column - labors_width + 1;
UnitInfo *cur = units[sel_row];
if (events->count(interface_key::SELECT) && (cur->allowEdit) && (columns[sel_column].labor != unit_labor::NONE))
{
df::unit *unit = cur->unit;
const SkillColumn &col = columns[sel_column];
if (col.special)
{
if (!unit->status.labors[col.labor])
{
for (int i = 0; i < NUM_COLUMNS; i++)
{
if ((columns[i].labor != unit_labor::NONE) && columns[i].special)
unit->status.labors[columns[i].labor] = false;
}
}
unit->military.pickup_flags.bits.update = true;
}
unit->status.labors[col.labor] = !unit->status.labors[col.labor];
}
if (events->count(interface_key::SECONDSCROLL_UP) || events->count(interface_key::SECONDSCROLL_DOWN))
{
descending = events->count(interface_key::SECONDSCROLL_UP);
sort_skill = columns[sel_column].skill;
sort_labor = columns[sel_column].labor;
std::sort(units.begin(), units.end(), sortBySkill);
}
if (events->count(interface_key::SECONDSCROLL_PAGEUP) || events->count(interface_key::SECONDSCROLL_PAGEDOWN))
{
descending = events->count(interface_key::SECONDSCROLL_PAGEUP);
switch (altsort)
{
case ALTSORT_NAME:
std::sort(units.begin(), units.end(), sortByName);
break;
case ALTSORT_PROFESSION:
std::sort(units.begin(), units.end(), sortByProfession);
break;
}
}
if (events->count(interface_key::CHANGETAB))
{
switch (altsort)
{
case ALTSORT_NAME:
altsort = ALTSORT_PROFESSION;
break;
case ALTSORT_PROFESSION:
altsort = ALTSORT_NAME;
break;
}
}
if (VIRTUAL_CAST_VAR(unitlist, df::viewscreen_unitlistst, parent))
{
if (events->count(interface_key::UNITJOB_VIEW) || events->count(interface_key::UNITJOB_ZOOM_CRE))
{
for (int i = 0; i < unitlist->units[unitlist->page].size(); i++)
{
if (unitlist->units[unitlist->page][i] == units[sel_row]->unit)
{
unitlist->cursor_pos[unitlist->page] = i;
unitlist->feed(events);
if (Screen::isDismissed(unitlist))
Screen::dismiss(this);
break;
}
}
}
}
}
void OutputString(int8_t color, int &x, int y, const std::string &text)
{
Screen::paintString(Screen::Pen(' ', color, 0), x, y, text);
x += text.length();
}
void viewscreen_unitlaborsst::render()
{
if (Screen::isDismissed(this))
return;
dfhack_viewscreen::render();
Screen::clear();
Screen::drawBorder(" Manage Labors ");
for (int col = 0; col < labors_width; col++)
{
int col_offset = col + first_column;
if (col_offset >= NUM_COLUMNS)
break;
int8_t fg = Units::getCasteProfessionColor(ui->race_id, -1, columns[col_offset].profession);
int8_t bg = 0;
if (col_offset == sel_column)
{
fg = 0;
bg = 7;
}
Screen::paintTile(Screen::Pen(columns[col_offset].label[0], fg, bg), 1 + name_width + 1 + prof_width + 1 + col, 1);
Screen::paintTile(Screen::Pen(columns[col_offset].label[1], fg, bg), 1 + name_width + 1 + prof_width + 1 + col, 2);
}
for (int row = 0; row < height; row++)
{
int row_offset = row + first_row;
if (row_offset >= units.size())
break;
UnitInfo *cur = units[row_offset];
df::unit *unit = cur->unit;
int8_t fg = 15, bg = 0;
if (row_offset == sel_row)
{
fg = 0;
bg = 7;
}
string name = cur->name;
name.resize(name_width);
Screen::paintString(Screen::Pen(' ', fg, bg), 1, 3 + row, name);
string profession = cur->profession;
profession.resize(prof_width);
fg = cur->color;
bg = 0;
Screen::paintString(Screen::Pen(' ', fg, bg), 1 + name_width + 1, 3 + row, profession);
// Print unit's skills and labor assignments
for (int col = 0; col < labors_width; col++)
{
int col_offset = col + first_column;
fg = 15;
bg = 0;
char c = 0xFA;
if ((col_offset == sel_column) && (row_offset == sel_row))
fg = 9;
if (columns[col_offset].skill != job_skill::NONE)
{
df::unit_skill *skill = binsearch_in_vector<df::unit_skill,df::enum_field<df::job_skill,int16_t>>(unit->status.current_soul->skills, &df::unit_skill::id, columns[col_offset].skill);
if ((skill != NULL) && (skill->rating || skill->experience))
{
int level = skill->rating;
if (level > NUM_SKILL_LEVELS - 1)
level = NUM_SKILL_LEVELS - 1;
c = skill_levels[level].abbrev;
}
else
c = '-';
}
if (columns[col_offset].labor != unit_labor::NONE)
{
if (unit->status.labors[columns[col_offset].labor])
{
bg = 7;
if (columns[col_offset].skill == job_skill::NONE)
c = 0xF9;
}
}
else
bg = 4;
Screen::paintTile(Screen::Pen(c, fg, bg), 1 + name_width + 1 + prof_width + 1 + col, 3 + row);
}
}
UnitInfo *cur = units[sel_row];
if (cur != NULL)
{
df::unit *unit = cur->unit;
int x = 1;
Screen::paintString(Screen::Pen(' ', 15, 0), x, 3 + height + 2, cur->transname);
x += cur->transname.length();
if (cur->transname.length())
{
Screen::paintString(Screen::Pen(' ', 15, 0), x, 3 + height + 2, ", ");
x += 2;
}
Screen::paintString(Screen::Pen(' ', 15, 0), x, 3 + height + 2, cur->profession);
x += cur->profession.length();
Screen::paintString(Screen::Pen(' ', 15, 0), x, 3 + height + 2, ": ");
x += 2;
string str;
if (columns[sel_column].skill == job_skill::NONE)
{
str = ENUM_ATTR_STR(unit_labor, caption, columns[sel_column].labor);
if (unit->status.labors[columns[sel_column].labor])
str += " Enabled";
else
str += " Not Enabled";
}
else
{
df::unit_skill *skill = binsearch_in_vector<df::unit_skill,df::enum_field<df::job_skill,int16_t>>(unit->status.current_soul->skills, &df::unit_skill::id, columns[sel_column].skill);
if (skill)
{
int level = skill->rating;
if (level > NUM_SKILL_LEVELS - 1)
level = NUM_SKILL_LEVELS - 1;
str = stl_sprintf("%s %s", skill_levels[level].name, ENUM_ATTR_STR(job_skill, caption_noun, columns[sel_column].skill));
if (level != NUM_SKILL_LEVELS - 1)
str += stl_sprintf(" (%d/%d)", skill->experience, skill_levels[level].points);
}
else
str = stl_sprintf("Not %s (0/500)", ENUM_ATTR_STR(job_skill, caption_noun, columns[sel_column].skill));
}
Screen::paintString(Screen::Pen(' ', 9, 0), x, 3 + height + 2, str);
}
int x = 1;
OutputString(10, x, gps->dimy - 3, "Enter"); // SELECT key
OutputString(15, x, gps->dimy - 3, ": Toggle labor, ");
OutputString(10, x, gps->dimy - 3, "v"); // UNITJOB_VIEW key
OutputString(15, x, gps->dimy - 3, ": ViewCre, ");
OutputString(10, x, gps->dimy - 3, "c"); // UNITJOB_ZOOM_CRE key
OutputString(15, x, gps->dimy - 3, ": Zoom-Cre, ");
OutputString(10, x, gps->dimy - 3, "Esc"); // LEAVESCREEN key
OutputString(15, x, gps->dimy - 3, ": Done");
x = 1;
OutputString(10, x, gps->dimy - 2, "+"); // SECONDSCROLL_DOWN key
OutputString(10, x, gps->dimy - 2, "-"); // SECONDSCROLL_UP key
OutputString(15, x, gps->dimy - 2, ": Sort by Skill, ");
OutputString(10, x, gps->dimy - 2, "*"); // SECONDSCROLL_PAGEDOWN key
OutputString(10, x, gps->dimy - 2, "/"); // SECONDSCROLL_PAGEUP key
OutputString(15, x, gps->dimy - 2, ": Sort by (");
OutputString(10, x, gps->dimy - 2, "Tab"); // CHANGETAB key
OutputString(15, x, gps->dimy - 2, ") ");
switch (altsort)
{
case ALTSORT_NAME:
OutputString(15, x, gps->dimy - 2, "Name");
break;
case ALTSORT_PROFESSION:
OutputString(15, x, gps->dimy - 2, "Profession");
break;
default:
OutputString(15, x, gps->dimy - 2, "Unknown");
break;
}
}
struct unitlist_hook : df::viewscreen_unitlistst
{
typedef df::viewscreen_unitlistst interpose_base;
DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input))
{
if (input->count(interface_key::UNITVIEW_PRF_PROF))
{
if (units[page].size())
{
Screen::show(new viewscreen_unitlaborsst(units[page]));
return;
}
}
INTERPOSE_NEXT(feed)(input);
}
};
IMPLEMENT_VMETHOD_INTERPOSE(unitlist_hook, feed);
DFhackCExport command_result plugin_init ( color_ostream &out, vector <PluginCommand> &commands)
{
if (gps)
{
if (!INTERPOSE_HOOK(unitlist_hook, feed).apply())
out.printerr("Could not interpose viewscreen_unitlistst::feed\n");
}
return CR_OK;
}
DFhackCExport command_result plugin_shutdown ( color_ostream &out )
{
INTERPOSE_HOOK(unitlist_hook, feed).remove();
return CR_OK;
}

@ -27,6 +27,7 @@ using namespace std;
#include "df/world.h"
#include "df/world_raws.h"
#include "df/building_def.h"
#include "df/region_map_entry.h"
using std::vector;
using std::string;
@ -224,8 +225,7 @@ command_result df_probe (color_ostream &out, vector <string> & parameters)
int bx = clip_range(block.region_pos.x + (offset % 3) - 1, 0, world->world_data->world_width-1);
int by = clip_range(block.region_pos.y + (offset / 3) - 1, 0, world->world_data->world_height-1);
df::world_data::T_region_map* biome =
&world->world_data->region_map[bx][by];
auto biome = &world->world_data->region_map[bx][by];
int sav = biome->savagery;
int evi = biome->evilness;

@ -25,8 +25,12 @@ using namespace std;
#include "df/world.h"
#include "df/world_data.h"
#include "df/world_region_details.h"
#include "df/world_region_feature.h"
#include "df/world_geo_biome.h"
#include "df/world_geo_layer.h"
#include "df/world_underground_region.h"
#include "df/feature_init.h"
#include "df/region_map_entry.h"
#include "df/inclusion_type.h"
#include "df/viewscreen_choose_start_sitest.h"
@ -108,9 +112,10 @@ struct compare_pair_second
}
};
static void printMatdata(color_ostream &con, const matdata &data)
static void printMatdata(color_ostream &con, const matdata &data, bool only_z = false)
{
con << std::setw(9) << data.count;
if (!only_z)
con << std::setw(9) << data.count;
if(data.lower_z != data.upper_z)
con <<" Z:" << std::setw(4) << data.lower_z << ".." << data.upper_z << std::endl;
@ -225,116 +230,247 @@ static coord2d biome_delta[] = {
coord2d(-1,-1), coord2d(0,-1), coord2d(1,-1)
};
static command_result embark_prospector(color_ostream &out, df::viewscreen_choose_start_sitest *screen,
bool showHidden, bool showValue)
struct EmbarkTileLayout {
coord2d biome_off, biome_pos;
df::region_map_entry *biome;
int elevation, max_soil_depth;
int min_z, base_z;
std::map<int, float> penalty;
};
bool estimate_underground(color_ostream &out, EmbarkTileLayout &tile, df::world_region_details *details, int x, int y)
{
if (!world || !world->world_data)
// Find actual biome
int bv = clip_range(details->biome[x][y] & 15, 1, 9);
tile.biome_off = biome_delta[bv-1];
df::world_data *data = world->world_data;
int bx = clip_range(details->pos.x + tile.biome_off.x, 0, data->world_width-1);
int by = clip_range(details->pos.y + tile.biome_off.y, 0, data->world_height-1);
tile.biome_pos = coord2d(bx, by);
tile.biome = &data->region_map[bx][by];
// Compute surface elevation
tile.elevation = (
details->elevation[x][y] + details->elevation[x][y+1] +
details->elevation[x+1][y] + details->elevation[x+1][y+1]
) / 4;
tile.max_soil_depth = std::max((154-tile.biome->elevation)/5,0);
tile.base_z = tile.elevation;
tile.penalty.clear();
auto &features = details->features[x][y];
// Collect global feature layer depths and apply penalties
std::map<int, int> layer_bottom, layer_top;
bool sea_found = false;
for (size_t i = 0; i < features.size(); i++)
{
out.printerr("World data is not available.\n");
return CR_FAILURE;
auto feature = features[i];
auto layer = df::world_underground_region::find(feature->layer);
if (!layer || feature->min_z == -30000) continue;
layer_bottom[layer->layer_depth] = feature->min_z;
layer_top[layer->layer_depth] = feature->max_z;
tile.base_z = std::min(tile.base_z, (int)feature->min_z);
float penalty = 1.0f;
switch (layer->type) {
case df::world_underground_region::Cavern:
penalty = 0.75f;
break;
case df::world_underground_region::MagmaSea:
sea_found = true;
tile.min_z = feature->min_z;
for (int i = feature->min_z; i <= feature->max_z; i++)
tile.penalty[i] = 0.2 + 0.6f*(i-feature->min_z)/(feature->max_z-feature->min_z+1);
break;
case df::world_underground_region::Underworld:
penalty = 0.0f;
break;
}
if (penalty != 1.0f)
{
for (int i = feature->min_z; i <= feature->max_z; i++)
tile.penalty[i] = penalty;
}
}
df::world_data *data = world->world_data;
coord2d cur_region = screen->region_pos;
int d_idx = linear_index(data->region_details, &df::world_region_details::pos, cur_region);
auto cur_details = vector_get(data->region_details, d_idx);
if (!sea_found)
{
out.printerr("Could not find magma sea.\n");
return false;
}
if (!cur_details)
// Scan for big local features and apply their penalties
for (size_t i = 0; i < features.size(); i++)
{
out.printerr("Current region details are not available.\n");
return CR_FAILURE;
auto feature = features[i];
auto lfeature = Maps::getLocalInitFeature(details->pos, feature->feature_idx);
if (!lfeature)
continue;
switch (lfeature->getType())
{
case feature_type::pit:
case feature_type::magma_pool:
case feature_type::volcano:
for (int i = layer_bottom[lfeature->end_depth];
i <= layer_top[lfeature->start_depth]; i++)
tile.penalty[i] = std::min(0.4f, map_find(tile.penalty, i, 1.0f));
break;
default:
break;
}
}
// Compute biomes
std::map<coord2d, int> biomes;
return true;
}
void add_materials(EmbarkTileLayout &tile, matdata &data, float amount, int min_z, int max_z)
{
for (int z = min_z; z <= max_z; z++)
data.add(z, int(map_find(tile.penalty, z, 1)*amount));
}
bool estimate_materials(color_ostream &out, EmbarkTileLayout &tile, MatMap &layerMats, MatMap &veinMats)
{
using namespace geo_layer_type;
df::world_geo_biome *geo_biome = df::world_geo_biome::find(tile.biome->geo_index);
if (screen->biome_highlighted)
if (!geo_biome)
{
out.print("Processing one embark tile of biome F%d.\n\n", screen->biome_idx+1);
biomes[screen->biome_rgn[screen->biome_idx]]++;
out.printerr("Region geo-biome not found: (%d,%d)\n",
tile.biome_pos.x, tile.biome_pos.y);
return false;
}
else
// soil depth increases by 1 every 5 levels below 150
int top_z_level = tile.elevation - tile.max_soil_depth;
for (unsigned i = 0; i < geo_biome->layers.size(); i++)
{
for (int x = screen->embark_pos_min.x; x <= screen->embark_pos_max.x; x++)
auto layer = geo_biome->layers[i];
switch (layer->type)
{
for (int y = screen->embark_pos_min.y; y <= screen->embark_pos_max.y; y++)
{
int bv = clip_range(cur_details->biome[x][y], 1, 9);
biomes[cur_region + biome_delta[bv-1]]++;
}
case SOIL:
case SOIL_OCEAN:
case SOIL_SAND:
top_z_level += layer->top_height - layer->bottom_height + 1;
break;
default:;
}
}
// Compute material maps
MatMap layerMats;
MatMap veinMats;
top_z_level = std::max(top_z_level, tile.elevation)-1;
for (auto biome_it = biomes.begin(); biome_it != biomes.end(); ++biome_it)
for (unsigned i = 0; i < geo_biome->layers.size(); i++)
{
int bx = clip_range(biome_it->first.x, 0, data->world_width-1);
int by = clip_range(biome_it->first.y, 0, data->world_height-1);
auto &region = data->region_map[bx][by];
df::world_geo_biome *geo_biome = df::world_geo_biome::find(region.geo_index);
auto layer = geo_biome->layers[i];
if (!geo_biome)
{
out.printerr("Region geo-biome not found: (%d,%d)\n", bx, by);
return CR_FAILURE;
}
int top_z = std::min(layer->top_height + top_z_level, tile.elevation-1);
int bottom_z = std::max(layer->bottom_height + top_z_level, tile.min_z);
if (i+1 == geo_biome->layers.size()) // stretch layer if needed
bottom_z = tile.min_z;
if (top_z < bottom_z)
continue;
float layer_size = 48*48;
int sums[ENUM_LAST_ITEM(inclusion_type)+1] = { 0 };
int cnt = biome_it->second;
for (unsigned j = 0; j < layer->vein_mat.size(); j++)
if (is_valid_enum_item<df::inclusion_type>(layer->vein_type[j]))
sums[layer->vein_type[j]] += layer->vein_unk_38[j];
for (unsigned i = 0; i < geo_biome->layers.size(); i++)
for (unsigned j = 0; j < layer->vein_mat.size(); j++)
{
auto layer = geo_biome->layers[i];
// TODO: find out how to estimate the real density
// this code assumes that vein_unk_38 is the weight
// used when choosing the vein material
float size = float(layer->vein_unk_38[j]);
df::inclusion_type type = layer->vein_type[j];
layerMats[layer->mat_index].add(layer->bottom_height, 0);
switch (type)
{
case inclusion_type::VEIN:
// 3 veins of 80 tiles avg
size = size * 80 * 3 / sums[type];
break;
case inclusion_type::CLUSTER:
// 1 cluster of 700 tiles avg
size = size * 700 * 1 / sums[type];
break;
case inclusion_type::CLUSTER_SMALL:
size = size * 6 * 7 / sums[type];
break;
case inclusion_type::CLUSTER_ONE:
size = size * 1 * 5 / sums[type];
break;
default:
// shouldn't actually happen
size = 1;
}
int level_cnt = layer->top_height - layer->bottom_height + 1;
int layer_size = 48*48*cnt*level_cnt;
layer_size -= size;
int sums[ENUM_LAST_ITEM(inclusion_type)+1] = { 0 };
add_materials(tile, veinMats[layer->vein_mat[j]], size, bottom_z, top_z);
}
for (unsigned j = 0; j < layer->vein_mat.size(); j++)
if (is_valid_enum_item<df::inclusion_type>(layer->vein_type[j]))
sums[layer->vein_type[j]] += layer->vein_unk_38[j];
add_materials(tile, layerMats[layer->mat_index], layer_size, bottom_z, top_z);
}
for (unsigned j = 0; j < layer->vein_mat.size(); j++)
{
// TODO: find out how to estimate the real density
// this code assumes that vein_unk_38 is the weight
// used when choosing the vein material
int size = layer->vein_unk_38[j]*cnt*level_cnt;
df::inclusion_type type = layer->vein_type[j];
return true;
}
switch (type)
{
case inclusion_type::VEIN:
// 3 veins of 80 tiles avg
size = size * 80 * 3 / sums[type];
break;
case inclusion_type::CLUSTER:
// 1 cluster of 700 tiles avg
size = size * 700 * 1 / sums[type];
break;
case inclusion_type::CLUSTER_SMALL:
size = size * 6 * 7 / sums[type];
break;
case inclusion_type::CLUSTER_ONE:
size = size * 1 * 5 / sums[type];
break;
default:
// shouldn't actually happen
size = cnt*level_cnt;
}
static command_result embark_prospector(color_ostream &out, df::viewscreen_choose_start_sitest *screen,
bool showHidden, bool showValue)
{
if (!world || !world->world_data)
{
out.printerr("World data is not available.\n");
return CR_FAILURE;
}
df::world_data *data = world->world_data;
coord2d cur_region = screen->region_pos;
int d_idx = linear_index(data->region_details, &df::world_region_details::pos, cur_region);
auto cur_details = vector_get(data->region_details, d_idx);
veinMats[layer->vein_mat[j]].add(layer->bottom_height, 0);
veinMats[layer->vein_mat[j]].add(layer->top_height, size);
if (!cur_details)
{
out.printerr("Current region details are not available.\n");
return CR_FAILURE;
}
layer_size -= size;
}
// Compute material maps
MatMap layerMats;
MatMap veinMats;
matdata world_bottom;
layerMats[layer->mat_index].add(layer->top_height, std::max(0,layer_size));
// Compute biomes
std::map<coord2d, int> biomes;
/*if (screen->biome_highlighted)
{
out.print("Processing one embark tile of biome F%d.\n\n", screen->biome_idx+1);
biomes[screen->biome_rgn[screen->biome_idx]]++;
}*/
for (int x = screen->embark_pos_min.x; x <= screen->embark_pos_max.x; x++)
{
for (int y = screen->embark_pos_min.y; y <= screen->embark_pos_max.y; y++)
{
EmbarkTileLayout tile;
if (!estimate_underground(out, tile, cur_details, x, y) ||
!estimate_materials(out, tile, layerMats, veinMats))
return CR_FAILURE;
world_bottom.add(tile.base_z, 0);
world_bottom.add(tile.elevation-1, 0);
}
}
@ -348,7 +484,10 @@ static command_result embark_prospector(color_ostream &out, df::viewscreen_choos
mats->Finish();
}
out << "Warning: the above data is only a very rough estimate." << std::endl;
out << "Embark depth: " << (world_bottom.upper_z-world_bottom.lower_z+1) << " ";
printMatdata(out, world_bottom, true);
out << std::endl << "Warning: the above data is only a very rough estimate." << std::endl;
return CR_OK;
}
@ -536,6 +675,8 @@ command_result prospector (color_ostream &con, vector <string> & parameters)
case tiletype_material::LAVA_STONE:
// TODO ?
break;
default:
break;
}
}
}

@ -1,29 +1,29 @@
OPTION(DL_RUBY "download libruby from the internet" ON)
IF (DL_RUBY AND NOT APPLE)
IF (UNIX)
FILE(DOWNLOAD http://cloud.github.com/downloads/jjyg/dfhack/libruby187.tar.gz ${CMAKE_CURRENT_SOURCE_DIR}/libruby187.tar.gz
FILE(DOWNLOAD http://cloud.github.com/downloads/jjyg/dfhack/libruby187.tar.gz ${CMAKE_CURRENT_BINARY_DIR}/libruby187.tar.gz
EXPECTED_MD5 eb2adea59911f68e6066966c1352f291)
EXECUTE_PROCESS(COMMAND ${CMAKE_COMMAND} -E tar xzf libruby187.tar.gz
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
FILE(RENAME libruby1.8.so.1.8.7 libruby.so)
SET(RUBYLIB libruby.so)
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
FILE(RENAME ${CMAKE_CURRENT_BINARY_DIR}/libruby1.8.so.1.8.7 ${CMAKE_CURRENT_BINARY_DIR}/libruby.so)
SET(RUBYLIB ${CMAKE_CURRENT_BINARY_DIR}/libruby.so)
ELSE (UNIX)
FILE(DOWNLOAD http://cloud.github.com/downloads/jjyg/dfhack/msvcrtruby187.tar.gz ${CMAKE_CURRENT_SOURCE_DIR}/msvcrtruby187.tar.gz
FILE(DOWNLOAD http://cloud.github.com/downloads/jjyg/dfhack/msvcrtruby187.tar.gz ${CMAKE_CURRENT_BINARY_DIR}/msvcrtruby187.tar.gz
EXPECTED_MD5 9f4a1659ac3a5308f32d3a1937bbeeae)
EXECUTE_PROCESS(COMMAND ${CMAKE_COMMAND} -E tar xzf msvcrtruby187.tar.gz
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
FILE(RENAME msvcrt-ruby18.dll libruby.dll)
SET(RUBYLIB libruby.dll)
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
FILE(RENAME ${CMAKE_CURRENT_BINARY_DIR}/msvcrt-ruby18.dll ${CMAKE_CURRENT_BINARY_DIR}/libruby.dll)
SET(RUBYLIB ${CMAKE_CURRENT_BINARY_DIR}/libruby.dll)
ENDIF(UNIX)
ENDIF(DL_RUBY AND NOT APPLE)
ADD_CUSTOM_COMMAND(
OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/ruby-autogen.rb
COMMAND ${PERL_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/codegen.pl ${dfhack_SOURCE_DIR}/library/include/df/codegen.out.xml ${CMAKE_CURRENT_SOURCE_DIR}/ruby-autogen.rb
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/ruby-autogen.rb
COMMAND ${PERL_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/codegen.pl ${dfhack_SOURCE_DIR}/library/include/df/codegen.out.xml ${CMAKE_CURRENT_BINARY_DIR}/ruby-autogen.rb
DEPENDS ${dfhack_SOURCE_DIR}/library/include/df/codegen.out.xml ${CMAKE_CURRENT_SOURCE_DIR}/codegen.pl
COMMENT ruby-autogen.rb
)
ADD_CUSTOM_TARGET(ruby-autogen-rb DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/ruby-autogen.rb)
ADD_CUSTOM_TARGET(ruby-autogen-rb DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/ruby-autogen.rb)
INCLUDE_DIRECTORIES("${dfhack_SOURCE_DIR}/depends/tthread")
@ -32,6 +32,8 @@ ADD_DEPENDENCIES(ruby ruby-autogen-rb)
INSTALL(FILES ${RUBYLIB} DESTINATION ${DFHACK_LIBRARY_DESTINATION})
INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/ruby-autogen.rb DESTINATION hack/ruby)
INSTALL(DIRECTORY .
DESTINATION hack/ruby
FILES_MATCHING PATTERN "*.rb")

@ -23,7 +23,7 @@ All ruby code runs while the main DF process and other plugins are suspended.
DFHack console
--------------
The ruby plugin defines 1 dfhack console command:
The ruby plugin defines one new dfhack console command:
rb_eval <ruby expression> ; evaluate a ruby expression and show the result in
the console. Ex: rb_eval df.unit_find().name.first_name
You can use single-quotes for strings ; avoid double-quotes that are parsed
@ -50,7 +50,7 @@ The script can access the console command arguments through the global variable
'$script_args', which is an array of ruby Strings.
The help string displayed in dfhack 'ls' command is the first line of the
script, if it is a comment (starts with '# ').
script, if it is a comment (ie starts with '# ').
Ruby helper functions
@ -67,7 +67,9 @@ obj1 and 2 should respond to #pos and #x #y #z.
Returns the MapBlock for the coordinates or nil.
df.map_tile_at(pos)
Returns a MapTile, holds all information relative to the map tile.
Returns a MapTile, holding all informations wrt the map tile (read&write).
This class is a ruby specific extention, to facilitate interaction with the
DF map data. Check out hack/ruby/map.rb.
df.each_map_block { |b| }
df.each_map_block_z(zlevel) { |b| }
@ -142,9 +144,16 @@ The ruby classes defined in ruby-autogen.rb are accessors to the underlying
df C++ objects in-memory. To allocate a new C++ object for use in DF, use the
RubyClass.cpp_new method (see buildings.rb for exemples), works for Compounds
only.
A special Compound DFHack::StlString is available for allocating a single c++
stl::string, so that you can call vmethods that take a string pointer argument
(eg getName).
ex: s = DFHack::StlString.cpp_new ; df.building_find.getName(s) ; p s.str
Deallocation is not supported. You may manually call df.free if you know
what you are doing (maps directly to the native malloc/free)
Deallocation may work, using the compound method _cpp_delete. Use with caution,
may crash your DF session. It may be simpler to just leak the memory.
_cpp_delete will try to free all memory directly used by the compound, eg
strings and vectors. It will *not* call the class destructor, and will not free
stuff behind pointers.
C++ std::string fields may be directly re-allocated using standard ruby strings,
e.g. some_unit.name.nickname = 'moo'
@ -160,11 +169,13 @@ To delete an element, vector.delete_at(index)
You can binary search an element in a vector for a given numeric field value:
df.world.unit.all.binsearch(42, :id)
will find the element whose 'id' field is 42 (needs the vector to be initially
will find the entry whose 'id' field is 42 (needs the vector to be initially
sorted by this field). The binsearch 2nd argument defaults to :id.
Any numeric field defined as being an enum value will be converted to a ruby
Symbol. This works for array indexes too.
ex: df.unit_find(:selected).status.labors[:HAUL_FOOD] = true
df.map_tile_at(df.cursor).designation.liquid_type = :Water
Virtual method calls are supported for C++ objects, with a maximum of 4
arguments. Arguments / return value are interpreted as Compound/Enums as
@ -194,7 +205,7 @@ Change current unit profession
Center the screen on unit ID '123'
df.center_viewscreen(df.unit_find(123))
Find an item at a given position, show its C++ classname
Find an item under the game cursor and show its C++ classname
p df.item_find(df.cursor)._rtti_classname
Find the raws name of the plant under cursor
@ -202,18 +213,31 @@ Find the raws name of the plant under cursor
p df.world.raws.plants.all[plant.mat_index].id
Dig a channel under the cursor
df.map_designation_at(df.cursor).dig = :Channel
df.map_block_at(df.cursor).flags.designated = true
df.map_tile_at(df.cursor).dig(:Channel)
Spawn 2/7 magma on the tile of the dwarf nicknamed 'hotfeet'
hot = df.unit_citizens.find { |u| u.name.nickname == 'hotfeet' }
df.map_tile_at(hot).spawn_magma(2)
Plugin compilation
------------------
The plugin consists of the *.rb file including user comfort functions and
describing basic classes used by the autogenerated code, and ruby-autogen.rb,
the auto-generated code.
The plugin consists of the main ruby.cpp native plugin and the *.rb files.
The native plugin handles only low-level ruby-to-df interaction (eg raw memory
read/write, and dfhack integration), and the .rb files hold end-user helper
functions.
On dfhack start, the native plugin will initialize the ruby interpreter, and
load hack/ruby/ruby.rb. This one then loads all other .rb files.
autogen is output by codegen.pl from dfhack/library/include/df/codegen.out.xml
The DF internal structures are described in ruby-autogen.rb .
It is output by ruby/codegen.pl, from dfhack/library/include/df/codegen.out.xml
It contains architecture-specific data (eg DF internal structures field offsets,
which differ between Windows and Linux. Linux and Macosx are the same, as they
both use gcc).
It is stored inside the build directory (eg build/plugins/ruby/ruby-autogen.rb)
For exemple,
<ld:global-type ld:meta="struct-type" type-name="unit">
@ -230,6 +254,7 @@ Will generate
The syntax for the 'field' method in ruby-autogen.rb is:
1st argument = name of the method
2nd argument = offset of this field from the beginning of the current struct.
This field depends on the compiler used by Toady to generate DF.
The block argument describes the type of the field: uint32, ptr to global...
Primitive type access is done through native methods from ruby.cpp (vector length,

@ -279,21 +279,30 @@ module DFHack
job = Job.cpp_new
refbuildingholder = GeneralRefBuildingHolderst.cpp_new
job.job_type = :DestroyBuilding
refbuildingholder.building_id = building.id
refbuildingholder.building_id = bld.id
job.references << refbuildingholder
building.jobs << job
bld.jobs << job
job_link job
job
end
# check item flags to see if it is suitable for use as a building material
def building_isitemfree(i)
!i.flags.in_job and
!i.flags.in_inventory and
!i.flags.removed and
!i.flags.in_building and
!i.flags.owned and
!i.flags.forbid
end
# exemple usage
def buildbed(pos=cursor)
raise 'where to ?' if pos.x < 0
item = world.items.all.find { |i|
i.kind_of?(ItemBedst) and
i.itemrefs.empty? and
!i.flags.in_job
building_isitemfree(i)
}
raise 'no free bed, build more !' if not item

@ -175,10 +175,10 @@ sub render_bitfield_fields {
if ($name)
{
if ($count == 1) {
push @lines_rb, "field(:$name, 0) { bit $shift }";
} elsif ($enum) {
if ($enum) {
push @lines_rb, "field(:$name, 0) { bits $shift, $count, $enum }";
} elsif ($count == 1) {
push @lines_rb, "field(:$name, 0) { bit $shift }";
} else {
push @lines_rb, "field(:$name, 0) { bits $shift, $count }";
}

@ -107,6 +107,31 @@ module DFHack
Tiletype::Direction[tiletype]
end
def shape_caption
TiletypeShape::Caption[shape]
end
def shape_basic
TiletypeShape::BasicShape[shape]
end
def shape_passablelow
TiletypeShape::PassableLow[shape]
end
def shape_passablehigh
TiletypeShape::PassableHigh[shape]
end
def shape_passableflow
TiletypeShape::PassableFlow[shape]
end
def shape_walkable
TiletypeShape::Walkable[shape]
end
# return all veins for current mapblock
def all_veins
mapblock.block_events.grep(BlockSquareEventMineralst)
@ -162,5 +187,33 @@ module DFHack
def inspect
"#<MapTile pos=[#@x, #@y, #@z] shape=#{shape} tilemat=#{tilemat} material=#{mat_info.token}>"
end
def dig(mode=:Default)
designation.dig = mode
mapblock.flags.designated = true
end
def spawn_liquid(quantity, is_magma=false, flowing=true)
designation.flow_size = quantity
designation.liquid_type = (is_magma ? :Magma : :Water)
designation.flow_forbid = true if is_magma or quantity >= 4
if flowing
mapblock.flags.update_liquid = true
mapblock.flags.update_liquid_twice = true
zf = df.world.map.z_level_flags[z]
zf.update = true
zf.update_twice = true
end
end
def spawn_water(quantity=7)
spawn_liquid(quantity)
end
def spawn_magma(quantity=7)
spawn_liquid(quantity, true)
end
end
end

@ -7,6 +7,7 @@ module DFHack
def _at(addr) ; d = dup ; d._memaddr = addr ; d ; end
def _get ; self ; end
def _cpp_init ; end
def _cpp_delete ; end
end
class Compound < MemStruct
@ -34,8 +35,8 @@ module DFHack
def float
Float.new
end
def bit(shift)
BitField.new(shift, 1)
def bit(shift, enum=nil)
BitField.new(shift, 1, enum)
end
def bits(shift, len, enum=nil)
BitField.new(shift, len, enum)
@ -114,6 +115,11 @@ module DFHack
def _cpp_init
_fields_ancestors.each { |n, o, s| s._at(@_memaddr+o)._cpp_init }
end
def _cpp_delete
_fields_ancestors.each { |n, o, s| s._at(@_memaddr+o)._cpp_delete }
DFHack.free(@_memaddr)
@_memaddr = nil # turn future segfaults in harmless ruby exceptions
end
def _set(h)
case h
when Hash; h.each { |k, v| send("#{k}=", v) }
@ -147,7 +153,7 @@ module DFHack
out << '>'
end
def inspect_field(n, o, s)
if s.kind_of?(BitField) and s._len == 1
if s.kind_of?(BitField) and s._len == 1 and not s._enum
send(n) ? n.to_s : ''
elsif s.kind_of?(Pointer)
"#{n}=#{s._at(@_memaddr+o).inspect}"
@ -242,7 +248,7 @@ module DFHack
def _get
v = DFHack.memory_read_int32(@_memaddr) >> @_shift
if @_len == 1
if @_len == 1 and not @_enum
((v & 1) == 0) ? false : true
else
v &= _mask
@ -252,7 +258,7 @@ module DFHack
end
def _set(v)
if @_len == 1
if @_len == 1 and (not @_enum or v == false or v == true)
# allow 'bit = 0'
v = (v && v != 0 ? 1 : 0)
end
@ -355,6 +361,7 @@ module DFHack
def empty? ; length == 0 ; end
def flatten ; map { |e| e.respond_to?(:flatten) ? e.flatten : e }.flatten ; end
def index(e=nil, &b) ; (0...length).find { |i| b ? b[self[i]] : self[i] == e } ; end
def map! ; (0...length).each { |i| self[i] = yield(self[i]) } ; end
def first ; self[0] ; end
def last ; self[length-1] ; end
end
@ -372,6 +379,9 @@ module DFHack
def _cpp_init
_length.times { |i| _tgat(i)._cpp_init }
end
def _cpp_delete
_length.times { |i| _tgat(i)._cpp_delete }
end
alias length _length
alias size _length
def _tgat(i)
@ -423,10 +433,10 @@ module DFHack
DFHack.memory_vector32_ptrat(@_memaddr, idx)
end
def insert_at(idx, val)
DFHack.memory_vector32_insert(@_memaddr, idx, val)
DFHack.memory_vector32_insertat(@_memaddr, idx, val)
end
def delete_at(idx)
DFHack.memory_vector32_delete(@_memaddr, idx)
DFHack.memory_vector32_deleteat(@_memaddr, idx)
end
def _set(v)
@ -434,6 +444,12 @@ module DFHack
v.each_with_index { |e, i| self[i] = e } # patch entries
end
def self._cpp_new
new._at DFHack.memory_vector_new
end
def _cpp_delete
DFHack.memory_vector_delete(@_memaddr)
end
def _cpp_init
DFHack.memory_vector_init(@_memaddr)
end
@ -496,10 +512,10 @@ module DFHack
DFHack.memory_vector16_ptrat(@_memaddr, idx)
end
def insert_at(idx, val)
DFHack.memory_vector16_insert(@_memaddr, idx, val)
DFHack.memory_vector16_insertat(@_memaddr, idx, val)
end
def delete_at(idx)
DFHack.memory_vector16_delete(@_memaddr, idx)
DFHack.memory_vector16_deleteat(@_memaddr, idx)
end
end
class StlVector8 < StlVector32
@ -510,10 +526,10 @@ module DFHack
DFHack.memory_vector8_ptrat(@_memaddr, idx)
end
def insert_at(idx, val)
DFHack.memory_vector8_insert(@_memaddr, idx, val)
DFHack.memory_vector8_insertat(@_memaddr, idx, val)
end
def delete_at(idx)
DFHack.memory_vector8_delete(@_memaddr, idx)
DFHack.memory_vector8_deleteat(@_memaddr, idx)
end
end
class StlBitVector < StlVector32
@ -522,10 +538,10 @@ module DFHack
DFHack.memory_vectorbool_length(@_memaddr)
end
def insert_at(idx, val)
DFHack.memory_vectorbool_insert(@_memaddr, idx, val)
DFHack.memory_vectorbool_insertat(@_memaddr, idx, val)
end
def delete_at(idx)
DFHack.memory_vectorbool_delete(@_memaddr, idx)
DFHack.memory_vectorbool_deleteat(@_memaddr, idx)
end
def [](idx)
idx += length if idx < 0
@ -541,6 +557,12 @@ module DFHack
DFHack.memory_vectorbool_setat(@_memaddr, idx, v)
end
end
def self._cpp_new
new._at DFHack.memory_vectorbool_new
end
def _cpp_delete
DFHack.memory_vectorbool_delete(@_memaddr)
end
end
class StlString < MemStruct
def _get
@ -551,6 +573,12 @@ module DFHack
DFHack.memory_write_stlstring(@_memaddr, v)
end
def self._cpp_new
new._at DFHack.memory_stlstring_new
end
def _cpp_delete
DFHack.memory_stlstring_delete(@_memaddr)
end
def _cpp_init
DFHack.memory_stlstring_init(@_memaddr)
end
@ -574,7 +602,7 @@ module DFHack
def length
DFHack.memory_bitarray_length(@_memaddr)
end
# TODO _cpp_init
# TODO _cpp_init, _cpp_delete
def size ; length ; end
def resize(len)
DFHack.memory_bitarray_resize(@_memaddr, len)
@ -608,7 +636,7 @@ module DFHack
def length ; _length ; end
def size ; _length ; end
# TODO _cpp_init
# TODO _cpp_init, _cpp_delete
def _tgat(i)
@_tg._at(_ptr + i*@_tglen) if i >= 0 and i < _length
end
@ -638,9 +666,9 @@ module DFHack
@_tg = tg
end
field(:_ptr, 0) { number 32, false }
field(:_prev, 4) { number 32, false }
field(:_next, 8) { number 32, false }
field(:_ptr, 0) { pointer }
field(:_prev, 4) { pointer }
field(:_next, 8) { pointer }
def item
# With the current xml structure, currently _tg designate
@ -654,22 +682,24 @@ module DFHack
def item=(v)
#addr = _ptr
#raise 'null pointer' if addr == 0
#raise 'null pointer' if not addr
#@_tg.at(addr)._set(v)
raise 'null pointer'
end
def prev
addr = _prev
return if addr == 0
return if not addr
@_tg._at(addr)._get
end
def next
addr = _next
return if addr == 0
return if not addr
@_tg._at(addr)._get
end
alias next= _next=
alias prev= _prev=
include Enumerable
def each
@ -702,6 +732,21 @@ module DFHack
def self.sym(v) ; (!v || (v == 0)) ? false : true ; end
end
class StlString < MemHack::Compound
field(:str, 0) { stl_string }
def self.cpp_new(init=nil)
s = MemHack::StlString._cpp_new
s._set(init) if init
new._at(s._memaddr)
end
def _cpp_delete
MemHack::StlString.new._at(@_memaddr+0)._cpp_delete
@_memaddr = nil
end
end
# cpp rtti name -> rb class
@rtti_n2c = {}
@rtti_c2n = {}

@ -4,6 +4,7 @@
#include "Export.h"
#include "PluginManager.h"
#include "VersionInfo.h"
#include "MemAccess.h"
#include "DataDefs.h"
#include "df/global_objects.h"
@ -528,7 +529,7 @@ static VALUE rb_dfmalloc(VALUE self, VALUE len)
if (!ptr)
return Qnil;
memset(ptr, 0, FIX2INT(len));
return rb_uint2inum((long)ptr);
return rb_uint2inum((uint32_t)ptr);
}
static VALUE rb_dffree(VALUE self, VALUE ptr)
@ -597,8 +598,59 @@ static VALUE rb_dfmemory_write_float(VALUE self, VALUE addr, VALUE val)
return Qtrue;
}
// return memory permissions at address (eg "rx", nil if unmapped)
static VALUE rb_dfmemory_check(VALUE self, VALUE addr)
{
void *ptr = (void*)rb_num2ulong(addr);
std::vector<t_memrange> ranges;
Core::getInstance().p->getMemRanges(ranges);
unsigned i = 0;
while (i < ranges.size() && ranges[i].end <= ptr)
i++;
if (i >= ranges.size() || ranges[i].start > ptr || !ranges[i].valid)
return Qnil;
std::string perm = "";
if (ranges[i].read)
perm += "r";
if (ranges[i].write)
perm += "w";
if (ranges[i].execute)
perm += "x";
if (ranges[i].shared)
perm += "s";
return rb_str_new(perm.c_str(), perm.length());
}
// memory write (tmp override page permissions, eg patch code)
static VALUE rb_dfmemory_patch(VALUE self, VALUE addr, VALUE raw)
{
int strlen = FIX2INT(rb_funcall(raw, rb_intern("length"), 0));
bool ret;
ret = Core::getInstance().p->patchMemory((void*)rb_num2ulong(addr),
rb_string_value_ptr(&raw), strlen);
return ret ? Qtrue : Qfalse;
}
// stl::string
static VALUE rb_dfmemory_stlstring_new(VALUE self)
{
std::string *ptr = new std::string;
return rb_uint2inum((uint32_t)ptr);
}
static VALUE rb_dfmemory_stlstring_delete(VALUE self, VALUE addr)
{
std::string *ptr = (std::string*)rb_num2ulong(addr);
if (ptr)
delete ptr;
return Qtrue;
}
static VALUE rb_dfmemory_stlstring_init(VALUE self, VALUE addr)
{
// XXX THIS IS TERRIBLE
@ -621,6 +673,18 @@ static VALUE rb_dfmemory_write_stlstring(VALUE self, VALUE addr, VALUE val)
// vector access
static VALUE rb_dfmemory_vec_new(VALUE self)
{
std::vector<uint8_t> *ptr = new std::vector<uint8_t>;
return rb_uint2inum((uint32_t)ptr);
}
static VALUE rb_dfmemory_vec_delete(VALUE self, VALUE addr)
{
std::vector<uint8_t> *ptr = (std::vector<uint8_t>*)rb_num2ulong(addr);
if (ptr)
delete ptr;
return Qtrue;
}
static VALUE rb_dfmemory_vec_init(VALUE self, VALUE addr)
{
std::vector<uint8_t> *ptr = new std::vector<uint8_t>;
@ -638,13 +702,13 @@ static VALUE rb_dfmemory_vec8_ptrat(VALUE self, VALUE addr, VALUE idx)
std::vector<uint8_t> *v = (std::vector<uint8_t>*)rb_num2ulong(addr);
return rb_uint2inum((uint32_t)&v->at(FIX2INT(idx)));
}
static VALUE rb_dfmemory_vec8_insert(VALUE self, VALUE addr, VALUE idx, VALUE val)
static VALUE rb_dfmemory_vec8_insertat(VALUE self, VALUE addr, VALUE idx, VALUE val)
{
std::vector<uint8_t> *v = (std::vector<uint8_t>*)rb_num2ulong(addr);
v->insert(v->begin()+FIX2INT(idx), rb_num2ulong(val));
return Qtrue;
}
static VALUE rb_dfmemory_vec8_delete(VALUE self, VALUE addr, VALUE idx)
static VALUE rb_dfmemory_vec8_deleteat(VALUE self, VALUE addr, VALUE idx)
{
std::vector<uint8_t> *v = (std::vector<uint8_t>*)rb_num2ulong(addr);
v->erase(v->begin()+FIX2INT(idx));
@ -662,13 +726,13 @@ static VALUE rb_dfmemory_vec16_ptrat(VALUE self, VALUE addr, VALUE idx)
std::vector<uint16_t> *v = (std::vector<uint16_t>*)rb_num2ulong(addr);
return rb_uint2inum((uint32_t)&v->at(FIX2INT(idx)));
}
static VALUE rb_dfmemory_vec16_insert(VALUE self, VALUE addr, VALUE idx, VALUE val)
static VALUE rb_dfmemory_vec16_insertat(VALUE self, VALUE addr, VALUE idx, VALUE val)
{
std::vector<uint16_t> *v = (std::vector<uint16_t>*)rb_num2ulong(addr);
v->insert(v->begin()+FIX2INT(idx), rb_num2ulong(val));
return Qtrue;
}
static VALUE rb_dfmemory_vec16_delete(VALUE self, VALUE addr, VALUE idx)
static VALUE rb_dfmemory_vec16_deleteat(VALUE self, VALUE addr, VALUE idx)
{
std::vector<uint16_t> *v = (std::vector<uint16_t>*)rb_num2ulong(addr);
v->erase(v->begin()+FIX2INT(idx));
@ -686,13 +750,13 @@ static VALUE rb_dfmemory_vec32_ptrat(VALUE self, VALUE addr, VALUE idx)
std::vector<uint32_t> *v = (std::vector<uint32_t>*)rb_num2ulong(addr);
return rb_uint2inum((uint32_t)&v->at(FIX2INT(idx)));
}
static VALUE rb_dfmemory_vec32_insert(VALUE self, VALUE addr, VALUE idx, VALUE val)
static VALUE rb_dfmemory_vec32_insertat(VALUE self, VALUE addr, VALUE idx, VALUE val)
{
std::vector<uint32_t> *v = (std::vector<uint32_t>*)rb_num2ulong(addr);
v->insert(v->begin()+FIX2INT(idx), rb_num2ulong(val));
return Qtrue;
}
static VALUE rb_dfmemory_vec32_delete(VALUE self, VALUE addr, VALUE idx)
static VALUE rb_dfmemory_vec32_deleteat(VALUE self, VALUE addr, VALUE idx)
{
std::vector<uint32_t> *v = (std::vector<uint32_t>*)rb_num2ulong(addr);
v->erase(v->begin()+FIX2INT(idx));
@ -700,6 +764,24 @@ static VALUE rb_dfmemory_vec32_delete(VALUE self, VALUE addr, VALUE idx)
}
// vector<bool>
static VALUE rb_dfmemory_vecbool_new(VALUE self)
{
std::vector<bool> *ptr = new std::vector<bool>;
return rb_uint2inum((uint32_t)ptr);
}
static VALUE rb_dfmemory_vecbool_delete(VALUE self, VALUE addr)
{
std::vector<bool> *ptr = (std::vector<bool>*)rb_num2ulong(addr);
if (ptr)
delete ptr;
return Qtrue;
}
static VALUE rb_dfmemory_vecbool_init(VALUE self, VALUE addr)
{
std::vector<bool> *ptr = new std::vector<bool>;
memcpy((void*)rb_num2ulong(addr), (void*)ptr, sizeof(*ptr));
return Qtrue;
}
static VALUE rb_dfmemory_vecbool_length(VALUE self, VALUE addr)
{
std::vector<bool> *v = (std::vector<bool>*)rb_num2ulong(addr);
@ -716,13 +798,13 @@ static VALUE rb_dfmemory_vecbool_setat(VALUE self, VALUE addr, VALUE idx, VALUE
v->at(FIX2INT(idx)) = (BOOL_ISFALSE(val) ? 0 : 1);
return Qtrue;
}
static VALUE rb_dfmemory_vecbool_insert(VALUE self, VALUE addr, VALUE idx, VALUE val)
static VALUE rb_dfmemory_vecbool_insertat(VALUE self, VALUE addr, VALUE idx, VALUE val)
{
std::vector<bool> *v = (std::vector<bool>*)rb_num2ulong(addr);
v->insert(v->begin()+FIX2INT(idx), (BOOL_ISFALSE(val) ? 0 : 1));
return Qtrue;
}
static VALUE rb_dfmemory_vecbool_delete(VALUE self, VALUE addr, VALUE idx)
static VALUE rb_dfmemory_vecbool_deleteat(VALUE self, VALUE addr, VALUE idx)
{
std::vector<bool> *v = (std::vector<bool>*)rb_num2ulong(addr);
v->erase(v->begin()+FIX2INT(idx));
@ -833,28 +915,37 @@ static void ruby_bind_dfhack(void) {
rb_define_singleton_method(rb_cDFHack, "memory_write_int16", RUBY_METHOD_FUNC(rb_dfmemory_write_int16), 2);
rb_define_singleton_method(rb_cDFHack, "memory_write_int32", RUBY_METHOD_FUNC(rb_dfmemory_write_int32), 2);
rb_define_singleton_method(rb_cDFHack, "memory_write_float", RUBY_METHOD_FUNC(rb_dfmemory_write_float), 2);
rb_define_singleton_method(rb_cDFHack, "memory_check", RUBY_METHOD_FUNC(rb_dfmemory_check), 1);
rb_define_singleton_method(rb_cDFHack, "memory_patch", RUBY_METHOD_FUNC(rb_dfmemory_patch), 2);
rb_define_singleton_method(rb_cDFHack, "memory_stlstring_new", RUBY_METHOD_FUNC(rb_dfmemory_stlstring_new), 0);
rb_define_singleton_method(rb_cDFHack, "memory_stlstring_delete", RUBY_METHOD_FUNC(rb_dfmemory_stlstring_delete), 1);
rb_define_singleton_method(rb_cDFHack, "memory_stlstring_init", RUBY_METHOD_FUNC(rb_dfmemory_stlstring_init), 1);
rb_define_singleton_method(rb_cDFHack, "memory_read_stlstring", RUBY_METHOD_FUNC(rb_dfmemory_read_stlstring), 1);
rb_define_singleton_method(rb_cDFHack, "memory_write_stlstring", RUBY_METHOD_FUNC(rb_dfmemory_write_stlstring), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vector_new", RUBY_METHOD_FUNC(rb_dfmemory_vec_new), 0);
rb_define_singleton_method(rb_cDFHack, "memory_vector_delete", RUBY_METHOD_FUNC(rb_dfmemory_vec_delete), 1);
rb_define_singleton_method(rb_cDFHack, "memory_vector_init", RUBY_METHOD_FUNC(rb_dfmemory_vec_init), 1);
rb_define_singleton_method(rb_cDFHack, "memory_vector8_length", RUBY_METHOD_FUNC(rb_dfmemory_vec8_length), 1);
rb_define_singleton_method(rb_cDFHack, "memory_vector8_ptrat", RUBY_METHOD_FUNC(rb_dfmemory_vec8_ptrat), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vector8_insert", RUBY_METHOD_FUNC(rb_dfmemory_vec8_insert), 3);
rb_define_singleton_method(rb_cDFHack, "memory_vector8_delete", RUBY_METHOD_FUNC(rb_dfmemory_vec8_delete), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vector8_insertat", RUBY_METHOD_FUNC(rb_dfmemory_vec8_insertat), 3);
rb_define_singleton_method(rb_cDFHack, "memory_vector8_deleteat", RUBY_METHOD_FUNC(rb_dfmemory_vec8_deleteat), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vector16_length", RUBY_METHOD_FUNC(rb_dfmemory_vec16_length), 1);
rb_define_singleton_method(rb_cDFHack, "memory_vector16_ptrat", RUBY_METHOD_FUNC(rb_dfmemory_vec16_ptrat), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vector16_insert", RUBY_METHOD_FUNC(rb_dfmemory_vec16_insert), 3);
rb_define_singleton_method(rb_cDFHack, "memory_vector16_delete", RUBY_METHOD_FUNC(rb_dfmemory_vec16_delete), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vector16_insertat", RUBY_METHOD_FUNC(rb_dfmemory_vec16_insertat), 3);
rb_define_singleton_method(rb_cDFHack, "memory_vector16_deleteat", RUBY_METHOD_FUNC(rb_dfmemory_vec16_deleteat), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vector32_length", RUBY_METHOD_FUNC(rb_dfmemory_vec32_length), 1);
rb_define_singleton_method(rb_cDFHack, "memory_vector32_ptrat", RUBY_METHOD_FUNC(rb_dfmemory_vec32_ptrat), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vector32_insert", RUBY_METHOD_FUNC(rb_dfmemory_vec32_insert), 3);
rb_define_singleton_method(rb_cDFHack, "memory_vector32_delete", RUBY_METHOD_FUNC(rb_dfmemory_vec32_delete), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vector32_insertat", RUBY_METHOD_FUNC(rb_dfmemory_vec32_insertat), 3);
rb_define_singleton_method(rb_cDFHack, "memory_vector32_deleteat", RUBY_METHOD_FUNC(rb_dfmemory_vec32_deleteat), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vectorbool_new", RUBY_METHOD_FUNC(rb_dfmemory_vecbool_new), 0);
rb_define_singleton_method(rb_cDFHack, "memory_vectorbool_delete", RUBY_METHOD_FUNC(rb_dfmemory_vecbool_delete), 1);
rb_define_singleton_method(rb_cDFHack, "memory_vectorbool_init", RUBY_METHOD_FUNC(rb_dfmemory_vecbool_init), 1);
rb_define_singleton_method(rb_cDFHack, "memory_vectorbool_length", RUBY_METHOD_FUNC(rb_dfmemory_vecbool_length), 1);
rb_define_singleton_method(rb_cDFHack, "memory_vectorbool_at", RUBY_METHOD_FUNC(rb_dfmemory_vecbool_at), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vectorbool_setat", RUBY_METHOD_FUNC(rb_dfmemory_vecbool_setat), 3);
rb_define_singleton_method(rb_cDFHack, "memory_vectorbool_insert", RUBY_METHOD_FUNC(rb_dfmemory_vecbool_insert), 3);
rb_define_singleton_method(rb_cDFHack, "memory_vectorbool_delete", RUBY_METHOD_FUNC(rb_dfmemory_vecbool_delete), 2);
rb_define_singleton_method(rb_cDFHack, "memory_vectorbool_insertat", RUBY_METHOD_FUNC(rb_dfmemory_vecbool_insertat), 3);
rb_define_singleton_method(rb_cDFHack, "memory_vectorbool_deleteat", RUBY_METHOD_FUNC(rb_dfmemory_vecbool_deleteat), 2);
rb_define_singleton_method(rb_cDFHack, "memory_bitarray_length", RUBY_METHOD_FUNC(rb_dfmemory_bitarray_length), 1);
rb_define_singleton_method(rb_cDFHack, "memory_bitarray_resize", RUBY_METHOD_FUNC(rb_dfmemory_bitarray_resize), 2);
rb_define_singleton_method(rb_cDFHack, "memory_bitarray_isset", RUBY_METHOD_FUNC(rb_dfmemory_bitarray_isset), 2);

@ -68,5 +68,14 @@ module DFHack
world.status.display_timer = 2000
end
end
# add an announcement to display in a game popup message
# (eg "the megabeast foobar arrived")
def popup_announcement(str, color=nil, bright=nil)
pop = PopupMessage.cpp_new(:text => str)
pop.color = color if color
pop.bright = bright if bright
world.status.popups << pop
end
end
end

@ -41,48 +41,60 @@ module DFHack
# returns an Array of all units that are current fort citizen (dwarves, on map, not hostile)
def unit_citizens
race = ui.race_id
civ = ui.civ_id
world.units.active.find_all { |u|
u.race == race and u.civ_id == civ and !u.flags1.dead and !u.flags1.merchant and
!u.flags1.diplomat and !u.flags2.resident and !u.flags3.ghostly and
!u.curse.add_tags1.OPPOSED_TO_LIFE and !u.curse.add_tags1.CRAZED and
u.mood != :Berserk
# TODO check curse ; currently this should keep vampires, but may include werebeasts
unit_iscitizen(u)
}
end
def unit_iscitizen(u)
u.race == ui.race_id and u.civ_id == ui.civ_id and !u.flags1.dead and !u.flags1.merchant and
!u.flags1.diplomat and !u.flags2.resident and !u.flags3.ghostly and
!u.curse.add_tags1.OPPOSED_TO_LIFE and !u.curse.add_tags1.CRAZED and
u.mood != :Berserk
# TODO check curse ; currently this should keep vampires, but may include werebeasts
end
# list workers (citizen, not crazy / child / inmood / noble)
def unit_workers
unit_citizens.find_all { |u|
u.mood == :None and
u.profession != :CHILD and
u.profession != :BABY and
# TODO MENIAL_WORK_EXEMPTION_SPOUSE
!unit_entitypositions(u).find { |pos| pos.flags[:MENIAL_WORK_EXEMPTION] }
world.units.active.find_all { |u|
unit_isworker(u)
}
end
def unit_isworker(u)
unit_iscitizen(u) and
u.mood == :None and
u.profession != :CHILD and
u.profession != :BABY and
# TODO MENIAL_WORK_EXEMPTION_SPOUSE
!unit_entitypositions(u).find { |pos| pos.flags[:MENIAL_WORK_EXEMPTION] }
end
# list currently idle workers
def unit_idlers
unit_workers.find_all { |u|
# current_job includes eat/drink/sleep/pickupequip
!u.job.current_job and
# filter 'attend meeting'
not u.specific_refs.find { |s| s.type == :ACTIVITY } and
# filter soldiers (TODO check schedule)
u.military.squad_index == -1 and
# filter 'on break'
not u.status.misc_traits.find { |t| t.id == :OnBreak }
world.units.active.find_all { |u|
unit_isidler(u)
}
end
def unit_isidler(u)
unit_isworker(u) and
# current_job includes eat/drink/sleep/pickupequip
!u.job.current_job and
# filter 'attend meeting'
not u.specific_refs.find { |s| s.type == :ACTIVITY } and
# filter soldiers (TODO check schedule)
u.military.squad_index == -1 and
# filter 'on break'
not u.status.misc_traits.find { |t| t.id == :OnBreak }
end
def unit_entitypositions(unit)
list = []
return list if not hf = world.history.figures.binsearch(unit.hist_figure_id)
return list if not hf = unit.hist_figure_tg
hf.entity_links.each { |el|
next if el._rtti_classname != :histfig_entity_link_positionst
next if not ent = world.entities.all.binsearch(el.entity_id)
next if not ent = el.entity_tg
next if not pa = ent.positions.assignments.binsearch(el.assignment_id)
next if not pos = ent.positions.own.binsearch(pa.position_id)
list << pos

@ -111,7 +111,8 @@ command_result df_seedwatch(color_ostream &out, vector<string>& parameters)
w->ReadGameMode(gm);// FIXME: check return value
// if game mode isn't fortress mode
if(gm.g_mode != game_mode::DWARF || gm.g_type != game_type::DWARF_MAIN)
if(gm.g_mode != game_mode::DWARF ||
!(gm.g_type == game_type::DWARF_MAIN || gm.g_type == game_type::DWARF_RECLAIM))
{
// just print the help
printHelp(out);
@ -299,7 +300,8 @@ DFhackCExport command_result plugin_onupdate(color_ostream &out)
t_gamemodes gm;
w->ReadGameMode(gm);// FIXME: check return value
// if game mode isn't fortress mode
if(gm.g_mode != game_mode::DWARF || gm.g_type != game_type::DWARF_MAIN)
if(gm.g_mode != game_mode::DWARF ||
!(gm.g_type == game_type::DWARF_MAIN || gm.g_type == game_type::DWARF_RECLAIM))
{
// stop running.
running = false;

@ -12,6 +12,7 @@
#include "df/world.h"
#include "df/job.h"
#include "df/job_item.h"
#include "df/job_item_ref.h"
#include "df/general_ref.h"
#include "df/builtin_mats.h"
#include "df/inorganic_raw.h"
@ -165,7 +166,10 @@ command_result df_showmood (color_ostream &out, vector <string> & parameters)
out.print("not yet claimed a workshop but will want");
out.print(" the following items:\n");
int count_got = job->items.size(), got;
// total amount of stuff fetched so far
int count_got = 0;
for (size_t i = 0; i < job->items.size(); i++)
count_got += job->items[i]->item->getTotalDimension();
for (size_t i = 0; i < job->job_items.size(); i++)
{
@ -269,7 +273,9 @@ command_result df_showmood (color_ostream &out, vector <string> & parameters)
}
}
got = count_got;
// total amount of stuff fetched for this requirement
// XXX may fail with cloth/thread/bars if need 1 and fetch 2
int got = count_got;
if (got > item->quantity)
got = item->quantity;
out.print(", quantity %i (got %i)\n", item->quantity, got);

@ -431,12 +431,17 @@ DEFINE_SORT_HANDLER(unit_sorters, dwarfmode, "/QueryBuilding/Some/Assign", scree
sort_null_first(parameters);
PARSE_SPEC("units", parameters);
if (compute_order(*pout, L, top, &order, *ui_building_assign_units))
{
reorder_cursor(ui_building_item_cursor, order);
reorder_vector(ui_building_assign_type, order);
reorder_vector(ui_building_assign_units, order);
// this is for cages. cages need some extra sorting
if(ui_building_assign_items->size() == ui_building_assign_units->size())
{
reorder_vector(ui_building_assign_items, order);
reorder_vector(ui_building_assign_is_marked, order);
}
}
}

@ -1 +1 @@
Subproject commit 17b653665567a5f1df628217820f76bb0b9c70a5
Subproject commit 2a62ba5ed2607f4dbf0473e77502d4e19c19678e

@ -13,6 +13,7 @@
#include "MiscUtils.h"
#include "DataDefs.h"
#include <VTableInterpose.h>
#include "df/ui.h"
#include "df/world.h"
#include "df/squad.h"
@ -26,6 +27,8 @@
#include "df/death_info.h"
#include "df/criminal_case.h"
#include "df/unit_inventory_item.h"
#include "df/viewscreen_dwarfmodest.h"
#include "df/squad_order_trainst.h"
#include <stdlib.h>
@ -67,6 +70,13 @@ DFhackCExport command_result plugin_init (color_ostream &out, std::vector <Plugi
" (humans, elves) can be put to work, but you can't assign rooms\n"
" to them and they don't show up in DwarfTherapist because the\n"
" game treats them like pets.\n"
" tweak stable-cursor [disable]\n"
" Keeps exact position of dwarfmode cursor during exits to main menu.\n"
" E.g. allows switching between t/q/k/d without losing position.\n"
" tweak patrol-duty [disable]\n"
" Causes 'Train' orders to no longer be considered 'patrol duty' so\n"
" soldiers will stop getting unhappy thoughts. Does NOT fix the problem\n"
" when soldiers go off-duty (i.e. civilian).\n"
));
return CR_OK;
}
@ -76,9 +86,6 @@ DFhackCExport command_result plugin_shutdown (color_ostream &out)
return CR_OK;
}
static command_result lair(color_ostream &out, std::vector<std::string> & params);
// to be called by tweak-fixmigrant
// units forced into the fort by removing the flags do not own their clothes
// which has the result that they drop all their clothes and become unhappy because they are naked
@ -136,6 +143,65 @@ command_result fix_clothing_ownership(color_ostream &out, df::unit* unit)
return CR_OK;
}
/*
* Save or restore cursor position on change to/from main dwarfmode menu.
*/
static df::coord last_view, last_cursor;
struct stable_cursor_hook : df::viewscreen_dwarfmodest
{
typedef df::viewscreen_dwarfmodest interpose_base;
DEFINE_VMETHOD_INTERPOSE(void, feed, (set<df::interface_key> *input))
{
bool was_default = (ui->main.mode == df::ui_sidebar_mode::Default);
df::coord view = Gui::getViewportPos();
df::coord cursor = Gui::getCursorPos();
INTERPOSE_NEXT(feed)(input);
bool is_default = (ui->main.mode == df::ui_sidebar_mode::Default);
df::coord cur_cursor = Gui::getCursorPos();
if (is_default && !was_default)
{
last_view = view; last_cursor = cursor;
}
else if (!is_default && was_default &&
Gui::getViewportPos() == last_view &&
last_cursor.isValid() && cur_cursor.isValid())
{
Gui::setCursorCoords(last_cursor.x, last_cursor.y, last_cursor.z);
// Force update of ui state
set<df::interface_key> tmp;
tmp.insert(interface_key::CURSOR_DOWN_Z);
INTERPOSE_NEXT(feed)(&tmp);
tmp.clear();
tmp.insert(interface_key::CURSOR_UP_Z);
INTERPOSE_NEXT(feed)(&tmp);
}
else if (cur_cursor.isValid())
{
last_cursor = df::coord();
}
}
};
struct patrol_duty_hook : df::squad_order_trainst
{
typedef df::squad_order_trainst interpose_base;
DEFINE_VMETHOD_INTERPOSE(bool, isPatrol, ())
{
return false;
}
};
IMPLEMENT_VMETHOD_INTERPOSE(stable_cursor_hook, feed);
IMPLEMENT_VMETHOD_INTERPOSE(patrol_duty_hook, isPatrol);
static command_result tweak(color_ostream &out, vector <string> &parameters)
{
CoreSuspender suspend;
@ -234,6 +300,22 @@ static command_result tweak(color_ostream &out, vector <string> &parameters)
unit->profession2 = df::profession::TRADER;
return fix_clothing_ownership(out, unit);
}
else if (cmd == "stable-cursor")
{
auto &hook = INTERPOSE_HOOK(stable_cursor_hook, feed);
if (vector_get(parameters, 1) == "disable")
hook.remove();
else
hook.apply();
}
else if (cmd == "patrol-duty")
{
auto &hook = INTERPOSE_HOOK(patrol_duty_hook, isPatrol);
if (vector_get(parameters, 1) == "disable")
hook.remove();
else
hook.apply();
}
else
return CR_WRONG_USAGE;

@ -20,6 +20,7 @@
#include "df/job_list_link.h"
#include "df/dfhack_material_category.h"
#include "df/item.h"
#include "df/item_quality.h"
#include "df/items_other_id.h"
#include "df/tool_uses.h"
#include "df/general_ref.h"
@ -283,6 +284,8 @@ struct ItemConstraint {
int weight;
std::vector<ProtectedJob*> jobs;
item_quality::item_quality min_quality;
int item_amount, item_count, item_inuse;
bool request_suspend, request_resume;
@ -292,8 +295,8 @@ struct ItemConstraint {
public:
ItemConstraint()
: is_craft(false), weight(0), item_amount(0), item_count(0), item_inuse(0)
, is_active(false), cant_resume_reported(false)
: is_craft(false), weight(0), min_quality(item_quality::Ordinary),item_amount(0),
item_count(0), item_inuse(0), is_active(false), cant_resume_reported(false)
{}
int goalCount() { return config.ival(0); }
@ -646,7 +649,7 @@ static ItemConstraint *get_constraint(color_ostream &out, const std::string &str
std::vector<std::string> tokens;
split_string(&tokens, str, "/");
if (tokens.size() > 3)
if (tokens.size() > 4)
return NULL;
int weight = 0;
@ -681,6 +684,21 @@ static ItemConstraint *get_constraint(color_ostream &out, const std::string &str
return NULL;
}
item_quality::item_quality minqual = item_quality::Ordinary;
std::string qualstr = vector_get(tokens, 3);
if(!qualstr.empty()) {
if(qualstr == "ordinary") minqual = item_quality::Ordinary;
else if(qualstr == "wellcrafted") minqual = item_quality::WellCrafted;
else if(qualstr == "finelycrafted") minqual = item_quality::FinelyCrafted;
else if(qualstr == "superior") minqual = item_quality::Superior;
else if(qualstr == "exceptional") minqual = item_quality::Exceptional;
else if(qualstr == "masterful") minqual = item_quality::Masterful;
else {
out.printerr("Cannot find quality: %s\nKnown qualities: ordinary, wellcrafted, finelycrafted, superior, exceptional, masterful\n", qualstr.c_str());
return NULL;
}
}
if (material.type >= 0)
weight += (material.index >= 0 ? 5000 : 1000);
@ -694,7 +712,8 @@ static ItemConstraint *get_constraint(color_ostream &out, const std::string &str
ItemConstraint *ct = constraints[i];
if (ct->is_craft == is_craft &&
ct->item == item && ct->material == material &&
ct->mat_mask.whole == mat_mask.whole)
ct->mat_mask.whole == mat_mask.whole &&
ct->min_quality == minqual)
return ct;
}
@ -703,6 +722,7 @@ static ItemConstraint *get_constraint(color_ostream &out, const std::string &str
nct->item = item;
nct->material = material;
nct->mat_mask = mat_mask;
nct->min_quality = minqual;
nct->weight = weight;
if (cfg)
@ -1179,6 +1199,9 @@ static void map_job_items(color_ostream &out)
(cv->item.subtype != -1 && cv->item.subtype != isubtype))
continue;
}
if(item->getQuality() < cv->min_quality) {
continue;
}
TMaterialCache::iterator it = cv->material_cache.find(matkey);
@ -1357,15 +1380,15 @@ static void print_constraint(color_ostream &out, ItemConstraint *cv, bool no_job
{
Console::color_value color;
if (cv->request_resume)
color = Console::COLOR_GREEN;
color = COLOR_GREEN;
else if (cv->request_suspend)
color = Console::COLOR_CYAN;
color = COLOR_CYAN;
else
color = Console::COLOR_DARKGREY;
color = COLOR_DARKGREY;
out.color(color);
out << prefix << "Constraint " << flush;
out.color(Console::COLOR_GREY);
out.color(COLOR_GREY);
out << cv->config.val() << " " << flush;
out.color(color);
out << (cv->goalByCount() ? "count " : "amount ")
@ -1414,18 +1437,18 @@ static void print_constraint(color_ostream &out, ItemConstraint *cv, bool no_job
{
if (pj->want_resumed)
{
out.color(Console::COLOR_YELLOW);
out.color(COLOR_YELLOW);
out << start << " (delayed)" << endl;
}
else
{
out.color(Console::COLOR_BLUE);
out.color(COLOR_BLUE);
out << start << " (suspended)" << endl;
}
}
else
{
out.color(Console::COLOR_GREEN);
out.color(COLOR_GREEN);
out << start << endl;
}
@ -1449,11 +1472,11 @@ static void print_job(color_ostream &out, ProtectedJob *pj)
isOptionEnabled(CF_AUTOMELT))
{
if (meltable_count <= 0)
out.color(Console::COLOR_CYAN);
out.color(COLOR_CYAN);
else if (pj->want_resumed && !pj->isActuallyResumed())
out.color(Console::COLOR_YELLOW);
out.color(COLOR_YELLOW);
else
out.color(Console::COLOR_GREEN);
out.color(COLOR_GREEN);
out << " Meltable: " << meltable_count << " objects." << endl;
out.reset_color();
}
@ -1480,13 +1503,14 @@ static command_result workflow_cmd(color_ostream &out, vector <string> & paramet
}
df::building *workshop = NULL;
df::job *job = NULL;
//FIXME: unused variable!
//df::job *job = NULL;
if (Gui::dwarfmode_hotkey(Core::getTopViewscreen()) &&
ui->main.mode == ui_sidebar_mode::QueryBuilding)
{
workshop = world->selected_building;
job = Gui::getSelectedWorkshopJob(out, true);
//job = Gui::getSelectedWorkshopJob(out, true);
}
std::string cmd = parameters.empty() ? "list" : parameters[0];

@ -0,0 +1,9 @@
-- Force a migrants event in next 10 ticks.
df.global.timed_events:insert('#',{
new = true,
type = df.timed_event_type.Migrants,
season = df.global.cur_season,
season_ticks = df.global.cur_season_tick+1,
entity = df.historical_entity.find(df.global.ui.civ_id)
})

@ -0,0 +1,64 @@
# script to fix loyalty cascade, when you order your militia to kill friendly units
def fixunit(unit)
return if unit.race != df.ui.race_id or unit.civ_id != df.ui.civ_id
links = unit.hist_figure_tg.entity_links
fixed = false
# check if the unit is a civ renegade
if i1 = links.index { |l|
l.kind_of?(DFHack::HistfigEntityLinkFormerMemberst) and
l.entity_id == df.ui.civ_id
} and i2 = links.index { |l|
l.kind_of?(DFHack::HistfigEntityLinkEnemyst) and
l.entity_id == df.ui.civ_id
}
fixed = true
i1, i2 = i2, i1 if i1 > i2
links.delete_at i2
links.delete_at i1
links << DFHack::HistfigEntityLinkMemberst.cpp_new(:entity_id => df.ui.civ_id, :link_strength => 100)
df.add_announcement "fixloyalty: #{unit.name} is now a member of #{df.ui.civ_tg.name} again"
end
# check if the unit is a group renegade
if i1 = links.index { |l|
l.kind_of?(DFHack::HistfigEntityLinkFormerMemberst) and
l.entity_id == df.ui.group_id
} and i2 = links.index { |l|
l.kind_of?(DFHack::HistfigEntityLinkEnemyst) and
l.entity_id == df.ui.group_id
}
fixed = true
i1, i2 = i2, i1 if i1 > i2
links.delete_at i2
links.delete_at i1
links << DFHack::HistfigEntityLinkMemberst.cpp_new(:entity_id => df.ui.group_id, :link_strength => 100)
df.add_announcement "fixloyalty: #{unit.name} is now a member of #{df.ui.group_tg.name} again"
end
# fix the 'is an enemy' cache matrix (mark to be recalculated by the game when needed)
if fixed and unit.unknown8.enemy_status_slot != -1
i = unit.unknown8.enemy_status_slot
unit.unknown8.enemy_status_slot = -1
cache = df.world.enemy_status_cache
cache.slot_used[i] = false
cache.rel_map[i].map! { -1 }
cache.rel_map.each { |a| a[i] = -1 }
cache.next_slot = i if cache.next_slot > i
end
# return true if we actually fixed the unit
fixed
end
count = 0
df.unit_citizens.each { |u|
count += 1 if fixunit(u)
}
if count > 0
puts "loyalty cascade fixed (#{count} dwarves)"
else
puts "no loyalty cascade found"
end

@ -0,0 +1,40 @@
-- Communicates current population to mountainhomes to avoid cap overshooting.
-- The reason for population cap problems is that the population value it
-- is compared against comes from the last dwarven caravan that successfully
-- left for mountainhomes. This script instantly updates it.
-- Note that a migration wave can still overshoot the limit by 1-2 dwarves because
-- of the last migrant bringing his family. Likewise, king arrival ignores cap.
local args = {...}
local ui = df.global.ui
local ui_stats = ui.tasks
local civ = df.historical_entity.find(ui.civ_id)
if not civ then
qerror('No active fortress.')
end
local civ_stats = civ.activity_stats
if not civ_stats then
if args[1] ~= 'force' then
qerror('No caravan report object; use "fix/population-cap force" to create one')
end
print('Creating an empty statistics structure...')
civ.activity_stats = {
new = true,
created_weapons = { resize = #ui_stats.created_weapons },
known_creatures1 = { resize = #ui_stats.known_creatures1 },
known_creatures = { resize = #ui_stats.known_creatures },
known_plants1 = { resize = #ui_stats.known_plants1 },
known_plants = { resize = #ui_stats.known_plants },
}
civ_stats = civ.activity_stats
end
-- Use max to keep at least some of the original caravan communication idea
civ_stats.population = math.max(civ_stats.population, ui_stats.population)
print('Home civ notified about current population.')

@ -0,0 +1,22 @@
-- Test lua viewscreens.
local gui = require 'gui'
local text = 'Woohoo, lua viewscreen :)'
local screen = mkinstance(gui.FramedScreen, {
frame_style = gui.GREY_LINE_FRAME,
frame_title = 'Hello World',
frame_width = #text+6,
frame_height = 3,
onRenderBody = function(self, dc)
dc:seek(3,1):string(text, COLOR_LIGHTGREEN)
end,
onInput = function(self,keys)
if keys.LEAVESCREEN or keys.SELECT then
self:dismiss()
end
end
}):init()
screen:show()

@ -0,0 +1,263 @@
-- Interface front-end for liquids plugin.
local utils = require 'utils'
local gui = require 'gui'
local guidm = require 'gui.dwarfmode'
local liquids = require('plugins.liquids')
local sel_rect = df.global.selection_rect
local brushes = {
{ tag = 'range', caption = 'Rectangle', range = true },
{ tag = 'block', caption = '16x16 block' },
{ tag = 'column', caption = 'Column' },
{ tag = 'flood', caption = 'Flood' },
}
local paints = {
{ tag = 'water', caption = 'Water', liquid = true, flow = true, key = 'w' },
{ tag = 'magma', caption = 'Magma', liquid = true, flow = true, key = 'l' },
{ tag = 'obsidian', caption = 'Obsidian Wall' },
{ tag = 'obsidian_floor', caption = 'Obsidian Floor' },
{ tag = 'riversource', caption = 'River Source' },
{ tag = 'flowbits', caption = 'Flow Updates', flow = true },
{ tag = 'wclean', caption = 'Clean Salt/Stagnant' },
}
local flowbits = {
{ tag = '+', caption = 'Enable Updates' },
{ tag = '-', caption = 'Disable Updates' },
{ tag = '.', caption = 'Keep Updates' },
}
local setmode = {
{ tag = '.', caption = 'Set Exactly' },
{ tag = '+', caption = 'Only Increase' },
{ tag = '-', caption = 'Only Decrease' },
}
local permaflows = {
{ tag = '.', caption = "Keep Permaflow" },
{ tag = '-', caption = 'Remove Permaflow' },
{ tag = 'N', caption = 'Set Permaflow N' },
{ tag = 'S', caption = 'Set Permaflow S' },
{ tag = 'E', caption = 'Set Permaflow E' },
{ tag = 'W', caption = 'Set Permaflow W' },
{ tag = 'NE', caption = 'Set Permaflow NE' },
{ tag = 'NW', caption = 'Set Permaflow NW' },
{ tag = 'SE', caption = 'Set Permaflow SE' },
{ tag = 'SW', caption = 'Set Permaflow SW' },
}
Toggle = defclass(Toggle)
function Toggle:init(items)
self:init_fields{
items = items,
selected = 1
}
return self
end
function Toggle:get()
return self.items[self.selected]
end
function Toggle:render(dc)
local item = self:get()
if item then
dc:string(item.caption)
if item.key then
dc:string(" ("):string(item.key, COLOR_LIGHTGREEN):string(")")
end
else
dc:string('NONE', COLOR_RED)
end
end
function Toggle:step(delta)
if #self.items > 1 then
delta = delta or 1
self.selected = 1 + (self.selected + delta - 1) % #self.items
end
end
LiquidsUI = defclass(LiquidsUI, guidm.MenuOverlay)
LiquidsUI.focus_path = 'liquids'
function LiquidsUI:init()
self:init_fields{
brush = mkinstance(Toggle):init(brushes),
paint = mkinstance(Toggle):init(paints),
flow = mkinstance(Toggle):init(flowbits),
set = mkinstance(Toggle):init(setmode),
permaflow = mkinstance(Toggle):init(permaflows),
amount = 7,
}
guidm.MenuOverlay.init(self)
return self
end
function LiquidsUI:onDestroy()
guidm.clearSelection()
end
function render_liquid(dc, block, x, y)
local dsgn = block.designation[x%16][y%16]
if dsgn.flow_size > 0 then
if dsgn.liquid_type == df.tile_liquid.Magma then
dc:pen(COLOR_RED):string("Magma")
else
dc:pen(COLOR_BLUE)
if dsgn.water_stagnant then dc:string("Stagnant ") end
if dsgn.water_salt then dc:string("Salty ") end
dc:string("Water")
end
dc:string(" ["..dsgn.flow_size.."/7]")
else
dc:string('No Liquid')
end
end
local permaflow_abbr = {
north = 'N', south = 'S', east = 'E', west = 'W',
northeast = 'NE', northwest = 'NW', southeast = 'SE', southwest = 'SW'
}
function render_flow_state(dc, block, x, y)
local flow = block.liquid_flow[x%16][y%16]
if block.flags.update_liquid then
dc:string("Updating", COLOR_GREEN)
else
dc:string("Static")
end
dc:string(", ")
if flow.perm_flow_dir ~= 0 then
local tag = df.tile_liquid_flow_dir[flow.perm_flow_dir]
dc:string("Permaflow "..(permaflow_abbr[tag] or tag), COLOR_CYAN)
elseif flow.temp_flow_timer > 0 then
dc:string("Flowing "..flow.temp_flow_timer, COLOR_GREEN)
else
dc:string("No Flow")
end
end
function LiquidsUI:onRenderBody(dc)
dc:clear():seek(1,1):string("Paint Liquids Cheat", COLOR_WHITE)
local cursor = guidm.getCursorPos()
local block = dfhack.maps.getTileBlock(cursor)
if block then
local x, y = pos2xyz(cursor)
local tile = block.tiletype[x%16][y%16]
dc:seek(2,3):string(df.tiletype.attrs[tile].caption, COLOR_CYAN)
dc:newline(2):pen(COLOR_DARKGREY)
render_liquid(dc, block, x, y)
dc:newline(2):pen(COLOR_DARKGREY)
render_flow_state(dc, block, x, y)
else
dc:seek(2,3):string("No map data", COLOR_RED):advance(0,2)
end
dc:newline():pen(COLOR_GREY)
dc:newline(1):string("b", COLOR_LIGHTGREEN):string(": ")
self.brush:render(dc)
dc:newline(1):string("p", COLOR_LIGHTGREEN):string(": ")
self.paint:render(dc)
local paint = self.paint:get()
dc:newline()
if paint.liquid then
dc:newline(1):string("Amount: "..self.amount)
dc:advance(1):string("("):string("-+", COLOR_LIGHTGREEN):string(")")
dc:newline(3):string("s", COLOR_LIGHTGREEN):string(": ")
self.set:render(dc)
else
dc:advance(0,2)
end
dc:newline()
if paint.flow then
dc:newline(1):string("f", COLOR_LIGHTGREEN):string(": ")
self.flow:render(dc)
dc:newline(1):string("r", COLOR_LIGHTGREEN):string(": ")
self.permaflow:render(dc)
else
dc:advance(0,2)
end
dc:newline():newline(1):pen(COLOR_WHITE)
dc:string("Esc", COLOR_LIGHTGREEN):string(": Back, ")
dc:string("Enter", COLOR_LIGHTGREEN):string(": Paint")
end
function LiquidsUI:onInput(keys)
local paint = self.paint:get()
local liquid = paint.liquid
if keys.CUSTOM_B then
self.brush:step()
elseif keys.CUSTOM_P then
self.paint:step()
elseif liquid and keys.SECONDSCROLL_UP then
self.amount = math.max(0, self.amount-1)
elseif liquid and keys.SECONDSCROLL_DOWN then
self.amount = math.min(7, self.amount+1)
elseif liquid and keys.CUSTOM_S then
self.set:step()
elseif paint.flow and keys.CUSTOM_F then
self.flow:step()
elseif paint.flow and keys.CUSTOM_R then
self.permaflow:step()
elseif keys.LEAVESCREEN then
if guidm.getSelection() then
guidm.clearSelection()
return
end
self:dismiss()
self:sendInputToParent('CURSOR_DOWN_Z')
self:sendInputToParent('CURSOR_UP_Z')
elseif keys.SELECT then
local cursor = guidm.getCursorPos()
local sp = guidm.getSelection()
local size = nil
if self.brush:get().range then
if not sp then
guidm.setSelectionStart(cursor)
return
else
guidm.clearSelection()
cursor, size = guidm.getSelectionRange(cursor, sp)
end
else
guidm.clearSelection()
end
liquids.paint(
cursor,
self.brush:get().tag, self.paint:get().tag,
self.amount, size,
self.set:get().tag, self.flow:get().tag,
self.permaflow:get().tag
)
elseif self:propagateMoveKeys(keys) then
return
elseif keys.D_LOOK_ARENA_WATER then
self.paint.selected = 1
elseif keys.D_LOOK_ARENA_MAGMA then
self.paint.selected = 2
end
end
if not string.match(dfhack.gui.getCurFocus(), '^dwarfmode/LookAround') then
qerror("This script requires the main dwarfmode view in 'k' mode")
end
local list = mkinstance(LiquidsUI):init()
list:show()

@ -0,0 +1,131 @@
-- Shows mechanisms linked to the current building.
local utils = require 'utils'
local gui = require 'gui'
local guidm = require 'gui.dwarfmode'
function listMechanismLinks(building)
local lst = {}
local function push(item, mode)
if item then
lst[#lst+1] = {
obj = item, mode = mode,
name = utils.getBuildingName(item)
}
end
end
push(building, 'self')
if not df.building_actual:is_instance(building) then
return lst
end
local item, tref, tgt
for _,v in ipairs(building.contained_items) do
item = v.item
if df.item_trappartsst:is_instance(item) then
tref = dfhack.items.getGeneralRef(item, df.general_ref_type.BUILDING_TRIGGER)
if tref then
push(tref:getBuilding(), 'trigger')
end
tref = dfhack.items.getGeneralRef(item, df.general_ref_type.BUILDING_TRIGGERTARGET)
if tref then
push(tref:getBuilding(), 'target')
end
end
end
return lst
end
MechanismList = defclass(MechanismList, guidm.MenuOverlay)
MechanismList.focus_path = 'mechanisms'
function MechanismList:init(building)
self:init_fields{
links = {}, selected = 1
}
guidm.MenuOverlay.init(self)
self:fillList(building)
return self
end
function MechanismList:fillList(building)
local links = listMechanismLinks(building)
self.old_viewport = self:getViewport()
self.old_cursor = guidm.getCursorPos()
if #links <= 1 then
links[1].mode = 'none'
end
self.links = links
self.selected = 1
end
local colors = {
self = COLOR_CYAN, none = COLOR_CYAN,
trigger = COLOR_GREEN, target = COLOR_GREEN
}
local icons = {
self = 128, none = 63, trigger = 27, target = 26
}
function MechanismList:onRenderBody(dc)
dc:clear()
dc:seek(1,1):string("Mechanism Links", COLOR_WHITE):newline()
for i,v in ipairs(self.links) do
local pen = { fg=colors[v.mode], bold = (i == self.selected) }
dc:newline(1):pen(pen):char(icons[v.mode])
dc:advance(1):string(v.name)
end
local nlinks = #self.links
if nlinks <= 1 then
dc:newline():newline(1):string("This building has no links", COLOR_LIGHTRED)
end
dc:newline():newline(1):pen(COLOR_WHITE)
dc:string("Esc", COLOR_LIGHTGREEN):string(": Back, ")
dc:string("Enter", COLOR_LIGHTGREEN):string(": Switch")
end
function MechanismList:changeSelected(delta)
if #self.links <= 1 then return end
self.selected = 1 + (self.selected + delta - 1) % #self.links
self:selectBuilding(self.links[self.selected].obj)
end
function MechanismList:onInput(keys)
if keys.SECONDSCROLL_UP then
self:changeSelected(-1)
elseif keys.SECONDSCROLL_DOWN then
self:changeSelected(1)
elseif keys.LEAVESCREEN then
self:dismiss()
if self.selected ~= 1 then
self:selectBuilding(self.links[1].obj, self.old_cursor, self.old_view)
end
elseif keys.SELECT_ALL then
if self.selected > 1 then
self:fillList(self.links[self.selected].obj)
end
elseif keys.SELECT then
self:dismiss()
elseif self:simulateViewScroll(keys) then
return
end
end
if dfhack.gui.getCurFocus() ~= 'dwarfmode/QueryBuilding/Some' then
qerror("This script requires the main dwarfmode view in 'q' mode")
end
local list = mkinstance(MechanismList):init(df.global.world.selected_building)
list:show()
list:changeSelected(1)

@ -0,0 +1,246 @@
-- Browses rooms owned by a unit.
local utils = require 'utils'
local gui = require 'gui'
local guidm = require 'gui.dwarfmode'
local room_type_table = {
[df.building_bedst] = { token = 'bed', qidx = 2, tile = 233 },
[df.building_tablest] = { token = 'table', qidx = 3, tile = 209 },
[df.building_chairst] = { token = 'chair', qidx = 4, tile = 210 },
[df.building_coffinst] = { token = 'coffin', qidx = 5, tile = 48 },
}
local room_quality_table = {
{ 1, 'Meager Quarters', 'Meager Dining Room', 'Meager Office', 'Grave' },
{ 100, 'Modest Quarters', 'Modest Dining Room', 'Modest Office', "Servant's Burial Chamber" },
{ 250, 'Quarters', 'Dining Room', 'Office', 'Burial Chamber' },
{ 500, 'Decent Quarters', 'Decent Dining Room', 'Decent Office', 'Tomb' },
{ 1000, 'Fine Quarters', 'Fine Dining Room', 'Splendid Office', 'Fine Tomb' },
{ 1500, 'Great Bedroom', 'Great Dining Room', 'Throne Room', 'Mausoleum' },
{ 2500, 'Grand Bedroom', 'Grand Dining Room', 'Opulent Throne Room', 'Grand Mausoleum' },
{ 10000, 'Royal Bedroom', 'Royal Dining Room', 'Royal Throne Room', 'Royal Mausoleum' }
}
function getRoomName(building, unit)
local info = room_type_table[building._type]
if not info or not building.is_room then
return utils.getBuildingName(building)
end
local quality = building:getRoomValue(unit)
local row = room_quality_table[1]
for _,v in ipairs(room_quality_table) do
if v[1] <= quality then
row = v
else
break
end
end
return row[info.qidx]
end
function makeRoomEntry(bld, unit, is_spouse)
local info = room_type_table[bld._type] or {}
return {
obj = bld,
token = info.token or '?',
tile = info.tile or '?',
caption = getRoomName(bld, unit),
can_use = (not is_spouse or bld:canUseSpouseRoom()),
owner = unit
}
end
function listRooms(unit, spouse)
local rv = {}
for _,v in pairs(unit.owned_buildings) do
if v.owner == unit then
rv[#rv+1] = makeRoomEntry(v, unit, spouse)
end
end
return rv
end
function concat_lists(...)
local rv = {}
for i = 1,select('#',...) do
local v = select(i,...)
if v then
for _,x in ipairs(v) do rv[#rv+1] = x end
end
end
return rv
end
RoomList = defclass(RoomList, guidm.MenuOverlay)
RoomList.focus_path = 'room-list'
function RoomList:init(unit)
local base_bld = df.global.world.selected_building
self:init_fields{
unit = unit, base_building = base_bld,
items = {}, selected = 1,
own_rooms = {}, spouse_rooms = {}
}
guidm.MenuOverlay.init(self)
self.old_viewport = self:getViewport()
self.old_cursor = guidm.getCursorPos()
if unit then
self.own_rooms = listRooms(unit)
self.spouse = df.unit.find(unit.relations.spouse_id)
if self.spouse then
self.spouse_rooms = listRooms(self.spouse, unit)
end
self.items = concat_lists(self.own_rooms, self.spouse_rooms)
end
if base_bld then
for i,v in ipairs(self.items) do
if v.obj == base_bld then
self.selected = i
v.tile = 26
goto found
end
end
self.base_item = makeRoomEntry(base_bld, unit)
self.base_item.owner = unit
self.base_item.old_owner = base_bld.owner
self.base_item.tile = 26
self.items = concat_lists({self.base_item}, self.items)
::found::
end
return self
end
local sex_char = { [0] = 12, [1] = 11 }
function drawUnitName(dc, unit)
dc:pen(COLOR_GREY)
if unit then
local color = dfhack.units.getProfessionColor(unit)
dc:char(sex_char[unit.sex] or '?'):advance(1):pen(color)
local vname = dfhack.units.getVisibleName(unit)
if vname and vname.has_name then
dc:string(dfhack.TranslateName(vname)..', ')
end
dc:string(dfhack.units.getProfessionName(unit))
else
dc:string("No Owner Assigned")
end
end
function drawRoomEntry(dc, entry, selected)
local color = COLOR_GREEN
if not entry.can_use then
color = COLOR_RED
elseif entry.obj.owner ~= entry.owner or not entry.owner then
color = COLOR_CYAN
end
dc:pen{fg = color, bold = (selected == entry)}
dc:char(entry.tile):advance(1):string(entry.caption)
end
function can_modify(sel_item)
return sel_item and sel_item.owner
and sel_item.can_use and not sel_item.owner.flags1.dead
end
function RoomList:onRenderBody(dc)
local sel_item = self.items[self.selected]
dc:clear():seek(1,1)
drawUnitName(dc, self.unit)
if self.base_item then
dc:newline():newline(2)
drawRoomEntry(dc, self.base_item, sel_item)
end
if #self.own_rooms > 0 then
dc:newline()
for _,v in ipairs(self.own_rooms) do
dc:newline(2)
drawRoomEntry(dc, v, sel_item)
end
end
if #self.spouse_rooms > 0 then
dc:newline():newline(1)
drawUnitName(dc, self.spouse)
dc:newline()
for _,v in ipairs(self.spouse_rooms) do
dc:newline(2)
drawRoomEntry(dc, v, sel_item)
end
end
if self.unit and #self.own_rooms == 0 and #self.spouse_rooms == 0 then
dc:newline():newline(2):string("No already assigned rooms.", COLOR_LIGHTRED)
end
dc:newline():newline(1):pen(COLOR_WHITE)
dc:string("Esc", COLOR_LIGHTGREEN):string(": Back")
if can_modify(sel_item) then
dc:string(", "):string("Enter", COLOR_LIGHTGREEN)
if sel_item.obj.owner == sel_item.owner then
dc:string(": Unassign")
else
dc:string(": Assign")
end
end
end
function RoomList:changeSelected(delta)
if #self.items <= 1 then return end
self.selected = 1 + (self.selected + delta - 1) % #self.items
self:selectBuilding(self.items[self.selected].obj)
end
function RoomList:onInput(keys)
local sel_item = self.items[self.selected]
if keys.SECONDSCROLL_UP then
self:changeSelected(-1)
elseif keys.SECONDSCROLL_DOWN then
self:changeSelected(1)
elseif keys.LEAVESCREEN then
self:dismiss()
if self.base_building then
if not sel_item or self.base_building ~= sel_item.obj then
self:selectBuilding(self.base_building, self.old_cursor, self.old_view)
end
if self.unit and self.base_building.owner == self.unit then
df.global.ui_building_in_assign = false
end
end
elseif keys.SELECT then
if can_modify(sel_item) then
local owner = sel_item.owner
if sel_item.obj.owner == owner then
owner = sel_item.old_owner
end
dfhack.buildings.setOwner(sel_item.obj, owner)
end
elseif self:simulateViewScroll(keys) then
return
end
end
local focus = dfhack.gui.getCurFocus()
if focus == 'dwarfmode/QueryBuilding/Some' then
local base = df.global.world.selected_building
mkinstance(RoomList):init(base.owner):show()
elseif focus == 'dwarfmode/QueryBuilding/Some/Assign/Unit' then
local unit = df.global.ui_building_assign_units[df.global.ui_building_item_cursor]
mkinstance(RoomList):init(unit):show()
else
qerror("This script requires the main dwarfmode view in 'q' mode")
end

@ -12,26 +12,16 @@ when 'here'
end
$magma_sources.each { |x, y, z|
if tile = df.map_tile_at(x, y, z) and DFHack::TiletypeShape::PassableFlow[tile.shape]
if tile = df.map_tile_at(x, y, z) and tile.shape_passableflow
des = tile.designation
des.flow_size += 1 if des.flow_size < 7
des.liquid_type = 1
des.flow_forbid = true
mf = tile.mapblock.flags
mf.update_liquid = true
mf.update_liquid_twice = true
zf = df.world.map.z_level_flags[z]
zf.update = true
zf.update_twice = true
tile.spawn_magma(des.flow_size + 1) if des.flow_size < 7
end
}
}
if df.cursor.x != -30000
if tile = df.map_tile_at(df.cursor)
if DFHack::TiletypeShape::PassableFlow[tile.shape]
if tile.shape_passableflow
$magma_sources << [df.cursor.x, df.cursor.y, df.cursor.z]
else
puts "Impassable tile: I'm afraid I can't do that, Dave"

@ -1,6 +1,9 @@
# slay all creatures of a given race
# race = name of the race to eradicate, use 'him' to target only the selected creature
race = $script_args[0]
# if the 2nd parameter is 'magma', magma rain for the targets instead of instant death
magma = ($script_args[1] == 'magma')
checkunit = lambda { |u|
u.body.blood_count != 0 and
@ -9,12 +12,39 @@ checkunit = lambda { |u|
not df.map_designation_at(u).hidden
}
slayit = lambda { |u|
if not magma
# just make them drop dead
u.body.blood_count = 0
# some races dont mind having no blood, ensure they are still taken care of.
u.animal.vanish_countdown = 2
else
# it's getting hot around here
# !!WARNING!! do not call on a magma-safe creature
ouh = df.onupdate_register(1) {
if u.flags1.dead
df.onupdate_unregister(ouh)
else
x, y, z = u.pos.x, u.pos.y, u.pos.z
z += 1 while tile = df.map_tile_at(x, y, z+1) and tile.shape_passableflow
df.map_tile_at(x, y, z).spawn_magma(7)
end
}
end
}
all_races = df.world.units.active.map { |u|
u.race_tg.creature_id if checkunit[u]
}.compact.uniq.sort
if !race
puts all_races
elsif race == 'him'
if him = df.unit_find
slayit[him]
else
puts "Choose target"
end
else
raw_race = df.match_rawname(race, all_races)
raise 'invalid race' if not raw_race
@ -24,7 +54,7 @@ else
count = 0
df.world.units.active.each { |u|
if u.race == race_nr and checkunit[u]
u.body.blood_count = 0
slayit[u]
count += 1
end
}