ScriptInstance.cs 35 KB

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