BSPrim.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  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 copyrightD
  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.Reflection;
  29. using System.Collections.Generic;
  30. using System.Xml;
  31. using log4net;
  32. using OMV = OpenMetaverse;
  33. using OpenSim.Framework;
  34. using OpenSim.Region.Physics.Manager;
  35. using OpenSim.Region.Physics.ConvexDecompositionDotNet;
  36. namespace OpenSim.Region.Physics.BulletSPlugin
  37. {
  38. [Serializable]
  39. public sealed class BSPrim : PhysicsActor
  40. {
  41. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  42. private static readonly string LogHeader = "[BULLETS PRIM]";
  43. private IMesh _mesh;
  44. private PrimitiveBaseShape _pbs;
  45. private ShapeData.PhysicsShapeType _shapeType;
  46. private ulong _meshKey;
  47. private ulong _hullKey;
  48. private List<ConvexResult> _hulls;
  49. private BSScene _scene;
  50. private String _avName;
  51. private uint _localID = 0;
  52. // _size is what the user passed. _scale is what we pass to the physics engine with the mesh.
  53. // Often _scale is unity because the meshmerizer will apply _size when creating the mesh.
  54. private OMV.Vector3 _size; // the multiplier for each mesh dimension as passed by the user
  55. private OMV.Vector3 _scale; // the multiplier for each mesh dimension for the mesh as created by the meshmerizer
  56. private bool _stopped;
  57. private bool _grabbed;
  58. private bool _isSelected;
  59. private bool _isVolumeDetect;
  60. private OMV.Vector3 _position;
  61. private float _mass;
  62. private float _density;
  63. private OMV.Vector3 _force;
  64. private OMV.Vector3 _velocity;
  65. private OMV.Vector3 _torque;
  66. private float _collisionScore;
  67. private OMV.Vector3 _acceleration;
  68. private OMV.Quaternion _orientation;
  69. private int _physicsActorType;
  70. private bool _isPhysical;
  71. private bool _flying;
  72. private float _friction;
  73. private float _restitution;
  74. private bool _setAlwaysRun;
  75. private bool _throttleUpdates;
  76. private bool _isColliding;
  77. private bool _collidingGround;
  78. private bool _collidingObj;
  79. private bool _floatOnWater;
  80. private OMV.Vector3 _rotationalVelocity;
  81. private bool _kinematic;
  82. private float _buoyancy;
  83. private OMV.Vector3 _angularVelocity;
  84. private List<BSPrim> _childrenPrims;
  85. private BSPrim _parentPrim;
  86. private int _subscribedEventsMs = 0;
  87. private int _lastCollisionTime = 0;
  88. long _collidingStep;
  89. long _collidingGroundStep;
  90. private BSDynamics _vehicle;
  91. private OMV.Vector3 _PIDTarget;
  92. private bool _usePID;
  93. private float _PIDTau;
  94. private bool _useHoverPID;
  95. private float _PIDHoverHeight;
  96. private PIDHoverType _PIDHoverType;
  97. private float _PIDHoverTao;
  98. public BSPrim(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size,
  99. OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical)
  100. {
  101. // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID);
  102. _localID = localID;
  103. _avName = primName;
  104. _scene = parent_scene;
  105. _position = pos;
  106. _size = size;
  107. _scale = new OMV.Vector3(1f, 1f, 1f); // the scale will be set by CreateGeom depending on object type
  108. _orientation = rotation;
  109. _buoyancy = 1f;
  110. _velocity = OMV.Vector3.Zero;
  111. _rotationalVelocity = OMV.Vector3.Zero;
  112. _angularVelocity = OMV.Vector3.Zero;
  113. _hullKey = 0;
  114. _meshKey = 0;
  115. _pbs = pbs;
  116. _isPhysical = pisPhysical;
  117. _isVolumeDetect = false;
  118. _subscribedEventsMs = 0;
  119. _friction = _scene.Params.defaultFriction; // TODO: compute based on object material
  120. _density = _scene.Params.defaultDensity; // TODO: compute based on object material
  121. _restitution = _scene.Params.defaultRestitution;
  122. _parentPrim = null; // not a child or a parent
  123. _vehicle = new BSDynamics(this); // add vehicleness
  124. _childrenPrims = new List<BSPrim>();
  125. if (_isPhysical)
  126. _mass = CalculateMass();
  127. else
  128. _mass = 0f;
  129. // do the actual object creation at taint time
  130. _scene.TaintedObject(delegate()
  131. {
  132. RecreateGeomAndObject();
  133. });
  134. }
  135. // called when this prim is being destroyed and we should free all the resources
  136. public void Destroy()
  137. {
  138. // m_log.DebugFormat("{0}: Destroy", LogHeader);
  139. // Undo any vehicle properties
  140. _vehicle.ProcessTypeChange(Vehicle.TYPE_NONE);
  141. _scene.RemoveVehiclePrim(this); // just to make sure
  142. _scene.TaintedObject(delegate()
  143. {
  144. // everything in the C# world will get garbage collected. Tell the C++ world to free stuff.
  145. BulletSimAPI.DestroyObject(_scene.WorldID, _localID);
  146. });
  147. }
  148. public override bool Stopped {
  149. get { return _stopped; }
  150. }
  151. public override OMV.Vector3 Size {
  152. get { return _size; }
  153. set {
  154. _size = value;
  155. _scene.TaintedObject(delegate()
  156. {
  157. if (_isPhysical) _mass = CalculateMass(); // changing size changes the mass
  158. BulletSimAPI.SetObjectScaleMass(_scene.WorldID, _localID, _scale, _mass, _isPhysical);
  159. RecreateGeomAndObject();
  160. });
  161. }
  162. }
  163. public override PrimitiveBaseShape Shape {
  164. set {
  165. _pbs = value;
  166. _scene.TaintedObject(delegate()
  167. {
  168. if (_isPhysical) _mass = CalculateMass(); // changing the shape changes the mass
  169. RecreateGeomAndObject();
  170. });
  171. }
  172. }
  173. public override uint LocalID {
  174. set { _localID = value; }
  175. get { return _localID; }
  176. }
  177. public override bool Grabbed {
  178. set { _grabbed = value;
  179. }
  180. }
  181. public override bool Selected {
  182. set {
  183. _isSelected = value;
  184. _scene.TaintedObject(delegate()
  185. {
  186. SetObjectDynamic();
  187. });
  188. }
  189. }
  190. public override void CrossingFailure() { return; }
  191. // link me to the specified parent
  192. public override void link(PhysicsActor obj) {
  193. BSPrim parent = (BSPrim)obj;
  194. // m_log.DebugFormat("{0}: link {1}/{2} to {3}", LogHeader, _avName, _localID, obj.LocalID);
  195. // TODO: decide if this parent checking needs to happen at taint time
  196. if (_parentPrim == null)
  197. {
  198. if (parent != null)
  199. {
  200. // I don't have a parent so I am joining a linkset
  201. parent.AddChildToLinkset(this);
  202. }
  203. }
  204. else
  205. {
  206. // I already have a parent, is parenting changing?
  207. if (parent != _parentPrim)
  208. {
  209. if (parent == null)
  210. {
  211. // we are being removed from a linkset
  212. _parentPrim.RemoveChildFromLinkset(this);
  213. }
  214. else
  215. {
  216. // asking to reparent a prim should not happen
  217. m_log.ErrorFormat("{0}: Reparenting a prim. ", LogHeader);
  218. }
  219. }
  220. }
  221. return;
  222. }
  223. // delink me from my linkset
  224. public override void delink() {
  225. // TODO: decide if this parent checking needs to happen at taint time
  226. // Race condition here: if link() and delink() in same simulation tick, the delink will not happen
  227. // m_log.DebugFormat("{0}: delink {1}/{2}", LogHeader, _avName, _localID);
  228. if (_parentPrim != null)
  229. {
  230. _parentPrim.RemoveChildFromLinkset(this);
  231. }
  232. return;
  233. }
  234. // I am the root of a linkset and a new child is being added
  235. public void AddChildToLinkset(BSPrim pchild)
  236. {
  237. BSPrim child = pchild;
  238. _scene.TaintedObject(delegate()
  239. {
  240. if (!_childrenPrims.Contains(child))
  241. {
  242. _childrenPrims.Add(child);
  243. child.ParentPrim = this; // the child has gained a parent
  244. RecreateGeomAndObject(); // rebuild my shape with the new child added
  245. }
  246. });
  247. return;
  248. }
  249. // I am the root of a linkset and one of my children is being removed.
  250. // Safe to call even if the child is not really in my linkset.
  251. public void RemoveChildFromLinkset(BSPrim pchild)
  252. {
  253. BSPrim child = pchild;
  254. _scene.TaintedObject(delegate()
  255. {
  256. if (_childrenPrims.Contains(child))
  257. {
  258. BulletSimAPI.RemoveConstraint(_scene.WorldID, child.LocalID, this.LocalID);
  259. _childrenPrims.Remove(child);
  260. child.ParentPrim = null; // the child has lost its parent
  261. RecreateGeomAndObject(); // rebuild my shape with the child removed
  262. }
  263. else
  264. {
  265. m_log.ErrorFormat("{0}: Asked to remove child from linkset that was not in linkset");
  266. }
  267. });
  268. return;
  269. }
  270. public BSPrim ParentPrim
  271. {
  272. set { _parentPrim = value; }
  273. }
  274. // return true if we are the root of a linkset (there are children to manage)
  275. public bool IsRootOfLinkset
  276. {
  277. get { return (_parentPrim == null && _childrenPrims.Count != 0); }
  278. }
  279. // Set motion values to zero.
  280. // Do it to the properties so the values get set in the physics engine.
  281. // Push the setting of the values to the viewer.
  282. private void ZeroMotion()
  283. {
  284. Velocity = OMV.Vector3.Zero;
  285. _acceleration = OMV.Vector3.Zero;
  286. RotationalVelocity = OMV.Vector3.Zero;
  287. base.RequestPhysicsterseUpdate();
  288. }
  289. public override void LockAngularMotion(OMV.Vector3 axis) { return; }
  290. public override OMV.Vector3 Position {
  291. get {
  292. // don't do the following GetObjectPosition because this function is called a zillion times
  293. // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID);
  294. return _position;
  295. }
  296. set {
  297. _position = value;
  298. _scene.TaintedObject(delegate()
  299. {
  300. BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation);
  301. // m_log.DebugFormat("{0}: setPosition: id={1}, position={2}", LogHeader, _localID, _position);
  302. });
  303. }
  304. }
  305. public override float Mass {
  306. get { return _mass; }
  307. }
  308. public override OMV.Vector3 Force {
  309. get { return _force; }
  310. set {
  311. _force = value;
  312. _scene.TaintedObject(delegate()
  313. {
  314. BulletSimAPI.SetObjectForce(_scene.WorldID, _localID, _force);
  315. });
  316. }
  317. }
  318. public override int VehicleType {
  319. get {
  320. return (int)_vehicle.Type; // if we are a vehicle, return that type
  321. }
  322. set {
  323. Vehicle type = (Vehicle)value;
  324. _vehicle.ProcessTypeChange(type);
  325. _scene.TaintedObject(delegate()
  326. {
  327. if (type == Vehicle.TYPE_NONE)
  328. {
  329. _scene.RemoveVehiclePrim(this);
  330. }
  331. else
  332. {
  333. // make it so the scene will call us each tick to do vehicle things
  334. _scene.AddVehiclePrim(this);
  335. }
  336. return;
  337. });
  338. }
  339. }
  340. public override void VehicleFloatParam(int param, float value)
  341. {
  342. _vehicle.ProcessFloatVehicleParam((Vehicle)param, value);
  343. }
  344. public override void VehicleVectorParam(int param, OMV.Vector3 value)
  345. {
  346. _vehicle.ProcessVectorVehicleParam((Vehicle)param, value);
  347. }
  348. public override void VehicleRotationParam(int param, OMV.Quaternion rotation)
  349. {
  350. _vehicle.ProcessRotationVehicleParam((Vehicle)param, rotation);
  351. }
  352. public override void VehicleFlags(int param, bool remove)
  353. {
  354. _vehicle.ProcessVehicleFlags(param, remove);
  355. }
  356. // Called each simulation step to advance vehicle characteristics
  357. public void StepVehicle(float timeStep)
  358. {
  359. _vehicle.Step(timeStep, _scene);
  360. }
  361. // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more
  362. public override void SetVolumeDetect(int param) {
  363. bool newValue = (param != 0);
  364. if (_isVolumeDetect != newValue)
  365. {
  366. _isVolumeDetect = newValue;
  367. _scene.TaintedObject(delegate()
  368. {
  369. SetObjectDynamic();
  370. });
  371. }
  372. return;
  373. }
  374. public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } }
  375. public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } }
  376. public override OMV.Vector3 Velocity {
  377. get { return _velocity; }
  378. set { _velocity = value;
  379. _scene.TaintedObject(delegate()
  380. {
  381. BulletSimAPI.SetObjectVelocity(_scene.WorldID, LocalID, _velocity);
  382. });
  383. }
  384. }
  385. public override OMV.Vector3 Torque {
  386. get { return _torque; }
  387. set { _torque = value;
  388. }
  389. }
  390. public override float CollisionScore {
  391. get { return _collisionScore; }
  392. set { _collisionScore = value;
  393. }
  394. }
  395. public override OMV.Vector3 Acceleration {
  396. get { return _acceleration; }
  397. }
  398. public override OMV.Quaternion Orientation {
  399. get { return _orientation; }
  400. set {
  401. _orientation = value;
  402. // m_log.DebugFormat("{0}: set orientation: id={1}, ori={2}", LogHeader, LocalID, _orientation);
  403. _scene.TaintedObject(delegate()
  404. {
  405. // _position = BulletSimAPI.GetObjectPosition(_scene.WorldID, _localID);
  406. BulletSimAPI.SetObjectTranslation(_scene.WorldID, _localID, _position, _orientation);
  407. });
  408. }
  409. }
  410. public override int PhysicsActorType {
  411. get { return _physicsActorType; }
  412. set { _physicsActorType = value;
  413. }
  414. }
  415. public override bool IsPhysical {
  416. get { return _isPhysical; }
  417. set {
  418. _isPhysical = value;
  419. _scene.TaintedObject(delegate()
  420. {
  421. SetObjectDynamic();
  422. });
  423. }
  424. }
  425. // An object is static (does not move) if selected or not physical
  426. private bool IsStatic
  427. {
  428. get { return _isSelected || !IsPhysical; }
  429. }
  430. // An object is solid if it's not phantom and if it's not doing VolumeDetect
  431. private bool IsSolid
  432. {
  433. get { return !IsPhantom && !_isVolumeDetect; }
  434. }
  435. // make gravity work if the object is physical and not selected
  436. // no locking here because only called when it is safe
  437. private void SetObjectDynamic()
  438. {
  439. // m_log.DebugFormat("{0}: ID={1}, SetObjectDynamic: IsStatic={2}, IsSolid={3}", LogHeader, _localID, IsStatic, IsSolid);
  440. // non-physical things work best with a mass of zero
  441. if (IsStatic)
  442. {
  443. _mass = 0f;
  444. }
  445. else
  446. {
  447. _mass = CalculateMass();
  448. // If it's dynamic, make sure the hull has been created for it
  449. // This shouldn't do much work if the object had previously been built
  450. RecreateGeomAndObject();
  451. }
  452. BulletSimAPI.SetObjectProperties(_scene.WorldID, LocalID, IsStatic, IsSolid, SubscribedEvents(), _mass);
  453. }
  454. // prims don't fly
  455. public override bool Flying {
  456. get { return _flying; }
  457. set { _flying = value; }
  458. }
  459. public override bool SetAlwaysRun {
  460. get { return _setAlwaysRun; }
  461. set { _setAlwaysRun = value; }
  462. }
  463. public override bool ThrottleUpdates {
  464. get { return _throttleUpdates; }
  465. set { _throttleUpdates = value; }
  466. }
  467. public override bool IsColliding {
  468. get { return (_collidingStep == _scene.SimulationStep); }
  469. set { _isColliding = value; }
  470. }
  471. public override bool CollidingGround {
  472. get { return (_collidingGroundStep == _scene.SimulationStep); }
  473. set { _collidingGround = value; }
  474. }
  475. public override bool CollidingObj {
  476. get { return _collidingObj; }
  477. set { _collidingObj = value; }
  478. }
  479. public bool IsPhantom {
  480. get {
  481. // SceneObjectPart removes phantom objects from the physics scene
  482. // so, although we could implement touching and such, we never
  483. // are invoked as a phantom object
  484. return false;
  485. }
  486. }
  487. public override bool FloatOnWater {
  488. set { _floatOnWater = value; }
  489. }
  490. public override OMV.Vector3 RotationalVelocity {
  491. get { return _rotationalVelocity; }
  492. set { _rotationalVelocity = value;
  493. // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity);
  494. _scene.TaintedObject(delegate()
  495. {
  496. BulletSimAPI.SetObjectAngularVelocity(_scene.WorldID, LocalID, _rotationalVelocity);
  497. });
  498. }
  499. }
  500. public OMV.Vector3 AngularVelocity {
  501. get { return _angularVelocity; }
  502. set { _angularVelocity = value; }
  503. }
  504. public override bool Kinematic {
  505. get { return _kinematic; }
  506. set { _kinematic = value;
  507. // m_log.DebugFormat("{0}: Kinematic={1}", LogHeader, _kinematic);
  508. }
  509. }
  510. public override float Buoyancy {
  511. get { return _buoyancy; }
  512. set { _buoyancy = value;
  513. _scene.TaintedObject(delegate()
  514. {
  515. BulletSimAPI.SetObjectBuoyancy(_scene.WorldID, _localID, _buoyancy);
  516. });
  517. }
  518. }
  519. // Used for MoveTo
  520. public override OMV.Vector3 PIDTarget {
  521. set { _PIDTarget = value; }
  522. }
  523. public override bool PIDActive {
  524. set { _usePID = value; }
  525. }
  526. public override float PIDTau {
  527. set { _PIDTau = value; }
  528. }
  529. // Used for llSetHoverHeight and maybe vehicle height
  530. // Hover Height will override MoveTo target's Z
  531. public override bool PIDHoverActive {
  532. set { _useHoverPID = value; }
  533. }
  534. public override float PIDHoverHeight {
  535. set { _PIDHoverHeight = value; }
  536. }
  537. public override PIDHoverType PIDHoverType {
  538. set { _PIDHoverType = value; }
  539. }
  540. public override float PIDHoverTau {
  541. set { _PIDHoverTao = value; }
  542. }
  543. // For RotLookAt
  544. public override OMV.Quaternion APIDTarget { set { return; } }
  545. public override bool APIDActive { set { return; } }
  546. public override float APIDStrength { set { return; } }
  547. public override float APIDDamping { set { return; } }
  548. public override void AddForce(OMV.Vector3 force, bool pushforce) {
  549. if (force.IsFinite())
  550. {
  551. _force.X += force.X;
  552. _force.Y += force.Y;
  553. _force.Z += force.Z;
  554. }
  555. else
  556. {
  557. m_log.WarnFormat("{0}: Got a NaN force applied to a Character", LogHeader);
  558. }
  559. _scene.TaintedObject(delegate()
  560. {
  561. BulletSimAPI.SetObjectForce(_scene.WorldID, _localID, _force);
  562. });
  563. }
  564. public override void AddAngularForce(OMV.Vector3 force, bool pushforce) {
  565. // m_log.DebugFormat("{0}: AddAngularForce. f={1}, push={2}", LogHeader, force, pushforce);
  566. }
  567. public override void SetMomentum(OMV.Vector3 momentum) {
  568. }
  569. public override void SubscribeEvents(int ms) {
  570. _subscribedEventsMs = ms;
  571. _lastCollisionTime = Util.EnvironmentTickCount() - _subscribedEventsMs; // make first collision happen
  572. }
  573. public override void UnSubscribeEvents() {
  574. _subscribedEventsMs = 0;
  575. }
  576. public override bool SubscribedEvents() {
  577. return (_subscribedEventsMs > 0);
  578. }
  579. #region Mass Calculation
  580. private float CalculateMass()
  581. {
  582. float volume = _size.X * _size.Y * _size.Z; // default
  583. float tmp;
  584. float returnMass = 0;
  585. float hollowAmount = (float)_pbs.ProfileHollow * 2.0e-5f;
  586. float hollowVolume = hollowAmount * hollowAmount;
  587. switch (_pbs.ProfileShape)
  588. {
  589. case ProfileShape.Square:
  590. // default box
  591. if (_pbs.PathCurve == (byte)Extrusion.Straight)
  592. {
  593. if (hollowAmount > 0.0)
  594. {
  595. switch (_pbs.HollowShape)
  596. {
  597. case HollowShape.Square:
  598. case HollowShape.Same:
  599. break;
  600. case HollowShape.Circle:
  601. hollowVolume *= 0.78539816339f;
  602. break;
  603. case HollowShape.Triangle:
  604. hollowVolume *= (0.5f * .5f);
  605. break;
  606. default:
  607. hollowVolume = 0;
  608. break;
  609. }
  610. volume *= (1.0f - hollowVolume);
  611. }
  612. }
  613. else if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  614. {
  615. //a tube
  616. volume *= 0.78539816339e-2f * (float)(200 - _pbs.PathScaleX);
  617. tmp= 1.0f -2.0e-2f * (float)(200 - _pbs.PathScaleY);
  618. volume -= volume*tmp*tmp;
  619. if (hollowAmount > 0.0)
  620. {
  621. hollowVolume *= hollowAmount;
  622. switch (_pbs.HollowShape)
  623. {
  624. case HollowShape.Square:
  625. case HollowShape.Same:
  626. break;
  627. case HollowShape.Circle:
  628. hollowVolume *= 0.78539816339f;;
  629. break;
  630. case HollowShape.Triangle:
  631. hollowVolume *= 0.5f * 0.5f;
  632. break;
  633. default:
  634. hollowVolume = 0;
  635. break;
  636. }
  637. volume *= (1.0f - hollowVolume);
  638. }
  639. }
  640. break;
  641. case ProfileShape.Circle:
  642. if (_pbs.PathCurve == (byte)Extrusion.Straight)
  643. {
  644. volume *= 0.78539816339f; // elipse base
  645. if (hollowAmount > 0.0)
  646. {
  647. switch (_pbs.HollowShape)
  648. {
  649. case HollowShape.Same:
  650. case HollowShape.Circle:
  651. break;
  652. case HollowShape.Square:
  653. hollowVolume *= 0.5f * 2.5984480504799f;
  654. break;
  655. case HollowShape.Triangle:
  656. hollowVolume *= .5f * 1.27323954473516f;
  657. break;
  658. default:
  659. hollowVolume = 0;
  660. break;
  661. }
  662. volume *= (1.0f - hollowVolume);
  663. }
  664. }
  665. else if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  666. {
  667. volume *= 0.61685027506808491367715568749226e-2f * (float)(200 - _pbs.PathScaleX);
  668. tmp = 1.0f - .02f * (float)(200 - _pbs.PathScaleY);
  669. volume *= (1.0f - tmp * tmp);
  670. if (hollowAmount > 0.0)
  671. {
  672. // calculate the hollow volume by it's shape compared to the prim shape
  673. hollowVolume *= hollowAmount;
  674. switch (_pbs.HollowShape)
  675. {
  676. case HollowShape.Same:
  677. case HollowShape.Circle:
  678. break;
  679. case HollowShape.Square:
  680. hollowVolume *= 0.5f * 2.5984480504799f;
  681. break;
  682. case HollowShape.Triangle:
  683. hollowVolume *= .5f * 1.27323954473516f;
  684. break;
  685. default:
  686. hollowVolume = 0;
  687. break;
  688. }
  689. volume *= (1.0f - hollowVolume);
  690. }
  691. }
  692. break;
  693. case ProfileShape.HalfCircle:
  694. if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  695. {
  696. volume *= 0.52359877559829887307710723054658f;
  697. }
  698. break;
  699. case ProfileShape.EquilateralTriangle:
  700. if (_pbs.PathCurve == (byte)Extrusion.Straight)
  701. {
  702. volume *= 0.32475953f;
  703. if (hollowAmount > 0.0)
  704. {
  705. // calculate the hollow volume by it's shape compared to the prim shape
  706. switch (_pbs.HollowShape)
  707. {
  708. case HollowShape.Same:
  709. case HollowShape.Triangle:
  710. hollowVolume *= .25f;
  711. break;
  712. case HollowShape.Square:
  713. hollowVolume *= 0.499849f * 3.07920140172638f;
  714. break;
  715. case HollowShape.Circle:
  716. // Hollow shape is a perfect cyllinder in respect to the cube's scale
  717. // Cyllinder hollow volume calculation
  718. hollowVolume *= 0.1963495f * 3.07920140172638f;
  719. break;
  720. default:
  721. hollowVolume = 0;
  722. break;
  723. }
  724. volume *= (1.0f - hollowVolume);
  725. }
  726. }
  727. else if (_pbs.PathCurve == (byte)Extrusion.Curve1)
  728. {
  729. volume *= 0.32475953f;
  730. volume *= 0.01f * (float)(200 - _pbs.PathScaleX);
  731. tmp = 1.0f - .02f * (float)(200 - _pbs.PathScaleY);
  732. volume *= (1.0f - tmp * tmp);
  733. if (hollowAmount > 0.0)
  734. {
  735. hollowVolume *= hollowAmount;
  736. switch (_pbs.HollowShape)
  737. {
  738. case HollowShape.Same:
  739. case HollowShape.Triangle:
  740. hollowVolume *= .25f;
  741. break;
  742. case HollowShape.Square:
  743. hollowVolume *= 0.499849f * 3.07920140172638f;
  744. break;
  745. case HollowShape.Circle:
  746. hollowVolume *= 0.1963495f * 3.07920140172638f;
  747. break;
  748. default:
  749. hollowVolume = 0;
  750. break;
  751. }
  752. volume *= (1.0f - hollowVolume);
  753. }
  754. }
  755. break;
  756. default:
  757. break;
  758. }
  759. float taperX1;
  760. float taperY1;
  761. float taperX;
  762. float taperY;
  763. float pathBegin;
  764. float pathEnd;
  765. float profileBegin;
  766. float profileEnd;
  767. if (_pbs.PathCurve == (byte)Extrusion.Straight || _pbs.PathCurve == (byte)Extrusion.Flexible)
  768. {
  769. taperX1 = _pbs.PathScaleX * 0.01f;
  770. if (taperX1 > 1.0f)
  771. taperX1 = 2.0f - taperX1;
  772. taperX = 1.0f - taperX1;
  773. taperY1 = _pbs.PathScaleY * 0.01f;
  774. if (taperY1 > 1.0f)
  775. taperY1 = 2.0f - taperY1;
  776. taperY = 1.0f - taperY1;
  777. }
  778. else
  779. {
  780. taperX = _pbs.PathTaperX * 0.01f;
  781. if (taperX < 0.0f)
  782. taperX = -taperX;
  783. taperX1 = 1.0f - taperX;
  784. taperY = _pbs.PathTaperY * 0.01f;
  785. if (taperY < 0.0f)
  786. taperY = -taperY;
  787. taperY1 = 1.0f - taperY;
  788. }
  789. volume *= (taperX1 * taperY1 + 0.5f * (taperX1 * taperY + taperX * taperY1) + 0.3333333333f * taperX * taperY);
  790. pathBegin = (float)_pbs.PathBegin * 2.0e-5f;
  791. pathEnd = 1.0f - (float)_pbs.PathEnd * 2.0e-5f;
  792. volume *= (pathEnd - pathBegin);
  793. // this is crude aproximation
  794. profileBegin = (float)_pbs.ProfileBegin * 2.0e-5f;
  795. profileEnd = 1.0f - (float)_pbs.ProfileEnd * 2.0e-5f;
  796. volume *= (profileEnd - profileBegin);
  797. returnMass = _density * volume;
  798. if (IsRootOfLinkset)
  799. {
  800. foreach (BSPrim prim in _childrenPrims)
  801. {
  802. returnMass += prim.CalculateMass();
  803. }
  804. }
  805. if (returnMass <= 0)
  806. returnMass = 0.0001f;
  807. if (returnMass > _scene.MaximumObjectMass)
  808. returnMass = _scene.MaximumObjectMass;
  809. return returnMass;
  810. }// end CalculateMass
  811. #endregion Mass Calculation
  812. // Create the geometry information in Bullet for later use
  813. // The objects needs a hull if it's physical otherwise a mesh is enough
  814. // No locking here because this is done when we know physics is not simulating
  815. // if 'forceRebuild' is true, the geometry is rebuilt. Otherwise a previously built version is used
  816. private void CreateGeom(bool forceRebuild)
  817. {
  818. // the mesher thought this was too simple to mesh. Use a native Bullet collision shape.
  819. if (!_scene.NeedsMeshing(_pbs))
  820. {
  821. if (_pbs.ProfileShape == ProfileShape.HalfCircle && _pbs.PathCurve == (byte)Extrusion.Curve1)
  822. {
  823. if (_size.X == _size.Y && _size.Y == _size.Z && _size.X == _size.Z)
  824. {
  825. // m_log.DebugFormat("{0}: CreateGeom: Defaulting to sphere of size {1}", LogHeader, _size);
  826. _shapeType = ShapeData.PhysicsShapeType.SHAPE_SPHERE;
  827. // Bullet native objects are scaled by the Bullet engine so pass the size in
  828. _scale = _size;
  829. }
  830. }
  831. else
  832. {
  833. // m_log.DebugFormat("{0}: CreateGeom: Defaulting to box. lid={1}, size={2}", LogHeader, LocalID, _size);
  834. _shapeType = ShapeData.PhysicsShapeType.SHAPE_BOX;
  835. _scale = _size;
  836. }
  837. }
  838. else
  839. {
  840. if (IsPhysical)
  841. {
  842. if (forceRebuild || _hullKey == 0)
  843. {
  844. // physical objects require a hull for interaction.
  845. // This will create the mesh if it doesn't already exist
  846. CreateGeomHull();
  847. }
  848. }
  849. else
  850. {
  851. if (forceRebuild || _meshKey == 0)
  852. {
  853. // Static (non-physical) objects only need a mesh for bumping into
  854. CreateGeomMesh();
  855. }
  856. }
  857. }
  858. }
  859. // No locking here because this is done when we know physics is not simulating
  860. private void CreateGeomMesh()
  861. {
  862. float lod = _pbs.SculptEntry ? _scene.SculptLOD : _scene.MeshLOD;
  863. ulong newMeshKey = (ulong)_pbs.GetMeshKey(_size, lod);
  864. // m_log.DebugFormat("{0}: CreateGeomMesh: lID={1}, oldKey={2}, newKey={3}", LogHeader, _localID, _meshKey, newMeshKey);
  865. // if this new shape is the same as last time, don't recreate the mesh
  866. if (_meshKey == newMeshKey) return;
  867. // Since we're recreating new, get rid of any previously generated shape
  868. if (_meshKey != 0)
  869. {
  870. // m_log.DebugFormat("{0}: CreateGeom: deleting old mesh. lID={1}, Key={2}", LogHeader, _localID, _meshKey);
  871. BulletSimAPI.DestroyMesh(_scene.WorldID, _meshKey);
  872. _mesh = null;
  873. _meshKey = 0;
  874. }
  875. _meshKey = newMeshKey;
  876. // always pass false for physicalness as this creates some sort of bounding box which we don't need
  877. _mesh = _scene.mesher.CreateMesh(_avName, _pbs, _size, lod, false);
  878. int[] indices = _mesh.getIndexListAsInt();
  879. List<OMV.Vector3> vertices = _mesh.getVertexList();
  880. float[] verticesAsFloats = new float[vertices.Count * 3];
  881. int vi = 0;
  882. foreach (OMV.Vector3 vv in vertices)
  883. {
  884. // m_log.DebugFormat("{0}: {1}: <{2:0.00}, {3:0.00}, {4:0.00}>", LogHeader, vi / 3, vv.X, vv.Y, vv.Z);
  885. verticesAsFloats[vi++] = vv.X;
  886. verticesAsFloats[vi++] = vv.Y;
  887. verticesAsFloats[vi++] = vv.Z;
  888. }
  889. // m_log.DebugFormat("{0}: CreateGeomMesh: calling CreateMesh. lid={1}, key={2}, indices={3}, vertices={4}",
  890. // LogHeader, _localID, _meshKey, indices.Length, vertices.Count);
  891. BulletSimAPI.CreateMesh(_scene.WorldID, _meshKey, indices.GetLength(0), indices,
  892. vertices.Count, verticesAsFloats);
  893. _shapeType = ShapeData.PhysicsShapeType.SHAPE_MESH;
  894. // meshes are already scaled by the meshmerizer
  895. _scale = new OMV.Vector3(1f, 1f, 1f);
  896. return;
  897. }
  898. // No locking here because this is done when we know physics is not simulating
  899. private void CreateGeomHull()
  900. {
  901. float lod = _pbs.SculptEntry ? _scene.SculptLOD : _scene.MeshLOD;
  902. ulong newHullKey = (ulong)_pbs.GetMeshKey(_size, lod);
  903. // m_log.DebugFormat("{0}: CreateGeomHull: lID={1}, oldKey={2}, newKey={3}", LogHeader, _localID, _hullKey, newHullKey);
  904. // if the hull hasn't changed, don't rebuild it
  905. if (newHullKey == _hullKey) return;
  906. // Since we're recreating new, get rid of any previously generated shape
  907. if (_hullKey != 0)
  908. {
  909. // m_log.DebugFormat("{0}: CreateGeom: deleting old hull. Key={1}", LogHeader, _hullKey);
  910. BulletSimAPI.DestroyHull(_scene.WorldID, _hullKey);
  911. _hullKey = 0;
  912. _hulls.Clear();
  913. BulletSimAPI.DestroyMesh(_scene.WorldID, _meshKey);
  914. _mesh = null; // the mesh cannot match either
  915. _meshKey = 0;
  916. }
  917. _hullKey = newHullKey;
  918. if (_meshKey != _hullKey)
  919. {
  920. // if the underlying mesh has changed, rebuild it
  921. CreateGeomMesh();
  922. }
  923. int[] indices = _mesh.getIndexListAsInt();
  924. List<OMV.Vector3> vertices = _mesh.getVertexList();
  925. //format conversion from IMesh format to DecompDesc format
  926. List<int> convIndices = new List<int>();
  927. List<float3> convVertices = new List<float3>();
  928. for (int ii = 0; ii < indices.GetLength(0); ii++)
  929. {
  930. convIndices.Add(indices[ii]);
  931. }
  932. foreach (OMV.Vector3 vv in vertices)
  933. {
  934. convVertices.Add(new float3(vv.X, vv.Y, vv.Z));
  935. }
  936. // setup and do convex hull conversion
  937. _hulls = new List<ConvexResult>();
  938. DecompDesc dcomp = new DecompDesc();
  939. dcomp.mIndices = convIndices;
  940. dcomp.mVertices = convVertices;
  941. ConvexBuilder convexBuilder = new ConvexBuilder(HullReturn);
  942. // create the hull into the _hulls variable
  943. convexBuilder.process(dcomp);
  944. // Convert the vertices and indices for passing to unmanaged
  945. // The hull information is passed as a large floating point array.
  946. // The format is:
  947. // convHulls[0] = number of hulls
  948. // convHulls[1] = number of vertices in first hull
  949. // convHulls[2] = hull centroid X coordinate
  950. // convHulls[3] = hull centroid Y coordinate
  951. // convHulls[4] = hull centroid Z coordinate
  952. // convHulls[5] = first hull vertex X
  953. // convHulls[6] = first hull vertex Y
  954. // convHulls[7] = first hull vertex Z
  955. // convHulls[8] = second hull vertex X
  956. // ...
  957. // convHulls[n] = number of vertices in second hull
  958. // convHulls[n+1] = second hull centroid X coordinate
  959. // ...
  960. //
  961. // TODO: is is very inefficient. Someday change the convex hull generator to return
  962. // data structures that do not need to be converted in order to pass to Bullet.
  963. // And maybe put the values directly into pinned memory rather than marshaling.
  964. int hullCount = _hulls.Count;
  965. int totalVertices = 1; // include one for the count of the hulls
  966. foreach (ConvexResult cr in _hulls)
  967. {
  968. totalVertices += 4; // add four for the vertex count and centroid
  969. totalVertices += cr.HullIndices.Count * 3; // we pass just triangles
  970. }
  971. float[] convHulls = new float[totalVertices];
  972. convHulls[0] = (float)hullCount;
  973. int jj = 1;
  974. foreach (ConvexResult cr in _hulls)
  975. {
  976. // copy vertices for index access
  977. float3[] verts = new float3[cr.HullVertices.Count];
  978. int kk = 0;
  979. foreach (float3 ff in cr.HullVertices)
  980. {
  981. verts[kk++] = ff;
  982. }
  983. // add to the array one hull's worth of data
  984. convHulls[jj++] = cr.HullIndices.Count;
  985. convHulls[jj++] = 0f; // centroid x,y,z
  986. convHulls[jj++] = 0f;
  987. convHulls[jj++] = 0f;
  988. foreach (int ind in cr.HullIndices)
  989. {
  990. convHulls[jj++] = verts[ind].x;
  991. convHulls[jj++] = verts[ind].y;
  992. convHulls[jj++] = verts[ind].z;
  993. }
  994. }
  995. // create the hull definition in Bullet
  996. // m_log.DebugFormat("{0}: CreateGeom: calling CreateHull. lid={1}, key={2}, hulls={3}", LogHeader, _localID, _hullKey, hullCount);
  997. BulletSimAPI.CreateHull(_scene.WorldID, _hullKey, hullCount, convHulls);
  998. _shapeType = ShapeData.PhysicsShapeType.SHAPE_HULL;
  999. // meshes are already scaled by the meshmerizer
  1000. _scale = new OMV.Vector3(1f, 1f, 1f);
  1001. return;
  1002. }
  1003. // Callback from convex hull creater with a newly created hull.
  1004. // Just add it to the collection of hulls for this shape.
  1005. private void HullReturn(ConvexResult result)
  1006. {
  1007. _hulls.Add(result);
  1008. return;
  1009. }
  1010. // Create an object in Bullet
  1011. // No locking here because this is done when the physics engine is not simulating
  1012. private void CreateObject()
  1013. {
  1014. if (IsRootOfLinkset)
  1015. {
  1016. // Create a linkset around this object
  1017. // CreateLinksetWithCompoundHull();
  1018. CreateLinksetWithConstraints();
  1019. }
  1020. else
  1021. {
  1022. // simple object
  1023. // the mesh or hull must have already been created in Bullet
  1024. ShapeData shape;
  1025. FillShapeInfo(out shape);
  1026. // m_log.DebugFormat("{0}: CreateObject: lID={1}, shape={2}", LogHeader, _localID, shape.Type);
  1027. BulletSimAPI.CreateObject(_scene.WorldID, shape);
  1028. }
  1029. }
  1030. // Create a linkset by creating a compound hull at the root prim that consists of all
  1031. // the children.
  1032. // NOTE: This does not allow proper collisions with the children prims so it is not a workable solution
  1033. void CreateLinksetWithCompoundHull()
  1034. {
  1035. // If I am the root prim of a linkset, replace my physical shape with all the
  1036. // pieces of the children.
  1037. // All of the children should have called CreateGeom so they have a hull
  1038. // in the physics engine already. Here we pull together all of those hulls
  1039. // into one shape.
  1040. int totalPrimsInLinkset = _childrenPrims.Count + 1;
  1041. // m_log.DebugFormat("{0}: CreateLinkset. Root prim={1}, prims={2}", LogHeader, LocalID, totalPrimsInLinkset);
  1042. ShapeData[] shapes = new ShapeData[totalPrimsInLinkset];
  1043. FillShapeInfo(out shapes[0]);
  1044. int ii = 1;
  1045. foreach (BSPrim prim in _childrenPrims)
  1046. {
  1047. // m_log.DebugFormat("{0}: CreateLinkset: adding prim {1}", LogHeader, prim.LocalID);
  1048. prim.FillShapeInfo(out shapes[ii]);
  1049. ii++;
  1050. }
  1051. BulletSimAPI.CreateLinkset(_scene.WorldID, totalPrimsInLinkset, shapes);
  1052. }
  1053. // Copy prim's info into the BulletSim shape description structure
  1054. public void FillShapeInfo(out ShapeData shape)
  1055. {
  1056. shape.ID = _localID;
  1057. shape.Type = _shapeType;
  1058. shape.Position = _position;
  1059. shape.Rotation = _orientation;
  1060. shape.Velocity = _velocity;
  1061. shape.Scale = _scale;
  1062. shape.Mass = _isPhysical ? _mass : 0f;
  1063. shape.Buoyancy = _buoyancy;
  1064. shape.HullKey = _hullKey;
  1065. shape.MeshKey = _meshKey;
  1066. shape.Friction = _friction;
  1067. shape.Restitution = _restitution;
  1068. shape.Collidable = (!IsPhantom) ? ShapeData.numericTrue : ShapeData.numericFalse;
  1069. shape.Static = _isPhysical ? ShapeData.numericFalse : ShapeData.numericTrue;
  1070. }
  1071. // Create the linkset by putting constraints between the objects of the set so they cannot move
  1072. // relative to each other.
  1073. // TODO: make this more effeicient: a large linkset gets rebuilt over and over and prims are added
  1074. void CreateLinksetWithConstraints()
  1075. {
  1076. // m_log.DebugFormat("{0}: CreateLinkset. Root prim={1}, prims={2}", LogHeader, LocalID, _childrenPrims.Count+1);
  1077. // remove any constraints that might be in place
  1078. foreach (BSPrim prim in _childrenPrims)
  1079. {
  1080. // m_log.DebugFormat("{0}: CreateLinkset: RemoveConstraint between root prim {1} and child prim {2}", LogHeader, LocalID, prim.LocalID);
  1081. BulletSimAPI.RemoveConstraint(_scene.WorldID, LocalID, prim.LocalID);
  1082. }
  1083. // create constraints between the root prim and each of the children
  1084. foreach (BSPrim prim in _childrenPrims)
  1085. {
  1086. // m_log.DebugFormat("{0}: CreateLinkset: AddConstraint between root prim {1} and child prim {2}", LogHeader, LocalID, prim.LocalID);
  1087. // Zero motion for children so they don't interpolate
  1088. prim.ZeroMotion();
  1089. // relative position normalized to the root prim
  1090. OMV.Vector3 childRelativePosition = (prim._position - this._position) * OMV.Quaternion.Inverse(this._orientation);
  1091. // relative rotation of the child to the parent
  1092. OMV.Quaternion relativeRotation = OMV.Quaternion.Inverse(prim._orientation) * this._orientation;
  1093. // this is a constraint that allows no freedom of movement between the two objects
  1094. // http://bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=4818
  1095. BulletSimAPI.AddConstraint(_scene.WorldID, LocalID, prim.LocalID,
  1096. childRelativePosition,
  1097. relativeRotation,
  1098. OMV.Vector3.Zero,
  1099. OMV.Quaternion.Identity,
  1100. OMV.Vector3.Zero, OMV.Vector3.Zero,
  1101. OMV.Vector3.Zero, OMV.Vector3.Zero);
  1102. }
  1103. }
  1104. // Rebuild the geometry and object.
  1105. // This is called when the shape changes so we need to recreate the mesh/hull.
  1106. // No locking here because this is done when the physics engine is not simulating
  1107. private void RecreateGeomAndObject()
  1108. {
  1109. // m_log.DebugFormat("{0}: RecreateGeomAndObject. lID={1}", LogHeader, _localID);
  1110. CreateGeom(true);
  1111. CreateObject();
  1112. return;
  1113. }
  1114. // The physics engine says that properties have updated. Update same and inform
  1115. // the world that things have changed.
  1116. // TODO: do we really need to check for changed? Maybe just copy values and call RequestPhysicsterseUpdate()
  1117. enum UpdatedProperties {
  1118. Position = 1 << 0,
  1119. Rotation = 1 << 1,
  1120. Velocity = 1 << 2,
  1121. Acceleration = 1 << 3,
  1122. RotationalVel = 1 << 4
  1123. }
  1124. const float ROTATION_TOLERANCE = 0.01f;
  1125. const float VELOCITY_TOLERANCE = 0.001f;
  1126. const float POSITION_TOLERANCE = 0.05f;
  1127. const float ACCELERATION_TOLERANCE = 0.01f;
  1128. const float ROTATIONAL_VELOCITY_TOLERANCE = 0.01f;
  1129. const bool SHOULD_DAMP_UPDATES = false;
  1130. public void UpdateProperties(EntityProperties entprop)
  1131. {
  1132. UpdatedProperties changed = 0;
  1133. if (SHOULD_DAMP_UPDATES)
  1134. {
  1135. // assign to the local variables so the normal set action does not happen
  1136. // if (_position != entprop.Position)
  1137. if (!_position.ApproxEquals(entprop.Position, POSITION_TOLERANCE))
  1138. {
  1139. _position = entprop.Position;
  1140. // m_log.DebugFormat("{0}: UpdateProperties: id={1}, pos = {2}", LogHeader, LocalID, _position);
  1141. changed |= UpdatedProperties.Position;
  1142. }
  1143. // if (_orientation != entprop.Rotation)
  1144. if (!_orientation.ApproxEquals(entprop.Rotation, ROTATION_TOLERANCE))
  1145. {
  1146. _orientation = entprop.Rotation;
  1147. // m_log.DebugFormat("{0}: UpdateProperties: id={1}, rot = {2}", LogHeader, LocalID, _orientation);
  1148. changed |= UpdatedProperties.Rotation;
  1149. }
  1150. // if (_velocity != entprop.Velocity)
  1151. if (!_velocity.ApproxEquals(entprop.Velocity, VELOCITY_TOLERANCE))
  1152. {
  1153. _velocity = entprop.Velocity;
  1154. // m_log.DebugFormat("{0}: UpdateProperties: velocity = {1}", LogHeader, _velocity);
  1155. changed |= UpdatedProperties.Velocity;
  1156. }
  1157. // if (_acceleration != entprop.Acceleration)
  1158. if (!_acceleration.ApproxEquals(entprop.Acceleration, ACCELERATION_TOLERANCE))
  1159. {
  1160. _acceleration = entprop.Acceleration;
  1161. // m_log.DebugFormat("{0}: UpdateProperties: acceleration = {1}", LogHeader, _acceleration);
  1162. changed |= UpdatedProperties.Acceleration;
  1163. }
  1164. // if (_rotationalVelocity != entprop.RotationalVelocity)
  1165. if (!_rotationalVelocity.ApproxEquals(entprop.RotationalVelocity, ROTATIONAL_VELOCITY_TOLERANCE))
  1166. {
  1167. _rotationalVelocity = entprop.RotationalVelocity;
  1168. // m_log.DebugFormat("{0}: UpdateProperties: rotationalVelocity = {1}", LogHeader, _rotationalVelocity);
  1169. changed |= UpdatedProperties.RotationalVel;
  1170. }
  1171. if (changed != 0)
  1172. {
  1173. // m_log.DebugFormat("{0}: UpdateProperties: id={1}, c={2}, pos={3}, rot={4}", LogHeader, LocalID, changed, _position, _orientation);
  1174. // Only update the position of single objects and linkset roots
  1175. if (this._parentPrim == null)
  1176. {
  1177. // m_log.DebugFormat("{0}: RequestTerseUpdate. id={1}, ch={2}, pos={3}, rot={4}", LogHeader, LocalID, changed, _position, _orientation);
  1178. base.RequestPhysicsterseUpdate();
  1179. }
  1180. }
  1181. }
  1182. else
  1183. {
  1184. // Don't check for damping here -- it's done in BulletSim and SceneObjectPart.
  1185. // Only updates only for individual prims and for the root object of a linkset.
  1186. if (this._parentPrim == null)
  1187. {
  1188. // Assign to the local variables so the normal set action does not happen
  1189. _position = entprop.Position;
  1190. _orientation = entprop.Rotation;
  1191. _velocity = entprop.Velocity;
  1192. _acceleration = entprop.Acceleration;
  1193. _rotationalVelocity = entprop.RotationalVelocity;
  1194. // m_log.DebugFormat("{0}: RequestTerseUpdate. id={1}, ch={2}, pos={3}, rot={4}", LogHeader, LocalID, changed, _position, _orientation);
  1195. base.RequestPhysicsterseUpdate();
  1196. }
  1197. }
  1198. }
  1199. // I've collided with something
  1200. public void Collide(uint collidingWith, ActorTypes type, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth)
  1201. {
  1202. // m_log.DebugFormat("{0}: Collide: ms={1}, id={2}, with={3}", LogHeader, _subscribedEventsMs, LocalID, collidingWith);
  1203. // The following lines make IsColliding() and IsCollidingGround() work
  1204. _collidingStep = _scene.SimulationStep;
  1205. if (collidingWith == BSScene.TERRAIN_ID || collidingWith == BSScene.GROUNDPLANE_ID)
  1206. {
  1207. _collidingGroundStep = _scene.SimulationStep;
  1208. }
  1209. if (_subscribedEventsMs == 0) return; // nothing in the object is waiting for collision events
  1210. // throttle the collisions to the number of milliseconds specified in the subscription
  1211. int nowTime = _scene.SimulationNowTime;
  1212. if (nowTime < (_lastCollisionTime + _subscribedEventsMs)) return;
  1213. _lastCollisionTime = nowTime;
  1214. // create the event for the collision
  1215. Dictionary<uint, ContactPoint> contactPoints = new Dictionary<uint, ContactPoint>();
  1216. contactPoints.Add(collidingWith, new ContactPoint(contactPoint, contactNormal, pentrationDepth));
  1217. CollisionEventUpdate args = new CollisionEventUpdate(LocalID, (int)type, 1, contactPoints);
  1218. base.SendCollisionUpdate(args);
  1219. }
  1220. }
  1221. }