ScriptInstance.cs 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  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.ParentGroup.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.RegionStart)
  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((int)Changed.REGION_RESTART) }, new DetectParams[0]));
  343. }
  344. else if (m_stateSource == StateSource.PrimCrossing || m_stateSource == StateSource.Teleporting)
  345. {
  346. // CHANGED_REGION
  347. PostEvent(new EventParams("changed",
  348. new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION) }, new DetectParams[0]));
  349. // CHANGED_TELEPORT
  350. if (m_stateSource == StateSource.Teleporting)
  351. PostEvent(new EventParams("changed",
  352. new Object[] { new LSL_Types.LSLInteger((int)Changed.TELEPORT) }, new DetectParams[0]));
  353. }
  354. }
  355. else
  356. {
  357. Start();
  358. PostEvent(new EventParams("state_entry",
  359. new Object[0], new DetectParams[0]));
  360. if (m_postOnRez)
  361. {
  362. PostEvent(new EventParams("on_rez",
  363. new Object[] {new LSL_Types.LSLInteger(m_StartParam)}, new DetectParams[0]));
  364. }
  365. if (m_stateSource == StateSource.AttachedRez)
  366. {
  367. PostEvent(new EventParams("attach",
  368. new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0]));
  369. }
  370. }
  371. }
  372. private void ReleaseControls()
  373. {
  374. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(m_LocalID);
  375. if (part != null)
  376. {
  377. int permsMask;
  378. UUID permsGranter;
  379. lock (part.TaskInventory)
  380. {
  381. if (!part.TaskInventory.ContainsKey(m_ItemID))
  382. return;
  383. permsGranter = part.TaskInventory[m_ItemID].PermsGranter;
  384. permsMask = part.TaskInventory[m_ItemID].PermsMask;
  385. }
  386. if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0)
  387. {
  388. ScenePresence presence = m_Engine.World.GetScenePresence(permsGranter);
  389. if (presence != null)
  390. presence.UnRegisterControlEventsToScript(m_LocalID, m_ItemID);
  391. }
  392. }
  393. }
  394. public void DestroyScriptInstance()
  395. {
  396. ReleaseControls();
  397. AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
  398. }
  399. public void RemoveState()
  400. {
  401. string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly),
  402. m_ItemID.ToString() + ".state");
  403. try
  404. {
  405. File.Delete(savedState);
  406. }
  407. catch(Exception)
  408. {
  409. }
  410. }
  411. public void VarDump(Dictionary<string, object> vars)
  412. {
  413. // m_log.Info("Variable dump for script "+ m_ItemID.ToString());
  414. // foreach (KeyValuePair<string, object> v in vars)
  415. // {
  416. // m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString());
  417. // }
  418. }
  419. public void Start()
  420. {
  421. lock (m_EventQueue)
  422. {
  423. if (Running)
  424. return;
  425. m_RunEvents = true;
  426. if (m_EventQueue.Count > 0)
  427. {
  428. if (m_CurrentResult == null)
  429. m_CurrentResult = m_Engine.QueueEventHandler(this);
  430. // else
  431. // m_log.Error("[Script] Tried to start a script that was already queued");
  432. }
  433. }
  434. }
  435. public bool Stop(int timeout)
  436. {
  437. IScriptWorkItem result;
  438. lock (m_EventQueue)
  439. {
  440. if (!Running)
  441. return true;
  442. if (m_CurrentResult == null)
  443. {
  444. m_RunEvents = false;
  445. return true;
  446. }
  447. if (m_CurrentResult.Cancel())
  448. {
  449. m_CurrentResult = null;
  450. m_RunEvents = false;
  451. return true;
  452. }
  453. result = m_CurrentResult;
  454. m_RunEvents = false;
  455. }
  456. if (result.Wait(new TimeSpan((long)timeout * 100000)))
  457. {
  458. return true;
  459. }
  460. lock (m_EventQueue)
  461. {
  462. result = m_CurrentResult;
  463. }
  464. if (result == null)
  465. return true;
  466. if (!m_InSelfDelete)
  467. result.Abort();
  468. lock (m_EventQueue)
  469. {
  470. m_CurrentResult = null;
  471. }
  472. return true;
  473. }
  474. public void SetState(string state)
  475. {
  476. if (state == State)
  477. return;
  478. PostEvent(new EventParams("state_exit", new Object[0],
  479. new DetectParams[0]));
  480. PostEvent(new EventParams("state", new Object[] { state },
  481. new DetectParams[0]));
  482. PostEvent(new EventParams("state_entry", new Object[0],
  483. new DetectParams[0]));
  484. throw new EventAbortException();
  485. }
  486. public void PostEvent(EventParams data)
  487. {
  488. // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}",
  489. // m_PrimName, m_ScriptName, data.EventName, m_State);
  490. if (!Running)
  491. return;
  492. // If min event delay is set then ignore any events untill the time has expired
  493. // This currently only allows 1 event of any type in the given time period.
  494. // This may need extending to allow for a time for each individual event type.
  495. if (m_eventDelayTicks != 0)
  496. {
  497. if (DateTime.Now.Ticks < m_nextEventTimeTicks)
  498. return;
  499. m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks;
  500. }
  501. lock (m_EventQueue)
  502. {
  503. if (m_EventQueue.Count >= m_MaxScriptQueue)
  504. return;
  505. if (data.EventName == "timer")
  506. {
  507. if (m_TimerQueued)
  508. return;
  509. m_TimerQueued = true;
  510. }
  511. if (data.EventName == "control")
  512. {
  513. int held = ((LSL_Types.LSLInteger)data.Params[1]).value;
  514. // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value;
  515. // If the last message was a 0 (nothing held)
  516. // and this one is also nothing held, drop it
  517. //
  518. if (m_LastControlLevel == held && held == 0)
  519. return;
  520. // If there is one or more queued, then queue
  521. // only changed ones, else queue unconditionally
  522. //
  523. if (m_ControlEventsInQueue > 0)
  524. {
  525. if (m_LastControlLevel == held)
  526. return;
  527. }
  528. m_LastControlLevel = held;
  529. m_ControlEventsInQueue++;
  530. }
  531. if (data.EventName == "collision")
  532. {
  533. if (m_CollisionInQueue)
  534. return;
  535. if (data.DetectParams == null)
  536. return;
  537. m_CollisionInQueue = true;
  538. }
  539. m_EventQueue.Enqueue(data);
  540. if (m_CurrentResult == null)
  541. {
  542. m_CurrentResult = m_Engine.QueueEventHandler(this);
  543. }
  544. }
  545. }
  546. /// <summary>
  547. /// Process the next event queued for this script
  548. /// </summary>
  549. /// <returns></returns>
  550. public object EventProcessor()
  551. {
  552. if (m_Suspended)
  553. return 0;
  554. lock (m_Script)
  555. {
  556. EventParams data = null;
  557. lock (m_EventQueue)
  558. {
  559. data = (EventParams) m_EventQueue.Dequeue();
  560. if (data == null) // Shouldn't happen
  561. {
  562. if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
  563. {
  564. m_CurrentResult = m_Engine.QueueEventHandler(this);
  565. }
  566. else
  567. {
  568. m_CurrentResult = null;
  569. }
  570. return 0;
  571. }
  572. if (data.EventName == "timer")
  573. m_TimerQueued = false;
  574. if (data.EventName == "control")
  575. {
  576. if (m_ControlEventsInQueue > 0)
  577. m_ControlEventsInQueue--;
  578. }
  579. if (data.EventName == "collision")
  580. m_CollisionInQueue = false;
  581. }
  582. //m_log.DebugFormat("[XENGINE]: Processing event {0} for {1}", data.EventName, this);
  583. m_DetectParams = data.DetectParams;
  584. if (data.EventName == "state") // Hardcoded state change
  585. {
  586. // m_log.DebugFormat("[Script] Script {0}.{1} state set to {2}",
  587. // m_PrimName, m_ScriptName, data.Params[0].ToString());
  588. m_State=data.Params[0].ToString();
  589. AsyncCommandManager.RemoveScript(m_Engine,
  590. m_LocalID, m_ItemID);
  591. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
  592. m_LocalID);
  593. if (part != null)
  594. {
  595. part.SetScriptEvents(m_ItemID,
  596. (int)m_Script.GetStateEventFlags(State));
  597. }
  598. }
  599. else
  600. {
  601. if (m_Engine.World.PipeEventsForScript(m_LocalID) ||
  602. data.EventName == "control") // Don't freeze avies!
  603. {
  604. SceneObjectPart part = m_Engine.World.GetSceneObjectPart(
  605. m_LocalID);
  606. // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}",
  607. // m_PrimName, m_ScriptName, data.EventName, m_State);
  608. try
  609. {
  610. m_CurrentEvent = data.EventName;
  611. m_EventStart = DateTime.Now;
  612. m_InEvent = true;
  613. m_Script.ExecuteEvent(State, data.EventName, data.Params);
  614. m_InEvent = false;
  615. m_CurrentEvent = String.Empty;
  616. if (m_SaveState)
  617. {
  618. // This will be the very first event we deliver
  619. // (state_entry) in default state
  620. //
  621. SaveState(m_Assembly);
  622. m_SaveState = false;
  623. }
  624. }
  625. catch (Exception e)
  626. {
  627. // m_log.DebugFormat("[SCRIPT] Exception: {0}", e.Message);
  628. m_InEvent = false;
  629. m_CurrentEvent = String.Empty;
  630. if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException))) && !(e is ThreadAbortException))
  631. {
  632. try
  633. {
  634. // DISPLAY ERROR INWORLD
  635. string text = FormatException(e);
  636. if (text.Length > 1000)
  637. text = text.Substring(0, 1000);
  638. m_Engine.World.SimChat(Utils.StringToBytes(text),
  639. ChatTypeEnum.DebugChannel, 2147483647,
  640. part.AbsolutePosition,
  641. part.Name, part.UUID, false);
  642. }
  643. catch (Exception)
  644. {
  645. }
  646. // catch (Exception e2) // LEGIT: User Scripting
  647. // {
  648. // m_log.Error("[SCRIPT]: "+
  649. // "Error displaying error in-world: " +
  650. // e2.ToString());
  651. // m_log.Error("[SCRIPT]: " +
  652. // "Errormessage: Error compiling script:\r\n" +
  653. // e.ToString());
  654. // }
  655. }
  656. else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException))
  657. {
  658. m_InSelfDelete = true;
  659. if (part != null)
  660. m_Engine.World.DeleteSceneObject(part.ParentGroup, false);
  661. }
  662. else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException))
  663. {
  664. m_InSelfDelete = true;
  665. if (part != null)
  666. part.Inventory.RemoveInventoryItem(m_ItemID);
  667. }
  668. }
  669. }
  670. }
  671. lock (m_EventQueue)
  672. {
  673. if ((m_EventQueue.Count > 0) && m_RunEvents && (!m_ShuttingDown))
  674. {
  675. m_CurrentResult = m_Engine.QueueEventHandler(this);
  676. }
  677. else
  678. {
  679. m_CurrentResult = null;
  680. }
  681. }
  682. m_DetectParams = null;
  683. return 0;
  684. }
  685. }
  686. public int EventTime()
  687. {
  688. if (!m_InEvent)
  689. return 0;
  690. return (DateTime.Now - m_EventStart).Seconds;
  691. }
  692. public void ResetScript()
  693. {
  694. if (m_Script == null)
  695. return;
  696. bool running = Running;
  697. RemoveState();
  698. ReleaseControls();
  699. Stop(0);
  700. SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
  701. part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0;
  702. part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero;
  703. AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
  704. m_EventQueue.Clear();
  705. m_Script.ResetVars();
  706. m_State = "default";
  707. part.SetScriptEvents(m_ItemID,
  708. (int)m_Script.GetStateEventFlags(State));
  709. if (running)
  710. Start();
  711. m_SaveState = true;
  712. PostEvent(new EventParams("state_entry",
  713. new Object[0], new DetectParams[0]));
  714. }
  715. public void ApiResetScript()
  716. {
  717. // bool running = Running;
  718. RemoveState();
  719. ReleaseControls();
  720. m_Script.ResetVars();
  721. SceneObjectPart part=m_Engine.World.GetSceneObjectPart(m_LocalID);
  722. part.Inventory.GetInventoryItem(m_ItemID).PermsMask = 0;
  723. part.Inventory.GetInventoryItem(m_ItemID).PermsGranter = UUID.Zero;
  724. AsyncCommandManager.RemoveScript(m_Engine, m_LocalID, m_ItemID);
  725. m_EventQueue.Clear();
  726. m_Script.ResetVars();
  727. m_State = "default";
  728. part.SetScriptEvents(m_ItemID,
  729. (int)m_Script.GetStateEventFlags(State));
  730. if (m_CurrentEvent != "state_entry")
  731. {
  732. m_SaveState = true;
  733. PostEvent(new EventParams("state_entry",
  734. new Object[0], new DetectParams[0]));
  735. throw new EventAbortException();
  736. }
  737. }
  738. public Dictionary<string, object> GetVars()
  739. {
  740. if (m_Script != null)
  741. return m_Script.GetVars();
  742. else
  743. return new Dictionary<string, object>();
  744. }
  745. public void SetVars(Dictionary<string, object> vars)
  746. {
  747. m_Script.SetVars(vars);
  748. }
  749. public DetectParams GetDetectParams(int idx)
  750. {
  751. if (m_DetectParams == null)
  752. return null;
  753. if (idx < 0 || idx >= m_DetectParams.Length)
  754. return null;
  755. return m_DetectParams[idx];
  756. }
  757. public UUID GetDetectID(int idx)
  758. {
  759. if (m_DetectParams == null)
  760. return UUID.Zero;
  761. if (idx < 0 || idx >= m_DetectParams.Length)
  762. return UUID.Zero;
  763. return m_DetectParams[idx].Key;
  764. }
  765. public void SaveState(string assembly)
  766. {
  767. // If we're currently in an event, just tell it to save upon return
  768. //
  769. if (m_InEvent)
  770. {
  771. m_SaveState = true;
  772. return;
  773. }
  774. PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID);
  775. string xml = ScriptSerializer.Serialize(this);
  776. // Compare hash of the state we just just created with the state last written to disk
  777. // If the state is different, update the disk file.
  778. UUID hash = UUID.Parse(Utils.MD5String(xml));
  779. if (hash != m_CurrentStateHash)
  780. {
  781. try
  782. {
  783. FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state"));
  784. System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
  785. Byte[] buf = enc.GetBytes(xml);
  786. fs.Write(buf, 0, buf.Length);
  787. fs.Close();
  788. }
  789. catch(Exception)
  790. {
  791. // m_log.Error("Unable to save xml\n"+e.ToString());
  792. }
  793. //if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), m_ItemID.ToString() + ".state")))
  794. //{
  795. // throw new Exception("Completed persistence save, but no file was created");
  796. //}
  797. m_CurrentStateHash = hash;
  798. }
  799. }
  800. public IScriptApi GetApi(string name)
  801. {
  802. if (m_Apis.ContainsKey(name))
  803. return m_Apis[name];
  804. return null;
  805. }
  806. public override string ToString()
  807. {
  808. return String.Format("{0} {1} on {2}", m_ScriptName, m_ItemID, m_PrimName);
  809. }
  810. string FormatException(Exception e)
  811. {
  812. if (e.InnerException == null) // Not a normal runtime error
  813. return e.ToString();
  814. string message = "Runtime error:\n" + e.InnerException.StackTrace;
  815. string[] lines = message.Split(new char[] {'\n'});
  816. foreach (string line in lines)
  817. {
  818. if (line.Contains("SecondLife.Script"))
  819. {
  820. int idx = line.IndexOf(':');
  821. if (idx != -1)
  822. {
  823. string val = line.Substring(idx+1);
  824. int lineNum = 0;
  825. if (int.TryParse(val, out lineNum))
  826. {
  827. KeyValuePair<int, int> pos =
  828. Compiler.FindErrorPosition(
  829. lineNum, 0, LineMap);
  830. int scriptLine = pos.Key;
  831. int col = pos.Value;
  832. if (scriptLine == 0)
  833. scriptLine++;
  834. if (col == 0)
  835. col++;
  836. message = string.Format("Runtime error:\n" +
  837. "({0}): {1}", scriptLine - 1,
  838. e.InnerException.Message);
  839. System.Console.WriteLine(e.ToString()+"\n");
  840. return message;
  841. }
  842. }
  843. }
  844. }
  845. // m_log.ErrorFormat("Scripting exception:");
  846. // m_log.ErrorFormat(e.ToString());
  847. return e.ToString();
  848. }
  849. public string GetAssemblyName()
  850. {
  851. return m_Assembly;
  852. }
  853. public string GetXMLState()
  854. {
  855. bool run = Running;
  856. Stop(100);
  857. Running = run;
  858. // We should not be doing this, but since we are about to
  859. // dispose this, it really doesn't make a difference
  860. // This is meant to work around a Windows only race
  861. //
  862. m_InEvent = false;
  863. // Force an update of the in-memory plugin data
  864. //
  865. PluginData = AsyncCommandManager.GetSerializationData(m_Engine, m_ItemID);
  866. return ScriptSerializer.Serialize(this);
  867. }
  868. public UUID RegionID
  869. {
  870. get { return m_RegionID; }
  871. }
  872. public void Suspend()
  873. {
  874. m_Suspended = true;
  875. }
  876. public void Resume()
  877. {
  878. m_Suspended = false;
  879. }
  880. }
  881. }