#region Copyright & License Information /* * Copyright 2007-2014 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using System; using System.Collections.Generic; using System.Linq; using Eluant; using OpenRA.Primitives; using OpenRA.Scripting; using OpenRA.Traits; namespace OpenRA.Mods.RA.Scripting { [Desc("Allows map scripts to attach triggers to this actor via the Triggers global.")] public class ScriptTriggersInfo : TraitInfo { } public sealed class ScriptTriggers : INotifyIdle, INotifyDamage, INotifyKilled, INotifyProduction, IDisposable { public event Action OnKilledInternal = _ => {}; List> onIdle = new List>(); List> onDamaged = new List>(); List> onKilled = new List>(); List> onProduction = new List>(); public void RegisterIdleCallback(LuaFunction func, ScriptContext context) { onIdle.Add(Pair.New((LuaFunction)func.CopyReference(), context)); } public void RegisterDamagedCallback(LuaFunction func, ScriptContext context) { onDamaged.Add(Pair.New((LuaFunction)func.CopyReference(), context)); } public void RegisterKilledCallback(LuaFunction func, ScriptContext context) { onKilled.Add(Pair.New((LuaFunction)func.CopyReference(), context)); } public void RegisterProductionCallback(LuaFunction func, ScriptContext context) { onProduction.Add(Pair.New((LuaFunction)func.CopyReference(), context)); } public void TickIdle(Actor self) { foreach (var f in onIdle) { var a = self.ToLuaValue(f.Second); f.First.Call(a).Dispose(); a.Dispose(); } } public void Damaged(Actor self, AttackInfo e) { foreach (var f in onDamaged) { var a = self.ToLuaValue(f.Second); var b = e.Attacker.ToLuaValue(f.Second); f.First.Call(a, b).Dispose(); a.Dispose(); b.Dispose(); } } public void Killed(Actor self, AttackInfo e) { // Run lua callbacks foreach (var f in onKilled) { var a = self.ToLuaValue(f.Second); var b = e.Attacker.ToLuaValue(f.Second); f.First.Call(a, b).Dispose(); a.Dispose(); b.Dispose(); } // Run any internally bound callbacks OnKilledInternal(self); } public void UnitProduced(Actor self, Actor other, CPos exit) { foreach (var f in onProduction) { var a = self.ToLuaValue(f.Second); var b = other.ToLuaValue(f.Second); f.First.Call(a, b).Dispose(); a.Dispose(); b.Dispose(); } } public void Dispose() { var pairs = new[] { onIdle, onDamaged, onKilled, onProduction }; pairs.SelectMany(l => l).Select(p => p.First).Do(f => f.Dispose()); pairs.Do(l => l.Clear()); } } }