diff --git a/Lua API.html b/Lua API.html index d73384241..1d61b1797 100644 --- a/Lua API.html +++ b/Lua API.html @@ -344,92 +344,97 @@ ul.auto-toc {

Contents

-

Named types

+

Named types

Named types are exposed in the df tree with names identical to the C++ version, except for the :: vs . difference.

All types and the global object have the following features:

@@ -678,7 +683,7 @@ xml have a type.find(key) function that wraps method provided in C++.

-

Global functions

+

Global functions

The df table itself contains the following functions and values:

-

Recursive table assignment

+

Recursive table assignment

Recursive assignment is invoked when a lua table is assigned to a C++ object or field, i.e. one of:

-

DFHack API

+

DFHack API

DFHack utility functions are placed in the dfhack global tree.

-

Native utilities

+

Native utilities

-

Input & Output

+

Input & Output

  • dfhack.print(args...)

    Output tab-separated args as standard lua print would do, @@ -846,7 +851,7 @@ string, global environment and command-line history file.

-

Exception handling

+

Exception handling

  • dfhack.error(msg[,level[,verbose]])

    Throws a dfhack exception object with location and stack trace. @@ -902,7 +907,7 @@ following properties:

-

Miscellaneous

+

Miscellaneous

  • dfhack.VERSION

    DFHack version string constant.

    @@ -915,7 +920,7 @@ both from the curry call and the closure call itself. I.e.
-

Locking and finalization

+

Locking and finalization

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

    Calls f with arguments after grabbing the DF core suspend lock. @@ -948,7 +953,7 @@ Implemented using call_with_final

-

Persistent configuration storage

+

Persistent configuration storage

This api is intended for storing configuration options in the world itself. It probably should be restricted to data that is world-dependent.

Entries are identified by a string key, but it is also possible to manage @@ -998,7 +1003,7 @@ as an all-zero mask.

the persistent entry will NOT delete the associated masks.

-

Material info lookup

+

Material info lookup

A material info record has fields:

  • type, index, material

    @@ -1042,7 +1047,7 @@ Accept dfhack_material_category auto-assign table.

-

Random number generation

+

Random number generation

  • dfhack.random.new([seed[,perturb_count]])

    Creates a new random number generator object. Without any @@ -1086,7 +1091,7 @@ Dimension may be 1, 2 or 3 (default).

-

C++ function wrappers

+

C++ function wrappers

Thin wrappers around C++ functions, similar to the ones for virtual methods. One notable difference is that these explicit wrappers allow argument count adjustment according to the usual lua rules, so trailing false/nil arguments @@ -1127,7 +1132,7 @@ can be omitted.

-

Gui module

+

Gui module

  • dfhack.gui.getCurViewscreen([skip_dismissed])

    Returns the topmost viewscreen. If skip_dismissed is true, @@ -1197,7 +1202,7 @@ operations accordingly. The units are used to call

-

Job module

+

Job module

  • dfhack.job.cloneJobStruct(job)

    Creates a deep copy of the given job.

    @@ -1258,7 +1263,7 @@ the flags in the job item.

-

Units module

+

Units module

  • dfhack.units.getPosition(unit)

    Returns true x,y,z of the unit, or nil if invalid; may be not equal to unit.pos if caged.

    @@ -1362,7 +1367,7 @@ or raws. The ignore_noble boolean disables the
-

Items module

+

Items module

  • dfhack.items.getPosition(item)

    Returns true x,y,z of the item, or nil if invalid; may be not equal to item.pos if in inventory.

    @@ -1432,7 +1437,7 @@ Returns false in case of error.

-

Maps module

+

Maps module

  • dfhack.maps.getSize()

    Returns map size in blocks: x, y, z

    @@ -1501,7 +1506,7 @@ burrows, or the presence of invaders.

-

Burrows module

+

Burrows module

  • dfhack.burrows.findByName(name)

    Returns the burrow pointer or nil.

    @@ -1536,7 +1541,7 @@ burrows, or the presence of invaders.

-

Buildings module

+

Buildings module

  • dfhack.buildings.getGeneralRef(building, type)

    Searches for a general_ref with the given type.

    @@ -1686,7 +1691,7 @@ can be determined this way, constructBuilding
-

Constructions module

+

Constructions module

  • dfhack.constructions.designateNew(pos,type,item_type,mat_index)

    Designates a new construction at given position. If there already is @@ -1702,7 +1707,7 @@ Returns true, was_only_planned if removed; or false if none fo

-

Screen API

+

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.

@@ -1890,7 +1895,7 @@ options; if multiple interpretations exist, the table will contain multiple keys
-

Internal API

+

Internal API

These functions are intended for the use by dfhack developers, and are only documented here for completeness:

    @@ -1959,7 +1964,7 @@ Returns: file_names or empty table if not found.

-

Core interpreter context

+

Core interpreter context

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

@@ -1990,7 +1995,7 @@ Using timeout_active(id,nil) cancels the timer
-

Event type

+

Event type

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. @@ -2022,7 +2027,7 @@ order using dfhack.safecall.

-

Lua Modules

+

Lua Modules

DFHack sets up the lua interpreter so that the built-in require function can be used to load shared lua code from hack/lua/. The dfhack namespace reference itself may be obtained via @@ -2051,7 +2056,7 @@ in this document.

-

Global environment

+

Global environment

A number of variables and functions are provided in the base global environment by the mandatory init file dfhack.lua:

    @@ -2114,7 +2119,7 @@ Returns nil if any of obj or indices is nil, or a numeric inde
-

utils

+

utils

  • utils.compare(a,b)

    Comparator function; returns -1 if a<b, 1 if a>b, 0 otherwise.

    @@ -2263,7 +2268,7 @@ throws an error.

-

dumper

+

dumper

A third-party lua table dumper module from http://lua-users.org/wiki/DataDumper. Defines one function:

@@ -2276,7 +2281,7 @@ the other arguments see the original documentation link above.

-

class

+

class

Implements a trivial single-inheritance class system.

  • Foo = defclass(Foo[, ParentClass])

    @@ -2367,7 +2372,7 @@ library itself uses them for constructors.

-

In-game UI Library

+

In-game UI Library

A number of lua modules with names starting with gui are dedicated to wrapping the natives of the dfhack.screen module in a way that is easy to use. This allows relatively easily and naturally creating @@ -2376,12 +2381,12 @@ dialogs that integrate in the main game UI window.

things ranging from the basic Painter, View and Screen classes, to fully functional predefined dialogs.

-

gui

+

gui

This module defines the most important classes and functions for implementing interfaces. This documents those of them that are considered stable.

-

Misc

+

Misc

  • USE_GRAPHICS

    Contains the value of dfhack.screen.inGraphicsMode(), which cannot be @@ -2420,7 +2425,7 @@ msec. This is intended for rendering blinking interface objects.

-

ViewRect class

+

ViewRect class

This class represents an on-screen rectangle with an associated independent clip area rectangle. It is the base of the Painter class, and is used by Views to track their client area.

@@ -2468,7 +2473,7 @@ it with the clip area of the original object.

-

Painter class

+

Painter class

The painting natives in dfhack.screen apply to the whole screen, are completely stateless and don't implement clipping.

The Painter class inherits from ViewRect to provide clipping and local @@ -2539,7 +2544,7 @@ painter:pen(foo):seek(x,y):char(1):advance(1):string('bar')...

-

View class

+

View class

This class is the common abstract base of both the stand-alone screens and common widgets to be used inside them. It defines the basic layout, rendering and event handling framework.

@@ -2663,7 +2668,7 @@ Returns true if any of the subviews handled the event.

-

Screen class

+

Screen class

This is a View subclass intended for use as a stand-alone dialog or screen. It adds the following methods:

    @@ -2717,7 +2722,7 @@ the screen is removed by any means here.

-

FramedScreen class

+

FramedScreen class

A Screen subclass that paints a visible frame around its body. Most dialogs should inherit from this class.

A framed screen has the following attributes:

@@ -2755,10 +2760,10 @@ Most dialogs should inherit from this class.

-

gui.widgets

+

gui.widgets

This module implements some basic widgets based on the View infrastructure.

-

Widget class

+

Widget class

Base of all the widgets. Inherits from View and has the following attributes:

  • frame = {...}

    @@ -2824,7 +2829,7 @@ inset, or a table with the following fields:

-

Panel class

+

Panel class

Inherits from Widget, and intended for grouping a number of subviews.

Has attributes:

    @@ -2837,7 +2842,7 @@ inset, or a table with the following fields:

-

Pages class

+

Pages class

Subclass of Panel; keeps exactly one child visible.

  • Pages{ ..., selected = ... }

    @@ -2853,7 +2858,7 @@ It is permitted to use the subview object, or its v
-

EditField class

+

EditField class

Subclass of Widget; implements a simple edit field.

Attributes:

@@ -2875,7 +2880,7 @@ If it returns false, the character is ignored.
-

Label class

+

Label class

This Widget subclass implements flowing semi-static text.

It has the following attributes:

@@ -2971,7 +2976,7 @@ this may be extended with mouse click support.

-

List class

+

List class

The List widget implements a simple list with paging.

It has the following attributes:

@@ -3057,7 +3062,7 @@ with the following fields:

-

FilteredList class

+

FilteredList class

This widget combines List, EditField and Label into a combo-box like construction that allows filtering the list by subwords of its items.

In addition to passing through all attributes supported by List, it @@ -3110,14 +3115,14 @@ index pos in the unfiltered list if p

-

Plugins

+

Plugins

DFHack plugins may export native functions and events to lua contexts. They are automatically imported by mkmodule('plugins.<name>'); this means that a lua module file is still necessary for require to read.

The following plugins have lua support.

-

burrows

+

burrows

Implements extended burrow manipulations.

Events:

    @@ -3155,16 +3160,16 @@ set is the same as used by the command line.

    The lua module file also re-exports functions from dfhack.burrows.

-

sort

+

sort

Does not export any native functions as of now. Instead, it calls lua code to perform the actual ordering of list items.

-

Eventful

+

Eventful

This plugin exports some events to lua thus allowing to run lua functions on DF world events.

-

List of events

+

List of events

  1. onReactionComplete(reaction,unit,input_items,input_reagents,output_items,call_native)

    Auto activates if detects reactions starting with LUA_HOOK_. Is called when reaction finishes.

    @@ -3194,7 +3199,7 @@ tweaking (e.g. adding custom reactions)

-

Events from EventManager

+

Events from EventManager

These events are straight from EventManager module. Each of them first needs to be enabled. See functions for more info. If you register a listener before the game is loaded, be aware that no events will be triggered immediately after loading, so you might need to add another event listener for when the game first loads in some cases.

  1. onBuildingCreatedDestroyed(building_id)

    @@ -3227,7 +3232,7 @@ tweaking (e.g. adding custom reactions)

-

Functions

+

Functions

  1. registerReaction(reaction_name,callback)

    Simplified way of using onReactionComplete; the callback is function (same params as event).

    @@ -3241,10 +3246,13 @@ tweaking (e.g. adding custom reactions)

  2. enableEvent(evType,frequency)

    Enable event checking for EventManager events. For event types use eventType table. Note that different types of events require different frequencies to be effective. The frequency is how many ticks EventManager will wait before checking if that type of event has happened. If multiple scripts or plugins use the same event type, the smallest frequency is the one that is used, so you might get events triggered more often than the frequency you use here.

  3. +
  4. registerSidebar(shop_name,callback)

    +

    Enable callback when sidebar for shop_name is drawn. Usefull for custom workshop views e.g. using gui.dwarfmode lib.

    +
-

Examples

+

Examples

Spawn dragon breath on each item attempt to contaminate wound:

 b=require "plugins.eventful"
@@ -3256,13 +3264,13 @@ end
 
 b=require "plugins.eventful"
 
-b.onReactionComplete.one=function(reaction,unit,in_items,in_reag,out_items,call_native)
+b.registerReaction("LUA_HOOK_LAY_BOMB",function(reaction,unit,in_items,in_reag,out_items,call_native)
   local pos=copyall(unit.pos)
   -- spawn dragonbreath after 100 ticks
   dfhack.timeout(100,"ticks",function() dfhack.maps.spawnFlow(pos,6,0,0,50000) end)
   --do not call real item creation code
   call_native.value=false
-end
+end)
 

Grenade example:

@@ -3279,9 +3287,57 @@ b.addReactionToShop("TAN_A_HIDE","LEATHERWORKS")
 
+
+

Building-hacks

+

This plugin overwrites some methods in workshop df class so that mechanical workshops are possible. Although +plugin export a function it's recommended to use lua decorated function.

+
+

Functions

+
+
registerBuilding(table) where table must contain name, as a workshop raw name, the rest are optional:
+
    +
  1. name -- custom workshop id e.g. SOAPMAKER
  2. +
  3. fix_impassible -- if true make impassible tiles impassible to liquids too
  4. +
  5. consume -- how much machine power is needed to work. Disables reactions if not supplied enough
  6. +
  7. produce -- how much machine power is produced. Use discouraged as there is no way to change this at runtime
  8. +
  9. gears -- a table or {x=?,y=?} of connection points for machines
  10. +
  11. action -- a table of number (how much ticks to skip) and a function which gets called on shop update
  12. +
  13. animate -- a table of frames which can be a table of:
      +
    1. tables of 4 numbers {tile,fore,back,bright} OR
    2. +
    3. empty table (tile not modified) OR
    4. +
    5. {x=<number> y=<number> + 4 numbers like in first case}, this generates full frame useful for animations that change little (1-2 tiles)
    6. +
    +
  14. +
+
+
Animate table also might contain:
+
    +
  1. frameLenght -- how many ticks does one frame take OR
  2. +
  3. isMechanical -- a bool that says to try to match to mechanical system (i.e. how gears are turning)
  4. +
+
+
+
+
+

Examples

+

Simple mechanical workshop:

+
+require('plugins.building-hacks').registerBuilding{name="BONE_GRINDER",
+  consume=15,
+  gears={x=0,y=0}, --connection point
+  animate={
+    isMechanical=true, --animate the same connection point as vanilla gear
+    frames={
+    {{x=0,y=0,42,7,0,0}}, --first frame, 1 changed tile
+    {{x=0,y=0,15,7,0,0}} -- second frame, same
+    }
+  }
+
+
+
-

Scripts

+

Scripts

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 @@ -3312,7 +3368,7 @@ The name argument should be the name stem, as

Note that this function lets errors propagate to the caller.

-

Save init script

+

Save init script

If a save directory contains a file called raw/init.lua, it is automatically loaded and executed every time the save is loaded. The same applies to any files called raw/init.d/*.lua. Every diff --git a/Lua API.rst b/Lua API.rst index 9afbb1e78..013e8f18d 100644 --- a/Lua API.rst +++ b/Lua API.rst @@ -3179,6 +3179,10 @@ Functions Enable event checking for EventManager events. For event types use ``eventType`` table. Note that different types of events require different frequencies to be effective. The frequency is how many ticks EventManager will wait before checking if that type of event has happened. If multiple scripts or plugins use the same event type, the smallest frequency is the one that is used, so you might get events triggered more often than the frequency you use here. +5. ``registerSidebar(shop_name,callback)`` + + Enable callback when sidebar for ``shop_name`` is drawn. Usefull for custom workshop views e.g. using gui.dwarfmode lib. + Examples -------- Spawn dragon breath on each item attempt to contaminate wound:: @@ -3192,13 +3196,13 @@ Reaction complete example:: b=require "plugins.eventful" - b.onReactionComplete.one=function(reaction,unit,in_items,in_reag,out_items,call_native) + b.registerReaction("LUA_HOOK_LAY_BOMB",function(reaction,unit,in_items,in_reag,out_items,call_native) local pos=copyall(unit.pos) -- spawn dragonbreath after 100 ticks dfhack.timeout(100,"ticks",function() dfhack.maps.spawnFlow(pos,6,0,0,50000) end) --do not call real item creation code call_native.value=false - end + end) Grenade example:: @@ -3212,6 +3216,48 @@ Integrated tannery:: b=require "plugins.eventful" b.addReactionToShop("TAN_A_HIDE","LEATHERWORKS") + +Building-hacks +============== + +This plugin overwrites some methods in workshop df class so that mechanical workshops are possible. Although +plugin export a function it's recommended to use lua decorated function. + +Functions +--------- + +``registerBuilding(table)`` where table must contain name, as a workshop raw name, the rest are optional: + 1. name -- custom workshop id e.g. ``SOAPMAKER`` + 2. fix_impassible -- if true make impassible tiles impassible to liquids too + 3. consume -- how much machine power is needed to work. Disables reactions if not supplied enough + 4. produce -- how much machine power is produced. Use discouraged as there is no way to change this at runtime + 5. gears -- a table or ``{x=?,y=?}`` of connection points for machines + 6. action -- a table of number (how much ticks to skip) and a function which gets called on shop update + 7. animate -- a table of frames which can be a table of: + + a. tables of 4 numbers ``{tile,fore,back,bright}`` OR + b. empty table (tile not modified) OR + c. ``{x= y= + 4 numbers like in first case}``, this generates full frame useful for animations that change little (1-2 tiles) + +Animate table also might contain: + 1. frameLenght -- how many ticks does one frame take OR + 2. isMechanical -- a bool that says to try to match to mechanical system (i.e. how gears are turning) + +Examples +-------- + +Simple mechanical workshop:: + + require('plugins.building-hacks').registerBuilding{name="BONE_GRINDER", + consume=15, + gears={x=0,y=0}, --connection point + animate={ + isMechanical=true, --animate the same connection point as vanilla gear + frames={ + {{x=0,y=0,42,7,0,0}}, --first frame, 1 changed tile + {{x=0,y=0,15,7,0,0}} -- second frame, same + } + } ======= Scripts diff --git a/NEWS b/NEWS index 180877984..db889b4ae 100644 --- a/NEWS +++ b/NEWS @@ -5,6 +5,8 @@ DFHack future - Lua API for listing files in directory. Needed for mod-manager. - Lua API for creating unit combat reports and writing to gamelog. - support for multiple raw/init.d/*.lua init scripts in one save. + - eventful now has a more friendly way of making custom sidebars + - new plugin: building-hacks. Allows to add custom functionality and/or animations to buildings. New scripts: - gui/mod-manager: allows installing/uninstalling mods into df from df/mods directory. diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index 6e1425b9c..e13284274 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -164,6 +164,7 @@ if (BUILD_SUPPORTED) DFHACK_PLUGIN(3dveins 3dveins.cpp) DFHACK_PLUGIN(strangemood strangemood.cpp) DFHACK_PLUGIN(command-prompt command-prompt.cpp) + DFHACK_PLUGIN(building-hacks building-hacks.cpp LINK_LIBRARIES lua) endif() # this is the skeleton plugin. If you want to make your own, make a copy and then change it diff --git a/plugins/building-hacks.cpp b/plugins/building-hacks.cpp new file mode 100644 index 000000000..b9c9ea3c9 --- /dev/null +++ b/plugins/building-hacks.cpp @@ -0,0 +1,389 @@ +//most of the code is shamelessly stolen from steam-engine.cpp +#include "Core.h" +#include "Error.h" +#include +#include +#include + +#include "LuaTools.h" +#include +#include "MiscUtils.h" + +#include "df/building_doorst.h" +#include "df/building_workshopst.h" +#include "df/machine.h" +#include "df/machine_tile_set.h" +#include "df/power_info.h" +#include "df/world.h" +#include "df/buildings_other_id.h" +#include "df/coord.h" +#include "df/tile_building_occ.h" +#include "df/building_drawbuffer.h" + +#include + +using namespace DFHack; +using namespace df::enums; +using df::global::world; + +DFHACK_PLUGIN("building-hacks"); +struct graphic_tile //could do just 31x31 and be done, but it's nicer to have flexible imho. +{ + int16_t tile; //originally uint8_t but we need to indicate non-animated tiles + int8_t fore; + int8_t back; + int8_t bright; +}; +struct workshop_hack_data +{ + int32_t myType; + bool impassible_fix; + //machine stuff + df::machine_tile_set connections; + df::power_info powerInfo; + //animation + std::vector > frames; + bool machine_timing; //6 frames used in vanilla + int frame_skip; // e.g. 2 means have to ticks between frames + //updateCallback: + int skip_updates; +}; +typedef std::map workshops_data_t; +workshops_data_t hacked_workshops; + +static void handle_update_action(color_ostream &out,df::building_workshopst*){}; + +DEFINE_LUA_EVENT_1(onUpdateAction,handle_update_action,df::building_workshopst*); +DFHACK_PLUGIN_LUA_EVENTS { + DFHACK_LUA_EVENT(onUpdateAction), + DFHACK_LUA_END +}; +struct work_hook : df::building_workshopst{ + typedef df::building_workshopst interpose_base; + + workshop_hack_data* find_def() + { + if (type == workshop_type::Custom) + { + auto it=hacked_workshops.find(this->getCustomType()); + if(it!=hacked_workshops.end()) + return &(it->second); + } + return NULL; + } + inline bool is_fully_built() + { + return getBuildStage() >= getMaxBuildStage(); + } + DEFINE_VMETHOD_INTERPOSE(uint32_t,getImpassableOccupancy,()) + { + if(auto def = find_def()) + { + if(def->impassible_fix) + return tile_building_occ::Impassable; + } + return INTERPOSE_NEXT(getImpassableOccupancy)(); + } + + DEFINE_VMETHOD_INTERPOSE(void, getPowerInfo, (df::power_info *info)) + { + if (auto def = find_def()) + { + info->produced = def->powerInfo.produced; + info->consumed = def->powerInfo.consumed; + return; + } + + INTERPOSE_NEXT(getPowerInfo)(info); + } + DEFINE_VMETHOD_INTERPOSE(df::machine_info*, getMachineInfo, ()) + { + if (find_def()) + return &machine; + + return INTERPOSE_NEXT(getMachineInfo)(); + } + DEFINE_VMETHOD_INTERPOSE(bool, isPowerSource, ()) + { + workshop_hack_data* def=find_def(); + if (def && def->powerInfo.produced>0) + return true; + + return INTERPOSE_NEXT(isPowerSource)(); + } + DEFINE_VMETHOD_INTERPOSE(void, categorize, (bool free)) + { + if (find_def()) + { + auto &vec = world->buildings.other[buildings_other_id::ANY_MACHINE]; + insert_into_vector(vec, &df::building::id, (df::building*)this); + } + + INTERPOSE_NEXT(categorize)(free); + } + + DEFINE_VMETHOD_INTERPOSE(void, uncategorize, ()) + { + if (find_def()) + { + auto &vec = world->buildings.other[buildings_other_id::ANY_MACHINE]; + erase_from_vector(vec, &df::building::id, id); + } + + INTERPOSE_NEXT(uncategorize)(); + } + DEFINE_VMETHOD_INTERPOSE(bool, canConnectToMachine, (df::machine_tile_set *info)) + { + if (auto def = find_def()) + { + int real_cx = centerx, real_cy = centery; + bool ok = false; + + for (size_t i = 0; i < def->connections.tiles.size(); i++) + { + // the original function connects to the center tile + centerx = x1 + def->connections.tiles[i].x; + centery = y1 + def->connections.tiles[i].y; + + if (!INTERPOSE_NEXT(canConnectToMachine)(info)) + continue; + + ok = true; + break; + } + + centerx = real_cx; centery = real_cy; + return ok; + } + else + return INTERPOSE_NEXT(canConnectToMachine)(info); + } + DEFINE_VMETHOD_INTERPOSE(bool, isUnpowered, ()) + { + if (auto def = find_def()) + { + if(def->powerInfo.consumed==0) + return false; + if(machine.machine_id==-1) + return true; + df::machine* target_machine=df::machine::find(machine.machine_id); + if(target_machine && target_machine->flags.bits.active) + return false; + return true; + } + + return INTERPOSE_NEXT(isUnpowered)(); + } + DEFINE_VMETHOD_INTERPOSE(void, updateAction, ()) + { + if(auto def = find_def()) + { + if(def->skip_updates!=0 && is_fully_built()) + { + df::world* world = df::global::world; + if(world->frame_counter % def->skip_updates == 0) + { + CoreSuspendClaimer suspend; + color_ostream_proxy out(Core::getInstance().getConsole()); + onUpdateAction(out,this); + } + } + } + INTERPOSE_NEXT(updateAction)(); + } + DEFINE_VMETHOD_INTERPOSE(void, drawBuilding, (df::building_drawbuffer *db, int16_t unk)) + { + INTERPOSE_NEXT(drawBuilding)(db, unk); + + if (auto def = find_def()) + { + if (!is_fully_built() || def->frames.size()==0) + return; + int frame=0; + if(!def->machine_timing) + { + int frame_mod=def->frames.size()* def->frame_skip; + df::world* world = df::global::world; + frame=(world->frame_counter % frame_mod)/def->frame_skip; + } + else + { + if(machine.machine_id!=-1) + { + df::machine* target_machine=df::machine::find(machine.machine_id); + if(target_machine) + { + frame=target_machine->visual_phase % def->frames.size(); + } + } + } + int w=db->x2-db->x1+1; + std::vector &cur_frame=def->frames[frame]; + for(int i=0;i=0) + { + int tx=i % w; + int ty=i / w; + db->tile[tx][ty]=cur_frame[i].tile; + db->back[tx][ty]=cur_frame[i].back; + db->bright[tx][ty]=cur_frame[i].bright; + db->fore[tx][ty]=cur_frame[i].fore; + } + } + } + } +}; +IMPLEMENT_VMETHOD_INTERPOSE(work_hook, getImpassableOccupancy); + +IMPLEMENT_VMETHOD_INTERPOSE(work_hook, getPowerInfo); +IMPLEMENT_VMETHOD_INTERPOSE(work_hook, getMachineInfo); +IMPLEMENT_VMETHOD_INTERPOSE(work_hook, isPowerSource); +IMPLEMENT_VMETHOD_INTERPOSE(work_hook, categorize); +IMPLEMENT_VMETHOD_INTERPOSE(work_hook, uncategorize); +IMPLEMENT_VMETHOD_INTERPOSE(work_hook, canConnectToMachine); +IMPLEMENT_VMETHOD_INTERPOSE(work_hook, isUnpowered); +IMPLEMENT_VMETHOD_INTERPOSE(work_hook, updateAction); +IMPLEMENT_VMETHOD_INTERPOSE(work_hook, drawBuilding); +void clear_mapping() +{ + hacked_workshops.clear(); +} +static void loadFrames(lua_State* L,workshop_hack_data& def,int stack_pos) +{ + luaL_checktype(L,stack_pos,LUA_TTABLE); + lua_pushvalue(L,stack_pos); + lua_pushnil(L); + while (lua_next(L, -2) != 0) { + luaL_checktype(L,-1,LUA_TTABLE); + lua_pushnil(L); + std::vector frame; + while (lua_next(L, -2) != 0) { + graphic_tile t; + lua_pushnumber(L,1); + lua_gettable(L,-2); + if(lua_isnil(L,-1)) + { + t.tile=-1; + lua_pop(L,1); + } + else + { + t.tile=lua_tonumber(L,-1); + lua_pop(L,1); + + lua_pushnumber(L,2); + lua_gettable(L,-2); + t.fore=lua_tonumber(L,-1); + lua_pop(L,1); + + lua_pushnumber(L,3); + lua_gettable(L,-2); + t.back=lua_tonumber(L,-1); + lua_pop(L,1); + + lua_pushnumber(L,4); + lua_gettable(L,-2); + t.bright=lua_tonumber(L,-1); + lua_pop(L,1); + + } + frame.push_back(t); + lua_pop(L,1); + } + lua_pop(L,1); + def.frames.push_back(frame); + } + lua_pop(L,1); + return ; +} +//arguments: custom type,impassible fix (bool), consumed power, produced power, list of connection points, update skip(0/nil to disable) +// table of frames,frame to tick ratio (-1 for machine control) +static int addBuilding(lua_State* L) +{ + workshop_hack_data newDefinition; + newDefinition.myType=luaL_checkint(L,1); + newDefinition.impassible_fix=luaL_checkint(L,2); + newDefinition.powerInfo.consumed=luaL_checkint(L,3); + newDefinition.powerInfo.produced=luaL_checkint(L,4); + //table of machine connection points + luaL_checktype(L,5,LUA_TTABLE); + lua_pushvalue(L,5); + lua_pushnil(L); + while (lua_next(L, -2) != 0) { + lua_getfield(L,-1,"x"); + int x=lua_tonumber(L,-1); + lua_pop(L,1); + lua_getfield(L,-1,"y"); + int y=lua_tonumber(L,-1); + lua_pop(L,1); + + newDefinition.connections.can_connect.push_back(-1);//TODO add this too... + newDefinition.connections.tiles.push_back(df::coord(x,y,0)); + + lua_pop(L,1); + } + lua_pop(L,1); + //updates + newDefinition.skip_updates=luaL_optinteger(L,6,0); + //animation + if(!lua_isnil(L,7)) + { + loadFrames(L,newDefinition,7); + newDefinition.frame_skip=luaL_optinteger(L,8,-1); + if(newDefinition.frame_skip==0) + newDefinition.frame_skip=1; + if(newDefinition.frame_skip<0) + newDefinition.machine_timing=true; + else + newDefinition.machine_timing=false; + } + hacked_workshops[newDefinition.myType]=newDefinition; + return 0; +} +DFHACK_PLUGIN_LUA_COMMANDS{ + DFHACK_LUA_COMMAND(addBuilding), + DFHACK_LUA_END +}; +static void enable_hooks(bool enable) +{ + INTERPOSE_HOOK(work_hook,getImpassableOccupancy).apply(enable); + //machine part + INTERPOSE_HOOK(work_hook,getPowerInfo).apply(enable); + INTERPOSE_HOOK(work_hook,getMachineInfo).apply(enable); + INTERPOSE_HOOK(work_hook,isPowerSource).apply(enable); + INTERPOSE_HOOK(work_hook,categorize).apply(enable); + INTERPOSE_HOOK(work_hook,uncategorize).apply(enable); + INTERPOSE_HOOK(work_hook,canConnectToMachine).apply(enable); + INTERPOSE_HOOK(work_hook,isUnpowered).apply(enable); + //update n render + INTERPOSE_HOOK(work_hook,updateAction).apply(enable); + INTERPOSE_HOOK(work_hook,drawBuilding).apply(enable); +} +DFhackCExport command_result plugin_onstatechange(color_ostream &out, state_change_event event) +{ + switch (event) { + case SC_WORLD_LOADED: + enable_hooks(true); + break; + case SC_WORLD_UNLOADED: + enable_hooks(false); + clear_mapping(); + break; + default: + break; + } + + return CR_OK; +} +DFhackCExport command_result plugin_init ( color_ostream &out, std::vector &commands) +{ + enable_hooks(true); + return CR_OK; +} + +DFhackCExport command_result plugin_shutdown ( color_ostream &out ) +{ + plugin_onstatechange(out,SC_WORLD_UNLOADED); + return CR_OK; +} diff --git a/plugins/lua/building-hacks.lua b/plugins/lua/building-hacks.lua new file mode 100644 index 000000000..e0a5b1010 --- /dev/null +++ b/plugins/lua/building-hacks.lua @@ -0,0 +1,109 @@ +local _ENV = mkmodule('plugins.building-hacks') +--[[ + from native: + addBuilding(custom type,impassible fix (bool), consumed power, produced power, list of connection points, + update skip(0/nil to disable),table of frames,frame to tick ratio (-1 for machine control)) + from here: + registerBuilding{ + name -- custom workshop id e.g. SOAPMAKER << required! + fix_impassible -- make impassible tiles impassible to liquids too + consume -- how much machine power is needed to work + produce -- how much machine power is produced + gears -- a table or {x=?,y=?} of connection points for machines + action -- a table of number (how much ticks to skip) and a function which gets called on shop update + animate -- a table of + frames -- a table of + tables of 4 numbers (tile,fore,back,bright) OR + empty table (tile not modified) OR + {x= y= + 4 numbers like in first case} -- this generates full frame even, usefull for animations that change little (1-2 tiles) + frameLenght -- how many ticks does one frame take OR + isMechanical -- a bool that says to try to match to mechanical system (i.e. how gears are turning) + } +]] +_registeredStuff={} +local function unregall(state) + if state==SC_WORLD_UNLOADED then + onUpdateAction._library=nil + dfhack.onStateChange.building_hacks= nil + _registeredStuff={} + end +end +local function onUpdateLocal(workshop) + local f=_registeredStuff[workshop:getCustomType()] + if f then + f(workshop) + end +end +local function findCustomWorkshop(name) + local raws=df.global.world.raws.buildings.all + for k,v in ipairs(raws) do + if v.code==name then + return v + end + end +end +local function registerUpdateAction(shopId,callback) + _registeredStuff[shopId]=callback + onUpdateAction._library=onUpdateLocal + dfhack.onStateChange.building_hacks=unregall +end +local function generateFrame(tiles,w,h) + local mTiles={} + for k,v in ipairs(tiles) do + mTiles[v.x]=mTiles[v.x] or {} + mTiles[v.x][v.y]=v + end + local ret={} + for ty=0,h-1 do + for tx=0,w-1 do + if mTiles[tx] and mTiles[tx][ty] then + table.insert(ret,mTiles[tx][ty]) -- leaves x and y in but who cares + else + table.insert(ret,{}) + end + end + end + return ret +end +local function processFrames(shop_def,frames) + local w,h=shop_def.dim_x,shop_def.dim_y + for frame_id,frame in ipairs(frames) do + if frame[1].x~=nil then + frames[frame_id]=generateFrame(frame,w,h) + end + end + return frames +end +function registerBuilding(args) + local shop_def=findCustomWorkshop(args.name) + local shop_id=shop_def.id + local fix_impassible + if args.fix_impassible then + fix_impassible=1 + else + fix_impassible=0 + end + local consume=args.consume or 0 + local produce=args.produce or 0 + local gears=args.gears or {} + local action=args.action --could be nil + local updateSkip=0 + if action~=nil then + updateSkip=action[1] + registerUpdateAction(shop_id,action[2]) + end + local animate=args.animate + local frameLength=1 + local frames + if animate~=nil then + frameLength=animate.frameLength + if animate.isMechanical then + frameLength=-1 + end + frames=processFrames(shop_def,animate.frames) + end + + addBuilding(shop_id,fix_impassible,consume,produce,gears,updateSkip,frames,frameLength) +end + +return _ENV \ No newline at end of file diff --git a/plugins/lua/eventful.lua b/plugins/lua/eventful.lua index a8840424b..2aa713583 100644 --- a/plugins/lua/eventful.lua +++ b/plugins/lua/eventful.lua @@ -25,13 +25,13 @@ local function getShopName(btype,bsubtype,bcustom) if typenames_shop[bsubtype]~=nil then return typenames_shop[bsubtype] else - return nil --todo add custom (not very useful) + return df.building_def_workshopst.find(bcustom).code end elseif btype==df.building_type.Furnace then if typenames_furnace[bsubtype]~=nil then return typenames_furnace[bsubtype] else - return nil --todo add custom (not very useful) + return df.building_def_furnacest.find(bcustom).code end end end @@ -77,9 +77,19 @@ local function onPostSidebar(workshop) wjob.choices_visible:insert("#",new_button) end end + if _registeredStuff.customSidebar and _registeredStuff.customSidebar[shop_id] then + _registeredStuff.customSidebar[shop_id](workshop) + end + end +end +local function customSidebarsCallback(workshop) + local shop_id=getShopName(workshop:getType(),workshop:getSubtype(),workshop:getCustomType()) + if shop_id then + if _registeredStuff.customSidebar and _registeredStuff.customSidebar[shop_id] then + _registeredStuff.customSidebar[shop_id](workshop) + end end end - function registerReaction(reaction_name,callback) _registeredStuff.reactionCallbacks=_registeredStuff.reactionCallbacks or {} _registeredStuff.reactionCallbacks[reaction_name]=callback @@ -87,6 +97,13 @@ function registerReaction(reaction_name,callback) dfhack.onStateChange.eventful=unregall end +function registerSidebar(shop_name,callback) + _registeredStuff.customSidebar=_registeredStuff.customSidebar or {} + _registeredStuff.customSidebar[shop_name]=callback + onWorkshopFillSidebarMenu._library=customSidebarsCallback + dfhack.onStateChange.eventful=unregall +end + function removeNative(shop_name,name) _registeredStuff.shopNonNative=_registeredStuff.shopNonNative or {} local shops=_registeredStuff.shopNonNative diff --git a/scripts/gui/advfort.lua b/scripts/gui/advfort.lua index e29042e54..ea93aa262 100644 --- a/scripts/gui/advfort.lua +++ b/scripts/gui/advfort.lua @@ -880,7 +880,7 @@ function usetool:init(args) wid.Label{ view_id="mainLabel", frame = {xalign=0,yalign=0}, - text={{key=keybinds.prevJob.key},{gap=1,text=dfhack.curry(usetool.getModeName,self)},{gap=1,key=keybinds.nextJob.key}, + text={{key=keybinds.prevJob.key},{gap=1,text=self:callback("getModeName")},{gap=1,key=keybinds.nextJob.key}, } },