ScriptInstance.cs 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.IO;
  29. using System.Runtime.Remoting;
  30. using System.Runtime.Remoting.Lifetime;
  31. using System.Threading;
  32. using System.Collections;
  33. using System.Collections.Generic;
  34. using System.Security.Policy;
  35. using System.Reflection;
  36. using System.Globalization;
  37. using System.Xml;
  38. using OpenMetaverse;
  39. using log4net;
  40. using Nini.Config;
  41. using Amib.Threading;
  42. using OpenSim.Framework;
  43. using OpenSim.Region.CoreModules;
  44. using OpenSim.Region.Framework.Scenes;
  45. using OpenSim.Region.Framework.Interfaces;
  46. using OpenSim.Region.ScriptEngine.Shared;
  47. using OpenSim.Region.ScriptEngine.Shared.Api;
  48. using OpenSim.Region.ScriptEngine.Shared.Api.Runtime;
  49. using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
  50. using OpenSim.Region.ScriptEngine.Shared.CodeTools;
  51. using OpenSim.Region.ScriptEngine.Interfaces;
  52. namespace OpenSim.Region.ScriptEngine.Shared.Instance
  53. {
  54. public class ScriptInstance : MarshalByRefObject, IScriptInstance
  55. {
  56. // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  57. private IScriptEngine m_Engine;
  58. private IScriptWorkItem m_CurrentResult = null;
  59. private Queue m_EventQueue = new Queue(32);
  60. private bool m_RunEvents = false;
  61. private UUID m_ItemID;
  62. private uint m_LocalID;
  63. private UUID m_ObjectID;
  64. private UUID m_AssetID;
  65. private IScript m_Script;
  66. private UUID m_AppDomain;
  67. private DetectParams[] m_DetectParams;
  68. private bool m_TimerQueued;
  69. private DateTime m_EventStart;
  70. private bool m_InEvent;
  71. private string m_PrimName;
  72. private string m_ScriptName;
  73. private string m_Assembly;
  74. private int m_StartParam;
  75. private string m_CurrentEvent = String.Empty;
  76. private bool m_InSelfDelete;
  77. private int m_MaxScriptQueue;
  78. private bool m_SaveState = true;
  79. private bool m_ShuttingDown;
  80. private int m_ControlEventsInQueue;
  81. private int m_LastControlLevel;
  82. private bool m_CollisionInQueue;
  83. private TaskInventoryItem m_thisScriptTask;
  84. // The following is for setting a minimum delay between events
  85. private double m_minEventDelay;
  86. private long m_eventDelayTicks;
  87. private long m_nextEventTimeTicks;
  88. private bool m_startOnInit = true;
  89. private UUID m_AttachedAvatar;
  90. private StateSource m_stateSource;
  91. private bool m_postOnRez;
  92. private bool m_startedFromSavedState;
  93. private UUID m_CurrentStateHash;
  94. private UUID m_RegionID;
  95. private Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>
  96. m_LineMap;
  97. public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>>
  98. LineMap
  99. {
  100. get { return m_LineMap; }
  101. set { m_LineMap = value; }
  102. }
  103. private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>();
  104. // Script state
  105. private string m_State="default";
  106. public Object[] PluginData = new Object[0];
  107. /// <summary>
  108. /// Used by llMinEventDelay to suppress events happening any faster than this speed.
  109. /// This currently restricts all events in one go. Not sure if each event type has
  110. /// its own check so take the simple route first.
  111. /// </summary>
  112. public double MinEventDelay
  113. {
  114. get { return m_minEventDelay; }
  115. set
  116. {
  117. if (value > 0.001)
  118. m_minEventDelay = value;
  119. else
  120. m_minEventDelay = 0.0;
  121. m_eventDelayTicks = (long)(m_minEventDelay * 10000000L);
  122. m_nextEventTimeTicks = DateTime.Now.Ticks;
  123. }
  124. }
  125. public bool Running
  126. {
  127. get { return m_RunEvents; }
  128. set { m_RunEvents = value; }
  129. }
  130. public bool ShuttingDown
  131. {
  132. get { return m_ShuttingDown; }
  133. set { m_ShuttingDown = value; }
  134. }
  135. public string State
  136. {
  137. get { return m_State; }
  138. set { m_State = value; }
  139. }
  140. public IScriptEngine Engine
  141. {
  142. get { return m_Engine; }
  143. }
  144. public UUID AppDomain
  145. {
  146. get { return m_AppDomain; }
  147. set { m_AppDomain = value; }
  148. }
  149. public string PrimName
  150. {
  151. get { return m_PrimName; }
  152. }
  153. public string ScriptName
  154. {
  155. get { return m_ScriptName; }
  156. }
  157. public UUID ItemID
  158. {
  159. get { return m_ItemID; }
  160. }
  161. public UUID ObjectID
  162. {
  163. get { return m_ObjectID; }
  164. }
  165. public uint LocalID
  166. {
  167. get { return m_LocalID; }
  168. }
  169. public UUID AssetID
  170. {
  171. get { return m_AssetID; }
  172. }
  173. public Queue EventQueue
  174. {
  175. get { return m_EventQueue; }
  176. }
  177. public void ClearQueue()
  178. {
  179. m_TimerQueued = false;
  180. m_EventQueue.Clear();
  181. }
  182. public int StartParam
  183. {
  184. get { return m_StartParam; }
  185. set { m_StartParam = value; }
  186. }
  187. public TaskInventoryItem ScriptTask
  188. {
  189. get { return m_thisScriptTask; }
  190. }
  191. public ScriptInstance(IScriptEngine engine, SceneObjectPart part,
  192. UUID itemID, UUID assetID, string assembly,
  193. AppDomain dom, string primName, string scriptName,
  194. int startParam, bool postOnRez, StateSource stateSource,
  195. int maxScriptQueue)
  196. {
  197. m_Engine = engine;
  198. m_LocalID = part.LocalId;
  199. m_ObjectID = part.UUID;
  200. m_ItemID = itemID;
  201. m_AssetID = assetID;
  202. m_PrimName = primName;
  203. m_ScriptName = scriptName;
  204. m_Assembly = assembly;
  205. m_StartParam = startParam;
  206. m_MaxScriptQueue = maxScriptQueue;
  207. m_stateSource = stateSource;
  208. m_postOnRez = postOnRez;
  209. m_AttachedAvatar = part.AttachedAvatar;
  210. m_RegionID = part.ParentGroup.Scene.RegionInfo.RegionID;
  211. if (part != null)
  212. {
  213. lock (part.TaskInventory)
  214. {
  215. if (part.TaskInventory.ContainsKey(m_ItemID))
  216. {
  217. m_thisScriptTask = part.TaskInventory[m_ItemID];
  218. }
  219. }
  220. }
  221. ApiManager am = new ApiManager();
  222. foreach (string api in am.GetApis())
  223. {
  224. m_Apis[api] = am.CreateApi(api);
  225. m_Apis[api].Initialize(engine, part, m_LocalID, itemID);
  226. }
  227. try
  228. {
  229. if (dom != System.AppDomain.CurrentDomain)
  230. m_Script = (IScript)dom.CreateInstanceAndUnwrap(
  231. Path.GetFileNameWithoutExtension(assembly),
  232. "SecondLife.Script");
  233. else
  234. m_Script = (IScript)Assembly.Load(
  235. Path.GetFileNameWithoutExtension(assembly)).CreateInstance(
  236. "SecondLife.Script");
  237. //ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
  238. //RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass);
  239. // lease.Register(this);
  240. }
  241. catch (Exception)
  242. {
  243. // m_log.ErrorFormat("[Script] Error loading assembly {0}\n"+e.ToString(), assembly);
  244. }
  245. try
  246. {
  247. foreach (KeyValuePair<string,IScriptApi> kv in m_Apis)
  248. {
  249. m_Script.InitApi(kv.Key, kv.Value);
  250. }
  251. // // m_log.Debug("[Script] Script instance created");
  252. part.SetScriptEvents(m_ItemID,
  253. (int)m_Script.GetStateEventFlags(State));
  254. }
  255. catch (Exception)
  256. {
  257. // m_log.Error("[Script] Error loading script instance\n"+e.ToString());
  258. return;
  259. }
  260. m_SaveState = true;
  261. string savedState = Path.Combine(Path.GetDirectoryName(assembly),
  262. m_ItemID.ToString() + ".state");
  263. if (File.Exists(savedState))
  264. {
  265. string xml = String.Empty;
  266. try
  267. {
  268. FileInfo fi = new FileInfo(savedState);
  269. int size = (int)fi.Length;
  270. if (size < 512000)
  271. {
  272. using (FileStream fs = File.Open(savedState,
  273. FileMode.Open, FileAccess.Read, FileShare.None))
  274. {
  275. System.Text.UTF8Encoding enc =
  276. new System.Text.UTF8Encoding();
  277. Byte[] data = new Byte[size];
  278. fs.Read(data, 0, size);
  279. xml = enc.GetString(data);
  280. ScriptSerializer.Deserialize(xml, this);
  281. AsyncCommandManager.CreateFromData(m_Engine,
  282. m_LocalID, m_ItemID, m_ObjectID,
  283. PluginData);
  284. // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", m_PrimName, m_ScriptName);
  285. part.SetScriptEvents(m_ItemID,
  286. (int)m_Script.GetStateEventFlags(State));
  287. if (m_RunEvents && (!m_ShuttingDown))
  288. {
  289. m_RunEvents = false;
  290. }
  291. else
  292. {
  293. m_RunEvents = false;
  294. m_startOnInit = false;
  295. }
  296. // we get new rez events on sim restart, too
  297. // but if there is state, then we fire the change
  298. // event
  299. // We loaded state, don't force a re-save
  300. m_SaveState = false;
  301. m_startedFromSavedState = true;
  302. }
  303. }
  304. else
  305. {
  306. // m_log.Error("[Script] Unable to load script state: Memory limit exceeded");
  307. }
  308. }
  309. catch (Exception)
  310. {
  311. // m_log.ErrorFormat("[Script] Unable to load script state from xml: {0}\n"+e.ToString(), xml);
  312. }
  313. }
  314. // else
  315. // {
  316. // ScenePresence presence = m_Engine.World.GetScenePresence(part.OwnerID);
  317. // if (presence != null && (!postOnRez))
  318. // presence.ControllingClient.SendAgentAlertMessage("Compile successful", false);
  319. // }
  320. }
  321. public void Init()
  322. {
  323. if (!m_startOnInit) return;
  324. if (m_startedFromSavedState)
  325. {
  326. Start();
  327. if (m_postOnRez)
  328. {
  329. PostEvent(new EventParams("on_rez",
  330. new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0]));
  331. }
  332. if (m_stateSource == StateSource.AttachedRez)
  333. {
  334. PostEvent(new EventParams("attach",
  335. new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
  336. }
  337. else if (m_stateSource == StateSource.NewRez)
  338. {
  339. // m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script");
  340. PostEvent(new EventParams("changed",
  341. new Object[] {new LSL_Types.LSLInteger(256)}, new DetectParams[0]));
  342. }
  343. else if (m_stateSource == StateSource.PrimCrossing)
  344. {
  345. // CHANGED_REGION
  346. PostEvent(new EventParams("changed",
  347. new Object[] {new LSL_Types.LSLInteger(512)}, new DetectParams[0]));
  348. }
  349. }
  350. else
  351. {
  352. Start();
  353. PostEvent(new EventParams("state_entry",
  354. new Object[0], new DetectParams[0]));
  355. if (m_postOnRez)
  356. {
  357. PostEvent(new EventParams("on_rez",
  358. new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0]));
  359. }
  360. if (m_stateSource == StateSource.AttachedRez)
  361. {
  362. PostEvent(new EventParams("attach",
  363. new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
  364. }
  365. }
  366. }
  367. private void ReleaseControls()
  368. {
  369. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(m_LocalID);
  370. if (part != null)
  371. {
  372. int permsMask;
  373. UUID permsGranter;
  374. lock (part.TaskInventory)
  375. {
  376. if (!part.TaskInventory.ContainsKey(m_ItemID))
  377. return;
  378. permsGranter = part.TaskInventory[m_ItemID].PermsGranter;
  379. permsMask = part.TaskInventory[m_ItemID].PermsMask;
  380. }
  381. if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)
  382. {
  383. ScenePresence presence = m_Engine.World.GetScenePresence(permsGranter);
  384. if (presence != null)
  385. presence.UnRegisterControlEventsToScript(m_LocalID, m_ItemID);
  386. }
  387. }
  388. }
  389. public void DestroyScriptInstance()
  390. {
  391. ReleaseControls();
  392. AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
  393. }
  394. public void RemoveState()
  395. {
  396. string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly),
  397. m_ItemID.ToString() + ".state");
  398. try
  399. {
  400. File.Delete(savedState);
  401. }
  402. catch(Exception)
  403. {
  404. }
  405. }
  406. public void VarDump(Dictionary<string, object> vars)
  407. {
  408. // m_log.Info("Variable dump for script "+ m_ItemID.ToString());
  409. // foreach (KeyValuePair<string, object> v in vars)
  410. // {
  411. // m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString());
  412. // }
  413. }
  414. public void Start()
  415. {
  416. lock (m_EventQueue)
  417. {
  418. if (Running)
  419. return;
  420. m_RunEvents = true;
  421. if (m_EventQueue.Count > 0)
  422. {
  423. if (m_CurrentResult == null)
  424. m_CurrentResult = m_Engine.QueueEventHandler(this);
  425. // else
  426. // m_log.Error("[Script] Tried to start a script that was already queued");
  427. }
  428. }
  429. }
  430. public bool Stop(int timeout)
  431. {
  432. IScriptWorkItem result;
  433. lock (m_EventQueue)
  434. {
  435. if (!Running)
  436. return true;
  437. if (m_CurrentResult == null)
  438. {
  439. m_RunEvents = false;
  440. return true;
  441. }
  442. if (m_CurrentResult.Cancel())
  443. {
  444. m_CurrentResult = null;
  445. m_RunEvents = false;
  446. return true;
  447. }
  448. result = m_CurrentResult;
  449. m_RunEvents = false;
  450. }
  451. if (result.Wait(new TimeSpan((long)timeout * 100000)))
  452. {
  453. return true;
  454. }
  455. lock (m_EventQueue)
  456. {
  457. result = m_CurrentResult;
  458. }
  459. if (result == null)
  460. return true;
  461. if (!m_InSelfDelete)
  462. result.Abort();
  463. lock (m_EventQueue)
  464. {
  465. m_CurrentResult = null;
  466. }
  467. return true;
  468. }
  469. public void SetState(string state)
  470. {
  471. if (state == State)
  472. return;
  473. PostEvent(new EventParams("state_exit", new Object[0],
  474. new DetectParams[0]));
  475. PostEvent(new EventParams("state", new Object[] { state },
  476. new DetectParams[0]));
  477. PostEvent(new EventParams("state_entry", new Object[0],
  478. new DetectParams[0]));
  479. throw new EventAbortException();
  480. }
  481. public void PostEvent(EventParams data)
  482. {
  483. // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}",
  484. // m_PrimName, m_ScriptName, data.EventName, m_State);
  485. if (!Running)
  486. return;
  487. // If min event delay is set then ignore any events untill the time has expired
  488. // This currently only allows 1 event of any type in the given time period.
  489. // This may need extending to allow for a time for each individual event type.
  490. if (m_eventDelayTicks != 0)
  491. {
  492. if (DateTime.Now.Ticks < m_nextEventTimeTicks)
  493. return;
  494. m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks;
  495. }
  496. lock (m_EventQueue)
  497. {
  498. if (m_EventQueue.Count >= m_MaxScriptQueue)
  499. return;
  500. if (data.EventName == "timer")
  501. {
  502. if (m_TimerQueued)
  503. return;
  504. m_TimerQueued = true;
  505. }
  506. if (data.EventName == "control")
  507. {
  508. int held = ((LSL_Types.LSLInteger)data.Params[1]).value;
  509. // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value;
  510. // If the last message was a 0 (nothing held)
  511. // and this one is also nothing held, drop it
  512. //
  513. if (m_LastControlLevel == held && held == 0)
  514. return;
  515. // If there is one or more queued, then queue
  516. // only changed ones, else queue unconditionally
  517. //
  518. if (m_ControlEventsInQueue > 0)
  519. {
  520. if (m_LastControlLevel == held)
  521. return;
  522. }
  523. m_LastControlLevel = held;
  524. m_ControlEventsInQueue++;
  525. }
  526. if (data.EventName == "collision")
  527. {
  528. if (m_CollisionInQueue)
  529. return;
  530. if (data.DetectParams == null)
  531. return;
  532. m_CollisionInQueue = true;
  533. }
  534. m_EventQueue.Enqueue(data);
  535. if (m_CurrentResult == null)
  536. {
  537. m_CurrentResult = m_Engine.QueueEventHandler(this);
  538. }
  539. }
  540. }
  541. /// <summary>
  542. /// Process the next event queued for this script
  543. /// </summary>
  544. /// <returns></returns>
  545. public object EventProcessor()
  546. {
  547. lock (m_Script)
  548. {
  549. EventParams data = null;
  550. lock (m_EventQueue)
  551. {
  552. data = (EventParams) m_EventQueue.Dequeue();
  553. if (data == null) // Shouldn't happen
  554. {
  555. if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
  556. {
  557. m_CurrentResult = m_Engine.QueueEventHandler(this);
  558. }
  559. else
  560. {
  561. m_CurrentResult = null;
  562. }
  563. return 0;
  564. }
  565. if (data.EventName == "timer")
  566. m_TimerQueued = false;
  567. if (data.EventName == "control")
  568. {
  569. if (m_ControlEventsInQueue > 0)
  570. m_ControlEventsInQueue--;
  571. }
  572. if (data.EventName == "collision")
  573. m_CollisionInQueue = false;
  574. }
  575. //m_log.DebugFormat("[XENGINE]: Processing event {0} for {1}", data.EventName, this);
  576. m_DetectParams = data.DetectParams;
  577. if (data.EventName == "state") // Hardcoded state change
  578. {
  579. // m_log.DebugFormat("[Script] Script {0}.{1} state set to {2}",
  580. // m_PrimName, m_ScriptName, data.Params[0].ToString());
  581. m_State=data.Params[0].ToString();
  582. AsyncCommandManager.RemoveScript(m_Engine,
  583. m_LocalID, m_ItemID);
  584. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
  585. m_LocalID);
  586. if (part != null)
  587. {
  588. part.SetScriptEvents(m_ItemID,
  589. (int)m_Script.GetStateEventFlags(State));
  590. }
  591. }
  592. else
  593. {
  594. if (m_Engine.World.PipeEventsForScript(m_LocalID) ||
  595. data.EventName == "control") // Don't freeze avies!
  596. {
  597. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
  598. m_LocalID);
  599. // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
  600. // m_PrimName, m_ScriptName, data.EventName, m_State);
  601. try
  602. {
  603. m_CurrentEvent = data.EventName;
  604. m_EventStart = DateTime.Now;
  605. m_InEvent = true;
  606. m_Script.ExecuteEvent(State, data.EventName, data.Params);
  607. m_InEvent = false;
  608. m_CurrentEvent = String.Empty;
  609. if (m_SaveState)
  610. {
  611. // This will be the very first event we deliver
  612. // (state_entry) in default state
  613. //
  614. SaveState(m_Assembly);
  615. m_SaveState = false;
  616. }
  617. }
  618. catch (Exception e)
  619. {
  620. // m_log.DebugFormat("[SCRIPT] Exception: {0}", e.Message);
  621. m_InEvent = false;
  622. m_CurrentEvent = String.Empty;
  623. if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException))) && !(e is ThreadAbortException))
  624. {
  625. try
  626. {
  627. // DISPLAY ERROR INWORLD
  628. string text = FormatException(e);
  629. if (text.Length > 1000)
  630. text = text.Substring(0, 1000);
  631. m_Engine.World.SimChat(Utils.StringToBytes(text),
  632. ChatTypeEnum.DebugChannel, 2147483647,
  633. part.AbsolutePosition,
  634. part.Name, part.UUID, false);
  635. }
  636. catch (Exception)
  637. {
  638. }
  639. // catch (Exception e2) // LEGIT: User Scripting
  640. // {
  641. // m_log.Error("[SCRIPT]: "+
  642. // "Error displaying error in-world: " +
  643. // e2.ToString());
  644. // m_log.Error("[SCRIPT]: " +
  645. // "Errormessage: Error compiling script:\r\n" +
  646. // e.ToString());
  647. // }
  648. }
  649. else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
  650. {
  651. m_InSelfDelete = true;
  652. if (part != null && part.ParentGroup != null)
  653. m_Engine.World.DeleteSceneObject(part.ParentGroup, false);
  654. }
  655. else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
  656. {
  657. m_InSelfDelete = true;
  658. if (part != null && part.ParentGroup != null)
  659. part.Inventory.RemoveInventoryItem(m_ItemID);
  660. }
  661. }
  662. }
  663. }
  664. lock (m_EventQueue)
  665. {
  666. if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
  667. {
  668. m_CurrentResult = m_Engine.QueueEventHandler(this);
  669. }
  670. else
  671. {
  672. m_CurrentResult = null;
  673. }
  674. }
  675. m_DetectParams = null;
  676. return 0;
  677. }
  678. }
  679. public int EventTime()
  680. {
  681. if (!m_InEvent)
  682. return 0;
  683. return (DateTime.Now - m_EventStart).Seconds;
  684. }
  685. public void ResetScript()
  686. {
  687. if (m_Script == null)
  688. return;
  689. bool running = Running;
  690. RemoveState();
  691. ReleaseControls();
  692. Stop(0);
  693. SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
  694. part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0;
  695. part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero;
  696. AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
  697. m_EventQueue.Clear();
  698. m_Script.ResetVars();
  699. m_State = "default";
  700. part.SetScriptEvents(m_ItemID,
  701. (int)m_Script.GetStateEventFlags(State));
  702. if (running)
  703. Start();
  704. m_SaveState = true;
  705. PostEvent(new EventParams("state_entry",
  706. new Object[0], new DetectParams[0]));
  707. }
  708. public void ApiResetScript()
  709. {
  710. // bool running = Running;
  711. RemoveState();
  712. ReleaseControls();
  713. m_Script.ResetVars();
  714. SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
  715. part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0;
  716. part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero;
  717. AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
  718. m_EventQueue.Clear();
  719. m_Script.ResetVars();
  720. m_State = "default";
  721. part.SetScriptEvents(m_ItemID,
  722. (int)m_Script.GetStateEventFlags(State));
  723. if (m_CurrentEvent != "state_entry")
  724. {
  725. m_SaveState = true;
  726. PostEvent(new EventParams("state_entry",
  727. new Object[0], new DetectParams[0]));
  728. throw new EventAbortException();
  729. }
  730. }
  731. public Dictionary<string, object> GetVars()
  732. {
  733. return m_Script.GetVars();
  734. }
  735. public void SetVars(Dictionary<string, object> vars)
  736. {
  737. m_Script.SetVars(vars);
  738. }
  739. public DetectParams GetDetectParams(int idx)
  740. {
  741. if (m_DetectParams == null)
  742. return null;
  743. if (idx < 0 || idx >= m_DetectParams.Length)
  744. return null;
  745. return m_DetectParams[idx];
  746. }
  747. public UUID GetDetectID(int idx)
  748. {
  749. if (m_DetectParams == null)
  750. return UUID.Zero;
  751. if (idx < 0 || idx >= m_DetectParams.Length)
  752. return UUID.Zero;
  753. return m_DetectParams[idx].Key;
  754. }
  755. public void SaveState(string assembly)
  756. {
  757. // If we're currently in an event, just tell it to save upon return
  758. //
  759. if (m_InEvent)
  760. {
  761. m_SaveState = true;
  762. return;
  763. }
  764. PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID);
  765. string xml = ScriptSerializer.Serialize(this);
  766. // Compare hash of the state we just just created with the state last written to disk
  767. // If the state is different, update the disk file.
  768. UUID hash = UUID.Parse(Utils.MD5String(xml));
  769. if (hash != m_CurrentStateHash)
  770. {
  771. try
  772. {
  773. FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state"));
  774. System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
  775. Byte[] buf = enc.GetBytes(xml);
  776. fs.Write(buf, 0, buf.Length);
  777. fs.Close();
  778. }
  779. catch(Exception)
  780. {
  781. // m_log.Error("Unable to save xml\n"+e.ToString());
  782. }
  783. //if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state")))
  784. //{
  785. // throw new Exception("Completed persistence save, but no file was created");
  786. //}
  787. m_CurrentStateHash = hash;
  788. }
  789. }
  790. public IScriptApi GetApi(string name)
  791. {
  792. if (m_Apis.ContainsKey(name))
  793. return m_Apis[name];
  794. return null;
  795. }
  796. public override string ToString()
  797. {
  798. return String.Format("{0} {1} on {2}", m_ScriptName, m_ItemID, m_PrimName);
  799. }
  800. string FormatException(Exception e)
  801. {
  802. if (e.InnerException == null) // Not a normal runtime error
  803. return e.ToString();
  804. string message = "Runtime error:\n" + e.InnerException.StackTrace;
  805. string[] lines = message.Split(new char[] {'\n'});
  806. foreach (string line in lines)
  807. {
  808. if (line.Contains("SecondLife.Script"))
  809. {
  810. int idx = line.IndexOf(':');
  811. if (idx != -1)
  812. {
  813. string val = line.Substring(idx+1);
  814. int lineNum = 0;
  815. if (int.TryParse(val, out lineNum))
  816. {
  817. KeyValuePair<int, int> pos =
  818. Compiler.FindErrorPosition(
  819. lineNum, 0, LineMap);
  820. int scriptLine = pos.Key;
  821. int col = pos.Value;
  822. if (scriptLine == 0)
  823. scriptLine++;
  824. if (col == 0)
  825. col++;
  826. message = string.Format("Runtime error:\n" +
  827. "({0}): {1}", scriptLine - 1,
  828. e.InnerException.Message);
  829. System.Console.WriteLine(e.ToString()+"\n");
  830. return message;
  831. }
  832. }
  833. }
  834. }
  835. // m_log.ErrorFormat("Scripting exception:");
  836. // m_log.ErrorFormat(e.ToString());
  837. return e.ToString();
  838. }
  839. public string GetAssemblyName()
  840. {
  841. return m_Assembly;
  842. }
  843. public string GetXMLState()
  844. {
  845. bool run = Running;
  846. Stop(100);
  847. Running = run;
  848. // We should not be doing this, but since we are about to
  849. // dispose this, it really doesn't make a difference
  850. // This is meant to work around a Windows only race
  851. //
  852. m_InEvent = false;
  853. // Force an update of the in-memory plugin data
  854. //
  855. PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID);
  856. return ScriptSerializer.Serialize(this);
  857. }
  858. public UUID RegionID
  859. {
  860. get { return m_RegionID; }
  861. }
  862. }
  863. }