ScriptInstance.cs 35 KB

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