SensorRepeat.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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.Collections.Generic;
  29. using OpenMetaverse;
  30. using OpenSim.Framework;
  31. using OpenSim.Region.Framework.Scenes;
  32. using OpenSim.Region.ScriptEngine.Shared;
  33. using OpenSim.Region.ScriptEngine.Shared.Api;
  34. namespace OpenSim.Region.ScriptEngine.Shared.Api.Plugins
  35. {
  36. public class SensorRepeat
  37. {
  38. public AsyncCommandManager m_CmdManager;
  39. public SensorRepeat(AsyncCommandManager CmdManager)
  40. {
  41. m_CmdManager = CmdManager;
  42. maximumRange = CmdManager.m_ScriptEngine.Config.GetDouble("SensorMaxRange", 96.0d);
  43. maximumToReturn = CmdManager.m_ScriptEngine.Config.GetInt("SensorMaxResults", 16);
  44. }
  45. private Object SenseLock = new Object();
  46. private const int AGENT = 1;
  47. private const int AGENT_BY_USERNAME = 0x10;
  48. private const int ACTIVE = 2;
  49. private const int PASSIVE = 4;
  50. private const int SCRIPTED = 8;
  51. private double maximumRange = 96.0;
  52. private int maximumToReturn = 16;
  53. //
  54. // SenseRepeater and Sensors
  55. //
  56. private class SenseRepeatClass
  57. {
  58. public uint localID;
  59. public UUID itemID;
  60. public double interval;
  61. public DateTime next;
  62. public string name;
  63. public UUID keyID;
  64. public int type;
  65. public double range;
  66. public double arc;
  67. public SceneObjectPart host;
  68. }
  69. //
  70. // Sensed entity
  71. //
  72. private class SensedEntity : IComparable
  73. {
  74. public SensedEntity(double detectedDistance, UUID detectedID)
  75. {
  76. distance = detectedDistance;
  77. itemID = detectedID;
  78. }
  79. public int CompareTo(object obj)
  80. {
  81. if (!(obj is SensedEntity)) throw new InvalidOperationException();
  82. SensedEntity ent = (SensedEntity)obj;
  83. if (ent == null || ent.distance < distance) return 1;
  84. if (ent.distance > distance) return -1;
  85. return 0;
  86. }
  87. public UUID itemID;
  88. public double distance;
  89. }
  90. private List<SenseRepeatClass> SenseRepeaters = new List<SenseRepeatClass>();
  91. private object SenseRepeatListLock = new object();
  92. public void SetSenseRepeatEvent(uint m_localID, UUID m_itemID,
  93. string name, UUID keyID, int type, double range,
  94. double arc, double sec, SceneObjectPart host)
  95. {
  96. // Always remove first, in case this is a re-set
  97. UnSetSenseRepeaterEvents(m_localID, m_itemID);
  98. if (sec == 0) // Disabling timer
  99. return;
  100. // Add to timer
  101. SenseRepeatClass ts = new SenseRepeatClass();
  102. ts.localID = m_localID;
  103. ts.itemID = m_itemID;
  104. ts.interval = sec;
  105. ts.name = name;
  106. ts.keyID = keyID;
  107. ts.type = type;
  108. if (range > maximumRange)
  109. ts.range = maximumRange;
  110. else
  111. ts.range = range;
  112. ts.arc = arc;
  113. ts.host = host;
  114. ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
  115. lock (SenseRepeatListLock)
  116. {
  117. SenseRepeaters.Add(ts);
  118. }
  119. }
  120. public void UnSetSenseRepeaterEvents(uint m_localID, UUID m_itemID)
  121. {
  122. // Remove from timer
  123. lock (SenseRepeatListLock)
  124. {
  125. List<SenseRepeatClass> NewSensors = new List<SenseRepeatClass>();
  126. foreach (SenseRepeatClass ts in SenseRepeaters)
  127. {
  128. if (ts.localID != m_localID && ts.itemID != m_itemID)
  129. {
  130. NewSensors.Add(ts);
  131. }
  132. }
  133. SenseRepeaters.Clear();
  134. SenseRepeaters = NewSensors;
  135. }
  136. }
  137. public void CheckSenseRepeaterEvents()
  138. {
  139. // Nothing to do here?
  140. if (SenseRepeaters.Count == 0)
  141. return;
  142. lock (SenseRepeatListLock)
  143. {
  144. // Go through all timers
  145. foreach (SenseRepeatClass ts in SenseRepeaters)
  146. {
  147. // Time has passed?
  148. if (ts.next.ToUniversalTime() < DateTime.Now.ToUniversalTime())
  149. {
  150. SensorSweep(ts);
  151. // set next interval
  152. ts.next = DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
  153. }
  154. }
  155. } // lock
  156. }
  157. public void SenseOnce(uint m_localID, UUID m_itemID,
  158. string name, UUID keyID, int type,
  159. double range, double arc, SceneObjectPart host)
  160. {
  161. // Add to timer
  162. SenseRepeatClass ts = new SenseRepeatClass();
  163. ts.localID = m_localID;
  164. ts.itemID = m_itemID;
  165. ts.interval = 0;
  166. ts.name = name;
  167. ts.keyID = keyID;
  168. ts.type = type;
  169. if (range > maximumRange)
  170. ts.range = maximumRange;
  171. else
  172. ts.range = range;
  173. ts.arc = arc;
  174. ts.host = host;
  175. SensorSweep(ts);
  176. }
  177. private void SensorSweep(SenseRepeatClass ts)
  178. {
  179. if (ts.host == null)
  180. {
  181. return;
  182. }
  183. List<SensedEntity> sensedEntities = new List<SensedEntity>();
  184. // Is the sensor type is AGENT and not SCRIPTED then include agents
  185. if ((ts.type & (AGENT | AGENT_BY_USERNAME)) != 0 && (ts.type & SCRIPTED) == 0)
  186. {
  187. sensedEntities.AddRange(doAgentSensor(ts));
  188. }
  189. // If SCRIPTED or PASSIVE or ACTIVE check objects
  190. if ((ts.type & SCRIPTED) != 0 || (ts.type & PASSIVE) != 0 || (ts.type & ACTIVE) != 0)
  191. {
  192. sensedEntities.AddRange(doObjectSensor(ts));
  193. }
  194. lock (SenseLock)
  195. {
  196. if (sensedEntities.Count == 0)
  197. {
  198. // send a "no_sensor"
  199. // Add it to queue
  200. m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
  201. new EventParams("no_sensor", new Object[0],
  202. new DetectParams[0]));
  203. }
  204. else
  205. {
  206. // Sort the list to get everything ordered by distance
  207. sensedEntities.Sort();
  208. int count = sensedEntities.Count;
  209. int idx;
  210. List<DetectParams> detected = new List<DetectParams>();
  211. for (idx = 0; idx < count; idx++)
  212. {
  213. try
  214. {
  215. DetectParams detect = new DetectParams();
  216. detect.Key = sensedEntities[idx].itemID;
  217. detect.Populate(m_CmdManager.m_ScriptEngine.World);
  218. detected.Add(detect);
  219. }
  220. catch (Exception)
  221. {
  222. // Ignore errors, the object has been deleted or the avatar has gone and
  223. // there was a problem in detect.Populate so nothing added to the list
  224. }
  225. if (detected.Count == maximumToReturn)
  226. break;
  227. }
  228. if (detected.Count == 0)
  229. {
  230. // To get here with zero in the list there must have been some sort of problem
  231. // like the object being deleted or the avatar leaving to have caused some
  232. // difficulty during the Populate above so fire a no_sensor event
  233. m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
  234. new EventParams("no_sensor", new Object[0],
  235. new DetectParams[0]));
  236. }
  237. else
  238. {
  239. m_CmdManager.m_ScriptEngine.PostScriptEvent(ts.itemID,
  240. new EventParams("sensor",
  241. new Object[] {new LSL_Types.LSLInteger(detected.Count) },
  242. detected.ToArray()));
  243. }
  244. }
  245. }
  246. }
  247. private List<SensedEntity> doObjectSensor(SenseRepeatClass ts)
  248. {
  249. List<EntityBase> Entities;
  250. List<SensedEntity> sensedEntities = new List<SensedEntity>();
  251. // If this is an object sense by key try to get it directly
  252. // rather than getting a list to scan through
  253. if (ts.keyID != UUID.Zero)
  254. {
  255. EntityBase e = null;
  256. m_CmdManager.m_ScriptEngine.World.Entities.TryGetValue(ts.keyID, out e);
  257. if (e == null)
  258. return sensedEntities;
  259. Entities = new List<EntityBase>();
  260. Entities.Add(e);
  261. }
  262. else
  263. {
  264. Entities = new List<EntityBase>(m_CmdManager.m_ScriptEngine.World.GetEntities());
  265. }
  266. SceneObjectPart SensePoint = ts.host;
  267. Vector3 fromRegionPos = SensePoint.AbsolutePosition;
  268. // pre define some things to avoid repeated definitions in the loop body
  269. Vector3 toRegionPos;
  270. double dis;
  271. int objtype;
  272. SceneObjectPart part;
  273. float dx;
  274. float dy;
  275. float dz;
  276. Quaternion q = SensePoint.RotationOffset;
  277. if (SensePoint.ParentGroup.IsAttachment)
  278. {
  279. // In attachments, the sensor cone always orients with the
  280. // avatar rotation. This may include a nonzero elevation if
  281. // in mouselook.
  282. ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.AttachedAvatar);
  283. q = avatar.Rotation;
  284. }
  285. LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W);
  286. LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
  287. double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);
  288. Vector3 ZeroVector = new Vector3(0, 0, 0);
  289. bool nameSearch = (ts.name != null && ts.name != "");
  290. foreach (EntityBase ent in Entities)
  291. {
  292. bool keep = true;
  293. if (nameSearch && ent.Name != ts.name) // Wrong name and it is a named search
  294. continue;
  295. if (ent.IsDeleted) // taken so long to do this it has gone from the scene
  296. continue;
  297. if (!(ent is SceneObjectGroup)) // dont bother if it is a pesky avatar
  298. continue;
  299. toRegionPos = ent.AbsolutePosition;
  300. // Calculation is in line for speed
  301. dx = toRegionPos.X - fromRegionPos.X;
  302. dy = toRegionPos.Y - fromRegionPos.Y;
  303. dz = toRegionPos.Z - fromRegionPos.Z;
  304. // Weed out those that will not fit in a cube the size of the range
  305. // no point calculating if they are within a sphere the size of the range
  306. // if they arent even in the cube
  307. if (Math.Abs(dx) > ts.range || Math.Abs(dy) > ts.range || Math.Abs(dz) > ts.range)
  308. dis = ts.range + 1.0;
  309. else
  310. dis = Math.Sqrt(dx * dx + dy * dy + dz * dz);
  311. if (keep && dis <= ts.range && ts.host.UUID != ent.UUID)
  312. {
  313. // In Range and not the object containing the script, is it the right Type ?
  314. objtype = 0;
  315. part = ((SceneObjectGroup)ent).RootPart;
  316. if (part.ParentGroup.AttachmentPoint != 0) // Attached so ignore
  317. continue;
  318. if (part.Inventory.ContainsScripts())
  319. {
  320. objtype |= ACTIVE | SCRIPTED; // Scripted and active. It COULD have one hidden ...
  321. }
  322. else
  323. {
  324. if (ent.Velocity.Equals(ZeroVector))
  325. {
  326. objtype |= PASSIVE; // Passive non-moving
  327. }
  328. else
  329. {
  330. objtype |= ACTIVE; // moving so active
  331. }
  332. }
  333. // If any of the objects attributes match any in the requested scan type
  334. if (((ts.type & objtype) != 0))
  335. {
  336. // Right type too, what about the other params , key and name ?
  337. if (ts.arc < Math.PI)
  338. {
  339. // not omni-directional. Can you see it ?
  340. // vec forward_dir = llRot2Fwd(llGetRot())
  341. // vec obj_dir = toRegionPos-fromRegionPos
  342. // dot=dot(forward_dir,obj_dir)
  343. // mag_fwd = mag(forward_dir)
  344. // mag_obj = mag(obj_dir)
  345. // ang = acos(dot /(mag_fwd*mag_obj))
  346. double ang_obj = 0;
  347. try
  348. {
  349. Vector3 diff = toRegionPos - fromRegionPos;
  350. LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z);
  351. double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir);
  352. double mag_obj = LSL_Types.Vector3.Mag(obj_dir);
  353. ang_obj = Math.Acos(dot / (mag_fwd * mag_obj));
  354. }
  355. catch
  356. {
  357. }
  358. if (ang_obj > ts.arc) keep = false;
  359. }
  360. if (keep == true)
  361. {
  362. // add distance for sorting purposes later
  363. sensedEntities.Add(new SensedEntity(dis, ent.UUID));
  364. }
  365. }
  366. }
  367. }
  368. return sensedEntities;
  369. }
  370. private List<SensedEntity> doAgentSensor(SenseRepeatClass ts)
  371. {
  372. List<SensedEntity> sensedEntities = new List<SensedEntity>();
  373. // If nobody about quit fast
  374. if (m_CmdManager.m_ScriptEngine.World.GetRootAgentCount() == 0)
  375. return sensedEntities;
  376. SceneObjectPart SensePoint = ts.host;
  377. Vector3 fromRegionPos = SensePoint.AbsolutePosition;
  378. Quaternion q = SensePoint.RotationOffset;
  379. if (SensePoint.ParentGroup.IsAttachment)
  380. {
  381. // In attachments, the sensor cone always orients with the
  382. // avatar rotation. This may include a nonzero elevation if
  383. // in mouselook.
  384. ScenePresence avatar = m_CmdManager.m_ScriptEngine.World.GetScenePresence(SensePoint.ParentGroup.AttachedAvatar);
  385. q = avatar.Rotation;
  386. }
  387. LSL_Types.Quaternion r = new LSL_Types.Quaternion(q.X, q.Y, q.Z, q.W);
  388. LSL_Types.Vector3 forward_dir = (new LSL_Types.Vector3(1, 0, 0) * r);
  389. double mag_fwd = LSL_Types.Vector3.Mag(forward_dir);
  390. bool attached = (SensePoint.ParentGroup.AttachmentPoint != 0);
  391. Vector3 toRegionPos;
  392. double dis;
  393. Action<ScenePresence> senseEntity = new Action<ScenePresence>(delegate(ScenePresence presence)
  394. {
  395. if (presence.IsDeleted || presence.IsChildAgent || presence.GodLevel > 0.0)
  396. return;
  397. // if the object the script is in is attached and the avatar is the owner
  398. // then this one is not wanted
  399. if (attached && presence.UUID == SensePoint.OwnerID)
  400. return;
  401. toRegionPos = presence.AbsolutePosition;
  402. dis = Math.Abs(Util.GetDistanceTo(toRegionPos, fromRegionPos));
  403. // are they in range
  404. if (dis <= ts.range)
  405. {
  406. // Are they in the required angle of view
  407. if (ts.arc < Math.PI)
  408. {
  409. // not omni-directional. Can you see it ?
  410. // vec forward_dir = llRot2Fwd(llGetRot())
  411. // vec obj_dir = toRegionPos-fromRegionPos
  412. // dot=dot(forward_dir,obj_dir)
  413. // mag_fwd = mag(forward_dir)
  414. // mag_obj = mag(obj_dir)
  415. // ang = acos(dot /(mag_fwd*mag_obj))
  416. double ang_obj = 0;
  417. try
  418. {
  419. Vector3 diff = toRegionPos - fromRegionPos;
  420. LSL_Types.Vector3 obj_dir = new LSL_Types.Vector3(diff.X, diff.Y, diff.Z);
  421. double dot = LSL_Types.Vector3.Dot(forward_dir, obj_dir);
  422. double mag_obj = LSL_Types.Vector3.Mag(obj_dir);
  423. ang_obj = Math.Acos(dot / (mag_fwd * mag_obj));
  424. }
  425. catch
  426. {
  427. }
  428. if (ang_obj <= ts.arc)
  429. {
  430. sensedEntities.Add(new SensedEntity(dis, presence.UUID));
  431. }
  432. }
  433. else
  434. {
  435. sensedEntities.Add(new SensedEntity(dis, presence.UUID));
  436. }
  437. }
  438. });
  439. // If this is an avatar sense by key try to get them directly
  440. // rather than getting a list to scan through
  441. if (ts.keyID != UUID.Zero)
  442. {
  443. ScenePresence sp;
  444. // Try direct lookup by UUID
  445. if (!m_CmdManager.m_ScriptEngine.World.TryGetScenePresence(ts.keyID, out sp))
  446. return sensedEntities;
  447. senseEntity(sp);
  448. }
  449. else if (ts.name != null && ts.name != "")
  450. {
  451. ScenePresence sp;
  452. // Try lookup by name will return if/when found
  453. if (((ts.type & AGENT) != 0) && m_CmdManager.m_ScriptEngine.World.TryGetAvatarByName(ts.name, out sp))
  454. senseEntity(sp);
  455. if ((ts.type & AGENT_BY_USERNAME) != 0)
  456. {
  457. m_CmdManager.m_ScriptEngine.World.ForEachScenePresence(
  458. delegate (ScenePresence ssp)
  459. {
  460. if (ssp.Lastname == "Resident")
  461. {
  462. if (ssp.Firstname.ToLower() == ts.name)
  463. senseEntity(ssp);
  464. return;
  465. }
  466. if (ssp.Name.Replace(" ", ".").ToLower() == ts.name)
  467. senseEntity(ssp);
  468. }
  469. );
  470. }
  471. return sensedEntities;
  472. }
  473. else
  474. {
  475. m_CmdManager.m_ScriptEngine.World.ForEachScenePresence(senseEntity);
  476. }
  477. return sensedEntities;
  478. }
  479. public Object[] GetSerializationData(UUID itemID)
  480. {
  481. List<Object> data = new List<Object>();
  482. lock (SenseRepeatListLock)
  483. {
  484. foreach (SenseRepeatClass ts in SenseRepeaters)
  485. {
  486. if (ts.itemID == itemID)
  487. {
  488. data.Add(ts.interval);
  489. data.Add(ts.name);
  490. data.Add(ts.keyID);
  491. data.Add(ts.type);
  492. data.Add(ts.range);
  493. data.Add(ts.arc);
  494. }
  495. }
  496. }
  497. return data.ToArray();
  498. }
  499. public void CreateFromData(uint localID, UUID itemID, UUID objectID,
  500. Object[] data)
  501. {
  502. SceneObjectPart part =
  503. m_CmdManager.m_ScriptEngine.World.GetSceneObjectPart(
  504. objectID);
  505. if (part == null)
  506. return;
  507. int idx = 0;
  508. while (idx < data.Length)
  509. {
  510. SenseRepeatClass ts = new SenseRepeatClass();
  511. ts.localID = localID;
  512. ts.itemID = itemID;
  513. ts.interval = (double)data[idx];
  514. ts.name = (string)data[idx+1];
  515. ts.keyID = (UUID)data[idx+2];
  516. ts.type = (int)data[idx+3];
  517. ts.range = (double)data[idx+4];
  518. ts.arc = (double)data[idx+5];
  519. ts.host = part;
  520. ts.next =
  521. DateTime.Now.ToUniversalTime().AddSeconds(ts.interval);
  522. SenseRepeaters.Add(ts);
  523. idx += 6;
  524. }
  525. }
  526. }
  527. }