Name | Type | is_array | initial_value |
//TESH.scrollpos=189
//TESH.alwaysfold=0
//===============================================================================\\
// \\
// Rune Ritual \\
// by \\
// TriggerHappy \\
// \\
// \\
//===============================================================================\\
// \\
// The caster channels his inner darkness, causing runes to circle around him. \\
// It drags the nearest four units towards the runes and they are struck with \\
// lightning periodicly. \\
// \\
//===============================================================================\\
// \\
// Requires: \\
// +TimerUtils \\
// +UnitStatus \\
// +SimError (optional) \\
// \\
//===============================================================================\\
scope RuneRitual initializer onInit //requires TimerUtils, UnitStatus optional SimError
globals
private constant integer SPELL_RAW_CODE = 'A000' // The spells raw code
private constant integer RUNE_DUMMY = 'h000' // The rune dummies raw code
private constant integer DMG_TICKS = 100 // How many timer intervals before the units get damaged
private constant real RUNE_DISTANCE = 300 // How far the units are made from the caster
private constant real TIMER_PERIOD = 0.03 // How far the units are made from the caster
private constant real SPIN_SPEED = 0.03 // how fast the runes spin
private constant boolean REQUIRE_UNITS = false // Displays an error if there are no enemy units around
private constant string DAMAGE_EFFECT = "Abilities\\Spells\\Other\\Monsoon\\MonsoonBoltTarget.mdl" // the effect when a unit is damaged
private constant attacktype ATTACK_TYPE = ATTACK_TYPE_NORMAL
private constant damagetype DAMAGE_TYPE = DAMAGE_TYPE_NORMAL
endglobals
private constant function AOE takes integer level returns real
return (level*400.0)-((level-1)*100.0)
endfunction
private constant function DURATION takes integer level returns real
return level*5.00-(level)
endfunction
private constant function DAMAGE takes integer level returns real
return level*50.00
endfunction
//===============================================================================\\
// DO NOT EDIT BELOW THIS LINE \\
//===============================================================================\\
private keyword data
globals
private group GLOBAL_GROUP = CreateGroup()
private player TEMP_PLAYER
private data TEMP_DATA
private hashtable HASH = InitHashtable()
endglobals
native UnitAlive takes unit id returns boolean
private struct data
unit array rune[4]
unit array picked[4]
unit caster
real x
real y
real spin = 0.00
integer level
integer in = 0
integer ticks = DMG_TICKS
real array runeX[4]
real array runeY[4]
timer t
static method callback takes nothing returns nothing
local data this = GetTimerData(GetExpiredTimer())
local integer i = 0
set this.ticks = this.ticks + 1
loop
exitwhen i > 4
set this.runeX[i] = this.x+RUNE_DISTANCE*Cos((i*90) * bj_DEGTORAD+this.spin)
set this.runeY[i] = this.y+RUNE_DISTANCE*Sin((i*90) * bj_DEGTORAD+this.spin)
call SetUnitX(this.rune[i], this.runeX[i])
call SetUnitY(this.rune[i], this.runeY[i])
if this.picked[i] != null then
call SetUnitX(this.picked[i], this.runeX[i])
call SetUnitY(this.picked[i], this.runeY[i])
endif
if this.ticks >= DMG_TICKS and UnitAlive(this.picked[i]) then
call DestroyEffect(AddSpecialEffectTarget(DAMAGE_EFFECT, this.picked[i], "origin"))
call UnitDamageTarget(this.caster, this.picked[i], DAMAGE(this.level), true, false, ATTACK_TYPE, DAMAGE_TYPE, null)
endif
set i = i + 1
endloop
if this.ticks >= DMG_TICKS then
set this.ticks = 0
endif
set this.spin = this.spin+SPIN_SPEED
endmethod
static method Enemies takes nothing returns boolean
local unit u = GetFilterUnit()
local boolean b = IsUnitEnemy(u, TEMP_PLAYER) and UnitAlive(u) and not LoadBoolean(HASH, GetHandleId(u), 0)
if TEMP_DATA.in < 4 and b then
set TEMP_DATA.picked[TEMP_DATA.in] = u
call StunUnit(u, true)
call SetUnitX(u, TEMP_DATA.runeX[TEMP_DATA.in])
call SetUnitY(u, TEMP_DATA.runeY[TEMP_DATA.in])
set TEMP_DATA.in = TEMP_DATA.in + 1
call SaveBoolean(HASH, GetHandleId(u), 0, true)
endif
set u = null
return b
endmethod
static method end takes nothing returns nothing
local timer t = GetExpiredTimer()
local data this = GetTimerData(t)
call ReleaseTimer(this.t)
set this.t = t
call this.destroy()
endmethod
static method create takes unit u returns data
local data this = data.allocate()
local integer i = 0
local real x
local real y
local real d
local timer t = NewTimer()
set this.caster = u
set this.y = GetUnitY(this.caster)
set this.x = GetUnitX(this.caster)
set this.level = GetUnitAbilityLevel(this.caster, SPELL_RAW_CODE)
set this.t = t
set d = DURATION(this.level)
call SaveBoolean(HASH, GetHandleId(u), 0, true)
set TEMP_DATA = this
set TEMP_PLAYER = GetOwningPlayer(this.caster)
call GroupEnumUnitsInRange(GLOBAL_GROUP, this.x, this.y, AOE(this.level), Filter(function data.Enemies))
static if REQUIRE_UNITS then
set bj_groupCountUnits = 0
call ForGroup(GLOBAL_GROUP, function CountUnitsInGroupEnum)
if bj_groupCountUnits == 0 then
static if LIBRARY_SimError then
call SimError(TEMP_PLAYER, "There are no enemy units around.")
else
call DisplayTimedTextToPlayer(TEMP_PLAYER, 0.52, 0.96, 2.00, "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n|cffffcc00There are no enemy units around.|r")
endif
call this.destroy()
return 0
endif
endif
loop
exitwhen i > 3
set x = this.x + RUNE_DISTANCE * Cos((i*90) * bj_DEGTORAD)
set y = this.y + RUNE_DISTANCE * Sin((i*90)* bj_DEGTORAD)
set this.rune[i] = CreateUnit(TEMP_PLAYER, RUNE_DUMMY, x, y, 0)
set i = i + 1
endloop
call SetTimerData(t, this)
call TimerStart(t, TIMER_PERIOD, true, function data.callback)
set t = NewTimer()
call SetTimerData(t, this)
call TimerStart(t, DURATION(this.level), false, function data.end)
return this
endmethod
method onDestroy takes nothing returns nothing
local integer i = 0
call ReleaseTimer(this.t)
call SaveBoolean(HASH, GetHandleId(this.caster), 0, false)
loop
exitwhen i > 4
call RemoveUnit(this.rune[i])
if this.picked[i] != null then
call SaveBoolean(HASH, GetHandleId(this.picked[i]), 0, false)
call StunUnit(this.picked[i], false)
set this.picked[i] = null
endif
set i = i + 1
endloop
endmethod
endstruct
private function Actions takes nothing returns boolean
local unit u = GetTriggerUnit()
if GetSpellAbilityId() == SPELL_RAW_CODE then
if LoadBoolean(HASH, GetHandleId(u), 0) then
static if LIBRARY_SimError then
call SimError(GetOwningPlayer(u), "You already have a rune ritual running.")
else
call DisplayTimedTextToPlayer(GetOwningPlayer(u), 0.52, 0.96, 2.00, "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n|cffffcc00You already have a rune ritual running.|r"
endif
set u = null
return false
else
call data.create(u)
endif
endif
set u = null
return false
endfunction
private function onInit takes nothing returns nothing
local trigger t = CreateTrigger()
call TriggerRegisterAnyUnitEventBJ(t, EVENT_PLAYER_UNIT_SPELL_EFFECT)
call TriggerAddCondition(t, Condition(function Actions))
endfunction
endscope
//TESH.scrollpos=0
//TESH.alwaysfold=0
library SimError initializer init
//**************************************************************************************************
//*
//* SimError
//*
//* Mimic an interface error message
//* call SimError(ForPlayer, msg)
//* ForPlayer : The player to show the error
//* msg : The error
//*
//* To implement this function, copy this trigger and paste it in your map.
//* Unless of course you are actually reading the library from wc3c's scripts section, then just
//* paste the contents into some custom text trigger in your map.
//*
//**************************************************************************************************
//==================================================================================================
globals
private sound error
endglobals
//====================================================================================================
function SimError takes player ForPlayer, string msg returns nothing
set msg="\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n|cffffcc00"+msg+"|r"
if (GetLocalPlayer() == ForPlayer) then
call ClearTextMessages()
call DisplayTimedTextToPlayer( ForPlayer, 0.52, 0.96, 2.00, msg )
call StartSound( error )
endif
endfunction
private function init takes nothing returns nothing
set error=CreateSoundFromLabel("InterfaceError",false,false,false,10,10)
//call StartSound( error ) //apparently the bug in which you play a sound for the first time
//and it doesn't work is not there anymore in patch 1.22
endfunction
endlibrary
//TESH.scrollpos=0
//TESH.alwaysfold=0
library TimerUtils initializer init
//*********************************************************************
//* TimerUtils (red+blue+orange flavors for 1.24b+)
//* ----------
//*
//* 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)
//* 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.
endglobals
//==========================================================================================
function NewTimer takes nothing returns timer
if (tN==0) then
//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")
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")
set tT[0]=CreateTimer()
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
else
set tN=tN-1
endif
call SetTimerData(tT[tN],0)
return tT[tN]
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
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
//TESH.scrollpos=54
//TESH.alwaysfold=0
library UnitStatus initializer Init requires TimerUtils, AutoIndex, optional xebasic
//******************************************************************************
//* BY: Rising_Dusk
//*
//* This library exists because oftentimes, a mapmaker needs to apply a specific
//* status effect to a unit. If he were to do it on his own, he'd need to find a
//* way to get the status effects to stack properly with one another and with
//* multiple instances of themselves. This script does just that with the five
//* most useful status options in WC3 that cannot be reproduced perfectly with
//* just code and not actual in-game buffs.
//*
//* WARNING: This library uses the following buffs. If you use any of the listed
//* buffs in your map, they will not stack with this script's buffs and
//* it may not work. If you need these effects, then only use this
//* script to achieve them.
//* - Drunken Haze
//* - Soul Burn
//* - Ensnare
//* - Storm Bolt
//* - Hurl Boulder
//*
//******************************************************************************
//*
//* The following status effects are supported by this library.
//*
//* - Silence
//* This status disables a given unit's ability to cast spells. This works
//* properly on spell immune and normal units.
//*
//* Example Usage:
//* call SilenceUnit(u, true) //Silences a unit
//* call SilenceUnit(u, false) //Removes silence from a unit
//* call SilenceUnitTimed(u, 4.0) //Adds a timed silence to a unit
//*
//* - Disarm
//* This status disables a given unit's ability to attack and attack ground.
//* This will not work properly on spell immune units because of a Blizzard
//* bug. The function calls will return false when used on units that are
//* spell immune. This status disables both ranged and melee attacks.
//*
//* Example Usage:
//* call DisarmUnit(u, true) //Disarms a unit
//* call DisarmUnit(u, false) //Removes disarm from a unit
//* call DisarmUnitTimed(u, 4.0) //Adds a timed disarm to a unit
//*
//* - Ensnare
//* This status disables a given unit's ability to move. This works properly
//* on spell immune and normal units. Because of the nature of the ability
//* this is based upon, it will exhibit strange behavior on flying units. If
//* this is used on flying units, they will retain their flying height, but
//* be treated as ground units by the game. There is unfortunately no
//* workaround for this behavior. It is recommended to not use it on flying
//* units because for that reason.
//*
//* Example Usage:
//* call EnsnareUnit(u, true) //Ensnares a unit
//* call EnsnareUnit(u, false) //Removes ensnare from a unit
//* call EnsnareUnitTimed(u, 4.0) //Adds a timed ensnare to a unit
//*
//* - Stun
//* This status is identical in nature to the standard melee stun. A stunned
//* unit cannot move, attack, or cast spells. Both spell immune and normal
//* units can be stunned.
//*
//* Example Usage:
//* call StunUnit(u, true) //Ensnares a unit
//* call StunUnit(u, false) //Removes stun from a unit
//* call StunUnitTimed(u, 4.0) //Adds a timed stun to a unit
//*
//* - Disable
//* Disable is a unique status meant to be used as a replacement for pausing a
//* unit using the PauseUnit native. Pausing a unit has the negative side
//* effects of removing the unit's command card and not preserving queued
//* orders. Disabling a unit retains both of those sought features. Disable is
//* a non-graphical stun at its core that is always 'underneath' stun when
//* both are applied on a unit at once as listed below.
//*
//* Disable also interacts with stun in a unique way.
//* - If stun is used on a disabled unit, the unit becomes stunned instead.
//* - If stun ends on a disabled unit, the unit is disabled until the disable
//* ends.
//* - If disable is used on a stunned unit, the unit remains visibly stunned.
//*
//* Example Usage:
//* call DisableUnit(u, true) //Disables a unit
//* call DisableUnit(u, false) //Removes disable from a unit
//* call DisableUnitTimed(u, 4.0) //Adds a timed disable to a unit
//*
//* WARNING: These status effects, when used on invulnerable units, will have
//* absolutely no effect.
//*
//******************************************************************************
//*
//* There is a textmacro call below that runs a series of ObjectMerger calls
//* inside of an embedded .lua script. This sub-script generates all of the
//* abilities and buffs required by this library automatically for you. Enable
//* it by uncommenting the textmacro, saving your map, closing your map,
//* reopening your map, and commenting the macro again.
//*
//* Note that you, as the user, may edit any of the buff icons or tooltips to
//* your liking. It is not recommended to edit the data fields for the spells,
//* though. They are the way they are so that they will work.
//*
//* WARNING: The ObjectMerger call for Disarm's ability seems to be unable to
//* properly configure the "Data - Attacks Prevented" field. If you
//* find that the DisarmUnit call isn't functioning as intended, then
//* set that field to "None", save your map, set the field back to
//* "Melee, Ranged", and then save your map again. It should now work
//* properly.
//*
//* You may change the raw ids of any of the generated abilities as needed for
//* your map. (If there are conflicts) If you want to do so, then make sure that
//* you change the raw ids inside all affected ObjectMerger calls and the
//* constants in the globals block below.
//*
//* WARNING: If you choose to change the raw id for the Silence ability, do NOT
//* let the buff raw id match the ability raw id. If you do, the buff's
//* special effect fields will not show in-game. (This may or may not
//* even affect you, but it is worth noting regardless)
//*
//* xebasic is an optional requirement. If you have xebasic in your map, this
//* script will use xebasic's dummy unit id instead of the constant below. If
//* you do not have xebasic in your map, for this to work you will need to make
//* (if you have not already) a dummy unit caster for your map. Put its raw id
//* below in the DUMMY_UNITID constant field.
//*
//* Enjoy!
//*
//* Uncomment the following textmacro to create the abilities.
///! runtextmacro GenerateAbilities()
//! textmacro GenerateAbilities
//! externalblock extension=lua ObjectMerger $FILENAME$
//! i
//! i function set(field, value)
//! i makechange(current, field, value)
//! i end
//! i function setl(field, level, value)
//! i makechange(current, field, level, value)
//! i end
//! i
//! i setobjecttype("abilities")
//! i
//! i createobject("AHtb", "stun"); set("anam", "Stun Ability")
//! i set ("aani", "") ; set ("aart", "") ; set ("amat", "") ; set ("amsp", 0) ; setl("Htb1", 1, 0.0);
//! i setl("aran", 1, 99999.0); setl("acdn", 1, 0.0); setl("ahdu", 1, 0.0) ; setl("adur", 1, 0.0) ; set ("arlv", 6) ;
//! i set ("alev", 1) ; setl("amcs", 1, 0) ; set ("arac", "other"); setl("atar", 1, "notself");
//! i
//! i createobject("ANso", "&sil"); set("anam", "Silence Ability")
//! i set ("aart", "") ; setl("Nso1", 1, 0.0); setl("Nso3", 1, 0.0) ; setl("Nso2", 1, 99999.0) ; setl("aran", 1, 99999.0);
//! i setl("abuf", 1, "&SIL"); setl("acdn", 1, 0.0); setl("ahdu", 1, 0.0) ; setl("adur", 1, 0.0) ; set ("arlv", 1);
//! i set ("alev", 1) ; setl("amcs", 1, 0) ; set ("arac", "other"); setl("atar", 1, "notself");
//! i
//! i createobject("ANdh", "&arm"); set("anam", "Disarm Ability")
//! i set ("aart", "") ; set ("amat", "") ; set ("amac", 0.0) ; set ("amsp", 0) ; setl("Nsi1", 1, 3) ;
//! i setl("Nsi2", 1, 0.0) ; setl("Nsi3", 1, 0.0) ; setl("aare", 1, 0.0); setl("aran", 1, 99999.0); setl("abuf", 1, "&ARM");
//! i setl("acdn", 1, 0.0) ; setl("ahdu", 1, 0.0) ; setl("adur", 1, 0.0); set ("arlv", 6) ; set ("alev", 1) ;
//! i setl("amcs", 1, 0) ; set ("arac", "other") ; setl("atar", 1, "notself");
//! i
//! i createobject("ACen", "&ens"); set("anam", "Ensnare Ability")
//! i set ("aart", "") ; set ("amat", "") ; set ("amsp", 0) ; setl("Ens1", 1, -1.0); setl("Ens2", 1, -1.0);
//! i setl("aran", 1, 99999.0) ; setl("abuf", 1, "&EN1,&EN2"); setl("acdn", 1, 0.0); setl("ahdu", 1, 0.0) ; set ("aher", 1) ;
//! i setl("adur", 1, 0.0) ; set ("arlv", 6) ; set ("alev", 1) ; setl("amcs", 1, 0) ; set ("arac", "other");
//! i setl("atar", 1, "notself"); set ("areq", "") ; set("ansf", "") ;
//! i
//! i createobject("ACtb", "&dis"); set("anam", "Disable Ability")
//! i set ("aani", "") ; set ("aart", "") ; set ("amat", "") ; set ("amsp", 0) ; setl("Ctb1", 1, 0.0) ;
//! i setl("aran", 1, 99999.0) ; setl("abuf", 1, "&DIS"); setl("acdn", 1, 0.0); setl("ahdu", 1, 0.0); setl("adur", 1, 0.0) ;
//! i set ("aher", 1) ; set ("arlv", 6) ; set ("alev", 1) ; setl("amcs", 1, 0) ; set ("arac", "other");
//! i setl("atar", 1, "notself");
//! i
//! i setobjecttype("buffs")
//! i
//! i createobject("BNso", "&SIL"); set("fnam", "Disabled (Spells)")
//! i set("ftip", "Disabled (Spells)") ; set("fube", "This unit cannot cast spells.");
//! i set("fart", "ReplaceableTextures\\CommandButtons\\BTNCancel.blp"); set("ftat", "") ; set("fta0", "");
//! i
//! i createobject("BNdh", "&ARM"); set("fnam", "Disabled (Attacks)")
//! i set("ftip", "Disabled (Attacks)") ; set("fube", "This unit cannot attack.");
//! i set("fart", "ReplaceableTextures\\CommandButtons\\BTNCancel.blp"); set("ftat", "") ; set("fta0", "");
//! i
//! i createobject("Beng", "&EN1"); set("fnam", "Disabled (Movement)")
//! i set("ftip", "Disabled (Movement)") ; set("fube", "This unit cannot move." );
//! i set("fart", "ReplaceableTextures\\CommandButtons\\BTNCancel.blp"); set("ftat", "") ; set("frac", "other");
//! i
//! i createobject("Bena", "&EN2"); set("fnam", "Disabled (Movement)")
//! i set("ftip", "Disabled (Movement)") ; set("fube", "This unit cannot move.");
//! i set("fart", "ReplaceableTextures\\CommandButtons\\BTNCancel.blp"); set("ftat", "") ; set("fta0", "");
//! i set("frac", "other");
//! i
//! i createobject("BPSE", "&DIS"); set("fnam", "Disabled")
//! i set("ftip", "Disabled") ; set("fube", "This unit cannot do anything.");
//! i set("fart", "ReplaceableTextures\\CommandButtons\\BTNCancel.blp"); set("ftat", "") ; set("fta0", "")
//! i
//! endexternalblock
//! endtextmacro GenerateAbilities
globals
//General constants
private constant integer DUMMY_UNITID = 'e000' //Replace this with your dummy's id
//Stun constants
private constant integer STUN_ID = 'stun' //This needs to match the ObjectMerger call above
private constant integer STUN_ORDER_ID = 852095 //Order id to stun a unit
private constant integer STUN_BUFF_ID = 'BPSE' //Normal storm bolt stun buff
//Silence constants
private constant integer SILENCE_ID = '&sil' //This needs to match the ObjectMerger call above
private constant integer SILENCE_ORDER_ID = 852668 //Order id to soul burn a unit
private constant integer SILENCE_BUFF_ID = '&SIL' //Generated soul burn based buff
//Disarm constants
private constant integer DISARM_ID = '&arm' //This needs to match the ObjectMerger call above
private constant integer DISARM_ORDER_ID = 852585 //Order id to drunken haze a unit
private constant integer DISARM_BUFF_ID = '&ARM' //Generated drunken haze based buff
//Ensnare constants
private constant integer ENSNARE_ID = '&ens' //This needs to match the ObjectMerger call above
private constant integer ENSNARE_ORDER_ID = 852106 //Order id to ensnare a unit
private constant integer ENSNARE_BUFF_ID = '&EN1' //Generated ensnare based buff (ground)
private constant integer ENSNARE_BUFF_ID2 = '&EN2' //Generated ensnare based buff (air)
//Disable constants
private constant integer DISABLE_ID = '&dis' //This needs to match the ObjectMerger call above
private constant integer DISABLE_ORDER_ID = 852252 //Order id to hurl boulder at a unit
private constant integer DISABLE_BUFF_ID = '&DIS' //Generated hurl boulder based buff
endglobals
globals
private unit Caster = null //Dummy caster
private timer Temp = null //For callback referencing
endglobals
//******************************************************************************
//! textmacro UnitStatus_GenerateBase takes TYPE, CONSTANT, STRUCTNAME, INJECTPOSTBUFF, INJECTCHECK, INJECTPREBUFF
private struct clear$TYPE$
unit u = null
//Exists only for clearing on Add/Remove situations
static method create takes unit t returns thistype
local thistype c = thistype.allocate()
set c.u = t
return c
endmethod
endstruct
private function TimerRemove$TYPE$ takes nothing returns nothing
local clear$TYPE$ c = clear$TYPE$(GetTimerData(GetExpiredTimer()))
local unit whichUnit = c.u
if $TYPE$Counter[GetUnitId(c.u)] == 0 then
//Make sure we should still remove it
call UnitRemoveAbility(c.u, $CONSTANT$_BUFF_ID)
$INJECTPOSTBUFF$
endif
call ReleaseTimer(GetExpiredTimer())
call c.destroy()
set whichUnit = null
endfunction
function $TYPE$Unit takes unit whichUnit, boolean flag returns boolean
local integer id = GetUnitId(whichUnit)
local boolean b = true
if whichUnit == null then
//Target can't be null
debug call BJDebugMsg(SCOPE_PREFIX+"Error: Null unit given to $TYPE$Unit")
return false
endif
if flag then
if $TYPE$Counter[id] == 0 $INJECTCHECK$ then
//Buff the unit
$INJECTPREBUFF$
call UnitShareVision(whichUnit, GetOwningPlayer(Caster), true)
set b = IssueTargetOrderById(Caster, $CONSTANT$_ORDER_ID, whichUnit)
call UnitShareVision(whichUnit, GetOwningPlayer(Caster), false)
endif
if not b then
//Cast failed somehow
debug call BJDebugMsg(SCOPE_PREFIX+"Error: Unit could not be buffed ($TYPE$Unit)")
return false
endif
set $TYPE$Counter[id] = $TYPE$Counter[id] + 1
elseif $TYPE$Counter[id] > 0 then //Only run this if unit is buffed at all
//Decrement Counter
set $TYPE$Counter[id] = $TYPE$Counter[id] - 1
if $TYPE$Counter[id] == 0 then
//Clear the buff
if GetUnitAbilityLevel(whichUnit, $CONSTANT$_BUFF_ID) == 0 then
//Remove it in a 0.01s callback because it hasn't been applied yet
set Temp = NewTimer()
call SetTimerData(Temp, integer(clear$TYPE$.create(whichUnit)))
call TimerStart(Temp, 0.01, false, function TimerRemove$TYPE$)
else
call UnitRemoveAbility(whichUnit, $CONSTANT$_BUFF_ID)
$INJECTPOSTBUFF$
endif
endif
else
//Unit doesn't have the buff we're trying to remove
return false
endif
return true
endfunction
private struct $STRUCTNAME$
timer t
unit tar
real dur
private static method end takes nothing returns nothing
call thistype(GetTimerData(GetExpiredTimer())).destroy()
endmethod
static method start takes unit target, real duration returns boolean
local thistype s
local boolean b = $TYPE$Unit(target, true)
if not b then
//Failed, return false
return false
endif
set s = thistype.allocate()
set s.tar = target
set s.dur = duration
set s.t = NewTimer()
call SetTimerData(s.t, integer(s))
call TimerStart(s.t, duration, false, function $STRUCTNAME$.end)
return true
endmethod
private method onDestroy takes nothing returns nothing
call $TYPE$Unit(.tar, false)
call ReleaseTimer(.t)
endmethod
endstruct
function $TYPE$UnitTimed takes unit whichUnit, real duration returns boolean
if duration <= 0.01 then
debug call BJDebugMsg(SCOPE_PREFIX+"Error: Less than 0.01 duration given to $TYPE$UnitTimed")
return false
endif
return $STRUCTNAME$.start(whichUnit, duration)
endfunction
//! endtextmacro
//******************************************************************************
//Declare all necessary globals first
globals
private integer array StunCounter
private integer array SilenceCounter
private integer array DisarmCounter
private integer array EnsnareCounter
private integer array DisableCounter
endglobals
//Special functions for Stun
private function StunLingeringDisable takes unit u returns nothing
local integer id = GetUnitId(u)
if DisableCounter[id] > 0 then
//Add the disabled buff because it lingers on
call UnitShareVision(u, GetOwningPlayer(Caster), true)
call IssueTargetOrderById(Caster, DISABLE_ORDER_ID, u)
call UnitShareVision(u, GetOwningPlayer(Caster), false)
endif
endfunction
private function StunFinishDisable takes unit u returns nothing
local integer id = GetUnitId(u)
if DisableCounter[id] > 0 then
//Remove the disable buff for first refcount stun
call UnitRemoveAbility(u, DISABLE_BUFF_ID)
endif
endfunction
//Generates all of the base code
//! runtextmacro UnitStatus_GenerateBase("Stun" , "STUN" , "stun" , "call StunLingeringDisable(whichUnit)", "", "call StunFinishDisable(whichUnit)")
//! runtextmacro UnitStatus_GenerateBase("Silence", "SILENCE", "silence", "", "", "")
//! runtextmacro UnitStatus_GenerateBase("Disarm" , "DISARM" , "disarm" , "", "", "")
//! runtextmacro UnitStatus_GenerateBase("Ensnare", "ENSNARE", "ensnare", "call UnitRemoveAbility(whichUnit, ENSNARE_BUFF_ID2)", "", "")
//! runtextmacro UnitStatus_GenerateBase("Disable", "DISABLE", "disable", "", "and StunCounter[id] == 0", "")
private function Init takes nothing returns nothing
static if LIBRARY_xebasic then
set Caster = CreateUnit(Player(15), XE_DUMMY_UNITID, 0., 0., 0.)
else
set Caster = CreateUnit(Player(15), DUMMY_UNITID , 0., 0., 0.)
endif
call UnitRemoveAbility(Caster, 'Amov')
if GetUnitAbilityLevel(Caster, 'Aloc') == 0 then
call UnitAddAbility(Caster, 'Aloc') //xe dummies don't have this automatically
endif
//Add the abilities
call UnitAddAbility(Caster, STUN_ID)
call UnitAddAbility(Caster, SILENCE_ID)
call UnitAddAbility(Caster, DISARM_ID)
call UnitAddAbility(Caster, ENSNARE_ID)
call UnitAddAbility(Caster, DISABLE_ID)
endfunction
endlibrary
//TESH.scrollpos=0
//TESH.alwaysfold=0
library xebasic
//**************************************************************************
//
// xebasic 0.4
// =======
// XE_DUMMY_UNITID : Rawcode of the dummy unit in your map. It should
// use the dummy.mdx model, so remember to import it as
// well, just use copy&paste to copy the dummy from the
// xe map to yours, then change the rawcode.
//
// XE_HEIGHT_ENABLER: Medivh's raven form ability, you may need to change
// this rawcode to another spell that morphs into a flier
// in case you modified medivh's spell in your map.
//
// XE_TREE_RECOGNITION: The ancients' Eat tree ability, same as with medivh
// raven form, you might have to change it.
//
// XE_ANIMATION_PERIOD: The global period of animation used by whatever
// timer that depends on it, if you put a low value
// the movement will look good but it may hurt your
// performance, if instead you use a high value it
// will not lag but will be fast.
//
// XE_MAX_COLLISION_SIZE: The maximum unit collision size in your map, if
// you got a unit bigger than 197.0 it would be
// a good idea to update this constant, since some
// enums will not find it. Likewise, if none of
// your units can go bellow X and X is much smaller
// than 197.0, it would be a good idea to update
// as well, since it will improve the performance
// those enums.
//
// Notice you probably don't have to update this library, unless I specify
// there are new constants which would be unlikely.
//
//**************************************************************************
//===========================================================================
globals
constant integer XE_DUMMY_UNITID = 'e000'
constant integer XE_HEIGHT_ENABLER = 'Amrf'
constant integer XE_TREE_RECOGNITION = 'Aeat'
constant real XE_ANIMATION_PERIOD = 0.025
constant real XE_MAX_COLLISION_SIZE = 197.0
endglobals
endlibrary
//TESH.scrollpos=197
//TESH.alwaysfold=0
library AutoIndex
//===========================================================================
// Information:
//==============
//
// AutoIndex is a very simple script to utilize. Just call GetUnitId(unit) to
// get get the unique value assigned to a particular unit. AutoIndex differs from
// other unit indexing libraries because it automatically assigns an ID to each
// unit as it enters the map, and automatically frees that ID as the unit leaves
// the map. This gives you several advantages as the user:
// -The GetUnitId function inlines directly to a GetUnitUserData call (or a
// LoadInteger call if the UseUnitUserData constant is set to false.)
// -You don't need to manually free IDs as units leave the map.
// -Detecting removing units to free their indexes is O(1), and less costly
// performance-wise than a timer scanning the map for removed units.
//
// If you turn on debug mode, AutoIndex will become slower, but it will be able
// to display several helpful error messages. It can detect the following issues:
// -Passing a removed or decayed unit to GetUnitId
// -Code outside of AutoIndex has overwritten a unit's UserData value.
// -GetUnitId was used on a filtered unit (a unit you don't want indexed).
//
// AutoIndex uses UnitUserData by default. If something else in your map
// would conflict with that, you can set the UseUnitUserData configuration
// constant to false, and a hashtable will be used instead. Note that hash-
// tables are about 60% slower.
//
// AutoIndex provides events upon indexing or deindexing units. This
// effectively allows you to notice when units enter or leave the game, and
// handle the creation or destruction of attached data or other things. Also
// included is the AutoStruct module, which automatically creates and destroys
// struct instances associated with units as they enter and leave the game.
//
//===========================================================================
// How to install AutoIndex:
//===========================
//
// 1.) Copy and paste this script into your map.
// 2.) Save it to allow the ObjectMerger macro to generate the "Leave Detect"
// ability for you. Close and re-open the map. After that, disable the macro
// to prevent the save delay.
//
//===========================================================================
// How to use AutoIndex:
//=======================
//
// So you can get a unique integer for each unit, but how do you use that to
// attach data to a unit? GetUnitId will always return a number in the range of
// 1-8190. This means it can be used as an array index, as demonstrated below:
/*
globals
integer array IntegerData
real array RealData
SomeStruct array SomeStructData
englobals
function Example takes nothing returns nothing
local unit u = CreateUnit(...)
local integer id = GetUnitId(u)
//You now have a unique index for the unit, so you can
//attach or retrieve data about the unit using arrays.
set IntegerData[id] = 5
set RealData[id] = 25.0
set SomeStructData[id] = SomeStruct.create()
//If you have access to the same unit in another function, you can
//retrieve the data by using GetUnitId() and reading the arrays.
endfunction
*/
// The UnitFilter function in the configuration section is provided so that
// you can make AutoIndex completely ignore certain unit-types. Ignored units
// won't be indexed or fire indexed/deindexed events. You may want to filter out
// dummy casters or system-private units, especially ones that use UnitUserData
// internally. xe dummy units are automatically filtered.
//
//===========================================================================
// How to use OnUnitIndexed / OnUnitDeindexed:
//=============================================
//
// AutoIndex will fire the OnUnitIndexed event when a unit enters the map,
// and the OnUnitDeindexed event when a unit leaves the map. Functions used
// as events must take a unit and return nothing. An example is given below:
/*
function UnitEntersMap takes unit u returns nothing
call BJDebugMsg(GetUnitName(u)+" was indexed with the ID "+I2S(GetUnitId(u)))
endfunction
function UnitLeavesMap takes unit u returns nothing
call BJDebugMsg(GetUnitName(u)+" was deindexed with the ID "+I2S(GetUnitId(u)))
endfunction
function Init takes nothing returns nothing
call OnUnitIndexed(UnitEntersMap)
call OnUnitDeindexed(UnitLeavesMap)
endfunction
*/
// As you can see, it works perfectly fine to call GetUnitId() on a unit
// during either of these events.
//
// If you call OnUnitIndexed during map initialization, every existing
// unit will be considered as entering the map. This saves you from needing
// to manually enumerate preplaced units (or units created by initialization
// code that ran before OnUnitIndexed was called).
//
// OnUnitDeindexed runs while a unit still exists, which means you can
// still do things such as destroy special effects attached to the unit.
// The unit will cease to exist immediately after the event is over.
//
//===========================================================================
// AutoIndex API:
//================
//
// GetUnitId(unit) -> integer
// This function returns a unique ID in the range of 1-8190 for the
// specified unit. Ruturns 0 if a null unit was passed. This function
// inlines directly to GetUnitUserData or LoadInteger if debug mode
// is disabled. If debug mode is enabled, this function will print
// an error message when passed a decayed or filtered unit.
//
// OnUnitIndexed(IndexFunc)
// This function accepts an IndexFunc, which must take a unit and
// return nothing. The IndexFunc will be fired instantly whenever
// a unit enters the map. You may use GetUnitId on the unit. When
// you call this function during map initialization, every existing
// unit will be considered as entering the map.
//
// OnUnitDeindexed(IndexFunc)
// Same as above, but runs whenever a unit is leaving the map. When
// this event runs, the unit still exists, but it will cease to exist
// as soon as the event ends. You may use GetUnitId on the unit.
//
//===========================================================================
// How to use the AutoStruct module:
//===================================
//
// The AutoStruct module allows you to automatically create and destroy
// struct instances as units enter and leave the game. An instance of the
// implementing struct will be created each time a unit enters the game,
// and destroyed when that unit leaves the game. (You cannot create or dest-
// roy instances manually.) This means that you should consider each inst-
// ance of an AutoStruct to be "owned by" a specific unit.
//
// AutoStruct restrictions:
// -You may not implement AutoStruct in any struct that declares its
// own create, destroy, or operator[] methods.
//
// -You may not manually create or destroy structs implementing AutoStruct.
// Creation and destruction are handled automatically as units enter/leave.
//
// -AutoStruct may be implemented in structs that extend interfaces or
// other structs, but only if the allocate() method takes no parameters.
// (The restriction of allocate() taking no parameters may be changed soon.)
//
// -AutoStruct will not work with structs that extend array, since they
// can't be created or destroyed.
//
// AutoStruct features:
// -An instance of the implementing struct will be created each time a
// unit enters the game. That instance will be destroyed when that unit
// leaves the game. The struct will always exist while the unit does.
//
// -You can retrieve an AutoStruct from a unit by using the syntax:
// local StructName mystruct = StructName[unit]
// //This inlines to a GetUnitId() call + array lookup.
//
// -You can refer to the unit that owns the instance by the member "me":
// //Outside of the struct: call BJDebugMsg(GetUnitName(mystruct.me))
// //From within the struct: call BJDebugMsg(GetUnitName(me))
//
// -You can use the optional methods onCreate and onDestroy to notice when
// instances of a struct implementing AutoStruct are created and destroyed.
// This is equivalent to detecting a unit entering and leaving the game.
/*
struct Example
private method onCreate takes nothing returns nothing
call BJDebugMsg(GetUnitName(me)+" has entered the game!")
endmethod
private method onDestroy takes nothing returns nothing
call BJDebugMsg(GetUnitName(me)+" has left the game!")
endmethod
implement AutoStruct
endstruct
*/
// -You can filter which units will recieve an AutoStruct by using the
// optional static method createFilter. The createFiler method must take
// a unit parameter and return a boolean (true if created, false if not).
/*
struct Example
private static method createFiler takes unit u returns boolean
return GetUnitTypeId(u) == 'hfoo' //Only Footmen will recieve this AutoStruct.
endmethod
implement AutoStruct
endstruct
*/
//
//===========================================================================
// Configuration:
//================
///! external ObjectMerger w3a Adef lvdt anam "Leave Detect" aart "" arac 0
//Save your map with this Object Merger call enabled, then close and reopen your
//map. Disable it by removing the exclamation to remove the delay while saving.
globals
private constant integer LeaveDetectAbilityID = 'lvdt'
//This rawcode must match the parameter after "Adef" in the
//ObjectMergermacro above. You can change both if you want.
private constant boolean UseUnitUserData = true
//If this is set to true, UnitUserData will be used. You should only set
//this to false if something else in your map already uses UnitUserData.
//A hashtable will be used instead, but it is about 60% slower.
endglobals
private function UnitFilter takes unit u returns boolean
return true
endfunction
//Make this function return false for any unit-types you wish to be ignored.
//Ignored units won't be indexed or fire OnUnitIndexed/OnUnitDeindexed
//events. Use the unit u parameter to refer to the unit being filtered.
//You do not need to filter out xe dummy units; they are already filtered.
//===========================================================================
// AutoStruct module:
//====================
function interface AutoStructCreator takes unit u returns integer
function interface AutoStructDestroyer takes unit u returns nothing
module AutoStruct
private static thistype array data
unit me //The unit that "owns" this struct instance is referred to as "me".
static method operator [] takes unit u returns thistype
return data[GetUnitId(u)] //Return the struct instance associated with the unit.
endmethod
private static method create takes unit u returns thistype
local thistype this
static if thistype.createFilter.exists then //If the createFiler exists...
if not createFilter(u) then //If the unit fails the createFilter...
return 0 //Don't allocate a struct for this unit.
endif
endif
set this = allocate() //Allocate the struct.
set me = u //Assign the "me" unit of this struct to the entering unit.
set data[GetUnitId(u)] = this //Attach this instance to the unit.
static if thistype.onCreate.exists then //If onCreate exists...
call onCreate() //Call the onCreate() method for this struct.
endif
return this
endmethod
//create is private; the user doesn't create AutoStructs. They are created
//automatically when a unit enters the game and passes the createFilter.
private method destroy takes nothing returns nothing
endmethod
//destroy is private; the user doesn't destroy AutoStructs. They are destroyed
//automatically when their corresponding units leave the game.
private static method destroyer takes unit u returns nothing
local thistype this = thistype[u] //Get the instance of the struct for this unit.
if this != 0 then //If it has an instance...
call deallocate() //Deallocate it, calling onDestroy.
set .data[GetUnitId(me)] = 0 //Null the unit's associated struct instance.
set me = null //Null the unit reference.
endif
endmethod
private static method onInit takes nothing returns nothing
call AutoIndex.addAutoStruct(thistype.create, thistype.destroyer)
//Pass pointers to the create and destroyer functions to AutoIndex, so
//that it can create/destroy instances as units are indexed/deindexed.
endmethod
endmodule
//===========================================================================
// AutoIndex struct:
//===================
hook RemoveUnit AutoIndex.hook_RemoveUnit
hook ReplaceUnitBJ AutoIndex.hook_ReplaceUnitBJ
debug hook SetUnitUserData AutoIndex.hook_SetUnitUserData
struct AutoIndex
private static trigger enter = CreateTrigger()
private static trigger order = CreateTrigger()
private static trigger creepdeath = CreateTrigger()
private static group preplaced = CreateGroup()
private static timer allowdecay = CreateTimer()
private static hashtable ht
private static boolean array dead
private static boolean array summoned
private static boolean array animated
private static boolean array nodecay
private static boolean array removing
private static IndexFunc array indexfuncs
private static integer indexfuncs_n = -1
private static IndexFunc array deindexfuncs
private static integer deindexfuncs_n = -1
private static IndexFunc indexfunc
private static AutoStructCreator array creators
private static AutoStructDestroyer array destroyers
private static integer autostructs_n = -1
private static unit array allowdecayunit
private static integer allowdecay_n = -1
private static boolean duringinit = true
private static boolean array altered
private static unit array idunit
//===========================================================================
static method getIndex takes unit u returns integer
static if UseUnitUserData then
return GetUnitUserData(u)
else
return LoadInteger(ht, 0, GetHandleId(u))
endif
endmethod
//Resolves to an inlinable one-liner after the static if.
static method getIndexDebug takes unit u returns integer
if u == null then
return 0
elseif GetUnitTypeId(u) == 0 then
call BJDebugMsg("AutoIndex error: Removed or decayed unit passed to GetUnitId.")
elseif idunit[getIndex(u)] != u and GetIssuedOrderId() != 852056 then
call BJDebugMsg("AutoIndex error: "+GetUnitName(u)+" is a filtered unit.")
endif
return getIndex(u)
endmethod
//If debug mode is enabled, use the getIndex method that shows errors.
static method setIndex takes unit u, integer index returns nothing
static if UseUnitUserData then
call SetUnitUserData(u, index)
else
call SaveInteger(ht, 0, GetHandleId(u), index)
endif
endmethod
//Resolves to an inlinable one-liner after the static if.
static method isUnitAnimateDead takes unit u returns boolean
return animated[getIndex(u)]
endmethod
//Don't use this; use IsUnitAnimateDead from AutoEvents instead.
//===========================================================================
private static method onUnitIndexed_sub takes nothing returns nothing
call indexfunc.evaluate(GetEnumUnit())
endmethod
static method onUnitIndexed takes IndexFunc func returns nothing
set indexfuncs_n = indexfuncs_n + 1
set indexfuncs[indexfuncs_n] = func
if duringinit then
set indexfunc = func
//During initialization, evaluate the indexfunc for every preplaced unit.
call ForGroup(preplaced, function AutoIndex.onUnitIndexed_sub)
endif
endmethod
static method onUnitDeindexed takes IndexFunc func returns nothing
set deindexfuncs_n = deindexfuncs_n + 1
set deindexfuncs[deindexfuncs_n] = func
endmethod
static method addAutoStruct takes AutoStructCreator creator, AutoStructDestroyer destroyer returns nothing
set autostructs_n = autostructs_n + 1
set creators[autostructs_n] = creator
set destroyers[autostructs_n] = destroyer
endmethod
//===========================================================================
private static method hook_RemoveUnit takes unit whichUnit returns nothing
set removing[getIndex(whichUnit)] = true
endmethod
private static method hook_ReplaceUnitBJ takes unit whichUnit, integer newUnitId, integer unitStateMethod returns nothing
set removing[getIndex(whichUnit)] = true
endmethod
//Intercepts whenever RemoveUnit or ReplaceUnitBJ is called and sets a flag.
private static method hook_SetUnitUserData takes unit whichUnit, integer data returns nothing
static if UseUnitUserData then
if idunit[getIndex(whichUnit)] == whichUnit then
if getIndex(whichUnit) == data then
call BJDebugMsg("AutoIndex error: Code outside AutoIndex attempted to alter "+GetUnitName(whichUnit)+"'s index.")
else
call BJDebugMsg("AutoIndex error: Code outside AutoIndex altered "+GetUnitName(whichUnit)+"'s index.")
if idunit[data] != null then
call BJDebugMsg("AutoIndex error: "+GetUnitName(whichUnit)+" and "+GetUnitName(idunit[data])+" now have the same index.")
endif
set altered[data] = true
endif
endif
endif
endmethod
//In debug mode, intercepts whenever SetUnitUserData is used on an indexed unit.
//Displays an error message if outside code tries to alter a unit's index.
//===========================================================================
private static method allowDecay takes nothing returns nothing
local integer n = allowdecay_n
loop
exitwhen n < 0
set nodecay[getIndex(allowdecayunit[n])] = false
set allowdecayunit[n] = null
set n = n - 1
endloop
set allowdecay_n = -1
endmethod
//Iterate through all the units in the stack and allow them to decay again.
private static method detectStatus takes nothing returns boolean
local unit u = GetTriggerUnit()
local integer index = getIndex(u)
local integer n
if idunit[index] == u then //Ignore non-indexed units.
if not IsUnitType(u, UNIT_TYPE_DEAD) then
if dead[index] then //The unit was dead, but now it's alive.
set dead[index] = false //The unit has been resurrected.
//! runtextmacro optional RunAutoEvent("Resurrect")
//If AutoEvents is in the map, run the resurrection events.
if IsUnitType(u, UNIT_TYPE_SUMMONED) and not summoned[index] then
set summoned[index] = true //If the unit gained the summoned flag,
set animated[index] = true //it's been raised with Animate Dead.
//! runtextmacro optional RunAutoEvent("AnimateDead")
//If AutoEvents is in the map, run the Animate Dead events.
endif
endif
else
if not removing[index] and not dead[index] and not animated[index] then
set dead[index] = true //The unit was alive, but now it's dead.
set nodecay[index] = true //A dead unit can't decay for at least 0. seconds.
set allowdecay_n = allowdecay_n + 1 //Add the unit to a stack. After the timer
set allowdecayunit[allowdecay_n] = u //expires, allow the unit to decay again.
call TimerStart(allowdecay, 0., false, function AutoIndex.allowDecay)
//! runtextmacro optional RunAutoEvent("Death")
//If AutoEvents is in the map, run the Death events.
//! runtextmacro optional TransportUnload()
//If TransportEvents is in the map, remove the dead unit from whatever transport it's in.
elseif removing[index] or (dead[index] and not nodecay[index]) or (not dead[index] and animated[index]) then
//If .nodecay was false and the unit is dead and was previously dead, the unit decayed.
//If .animated was true and the unit is dead, the unit died and exploded.
//If .removing was true, the unit is being removed or replaced.
//! runtextmacro optional TransportUnload()
//If TransportEvents is in the map, remove the leaving unit from whatever transport it's in.
set n = deindexfuncs_n
loop //Run the OnUnitDeindexed events.
exitwhen n < 0
call deindexfuncs[n].evaluate(u)
set n = n - 1
endloop
//! runtextmacro optional DestroyUnitLists()
//If UnitListModule is in the map, destroy all of the UnitLists associated with the leaving unit.
set n = autostructs_n
loop //Destroy AutoStructs for the leaving unit.
exitwhen n < 0
call destroyers[n].evaluate(u)
set n = n - 1
endloop
//! runtextmacro optional TransportClean()
//If TransportEvents is in the map, and the leaving unit is a
//transport, clean the transport- related data from the unit.
call AutoIndex(index).destroy() //Free the index by destroying the AutoIndex struct.
set idunit[index] = null //Null this unit reference to prevent a leak.
endif
endif
endif
set u = null
return false
endmethod
//===========================================================================
private static method unitEntersMap takes unit u returns nothing
local integer index
local integer n = 0
if getIndex(u) != 0 then
return //Don't index a unit that already has an ID.
endif
static if LIBRARY_xebasic then
if GetUnitTypeId(u) == XE_DUMMY_UNITID then
return //Don't index xe dummy units.
endif
endif
if not UnitFilter(u) then
return //Don't index units that fail the unit filter.
endif
set index = create()
call setIndex(u, index) //Assign an index to the entering unit.
call UnitAddAbility(u, LeaveDetectAbilityID) //Add the leave detect ability to the entering unit.
call UnitMakeAbilityPermanent(u, true, LeaveDetectAbilityID) //Prevent it from disappearing on morph.
set dead[index] = IsUnitType(u, UNIT_TYPE_DEAD) //Reset all of the flags for the entering
set summoned[index] = IsUnitType(u, UNIT_TYPE_SUMMONED) //unit. These flags are necessary to detect
set animated[index] = false //when the unit leaves the map.
set nodecay[index] = false
set removing[index] = false
debug set altered[index] = false //In debug mode, this flag tracks wheter a unit's index was altered.
set idunit[index] = u //Attach the unit that is supposed to have this index to the index.
if duringinit then
call GroupAddUnit(preplaced, u) //Add units that are created during initialization to the preplaced
//units group. This ensures that all units are noticed by OnUnitIndexed during initialization.
endif
loop //Create AutoStructs for the entering unit.
exitwhen n > autostructs_n
call creators[n].evaluate(u)
set n = n + 1
endloop
set n = 0
loop //Run the OnUnitIndexed events.
exitwhen n > indexfuncs_n
call indexfuncs[n].evaluate(u)
set n = n + 1
endloop
endmethod
private static method onIssuedOrder takes nothing returns boolean
if getIndex(GetTriggerUnit()) == 0 then
call unitEntersMap(GetTriggerUnit())
endif //If the unit doesn't have an index at this point, assign it one.
//This is necessary to catch units with default-on autocast abilities
//when using GetUnitId on a newly created unit within an order event.
//! runtextmacro optional TransportUnloadCheck()
//If TransportEvents is in the map, check whether a unit is unloading.
return GetIssuedOrderId() == 852056 //If the order is Undefend, allow detectStatus to run.
endmethod
private static method initEnteringUnit takes nothing returns boolean
call unitEntersMap(GetFilterUnit())
return false
endmethod
//===========================================================================
private static method afterInit takes nothing returns nothing
set duringinit = false //Initialization is over; set a flag.
call DestroyTimer(GetExpiredTimer()) //Destroy the timer.
call GroupClear(preplaced) //The preplaced units group is
call DestroyGroup(preplaced) //no longer needed, so clean it.
set preplaced = null
endmethod
private static method onInit takes nothing returns nothing
local region maparea = CreateRegion()
local rect bounds = GetWorldBounds()
local group g = CreateGroup()
local integer i = 15
static if not UseUnitUserData then
set ht = InitHashtable() //Only create a hashtable if it will be used.
endif
loop
exitwhen i < 0
call SetPlayerAbilityAvailable(Player(i), LeaveDetectAbilityID, false)
//Make the LeaveDetect ability unavailable so that it doesn't show up on the command card of every unit.
call TriggerRegisterPlayerUnitEvent(order, Player(i), EVENT_PLAYER_UNIT_ISSUED_ORDER, null)
//Register the "EVENT_PLAYER_UNIT_ISSUED_ORDER" event for each player.
call GroupEnumUnitsOfPlayer(g, Player(i), function AutoIndex.initEnteringUnit)
//Enum every non-filtered unit on the map during initialization and assign it a unique
//index. By using GroupEnumUnitsOfPlayer, even units with Locust can be detected.
set i = i - 1
endloop
call TriggerAddCondition(order, And(function AutoIndex.onIssuedOrder, function AutoIndex.detectStatus))
//The detectStatus method will fire every time a non-filtered unit recieves an undefend order.
//And() is used here to avoid using a trigger action, which starts a new thread and is slower.
call TriggerRegisterPlayerUnitEvent(creepdeath, Player(12), EVENT_PLAYER_UNIT_DEATH, null)
call TriggerAddCondition(creepdeath, function AutoIndex.detectStatus)
//The detectStatus method must also fire when a neutral hostile creep dies, in case it was
//sleeping. Sleeping creeps don't fire undefend orders on non-damaging deaths.
call RegionAddRect(maparea, bounds) //GetWorldBounds() includes the shaded boundry areas.
call TriggerRegisterEnterRegion(enter, maparea, function AutoIndex.initEnteringUnit)
//The filter function of an EnterRegion trigger runs instantly when a unit is created.
call TimerStart(CreateTimer(), 0., false, function AutoIndex.afterInit)
//After any time elapses, perform after-initialization actions.
call GroupClear(g)
call DestroyGroup(g)
call RemoveRect(bounds)
set g = null
set bounds = null
endmethod
endstruct
//===========================================================================
// User functions:
//=================
function GetUnitId takes unit u returns integer
static if DEBUG_MODE then
return AutoIndex.getIndexDebug(u)
else
return AutoIndex.getIndex(u)
endif
endfunction
function interface IndexFunc takes unit u returns nothing
function OnUnitIndexed takes IndexFunc func returns nothing
call AutoIndex.onUnitIndexed(func)
endfunction
function OnUnitDeindexed takes IndexFunc func returns nothing
call AutoIndex.onUnitDeindexed(func)
endfunction
endlibrary