Name | Type | is_array | initial_value |
u | unit | No |
library TrainingDetection initializer Init/* v3.1a -- www.hiveworkshop.com/threads/trainingdetection.248978/
Information
The system provides information about objects being trained.
It also allows you to loop through the current training queue,
and saves the amount object types that were entirely trained by a unit.
Objects are: Units, Researches/Techs, Upgrades
*/ requires /*
*/ TimerUtils /* www.wc3c.net/showthread.php?t=101322
*/ Table /* www.hiveworkshop.com/forums/jass-resources-412/snippet-new-table-188084/
API
*/
//! novjass
// Last & Current getters
GetCurrentTrainedObjectId takes unit whichbuilding returns integer
GetLastTrainedObjectId takes unit whichbuilding returns integer
GetBuildTimeRemaining takes unit whichbuilding returns real
// It will return the remaining time for a unit being trained.
// Sadly the native only works for normal units, not for heroes.
// For anything but a normal unit it will return 0.
// Queue Getters
// Attention!
// The slot number might not be identical with the true position in order-queue.
// Only the size number is identical. But the true slot positon might change.
// With knowing the size you might loop through the queue each get each element.
GetTrainingQueueSize takes unit whichbuilding returns integer
GetTrainedObjectId takes unit whichbuilding, integer whichslot returns
ReOrderTrainingQueue takes unit building returns nothing
// ReOrder will internally stop and start trainings to simulate cancel at front,
// be aware of that. After cleaning the queue, all units will have correct position in queue.
// (works with GetCleanTrainingQueue, see later)
CancelTrainingBack takes unit building returns nothing
// Back works same as using order native with CANCEL-id
CancelTrainingFront takes unit building returns nothing
// Front will internally stop and start trainings to simulate cancel at front, be aware of that.
// Count objects
CountFinishedUnits takes unit whichbuilding returns integer
CountFinishedTechs takes unit whichbuilding returns integer
CountFinishedUpgrades takes unit whichbuilding returns integer
// A bit advanced:
GetCleanTraningQueue takes unit building, boolean keepFirst returns nothing
// After calling it the building will have all traings canceled.
// set keepFirst "true" to not having currently object training canceled. This is an
// exception, because first element does not need to get canceled to retrieve
// the correct object ID.
// After calling, you will have access to:
integer array TrainingDetection_Queue[]
// which will hold correct order of trained objects. Loop from 1 to .. until Queue[i] == 0.
// to access all elements. The array should be used to re-order the building's training.
// It does not matter if you keepFirst, or not, Queue[1] is always the first object in training.
// ==> you may use this tequnique to only re-order certain objects, for example,
// how it's used inside function CancelTrainingFront, which does not keep first, and then
// starts at Queue[2] to re-order training the objects.
//! endnovjass
// ============================= End API ============================= //
native GetUnitBuildTime takes integer unitid returns integer
private struct TimeData
readonly boolean allocated
readonly timer clock
private static key k
private static Table table = k
method destroy takes nothing returns nothing
if .allocated then
// for safety we let expire the timer like instantly
call TimerStart(.clock, 0, false, null)
call ReleaseTimer(.clock)
call .deallocate()
set .allocated = false
endif
endmethod
static method create takes unit building, integer unitId returns thistype
local thistype this = thistype.allocate()
set .allocated = true
set table[GetHandleId(building)] = this
call TimerStart(NewTimerEx(this), GetUnitBuildTime(unitId), false, null)
return this
endmethod
static method operator [] takes unit building returns thistype
return table[GetHandleId(building)]
endmethod
endstruct
globals
private TableArray table
// First 7 slots are rserved for training units.
private constant integer COUNT_KEY = 8 // How many objects are currently in queue.
private constant integer CURRENT_KEY = 9 // Currently trained object.
private constant integer LAST_KEY = 10 // Last Trained object.
private constant integer TRAIN_UNITS_KEY = 11 // Amount of trained units.
private constant integer TRAIN_UPGRADES_KEY = 12 // Amount of made upgrads.
private constant integer TRAIN_TECHS_KEY = 13 // Amount of made researches.
private constant integer LAST_CANCEL_KEY = 14
private constant integer MAX_KEY = 14
private constant string EMPTY_STRING = "Default string" // This is an indicator for an invalid ObjectName.
private constant integer ORDER_CANCEL = 851976
endglobals
// QueueClean will clean the queue from an object that was
// canceled or finished training.
private function QueueClean takes unit building, integer trainId returns nothing
local integer unitId = GetHandleId(building)
local integer i = 0
local integer trainCounter = table[COUNT_KEY][unitId]
set table[LAST_CANCEL_KEY][unitId] = trainId
set table[COUNT_KEY][unitId] = (trainCounter - 1)
if (trainCounter == 1) then // No loop needed if only 1 trained object exists.
set table[CURRENT_KEY][unitId] = 0
set table[1][unitId] = 0
else
loop // Loop thorugh queue to get correct object
set i = (i + 1)
if (table[i][unitId] == trainId) then
if (i != trainCounter) then
// we move last object from queue to fill the gap
set table[i][unitId] = table[trainCounter][unitId]
endif
set table[trainCounter][unitId] = 0
exitwhen(true)
endif
endloop
endif
endfunction
// Building gets order to train an object.
private function TrainOrder takes nothing returns boolean
local integer trainId = GetIssuedOrderId()
local integer unitId
local integer trainCounter
if (GetObjectName(trainId) != EMPTY_STRING and GetObjectName(trainId) != null) then
set unitId = GetHandleId(GetTriggerUnit())
set trainCounter = table[COUNT_KEY][unitId] + 1
set table[COUNT_KEY][unitId] = trainCounter
set table[trainCounter][unitId] = trainId
endif
return false
endfunction
// Building starts to train an object.
private function TrainStart takes nothing returns boolean
local unit u = GetTriggerUnit()
local integer unitId = GetHandleId(u)
local integer trainId = GetTrainedUnitType()
call TimeData[u].destroy()
if (trainId == 0) then // Check if object is no unit.
set trainId = GetResearched()
if (trainId == 0) then // Check if object is no tech.
set trainId = GetUnitTypeId(u) // -> Object is an upgrade.
endif
elseif not IsHeroUnitId(trainId) then
// Start timer for training unit
call TimeData.create(u, trainId)
endif
set table[CURRENT_KEY][unitId] = trainId
set u = null
return false
endfunction
// Building cansels training for a object in queue.
private function TrainCancel takes nothing returns boolean
local integer i = GetTrainedUnitType()
local unit u = GetTriggerUnit()
if (i == 0) then // Check if canceled object is an unit or a research, no need to check for upgrade in here.
call QueueClean(u, GetResearched())
else
call QueueClean(u, i)
if not IsHeroUnitId(i) and table[COUNT_KEY][GetHandleId(u)] == 0 then
// deallocate TimeData
call TimeData[u].destroy()
endif
endif
set u = null
return false
endfunction
// Building finished training an objec.t
private function TrainFinish takes nothing returns boolean
local unit building = GetTriggerUnit()
local integer unitId = GetHandleId(building)
local integer trainId = GetTrainedUnitType()
if (trainId == 0) then // Check if object was no unit.
set trainId = GetResearched()
if (trainId == 0) then // Check if object was no research.
set trainId = GetUnitTypeId(building) // -> Object was an upgrade
set table[TRAIN_UPGRADES_KEY][unitId] = table[TRAIN_UPGRADES_KEY][unitId] + 1
else
set table[TRAIN_TECHS_KEY][unitId] = table[TRAIN_TECHS_KEY][unitId] + 1
endif
else
set table[TRAIN_UNITS_KEY][unitId] = table[TRAIN_UNITS_KEY][unitId] + 1
if not IsHeroUnitId(trainId) then
call TimeData[building].destroy()
endif
endif
set table[LAST_KEY][unitId] = trainId
set table[CURRENT_KEY][unitId] = 0
call QueueClean(building, trainId)
set building = null
return false
endfunction
private function Init takes nothing returns nothing
local trigger trigger_order = CreateTrigger()
local trigger trigger_start = CreateTrigger()
local trigger trigger_cancel = CreateTrigger()
local trigger trigger_finish = CreateTrigger()
local player p
local integer i = 0
set table = TableArray[MAX_KEY+1]
loop
exitwhen i > bj_MAX_PLAYERS
set p = Player(i)
call TriggerRegisterPlayerUnitEvent(trigger_order, p, EVENT_PLAYER_UNIT_ISSUED_ORDER, null)
call TriggerRegisterPlayerUnitEvent(trigger_start, p, EVENT_PLAYER_UNIT_RESEARCH_START, null)
call TriggerRegisterPlayerUnitEvent(trigger_start, p, EVENT_PLAYER_UNIT_TRAIN_START, null)
call TriggerRegisterPlayerUnitEvent(trigger_start, p, EVENT_PLAYER_UNIT_UPGRADE_START, null)
call TriggerRegisterPlayerUnitEvent(trigger_cancel, p, EVENT_PLAYER_UNIT_TRAIN_CANCEL, null)
call TriggerRegisterPlayerUnitEvent(trigger_cancel, p, EVENT_PLAYER_UNIT_RESEARCH_CANCEL, null)
call TriggerRegisterPlayerUnitEvent(trigger_cancel, p, EVENT_PLAYER_UNIT_UPGRADE_CANCEL, null)
call TriggerRegisterPlayerUnitEvent(trigger_finish, p, EVENT_PLAYER_UNIT_TRAIN_FINISH, null)
call TriggerRegisterPlayerUnitEvent(trigger_finish, p, EVENT_PLAYER_UNIT_RESEARCH_FINISH, null)
call TriggerRegisterPlayerUnitEvent(trigger_finish, p, EVENT_PLAYER_UNIT_UPGRADE_FINISH, null)
set i = i + 1
endloop
call TriggerAddCondition(trigger_order, Condition(function TrainOrder))
call TriggerAddCondition(trigger_start, Condition(function TrainStart))
call TriggerAddCondition(trigger_finish, Condition(function TrainFinish))
call TriggerAddCondition(trigger_cancel, Condition(function TrainCancel))
endfunction
function CountFinishedUpgrades takes unit building returns integer
return table[TRAIN_UPGRADES_KEY][GetHandleId(building)]
endfunction
function CountFinishedUnits takes unit building returns integer
return table[TRAIN_UNITS_KEY][GetHandleId(building)]
endfunction
function CountFinishedTechs takes unit building returns integer
return table[TRAIN_TECHS_KEY][GetHandleId(building)]
endfunction
function GetTrainingQueueSize takes unit building returns integer
return table[COUNT_KEY][GetHandleId(building)]
endfunction
function GetTrainedObjectId takes unit building, integer slot returns integer
if (slot > 0) and (slot < 8) then
return table[slot][GetHandleId(building)]
else
return 0
endif
endfunction
function GetLastTrainedObjectId takes unit building returns integer
return table[LAST_KEY][GetHandleId(building)]
endfunction
function GetCurrentTrainedObjectId takes unit building returns integer
return table[CURRENT_KEY][GetHandleId(building)]
endfunction
function GetUnitBuildTimeRemaining takes unit building returns real
local TimeData this = TimeData[building]
if this.allocated then
return TimerGetRemaining(this.clock)
else
return 0.
endif
endfunction
private function GetLastCanceledObjectId takes unit building returns integer
return table[LAST_CANCEL_KEY][GetHandleId(building)]
endfunction
globals
public integer array Queue[10]
endglobals
function GetCleanTraningQueue takes unit building, boolean keepFirst returns nothing
local integer i
local integer lowerBound
local integer size = GetTrainingQueueSize(building)
if size < 1 or (size == 1 and keepFirst) then
return
endif
if keepFirst then
set lowerBound = 2
set Queue[1] = GetCurrentTrainedObjectId(building)
else
set lowerBound = 1
endif
set i = size
loop
exitwhen i < lowerBound
call IssueImmediateOrderById(building, ORDER_CANCEL)
set Queue[i] = GetLastCanceledObjectId(building)
set i = i - 1
endloop
set Queue[size + 1] = 0
endfunction
private function ReOrderTrainingQueue_p takes unit building, boolean keepFirst returns nothing
local integer i
local integer size = GetTrainingQueueSize(building)
if size < 1 or (size == 1 and keepFirst) then
return
endif
call GetCleanTraningQueue(building, keepFirst)
if keepFirst then
set i = 1
else
set i = 2
endif
loop
exitwhen i > size
call IssueImmediateOrderById(building, Queue[i])
set i = i + 1
endloop
endfunction
function ReOrderTrainingQueue takes unit building returns nothing
call ReOrderTrainingQueue_p(building, true)
endfunction
function CancelTrainingBack takes unit building returns nothing
call IssueImmediateOrderById(building, ORDER_CANCEL)
endfunction
function CancelTrainingFront takes unit building returns nothing
call ReOrderTrainingQueue_p(building, false)
endfunction
endlibrary
library Table /* made by Bribe, special thanks to Vexorian & Nestharus, version 3.1.0.3
One map, one hashtable. Welcome to NewTable 3.1
This library was originally called NewTable so it didn't conflict with
the API of Table by Vexorian. However, the damage is done and it's too
late to change the library name now. To help with damage control, I
have provided an extension library called TableBC, which bridges all
the functionality of Vexorian's Table except for 2-D string arrays &
the ".flush(integer)" method. I use ".flush()" to flush a child hash-
table, because I wanted the API in NewTable to reflect the API of real
hashtables (I thought this would be more intuitive).
API
------------
struct Table
| static method create takes nothing returns Table
| create a new Table
|
| method destroy takes nothing returns nothing
| destroy it
|
| method flush takes nothing returns nothing
| flush all stored values inside of it
|
| method remove takes integer key returns nothing
| remove the value at index "key"
|
| method operator []= takes integer key, $TYPE$ value returns nothing
| assign "value" to index "key"
|
| method operator [] takes integer key returns $TYPE$
| load the value at index "key"
|
| method has takes integer key returns boolean
| whether or not the key was assigned
|
----------------
struct TableArray
| static method operator [] takes integer array_size returns TableArray
| create a new array of Tables of size "array_size"
|
| method destroy takes nothing returns nothing
| destroy it
|
| method flush takes nothing returns nothing
| flush and destroy it
|
| method operator size takes nothing returns integer
| returns the size of the TableArray
|
| method operator [] takes integer key returns Table
| returns a Table accessible exclusively to index "key"
*/
globals
private integer less = 0 //Index generation for TableArrays (below 0).
private integer more = 8190 //Index generation for Tables.
//Configure it if you use more than 8190 "key" variables in your map (this will never happen though).
private hashtable ht = InitHashtable()
private key sizeK
private key listK
endglobals
private struct dex extends array
static method operator size takes nothing returns Table
return sizeK
endmethod
static method operator list takes nothing returns Table
return listK
endmethod
endstruct
private struct handles extends array
method has takes integer key returns boolean
return HaveSavedHandle(ht, this, key)
endmethod
method remove takes integer key returns nothing
call RemoveSavedHandle(ht, this, key)
endmethod
endstruct
private struct agents extends array
method operator []= takes integer key, agent value returns nothing
call SaveAgentHandle(ht, this, key, value)
endmethod
endstruct
//! textmacro NEW_ARRAY_BASIC takes SUPER, FUNC, TYPE
private struct $TYPE$s extends array
method operator [] takes integer key returns $TYPE$
return Load$FUNC$(ht, this, key)
endmethod
method operator []= takes integer key, $TYPE$ value returns nothing
call Save$FUNC$(ht, this, key, value)
endmethod
method has takes integer key returns boolean
return HaveSaved$SUPER$(ht, this, key)
endmethod
method remove takes integer key returns nothing
call RemoveSaved$SUPER$(ht, this, key)
endmethod
endstruct
private module $TYPE$m
method operator $TYPE$ takes nothing returns $TYPE$s
return this
endmethod
endmodule
//! endtextmacro
//! textmacro NEW_ARRAY takes FUNC, TYPE
private struct $TYPE$s extends array
method operator [] takes integer key returns $TYPE$
return Load$FUNC$Handle(ht, this, key)
endmethod
method operator []= takes integer key, $TYPE$ value returns nothing
call Save$FUNC$Handle(ht, this, key, value)
endmethod
endstruct
private module $TYPE$m
method operator $TYPE$ takes nothing returns $TYPE$s
return this
endmethod
endmodule
//! endtextmacro
//Run these textmacros to include the entire hashtable API as wrappers.
//Don't be intimidated by the number of macros - Vexorian's map optimizer is
//supposed to kill functions which inline (all of these functions inline).
//! runtextmacro NEW_ARRAY_BASIC("Real", "Real", "real")
//! runtextmacro NEW_ARRAY_BASIC("Boolean", "Boolean", "boolean")
//! runtextmacro NEW_ARRAY_BASIC("String", "Str", "string")
//New textmacro to allow table.integer[] syntax for compatibility with textmacros that might desire it.
//! runtextmacro NEW_ARRAY_BASIC("Integer", "Integer", "integer")
//! runtextmacro NEW_ARRAY("Player", "player")
//! runtextmacro NEW_ARRAY("Widget", "widget")
//! runtextmacro NEW_ARRAY("Destructable", "destructable")
//! runtextmacro NEW_ARRAY("Item", "item")
//! runtextmacro NEW_ARRAY("Unit", "unit")
//! runtextmacro NEW_ARRAY("Ability", "ability")
//! runtextmacro NEW_ARRAY("Timer", "timer")
//! runtextmacro NEW_ARRAY("Trigger", "trigger")
//! runtextmacro NEW_ARRAY("TriggerCondition", "triggercondition")
//! runtextmacro NEW_ARRAY("TriggerAction", "triggeraction")
//! runtextmacro NEW_ARRAY("TriggerEvent", "event")
//! runtextmacro NEW_ARRAY("Force", "force")
//! runtextmacro NEW_ARRAY("Group", "group")
//! runtextmacro NEW_ARRAY("Location", "location")
//! runtextmacro NEW_ARRAY("Rect", "rect")
//! runtextmacro NEW_ARRAY("BooleanExpr", "boolexpr")
//! runtextmacro NEW_ARRAY("Sound", "sound")
//! runtextmacro NEW_ARRAY("Effect", "effect")
//! runtextmacro NEW_ARRAY("UnitPool", "unitpool")
//! runtextmacro NEW_ARRAY("ItemPool", "itempool")
//! runtextmacro NEW_ARRAY("Quest", "quest")
//! runtextmacro NEW_ARRAY("QuestItem", "questitem")
//! runtextmacro NEW_ARRAY("DefeatCondition", "defeatcondition")
//! runtextmacro NEW_ARRAY("TimerDialog", "timerdialog")
//! runtextmacro NEW_ARRAY("Leaderboard", "leaderboard")
//! runtextmacro NEW_ARRAY("Multiboard", "multiboard")
//! runtextmacro NEW_ARRAY("MultiboardItem", "multiboarditem")
//! runtextmacro NEW_ARRAY("Trackable", "trackable")
//! runtextmacro NEW_ARRAY("Dialog", "dialog")
//! runtextmacro NEW_ARRAY("Button", "button")
//! runtextmacro NEW_ARRAY("TextTag", "texttag")
//! runtextmacro NEW_ARRAY("Lightning", "lightning")
//! runtextmacro NEW_ARRAY("Image", "image")
//! runtextmacro NEW_ARRAY("Ubersplat", "ubersplat")
//! runtextmacro NEW_ARRAY("Region", "region")
//! runtextmacro NEW_ARRAY("FogState", "fogstate")
//! runtextmacro NEW_ARRAY("FogModifier", "fogmodifier")
//! runtextmacro NEW_ARRAY("Hashtable", "hashtable")
struct Table extends array
// Implement modules for intuitive syntax (tb.handle; tb.unit; etc.)
implement realm
implement integerm
implement booleanm
implement stringm
implement playerm
implement widgetm
implement destructablem
implement itemm
implement unitm
implement abilitym
implement timerm
implement triggerm
implement triggerconditionm
implement triggeractionm
implement eventm
implement forcem
implement groupm
implement locationm
implement rectm
implement boolexprm
implement soundm
implement effectm
implement unitpoolm
implement itempoolm
implement questm
implement questitemm
implement defeatconditionm
implement timerdialogm
implement leaderboardm
implement multiboardm
implement multiboarditemm
implement trackablem
implement dialogm
implement buttonm
implement texttagm
implement lightningm
implement imagem
implement ubersplatm
implement regionm
implement fogstatem
implement fogmodifierm
implement hashtablem
method operator handle takes nothing returns handles
return this
endmethod
method operator agent takes nothing returns agents
return this
endmethod
//set this = tb[GetSpellAbilityId()]
method operator [] takes integer key returns Table
return LoadInteger(ht, this, key)
endmethod
//set tb[389034] = 8192
method operator []= takes integer key, Table tb returns nothing
call SaveInteger(ht, this, key, tb)
endmethod
//set b = tb.has(2493223)
method has takes integer key returns boolean
return HaveSavedInteger(ht, this, key)
endmethod
//call tb.remove(294080)
method remove takes integer key returns nothing
call RemoveSavedInteger(ht, this, key)
endmethod
//Remove all data from a Table instance
method flush takes nothing returns nothing
call FlushChildHashtable(ht, this)
endmethod
//local Table tb = Table.create()
static method create takes nothing returns Table
local Table this = dex.list[0]
if this == 0 then
set this = more + 1
set more = this
else
set dex.list[0] = dex.list[this]
call dex.list.remove(this) //Clear hashed memory
endif
debug set dex.list[this] = -1
return this
endmethod
// Removes all data from a Table instance and recycles its index.
//
// call tb.destroy()
//
method destroy takes nothing returns nothing
debug if dex.list[this] != -1 then
debug call BJDebugMsg("Table Error: Tried to double-free instance: " + I2S(this))
debug return
debug endif
call this.flush()
set dex.list[this] = dex.list[0]
set dex.list[0] = this
endmethod
//! runtextmacro optional TABLE_BC_METHODS()
endstruct
//! runtextmacro optional TABLE_BC_STRUCTS()
struct TableArray extends array
//Returns a new TableArray to do your bidding. Simply use:
//
// local TableArray ta = TableArray[array_size]
//
static method operator [] takes integer array_size returns TableArray
local Table tb = dex.size[array_size] //Get the unique recycle list for this array size
local TableArray this = tb[0] //The last-destroyed TableArray that had this array size
debug if array_size <= 0 then
debug call BJDebugMsg("TypeError: Invalid specified TableArray size: " + I2S(array_size))
debug return 0
debug endif
if this == 0 then
set this = less - array_size
set less = this
else
set tb[0] = tb[this] //Set the last destroyed to the last-last destroyed
call tb.remove(this) //Clear hashed memory
endif
set dex.size[this] = array_size //This remembers the array size
return this
endmethod
//Returns the size of the TableArray
method operator size takes nothing returns integer
return dex.size[this]
endmethod
//This magic method enables two-dimensional[array][syntax] for Tables,
//similar to the two-dimensional utility provided by hashtables them-
//selves.
//
//ta[integer a].unit[integer b] = unit u
//ta[integer a][integer c] = integer d
//
//Inline-friendly when not running in debug mode
//
method operator [] takes integer key returns Table
static if DEBUG_MODE then
local integer i = this.size
if i == 0 then
call BJDebugMsg("IndexError: Tried to get key from invalid TableArray instance: " + I2S(this))
return 0
elseif key < 0 or key >= i then
call BJDebugMsg("IndexError: Tried to get key [" + I2S(key) + "] from outside TableArray bounds: " + I2S(i))
return 0
endif
endif
return this + key
endmethod
//Destroys a TableArray without flushing it; I assume you call .flush()
//if you want it flushed too. This is a public method so that you don't
//have to loop through all TableArray indices to flush them if you don't
//need to (ie. if you were flushing all child-keys as you used them).
//
method destroy takes nothing returns nothing
local Table tb = dex.size[this.size]
debug if this.size == 0 then
debug call BJDebugMsg("TypeError: Tried to destroy an invalid TableArray: " + I2S(this))
debug return
debug endif
if tb == 0 then
//Create a Table to index recycled instances with their array size
set tb = Table.create()
set dex.size[this.size] = tb
endif
call dex.size.remove(this) //Clear the array size from hash memory
set tb[this] = tb[0]
set tb[0] = this
endmethod
private static Table tempTable
private static integer tempEnd
//Avoids hitting the op limit
private static method clean takes nothing returns nothing
local Table tb = .tempTable
local integer end = tb + 0x1000
if end < .tempEnd then
set .tempTable = end
call ForForce(bj_FORCE_PLAYER[0], function thistype.clean)
else
set end = .tempEnd
endif
loop
call tb.flush()
set tb = tb + 1
exitwhen tb == end
endloop
endmethod
//Flushes the TableArray and also destroys it. Doesn't get any more
//similar to the FlushParentHashtable native than this.
//
method flush takes nothing returns nothing
debug if this.size == 0 then
debug call BJDebugMsg("TypeError: Tried to flush an invalid TableArray instance: " + I2S(this))
debug return
debug endif
set .tempTable = this
set .tempEnd = this + this.size
call ForForce(bj_FORCE_PLAYER[0], function thistype.clean)
call this.destroy()
endmethod
endstruct
endlibrary
library TimerUtils initializer init
//*********************************************************************
//* TimerUtils (red+blue+orange flavors for 1.24b+) 2.0
//* ----------
//*
//* To implement it , create a custom text trigger called TimerUtils
//* and paste the contents of this script there.
//*
//* To copy from a map to another, copy the trigger holding this
//* library to your map.
//*
//* (requires vJass) More scripts: htt://www.wc3c.net
//*
//* For your timer needs:
//* * Attaching
//* * Recycling (with double-free protection)
//*
//* set t=NewTimer() : Get a timer (alternative to CreateTimer)
//* set t=NewTimerEx(x) : Get a timer (alternative to CreateTimer), call
//* Initialize timer data as x, instead of 0.
//*
//* ReleaseTimer(t) : Relese a timer (alt to DestroyTimer)
//* SetTimerData(t,2) : Attach value 2 to timer
//* GetTimerData(t) : Get the timer's value.
//* You can assume a timer's value is 0
//* after NewTimer.
//*
//* Multi-flavor:
//* Set USE_HASH_TABLE to true if you don't want to complicate your life.
//*
//* If you like speed and giberish try learning about the other flavors.
//*
//********************************************************************
//================================================================
globals
//How to tweak timer utils:
// USE_HASH_TABLE = true (new blue)
// * SAFEST
// * SLOWEST (though hash tables are kind of fast)
//
// USE_HASH_TABLE = false, USE_FLEXIBLE_OFFSET = true (orange)
// * kinda safe (except there is a limit in the number of timers)
// * ALMOST FAST
//
// USE_HASH_TABLE = false, USE_FLEXIBLE_OFFSET = false (red)
// * THE FASTEST (though is only faster than the previous method
// after using the optimizer on the map)
// * THE LEAST SAFE ( you may have to tweak OFSSET manually for it to
// work)
//
private constant boolean USE_HASH_TABLE = true
private constant boolean USE_FLEXIBLE_OFFSET = false
private constant integer OFFSET = 0x100000
private integer VOFFSET = OFFSET
//Timers to preload at map init:
private constant integer QUANTITY = 256
//Changing this to something big will allow you to keep recycling
// timers even when there are already AN INCREDIBLE AMOUNT of timers in
// the stack. But it will make things far slower so that's probably a bad idea...
private constant integer ARRAY_SIZE = 8190
endglobals
//==================================================================================================
globals
private integer array data[ARRAY_SIZE]
private hashtable ht
endglobals
//It is dependent on jasshelper's recent inlining optimization in order to perform correctly.
function SetTimerData takes timer t, integer value returns nothing
static if(USE_HASH_TABLE) then
// new blue
call SaveInteger(ht,0,GetHandleId(t), value)
elseif (USE_FLEXIBLE_OFFSET) then
// orange
static if (DEBUG_MODE) then
if(GetHandleId(t)-VOFFSET<0) then
call BJDebugMsg("SetTimerData: Wrong handle id, only use SetTimerData on timers created by NewTimer")
endif
endif
set data[GetHandleId(t)-VOFFSET]=value
else
// new red
static if (DEBUG_MODE) then
if(GetHandleId(t)-OFFSET<0) then
call BJDebugMsg("SetTimerData: Wrong handle id, only use SetTimerData on timers created by NewTimer")
endif
endif
set data[GetHandleId(t)-OFFSET]=value
endif
endfunction
function GetTimerData takes timer t returns integer
static if(USE_HASH_TABLE) then
// new blue
return LoadInteger(ht,0,GetHandleId(t) )
elseif (USE_FLEXIBLE_OFFSET) then
// orange
static if (DEBUG_MODE) then
if(GetHandleId(t)-VOFFSET<0) then
call BJDebugMsg("SetTimerData: Wrong handle id, only use SetTimerData on timers created by NewTimer")
endif
endif
return data[GetHandleId(t)-VOFFSET]
else
// new red
static if (DEBUG_MODE) then
if(GetHandleId(t)-OFFSET<0) then
call BJDebugMsg("SetTimerData: Wrong handle id, only use SetTimerData on timers created by NewTimer")
endif
endif
return data[GetHandleId(t)-OFFSET]
endif
endfunction
//==========================================================================================
globals
private timer array tT[ARRAY_SIZE]
private integer tN = 0
private constant integer HELD=0x28829022
//use a totally random number here, the more improbable someone uses it, the better.
private boolean didinit = false
endglobals
private keyword init
//==========================================================================================
// I needed to decide between duplicating code ignoring the "Once and only once" rule
// and using the ugly textmacros. I guess textmacros won.
//
//! textmacro TIMERUTIS_PRIVATE_NewTimerCommon takes VALUE
// On second thought, no.
//! endtextmacro
function NewTimerEx takes integer value returns timer
if (tN==0) then
if (not didinit) then
//This extra if shouldn't represent a major performance drawback
//because QUANTITY rule is not supposed to be broken every day.
call init.evaluate()
set tN = tN - 1
else
//If this happens then the QUANTITY rule has already been broken, try to fix the
// issue, else fail.
debug call BJDebugMsg("NewTimer: Warning, Exceeding TimerUtils_QUANTITY, make sure all timers are getting recycled correctly")
set tT[0]=CreateTimer()
static if( not USE_HASH_TABLE) then
debug call BJDebugMsg("In case of errors, please increase it accordingly, or set TimerUtils_USE_HASH_TABLE to true")
static if( USE_FLEXIBLE_OFFSET) then
if (GetHandleId(tT[0])-VOFFSET<0) or (GetHandleId(tT[0])-VOFFSET>=ARRAY_SIZE) then
//all right, couldn't fix it
call BJDebugMsg("NewTimer: Unable to allocate a timer, you should probably set TimerUtils_USE_HASH_TABLE to true or fix timer leaks.")
return null
endif
else
if (GetHandleId(tT[0])-OFFSET<0) or (GetHandleId(tT[0])-OFFSET>=ARRAY_SIZE) then
//all right, couldn't fix it
call BJDebugMsg("NewTimer: Unable to allocate a timer, you should probably set TimerUtils_USE_HASH_TABLE to true or fix timer leaks.")
return null
endif
endif
endif
endif
else
set tN=tN-1
endif
call SetTimerData(tT[tN],value)
return tT[tN]
endfunction
function NewTimer takes nothing returns timer
return NewTimerEx(0)
endfunction
//==========================================================================================
function ReleaseTimer takes timer t returns nothing
if(t==null) then
debug call BJDebugMsg("Warning: attempt to release a null timer")
return
endif
if (tN==ARRAY_SIZE) then
debug call BJDebugMsg("Warning: Timer stack is full, destroying timer!!")
//stack is full, the map already has much more troubles than the chance of bug
call DestroyTimer(t)
else
call PauseTimer(t)
if(GetTimerData(t)==HELD) then
debug call BJDebugMsg("Warning: ReleaseTimer: Double free!")
return
endif
call SetTimerData(t,HELD)
set tT[tN]=t
set tN=tN+1
endif
endfunction
private function init takes nothing returns nothing
local integer i=0
local integer o=-1
local boolean oops = false
if ( didinit ) then
return
else
set didinit = true
endif
static if( USE_HASH_TABLE ) then
set ht = InitHashtable()
loop
exitwhen(i==QUANTITY)
set tT[i]=CreateTimer()
call SetTimerData(tT[i], HELD)
set i=i+1
endloop
set tN = QUANTITY
else
loop
set i=0
loop
exitwhen (i==QUANTITY)
set tT[i] = CreateTimer()
if(i==0) then
set VOFFSET = GetHandleId(tT[i])
static if(USE_FLEXIBLE_OFFSET) then
set o=VOFFSET
else
set o=OFFSET
endif
endif
if (GetHandleId(tT[i])-o>=ARRAY_SIZE) then
exitwhen true
endif
if (GetHandleId(tT[i])-o>=0) then
set i=i+1
endif
endloop
set tN = i
exitwhen(tN == QUANTITY)
set oops = true
exitwhen not USE_FLEXIBLE_OFFSET
debug call BJDebugMsg("TimerUtils_init: Failed a initialization attempt, will try again")
endloop
if(oops) then
static if ( USE_FLEXIBLE_OFFSET) then
debug call BJDebugMsg("The problem has been fixed.")
//If this message doesn't appear then there is so much
//handle id fragmentation that it was impossible to preload
//so many timers and the thread crashed! Therefore this
//debug message is useful.
elseif(DEBUG_MODE) then
call BJDebugMsg("There were problems and the new timer limit is "+I2S(i))
call BJDebugMsg("This is a rare ocurrence, if the timer limit is too low:")
call BJDebugMsg("a) Change USE_FLEXIBLE_OFFSET to true (reduces performance a little)")
call BJDebugMsg("b) or try changing OFFSET to "+I2S(VOFFSET) )
endif
endif
endif
endfunction
endlibrary
scope TestMap initializer TestInit
private function Clear takes nothing returns nothing
call ClearTextMessages()
endfunction
private function Print takes string s returns nothing
call DisplayTimedTextToPlayer(GetLocalPlayer(), 0, 0, 9, s)
endfunction
private function Selection takes nothing returns nothing
local player p = GetTriggerPlayer()
local unit building = GetTriggerUnit()
local string objectName = null
local integer objectId
local integer i
local integer k
local string namesInQueue = "|c001BE5B8"
if IsUnitType(building, UNIT_TYPE_STRUCTURE) then
call ClearTextMessages()
//Print amount ob objects
call Print("---------------------------------------")
set objectName = GetUnitName(building)
call Print("|c00959697" + objectName + "|CFF7EBFF1 is currently training |r" + I2S(GetTrainingQueueSize(building)) + " objects:")
// Print all objects in queue
set i = 1
loop
set objectId = GetTrainedObjectId(building, i)
exitwhen(objectId == 0)
set objectName = GetObjectName(objectId)
if (i == 1) then
set namesInQueue = (namesInQueue + objectName)
else
set namesInQueue = (namesInQueue + ", " + objectName)
endif
set i = i + 1
endloop
call Print(namesInQueue)
// Print current object
set objectId = GetCurrentTrainedObjectId(building)
if (objectId != 0) then
set objectName = GetObjectName(objectId)
else
set objectName = "null"
endif
call Print("|CFF7EBFF1current: |c00ffcc00" + objectName + "|r ObjectId: " + I2S(objectId))
// Print last object
set objectId = GetLastTrainedObjectId(building)
if (objectId != 0) then
set objectName = GetObjectName(objectId)
else
set objectName = "null"
endif
call Print("|CFF7EBFF1last: |c00ffcc00" + objectName + "|r ObjectId: " + I2S(objectId))
// Print finished objects amount
set i = CountFinishedUnits(building)
call Print("|CFF7EBFF1units: |c00ffcc00" + I2S(i))
set i = CountFinishedTechs(building)
call Print("|CFF7EBFF1techs: |c00ffcc00" + I2S(i))
set i = CountFinishedUpgrades(building)
call Print("|CFF7EBFF1upgrades: |c00ffcc00" + I2S(i))
call Print("---------------------------------------")
endif
set building = null
endfunction
globals
private group G = CreateGroup()
private hashtable hash = InitHashtable()
endglobals
private function filter takes nothing returns boolean
return IsUnitType(GetFilterUnit(), UNIT_TYPE_STRUCTURE) and not IsUnitDeadBJ(GetFilterUnit())
endfunction
private function callback takes nothing returns nothing
local unit u
local integer id
local texttag tt
local real time
call GroupEnumUnitsInRect(G, bj_mapInitialPlayableArea, Filter(function filter))
loop
set u = FirstOfGroup(G)
call GroupRemoveUnit(G, u)
exitwhen u == null
set id = GetHandleId(u)
if HaveSavedHandle(hash, id, 0) then
set tt = LoadTextTagHandle(hash, id, 0)
else
set tt = CreateTextTag()
call SetTextTagPosUnit(tt, u, 0)
call SaveTextTagHandle(hash, id, 0, tt)
endif
set time = GetUnitBuildTimeRemaining(u)
if time != 0 then
call SetTextTagText(tt, "|c00ffcc00" + R2SW(time, 1, 1) + "|r", 10 * 0.023 / 10)
call SetTextTagVisibility(tt, true)
else
call SetTextTagVisibility(tt, false)
endif
endloop
endfunction
function TestInit takes nothing returns nothing
local trigger select = CreateTrigger()
local trigger clear = CreateTrigger()
local player p = GetLocalPlayer()
call TriggerRegisterPlayerUnitEvent(select, p, EVENT_PLAYER_UNIT_SELECTED, null)
call TriggerAddAction( select, function Selection)
call TriggerRegisterPlayerChatEvent(clear, p, "-c", true)
call TriggerAddAction( clear, function Clear)
call SetPlayerState(p, PLAYER_STATE_RESOURCE_GOLD, 10000)
call SetPlayerState(p, PLAYER_STATE_RESOURCE_LUMBER, 10000)
call DisplayTimedTextToPlayer(p, 0, 0, 8, "Write -c to clear text")
call TimerStart(CreateTimer(), 0.1, true, function callback)
endfunction
endscope