1
0

BSPrim.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  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 class BSPrim : BSPhysObject
  40. {
  41. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  42. private static readonly string LogHeader = "[BULLETS PRIM]";
  43. // _size is what the user passed. Scale is what we pass to the physics engine with the mesh.
  44. private OMV.Vector3 _size; // the multiplier for each mesh dimension as passed by the user
  45. private bool _grabbed;
  46. private bool _isSelected;
  47. private bool _isVolumeDetect;
  48. private float _mass; // the mass of this object
  49. private OMV.Vector3 _acceleration;
  50. private int _physicsActorType;
  51. private bool _isPhysical;
  52. private bool _flying;
  53. private bool _setAlwaysRun;
  54. private bool _throttleUpdates;
  55. private bool _floatOnWater;
  56. private OMV.Vector3 _rotationalVelocity;
  57. private bool _kinematic;
  58. private float _buoyancy;
  59. private int CrossingFailures { get; set; }
  60. // Keep a handle to the vehicle actor so it is easy to set parameters on same.
  61. public const string VehicleActorName = "BasicVehicle";
  62. // Parameters for the hover actor
  63. public const string HoverActorName = "BSPrim.HoverActor";
  64. // Parameters for the axis lock actor
  65. public const String LockedAxisActorName = "BSPrim.LockedAxis";
  66. // Parameters for the move to target actor
  67. public const string MoveToTargetActorName = "BSPrim.MoveToTargetActor";
  68. // Parameters for the setForce and setTorque actors
  69. public const string SetForceActorName = "BSPrim.SetForceActor";
  70. public const string SetTorqueActorName = "BSPrim.SetTorqueActor";
  71. public BSPrim(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size,
  72. OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical)
  73. : base(parent_scene, localID, primName, "BSPrim")
  74. {
  75. // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID);
  76. _physicsActorType = (int)ActorTypes.Prim;
  77. RawPosition = pos;
  78. _size = size;
  79. Scale = size; // prims are the size the user wants them to be (different for BSCharactes).
  80. RawOrientation = rotation;
  81. _buoyancy = 0f;
  82. RawVelocity = OMV.Vector3.Zero;
  83. _rotationalVelocity = OMV.Vector3.Zero;
  84. BaseShape = pbs;
  85. _isPhysical = pisPhysical;
  86. _isVolumeDetect = false;
  87. // Add a dynamic vehicle to our set of actors that can move this prim.
  88. PhysicalActors.Add(VehicleActorName, new BSDynamics(PhysScene, this, VehicleActorName));
  89. _mass = CalculateMass();
  90. // DetailLog("{0},BSPrim.constructor,call", LocalID);
  91. // do the actual object creation at taint time
  92. PhysScene.TaintedObject("BSPrim.create", delegate()
  93. {
  94. // Make sure the object is being created with some sanity.
  95. ExtremeSanityCheck(true /* inTaintTime */);
  96. CreateGeomAndObject(true);
  97. CurrentCollisionFlags = PhysScene.PE.GetCollisionFlags(PhysBody);
  98. });
  99. }
  100. // called when this prim is being destroyed and we should free all the resources
  101. public override void Destroy()
  102. {
  103. // m_log.DebugFormat("{0}: Destroy, id={1}", LogHeader, LocalID);
  104. base.Destroy();
  105. // Undo any vehicle properties
  106. this.VehicleType = (int)Vehicle.TYPE_NONE;
  107. PhysScene.TaintedObject("BSPrim.Destroy", delegate()
  108. {
  109. DetailLog("{0},BSPrim.Destroy,taint,", LocalID);
  110. // If there are physical body and shape, release my use of same.
  111. PhysScene.Shapes.DereferenceBody(PhysBody, null);
  112. PhysBody.Clear();
  113. PhysShape.Dereference(PhysScene);
  114. PhysShape = new BSShapeNull();
  115. });
  116. }
  117. // No one uses this property.
  118. public override bool Stopped {
  119. get { return false; }
  120. }
  121. public override OMV.Vector3 Size {
  122. get { return _size; }
  123. set {
  124. // We presume the scale and size are the same. If scale must be changed for
  125. // the physical shape, that is done when the geometry is built.
  126. _size = value;
  127. Scale = _size;
  128. ForceBodyShapeRebuild(false);
  129. }
  130. }
  131. public override PrimitiveBaseShape Shape {
  132. set {
  133. BaseShape = value;
  134. PrimAssetState = PrimAssetCondition.Unknown;
  135. ForceBodyShapeRebuild(false);
  136. }
  137. }
  138. public override bool ForceBodyShapeRebuild(bool inTaintTime)
  139. {
  140. PhysScene.TaintedObject(inTaintTime, "BSPrim.ForceBodyShapeRebuild", delegate()
  141. {
  142. _mass = CalculateMass(); // changing the shape changes the mass
  143. CreateGeomAndObject(true);
  144. });
  145. return true;
  146. }
  147. public override bool Grabbed {
  148. set { _grabbed = value;
  149. }
  150. }
  151. public override bool Selected {
  152. set
  153. {
  154. if (value != _isSelected)
  155. {
  156. _isSelected = value;
  157. PhysScene.TaintedObject("BSPrim.setSelected", delegate()
  158. {
  159. DetailLog("{0},BSPrim.selected,taint,selected={1}", LocalID, _isSelected);
  160. SetObjectDynamic(false);
  161. });
  162. }
  163. }
  164. }
  165. public override bool IsSelected
  166. {
  167. get { return _isSelected; }
  168. }
  169. public override void CrossingFailure()
  170. {
  171. CrossingFailures++;
  172. if (CrossingFailures > BSParam.CrossingFailuresBeforeOutOfBounds)
  173. {
  174. base.RaiseOutOfBounds(RawPosition);
  175. }
  176. else if (CrossingFailures == BSParam.CrossingFailuresBeforeOutOfBounds)
  177. {
  178. m_log.WarnFormat("{0} Too many crossing failures for {1}", LogHeader, Name);
  179. }
  180. return;
  181. }
  182. // link me to the specified parent
  183. public override void link(PhysicsActor obj) {
  184. }
  185. // delink me from my linkset
  186. public override void delink() {
  187. }
  188. // Set motion values to zero.
  189. // Do it to the properties so the values get set in the physics engine.
  190. // Push the setting of the values to the viewer.
  191. // Called at taint time!
  192. public override void ZeroMotion(bool inTaintTime)
  193. {
  194. RawVelocity = OMV.Vector3.Zero;
  195. _acceleration = OMV.Vector3.Zero;
  196. _rotationalVelocity = OMV.Vector3.Zero;
  197. // Zero some other properties in the physics engine
  198. PhysScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate()
  199. {
  200. if (PhysBody.HasPhysicalBody)
  201. PhysScene.PE.ClearAllForces(PhysBody);
  202. });
  203. }
  204. public override void ZeroAngularMotion(bool inTaintTime)
  205. {
  206. _rotationalVelocity = OMV.Vector3.Zero;
  207. // Zero some other properties in the physics engine
  208. PhysScene.TaintedObject(inTaintTime, "BSPrim.ZeroMotion", delegate()
  209. {
  210. // DetailLog("{0},BSPrim.ZeroAngularMotion,call,rotVel={1}", LocalID, _rotationalVelocity);
  211. if (PhysBody.HasPhysicalBody)
  212. {
  213. PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, _rotationalVelocity);
  214. PhysScene.PE.SetAngularVelocity(PhysBody, _rotationalVelocity);
  215. }
  216. });
  217. }
  218. public override void LockAngularMotion(OMV.Vector3 axis)
  219. {
  220. DetailLog("{0},BSPrim.LockAngularMotion,call,axis={1}", LocalID, axis);
  221. // "1" means free, "0" means locked
  222. OMV.Vector3 locking = LockedAxisFree;
  223. if (axis.X != 1) locking.X = 0f;
  224. if (axis.Y != 1) locking.Y = 0f;
  225. if (axis.Z != 1) locking.Z = 0f;
  226. LockedAngularAxis = locking;
  227. EnableActor(LockedAngularAxis != LockedAxisFree, LockedAxisActorName, delegate()
  228. {
  229. return new BSActorLockAxis(PhysScene, this, LockedAxisActorName);
  230. });
  231. // Update parameters so the new actor's Refresh() action is called at the right time.
  232. PhysScene.TaintedObject("BSPrim.LockAngularMotion", delegate()
  233. {
  234. UpdatePhysicalParameters();
  235. });
  236. return;
  237. }
  238. public override OMV.Vector3 Position {
  239. get {
  240. // don't do the GetObjectPosition for root elements because this function is called a zillion times.
  241. // RawPosition = ForcePosition;
  242. return RawPosition;
  243. }
  244. set {
  245. // If the position must be forced into the physics engine, use ForcePosition.
  246. // All positions are given in world positions.
  247. if (RawPosition == value)
  248. {
  249. DetailLog("{0},BSPrim.setPosition,call,positionNotChanging,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
  250. return;
  251. }
  252. RawPosition = value;
  253. PositionSanityCheck(false);
  254. PhysScene.TaintedObject("BSPrim.setPosition", delegate()
  255. {
  256. DetailLog("{0},BSPrim.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
  257. ForcePosition = RawPosition;
  258. });
  259. }
  260. }
  261. // NOTE: overloaded by BSPrimDisplaced to handle offset for center-of-gravity.
  262. public override OMV.Vector3 ForcePosition {
  263. get {
  264. RawPosition = PhysScene.PE.GetPosition(PhysBody);
  265. return RawPosition;
  266. }
  267. set {
  268. RawPosition = value;
  269. if (PhysBody.HasPhysicalBody)
  270. {
  271. PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
  272. ActivateIfPhysical(false);
  273. }
  274. }
  275. }
  276. // Check that the current position is sane and, if not, modify the position to make it so.
  277. // Check for being below terrain and being out of bounds.
  278. // Returns 'true' of the position was made sane by some action.
  279. private bool PositionSanityCheck(bool inTaintTime)
  280. {
  281. bool ret = false;
  282. // We don't care where non-physical items are placed
  283. if (!IsPhysicallyActive)
  284. return ret;
  285. if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition))
  286. {
  287. // The physical object is out of the known/simulated area.
  288. // Upper levels of code will handle the transition to other areas so, for
  289. // the time, we just ignore the position.
  290. return ret;
  291. }
  292. float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition);
  293. OMV.Vector3 upForce = OMV.Vector3.Zero;
  294. float approxSize = Math.Max(Size.X, Math.Max(Size.Y, Size.Z));
  295. if ((RawPosition.Z + approxSize / 2f) < terrainHeight)
  296. {
  297. DetailLog("{0},BSPrim.PositionAdjustUnderGround,call,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight);
  298. float targetHeight = terrainHeight + (Size.Z / 2f);
  299. // If the object is below ground it just has to be moved up because pushing will
  300. // not get it through the terrain
  301. RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, targetHeight);
  302. if (inTaintTime)
  303. {
  304. ForcePosition = RawPosition;
  305. }
  306. // If we are throwing the object around, zero its other forces
  307. ZeroMotion(inTaintTime);
  308. ret = true;
  309. }
  310. if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
  311. {
  312. float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition);
  313. // TODO: a floating motor so object will bob in the water
  314. if (Math.Abs(RawPosition.Z - waterHeight) > 0.1f)
  315. {
  316. // Upforce proportional to the distance away from the water. Correct the error in 1 sec.
  317. upForce.Z = (waterHeight - RawPosition.Z) * 1f;
  318. // Apply upforce and overcome gravity.
  319. OMV.Vector3 correctionForce = upForce - PhysScene.DefaultGravity;
  320. DetailLog("{0},BSPrim.PositionSanityCheck,applyForce,pos={1},upForce={2},correctionForce={3}", LocalID, RawPosition, upForce, correctionForce);
  321. AddForce(correctionForce, false, inTaintTime);
  322. ret = true;
  323. }
  324. }
  325. return ret;
  326. }
  327. // Occasionally things will fly off and really get lost.
  328. // Find the wanderers and bring them back.
  329. // Return 'true' if some parameter need some sanity.
  330. private bool ExtremeSanityCheck(bool inTaintTime)
  331. {
  332. bool ret = false;
  333. uint wayOutThere = Constants.RegionSize * Constants.RegionSize;
  334. // There have been instances of objects getting thrown way out of bounds and crashing
  335. // the border crossing code.
  336. if ( RawPosition.X < -Constants.RegionSize || RawPosition.X > wayOutThere
  337. || RawPosition.Y < -Constants.RegionSize || RawPosition.Y > wayOutThere
  338. || RawPosition.Z < -Constants.RegionSize || RawPosition.Z > wayOutThere)
  339. {
  340. RawPosition = new OMV.Vector3(10, 10, 50);
  341. ZeroMotion(inTaintTime);
  342. ret = true;
  343. }
  344. if (RawVelocity.LengthSquared() > BSParam.MaxLinearVelocity)
  345. {
  346. RawVelocity = Util.ClampV(RawVelocity, BSParam.MaxLinearVelocity);
  347. ret = true;
  348. }
  349. if (_rotationalVelocity.LengthSquared() > BSParam.MaxAngularVelocitySquared)
  350. {
  351. _rotationalVelocity = Util.ClampV(_rotationalVelocity, BSParam.MaxAngularVelocity);
  352. ret = true;
  353. }
  354. return ret;
  355. }
  356. // Return the effective mass of the object.
  357. // The definition of this call is to return the mass of the prim.
  358. // If the simulator cares about the mass of the linkset, it will sum it itself.
  359. public override float Mass
  360. {
  361. get { return _mass; }
  362. }
  363. // TotalMass returns the mass of the large object the prim may be in (overridden by linkset code)
  364. public virtual float TotalMass
  365. {
  366. get { return _mass; }
  367. }
  368. // used when we only want this prim's mass and not the linkset thing
  369. public override float RawMass {
  370. get { return _mass; }
  371. }
  372. // Set the physical mass to the passed mass.
  373. // Note that this does not change _mass!
  374. public override void UpdatePhysicalMassProperties(float physMass, bool inWorld)
  375. {
  376. if (PhysBody.HasPhysicalBody && PhysShape.HasPhysicalShape)
  377. {
  378. if (IsStatic)
  379. {
  380. PhysScene.PE.SetGravity(PhysBody, PhysScene.DefaultGravity);
  381. Inertia = OMV.Vector3.Zero;
  382. PhysScene.PE.SetMassProps(PhysBody, 0f, Inertia);
  383. PhysScene.PE.UpdateInertiaTensor(PhysBody);
  384. }
  385. else
  386. {
  387. if (inWorld)
  388. {
  389. // Changing interesting properties doesn't change proxy and collision cache
  390. // information. The Bullet solution is to re-add the object to the world
  391. // after parameters are changed.
  392. PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
  393. }
  394. // The computation of mass props requires gravity to be set on the object.
  395. Gravity = ComputeGravity(Buoyancy);
  396. PhysScene.PE.SetGravity(PhysBody, Gravity);
  397. OMV.Vector3 currentScale = PhysScene.PE.GetLocalScaling(PhysShape.physShapeInfo); // DEBUG DEBUG
  398. DetailLog("{0},BSPrim.UpdateMassProperties,currentScale{1},shape={2}", LocalID, currentScale, PhysShape.physShapeInfo); // DEBUG DEBUG
  399. Inertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass);
  400. PhysScene.PE.SetMassProps(PhysBody, physMass, Inertia);
  401. PhysScene.PE.UpdateInertiaTensor(PhysBody);
  402. DetailLog("{0},BSPrim.UpdateMassProperties,mass={1},localInertia={2},grav={3},inWorld={4}",
  403. LocalID, physMass, Inertia, Gravity, inWorld);
  404. if (inWorld)
  405. {
  406. AddObjectToPhysicalWorld();
  407. }
  408. }
  409. }
  410. }
  411. // Return what gravity should be set to this very moment
  412. public OMV.Vector3 ComputeGravity(float buoyancy)
  413. {
  414. OMV.Vector3 ret = PhysScene.DefaultGravity;
  415. if (!IsStatic)
  416. {
  417. ret *= (1f - buoyancy);
  418. ret *= GravModifier;
  419. }
  420. return ret;
  421. }
  422. // Is this used?
  423. public override OMV.Vector3 CenterOfMass
  424. {
  425. get { return RawPosition; }
  426. }
  427. // Is this used?
  428. public override OMV.Vector3 GeometricCenter
  429. {
  430. get { return RawPosition; }
  431. }
  432. public override OMV.Vector3 Force {
  433. get { return RawForce; }
  434. set {
  435. RawForce = value;
  436. EnableActor(RawForce != OMV.Vector3.Zero, SetForceActorName, delegate()
  437. {
  438. return new BSActorSetForce(PhysScene, this, SetForceActorName);
  439. });
  440. }
  441. }
  442. // Find and return a handle to the current vehicle actor.
  443. // Return 'null' if there is no vehicle actor.
  444. public BSDynamics GetVehicleActor()
  445. {
  446. BSDynamics ret = null;
  447. BSActor actor;
  448. if (PhysicalActors.TryGetActor(VehicleActorName, out actor))
  449. {
  450. ret = actor as BSDynamics;
  451. }
  452. return ret;
  453. }
  454. public override int VehicleType {
  455. get {
  456. int ret = (int)Vehicle.TYPE_NONE;
  457. BSDynamics vehicleActor = GetVehicleActor();
  458. if (vehicleActor != null)
  459. ret = (int)vehicleActor.Type;
  460. return ret;
  461. }
  462. set {
  463. Vehicle type = (Vehicle)value;
  464. PhysScene.TaintedObject("setVehicleType", delegate()
  465. {
  466. // Some vehicle scripts change vehicle type on the fly as an easy way to
  467. // change all the parameters. Like a plane changing to CAR when on the
  468. // ground. In this case, don't want to zero motion.
  469. // ZeroMotion(true /* inTaintTime */);
  470. BSDynamics vehicleActor = GetVehicleActor();
  471. if (vehicleActor != null)
  472. {
  473. vehicleActor.ProcessTypeChange(type);
  474. ActivateIfPhysical(false);
  475. }
  476. });
  477. }
  478. }
  479. public override void VehicleFloatParam(int param, float value)
  480. {
  481. PhysScene.TaintedObject("BSPrim.VehicleFloatParam", delegate()
  482. {
  483. BSDynamics vehicleActor = GetVehicleActor();
  484. if (vehicleActor != null)
  485. {
  486. vehicleActor.ProcessFloatVehicleParam((Vehicle)param, value);
  487. ActivateIfPhysical(false);
  488. }
  489. });
  490. }
  491. public override void VehicleVectorParam(int param, OMV.Vector3 value)
  492. {
  493. PhysScene.TaintedObject("BSPrim.VehicleVectorParam", delegate()
  494. {
  495. BSDynamics vehicleActor = GetVehicleActor();
  496. if (vehicleActor != null)
  497. {
  498. vehicleActor.ProcessVectorVehicleParam((Vehicle)param, value);
  499. ActivateIfPhysical(false);
  500. }
  501. });
  502. }
  503. public override void VehicleRotationParam(int param, OMV.Quaternion rotation)
  504. {
  505. PhysScene.TaintedObject("BSPrim.VehicleRotationParam", delegate()
  506. {
  507. BSDynamics vehicleActor = GetVehicleActor();
  508. if (vehicleActor != null)
  509. {
  510. vehicleActor.ProcessRotationVehicleParam((Vehicle)param, rotation);
  511. ActivateIfPhysical(false);
  512. }
  513. });
  514. }
  515. public override void VehicleFlags(int param, bool remove)
  516. {
  517. PhysScene.TaintedObject("BSPrim.VehicleFlags", delegate()
  518. {
  519. BSDynamics vehicleActor = GetVehicleActor();
  520. if (vehicleActor != null)
  521. {
  522. vehicleActor.ProcessVehicleFlags(param, remove);
  523. }
  524. });
  525. }
  526. // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more
  527. public override void SetVolumeDetect(int param) {
  528. bool newValue = (param != 0);
  529. if (_isVolumeDetect != newValue)
  530. {
  531. _isVolumeDetect = newValue;
  532. PhysScene.TaintedObject("BSPrim.SetVolumeDetect", delegate()
  533. {
  534. // DetailLog("{0},setVolumeDetect,taint,volDetect={1}", LocalID, _isVolumeDetect);
  535. SetObjectDynamic(true);
  536. });
  537. }
  538. return;
  539. }
  540. public override void SetMaterial(int material)
  541. {
  542. base.SetMaterial(material);
  543. PhysScene.TaintedObject("BSPrim.SetMaterial", delegate()
  544. {
  545. UpdatePhysicalParameters();
  546. });
  547. }
  548. public override float Friction
  549. {
  550. get { return base.Friction; }
  551. set
  552. {
  553. if (base.Friction != value)
  554. {
  555. base.Friction = value;
  556. PhysScene.TaintedObject("BSPrim.setFriction", delegate()
  557. {
  558. UpdatePhysicalParameters();
  559. });
  560. }
  561. }
  562. }
  563. public override float Restitution
  564. {
  565. get { return base.Restitution; }
  566. set
  567. {
  568. if (base.Restitution != value)
  569. {
  570. base.Restitution = value;
  571. PhysScene.TaintedObject("BSPrim.setRestitution", delegate()
  572. {
  573. UpdatePhysicalParameters();
  574. });
  575. }
  576. }
  577. }
  578. // The simulator/viewer keep density as 100kg/m3.
  579. // Remember to use BSParam.DensityScaleFactor to create the physical density.
  580. public override float Density
  581. {
  582. get { return base.Density; }
  583. set
  584. {
  585. if (base.Density != value)
  586. {
  587. base.Density = value;
  588. PhysScene.TaintedObject("BSPrim.setDensity", delegate()
  589. {
  590. UpdatePhysicalParameters();
  591. });
  592. }
  593. }
  594. }
  595. public override float GravModifier
  596. {
  597. get { return base.GravModifier; }
  598. set
  599. {
  600. if (base.GravModifier != value)
  601. {
  602. base.GravModifier = value;
  603. PhysScene.TaintedObject("BSPrim.setGravityModifier", delegate()
  604. {
  605. UpdatePhysicalParameters();
  606. });
  607. }
  608. }
  609. }
  610. public override OMV.Vector3 Velocity {
  611. get { return RawVelocity; }
  612. set {
  613. RawVelocity = value;
  614. PhysScene.TaintedObject("BSPrim.setVelocity", delegate()
  615. {
  616. // DetailLog("{0},BSPrim.SetVelocity,taint,vel={1}", LocalID, RawVelocity);
  617. ForceVelocity = RawVelocity;
  618. });
  619. }
  620. }
  621. public override OMV.Vector3 ForceVelocity {
  622. get { return RawVelocity; }
  623. set {
  624. PhysScene.AssertInTaintTime("BSPrim.ForceVelocity");
  625. RawVelocity = Util.ClampV(value, BSParam.MaxLinearVelocity);
  626. if (PhysBody.HasPhysicalBody)
  627. {
  628. DetailLog("{0},BSPrim.ForceVelocity,taint,vel={1}", LocalID, RawVelocity);
  629. PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity);
  630. ActivateIfPhysical(false);
  631. }
  632. }
  633. }
  634. public override OMV.Vector3 Torque {
  635. get { return RawTorque; }
  636. set {
  637. RawTorque = value;
  638. EnableActor(RawTorque != OMV.Vector3.Zero, SetTorqueActorName, delegate()
  639. {
  640. return new BSActorSetTorque(PhysScene, this, SetTorqueActorName);
  641. });
  642. DetailLog("{0},BSPrim.SetTorque,call,torque={1}", LocalID, RawTorque);
  643. }
  644. }
  645. public override OMV.Vector3 Acceleration {
  646. get { return _acceleration; }
  647. set { _acceleration = value; }
  648. }
  649. public override OMV.Quaternion Orientation {
  650. get {
  651. return RawOrientation;
  652. }
  653. set {
  654. if (RawOrientation == value)
  655. return;
  656. RawOrientation = value;
  657. PhysScene.TaintedObject("BSPrim.setOrientation", delegate()
  658. {
  659. ForceOrientation = RawOrientation;
  660. });
  661. }
  662. }
  663. // Go directly to Bullet to get/set the value.
  664. public override OMV.Quaternion ForceOrientation
  665. {
  666. get
  667. {
  668. RawOrientation = PhysScene.PE.GetOrientation(PhysBody);
  669. return RawOrientation;
  670. }
  671. set
  672. {
  673. RawOrientation = value;
  674. if (PhysBody.HasPhysicalBody)
  675. PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
  676. }
  677. }
  678. public override int PhysicsActorType {
  679. get { return _physicsActorType; }
  680. set { _physicsActorType = value; }
  681. }
  682. public override bool IsPhysical {
  683. get { return _isPhysical; }
  684. set {
  685. if (_isPhysical != value)
  686. {
  687. _isPhysical = value;
  688. PhysScene.TaintedObject("BSPrim.setIsPhysical", delegate()
  689. {
  690. DetailLog("{0},setIsPhysical,taint,isPhys={1}", LocalID, _isPhysical);
  691. SetObjectDynamic(true);
  692. // whether phys-to-static or static-to-phys, the object is not moving.
  693. ZeroMotion(true);
  694. });
  695. }
  696. }
  697. }
  698. // An object is static (does not move) if selected or not physical
  699. public override bool IsStatic
  700. {
  701. get { return _isSelected || !IsPhysical; }
  702. }
  703. // An object is solid if it's not phantom and if it's not doing VolumeDetect
  704. public override bool IsSolid
  705. {
  706. get { return !IsPhantom && !_isVolumeDetect; }
  707. }
  708. // The object is moving and is actively being dynamic in the physical world
  709. public override bool IsPhysicallyActive
  710. {
  711. get { return !_isSelected && IsPhysical; }
  712. }
  713. // Make gravity work if the object is physical and not selected
  714. // Called at taint-time!!
  715. private void SetObjectDynamic(bool forceRebuild)
  716. {
  717. // Recreate the physical object if necessary
  718. CreateGeomAndObject(forceRebuild);
  719. }
  720. // Convert the simulator's physical properties into settings on BulletSim objects.
  721. // There are four flags we're interested in:
  722. // IsStatic: Object does not move, otherwise the object has mass and moves
  723. // isSolid: other objects bounce off of this object
  724. // isVolumeDetect: other objects pass through but can generate collisions
  725. // collisionEvents: whether this object returns collision events
  726. // NOTE: overloaded by BSPrimLinkable to also update linkset physical parameters.
  727. public virtual void UpdatePhysicalParameters()
  728. {
  729. if (!PhysBody.HasPhysicalBody)
  730. {
  731. // This would only happen if updates are called for during initialization when the body is not set up yet.
  732. // DetailLog("{0},BSPrim.UpdatePhysicalParameters,taint,calledWithNoPhysBody", LocalID);
  733. return;
  734. }
  735. // Mangling all the physical properties requires the object not be in the physical world.
  736. // This is a NOOP if the object is not in the world (BulletSim and Bullet ignore objects not found).
  737. PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
  738. // Set up the object physicalness (does gravity and collisions move this object)
  739. MakeDynamic(IsStatic);
  740. // Update vehicle specific parameters (after MakeDynamic() so can change physical parameters)
  741. PhysicalActors.Refresh();
  742. // Arrange for collision events if the simulator wants them
  743. EnableCollisions(SubscribedEvents());
  744. // Make solid or not (do things bounce off or pass through this object).
  745. MakeSolid(IsSolid);
  746. AddObjectToPhysicalWorld();
  747. // Rebuild its shape
  748. PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody);
  749. DetailLog("{0},BSPrim.UpdatePhysicalParameters,taintExit,static={1},solid={2},mass={3},collide={4},cf={5:X},cType={6},body={7},shape={8}",
  750. LocalID, IsStatic, IsSolid, Mass, SubscribedEvents(),
  751. CurrentCollisionFlags, PhysBody.collisionType, PhysBody, PhysShape);
  752. }
  753. // "Making dynamic" means changing to and from static.
  754. // When static, gravity does not effect the object and it is fixed in space.
  755. // When dynamic, the object can fall and be pushed by others.
  756. // This is independent of its 'solidness' which controls what passes through
  757. // this object and what interacts with it.
  758. protected virtual void MakeDynamic(bool makeStatic)
  759. {
  760. if (makeStatic)
  761. {
  762. // Become a Bullet 'static' object type
  763. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_STATIC_OBJECT);
  764. // Stop all movement
  765. ZeroMotion(true);
  766. // Set various physical properties so other object interact properly
  767. PhysScene.PE.SetFriction(PhysBody, Friction);
  768. PhysScene.PE.SetRestitution(PhysBody, Restitution);
  769. PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
  770. // Mass is zero which disables a bunch of physics stuff in Bullet
  771. UpdatePhysicalMassProperties(0f, false);
  772. // Set collision detection parameters
  773. if (BSParam.CcdMotionThreshold > 0f)
  774. {
  775. PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
  776. PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
  777. }
  778. // The activation state is 'disabled' so Bullet will not try to act on it.
  779. // PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_SIMULATION);
  780. // Start it out sleeping and physical actions could wake it up.
  781. PhysScene.PE.ForceActivationState(PhysBody, ActivationState.ISLAND_SLEEPING);
  782. // This collides like a static object
  783. PhysBody.collisionType = CollisionType.Static;
  784. }
  785. else
  786. {
  787. // Not a Bullet static object
  788. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.CF_STATIC_OBJECT);
  789. // Set various physical properties so other object interact properly
  790. PhysScene.PE.SetFriction(PhysBody, Friction);
  791. PhysScene.PE.SetRestitution(PhysBody, Restitution);
  792. // DetailLog("{0},BSPrim.MakeDynamic,frict={1},rest={2}", LocalID, Friction, Restitution);
  793. // per http://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?t=3382
  794. // Since this can be called multiple times, only zero forces when becoming physical
  795. // PhysicsScene.PE.ClearAllForces(BSBody);
  796. // For good measure, make sure the transform is set through to the motion state
  797. ForcePosition = RawPosition;
  798. ForceVelocity = RawVelocity;
  799. ForceRotationalVelocity = _rotationalVelocity;
  800. // A dynamic object has mass
  801. UpdatePhysicalMassProperties(RawMass, false);
  802. // Set collision detection parameters
  803. if (BSParam.CcdMotionThreshold > 0f)
  804. {
  805. PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
  806. PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
  807. }
  808. // Various values for simulation limits
  809. PhysScene.PE.SetDamping(PhysBody, BSParam.LinearDamping, BSParam.AngularDamping);
  810. PhysScene.PE.SetDeactivationTime(PhysBody, BSParam.DeactivationTime);
  811. PhysScene.PE.SetSleepingThresholds(PhysBody, BSParam.LinearSleepingThreshold, BSParam.AngularSleepingThreshold);
  812. PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
  813. // This collides like an object.
  814. PhysBody.collisionType = CollisionType.Dynamic;
  815. // Force activation of the object so Bullet will act on it.
  816. // Must do the ForceActivationState2() to overcome the DISABLE_SIMULATION from static objects.
  817. PhysScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG);
  818. }
  819. }
  820. // "Making solid" means that other object will not pass through this object.
  821. // To make transparent, we create a Bullet ghost object.
  822. // Note: This expects to be called from the UpdatePhysicalParameters() routine as
  823. // the functions after this one set up the state of a possibly newly created collision body.
  824. private void MakeSolid(bool makeSolid)
  825. {
  826. CollisionObjectTypes bodyType = (CollisionObjectTypes)PhysScene.PE.GetBodyType(PhysBody);
  827. if (makeSolid)
  828. {
  829. // Verify the previous code created the correct shape for this type of thing.
  830. if ((bodyType & CollisionObjectTypes.CO_RIGID_BODY) == 0)
  831. {
  832. m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for solidity. id={1}, type={2}", LogHeader, LocalID, bodyType);
  833. }
  834. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE);
  835. }
  836. else
  837. {
  838. if ((bodyType & CollisionObjectTypes.CO_GHOST_OBJECT) == 0)
  839. {
  840. m_log.ErrorFormat("{0} MakeSolid: physical body of wrong type for non-solidness. id={1}, type={2}", LogHeader, LocalID, bodyType);
  841. }
  842. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE);
  843. // Change collision info from a static object to a ghosty collision object
  844. PhysBody.collisionType = CollisionType.VolumeDetect;
  845. }
  846. }
  847. // Turn on or off the flag controlling whether collision events are returned to the simulator.
  848. private void EnableCollisions(bool wantsCollisionEvents)
  849. {
  850. if (wantsCollisionEvents)
  851. {
  852. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
  853. }
  854. else
  855. {
  856. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
  857. }
  858. }
  859. // Add me to the physical world.
  860. // Object MUST NOT already be in the world.
  861. // This routine exists because some assorted properties get mangled by adding to the world.
  862. internal void AddObjectToPhysicalWorld()
  863. {
  864. if (PhysBody.HasPhysicalBody)
  865. {
  866. PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody);
  867. }
  868. else
  869. {
  870. m_log.ErrorFormat("{0} Attempt to add physical object without body. id={1}", LogHeader, LocalID);
  871. DetailLog("{0},BSPrim.AddObjectToPhysicalWorld,addObjectWithoutBody,cType={1}", LocalID, PhysBody.collisionType);
  872. }
  873. }
  874. // prims don't fly
  875. public override bool Flying {
  876. get { return _flying; }
  877. set {
  878. _flying = value;
  879. }
  880. }
  881. public override bool SetAlwaysRun {
  882. get { return _setAlwaysRun; }
  883. set { _setAlwaysRun = value; }
  884. }
  885. public override bool ThrottleUpdates {
  886. get { return _throttleUpdates; }
  887. set { _throttleUpdates = value; }
  888. }
  889. public bool IsPhantom {
  890. get {
  891. // SceneObjectPart removes phantom objects from the physics scene
  892. // so, although we could implement touching and such, we never
  893. // are invoked as a phantom object
  894. return false;
  895. }
  896. }
  897. public override bool FloatOnWater {
  898. set {
  899. _floatOnWater = value;
  900. PhysScene.TaintedObject("BSPrim.setFloatOnWater", delegate()
  901. {
  902. if (_floatOnWater)
  903. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
  904. else
  905. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
  906. });
  907. }
  908. }
  909. public override OMV.Vector3 RotationalVelocity {
  910. get {
  911. return _rotationalVelocity;
  912. }
  913. set {
  914. _rotationalVelocity = value;
  915. Util.ClampV(_rotationalVelocity, BSParam.MaxAngularVelocity);
  916. // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity);
  917. PhysScene.TaintedObject("BSPrim.setRotationalVelocity", delegate()
  918. {
  919. ForceRotationalVelocity = _rotationalVelocity;
  920. });
  921. }
  922. }
  923. public override OMV.Vector3 ForceRotationalVelocity {
  924. get {
  925. return _rotationalVelocity;
  926. }
  927. set {
  928. _rotationalVelocity = Util.ClampV(value, BSParam.MaxAngularVelocity);
  929. if (PhysBody.HasPhysicalBody)
  930. {
  931. DetailLog("{0},BSPrim.ForceRotationalVel,taint,rotvel={1}", LocalID, _rotationalVelocity);
  932. PhysScene.PE.SetAngularVelocity(PhysBody, _rotationalVelocity);
  933. // PhysicsScene.PE.SetInterpolationAngularVelocity(PhysBody, _rotationalVelocity);
  934. ActivateIfPhysical(false);
  935. }
  936. }
  937. }
  938. public override bool Kinematic {
  939. get { return _kinematic; }
  940. set { _kinematic = value;
  941. // m_log.DebugFormat("{0}: Kinematic={1}", LogHeader, _kinematic);
  942. }
  943. }
  944. public override float Buoyancy {
  945. get { return _buoyancy; }
  946. set {
  947. _buoyancy = value;
  948. PhysScene.TaintedObject("BSPrim.setBuoyancy", delegate()
  949. {
  950. ForceBuoyancy = _buoyancy;
  951. });
  952. }
  953. }
  954. public override float ForceBuoyancy {
  955. get { return _buoyancy; }
  956. set {
  957. _buoyancy = value;
  958. // DetailLog("{0},BSPrim.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
  959. // Force the recalculation of the various inertia,etc variables in the object
  960. UpdatePhysicalMassProperties(RawMass, true);
  961. DetailLog("{0},BSPrim.ForceBuoyancy,buoy={1},mass={2},grav={3}", LocalID, _buoyancy, RawMass, Gravity);
  962. ActivateIfPhysical(false);
  963. }
  964. }
  965. public override bool PIDActive {
  966. set {
  967. base.MoveToTargetActive = value;
  968. EnableActor(MoveToTargetActive, MoveToTargetActorName, delegate()
  969. {
  970. return new BSActorMoveToTarget(PhysScene, this, MoveToTargetActorName);
  971. });
  972. }
  973. }
  974. public override OMV.Vector3 PIDTarget
  975. {
  976. set
  977. {
  978. base.PIDTarget = value;
  979. BSActor actor;
  980. if (PhysicalActors.TryGetActor(MoveToTargetActorName, out actor))
  981. {
  982. // if the actor exists, tell it to refresh its values.
  983. actor.Refresh();
  984. }
  985. }
  986. }
  987. // Used for llSetHoverHeight and maybe vehicle height
  988. // Hover Height will override MoveTo target's Z
  989. public override bool PIDHoverActive {
  990. set {
  991. base.HoverActive = value;
  992. EnableActor(HoverActive, HoverActorName, delegate()
  993. {
  994. return new BSActorHover(PhysScene, this, HoverActorName);
  995. });
  996. }
  997. }
  998. public override void AddForce(OMV.Vector3 force, bool pushforce) {
  999. // Per documentation, max force is limited.
  1000. OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude);
  1001. // Since this force is being applied in only one step, make this a force per second.
  1002. addForce /= PhysScene.LastTimeStep;
  1003. AddForce(addForce, pushforce, false /* inTaintTime */);
  1004. }
  1005. // Applying a force just adds this to the total force on the object.
  1006. // This added force will only last the next simulation tick.
  1007. public override void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) {
  1008. // for an object, doesn't matter if force is a pushforce or not
  1009. if (IsPhysicallyActive)
  1010. {
  1011. if (force.IsFinite())
  1012. {
  1013. // DetailLog("{0},BSPrim.addForce,call,force={1}", LocalID, addForce);
  1014. OMV.Vector3 addForce = force;
  1015. PhysScene.TaintedObject(inTaintTime, "BSPrim.AddForce", delegate()
  1016. {
  1017. // Bullet adds this central force to the total force for this tick.
  1018. // Deep down in Bullet:
  1019. // linearVelocity += totalForce / mass * timeStep;
  1020. DetailLog("{0},BSPrim.addForce,taint,force={1}", LocalID, addForce);
  1021. if (PhysBody.HasPhysicalBody)
  1022. {
  1023. PhysScene.PE.ApplyCentralForce(PhysBody, addForce);
  1024. ActivateIfPhysical(false);
  1025. }
  1026. });
  1027. }
  1028. else
  1029. {
  1030. m_log.WarnFormat("{0}: AddForce: Got a NaN force applied to a prim. LocalID={1}", LogHeader, LocalID);
  1031. return;
  1032. }
  1033. }
  1034. }
  1035. public void AddForceImpulse(OMV.Vector3 impulse, bool pushforce, bool inTaintTime) {
  1036. // for an object, doesn't matter if force is a pushforce or not
  1037. if (!IsPhysicallyActive)
  1038. {
  1039. if (impulse.IsFinite())
  1040. {
  1041. OMV.Vector3 addImpulse = Util.ClampV(impulse, BSParam.MaxAddForceMagnitude);
  1042. // DetailLog("{0},BSPrim.addForceImpulse,call,impulse={1}", LocalID, impulse);
  1043. PhysScene.TaintedObject(inTaintTime, "BSPrim.AddImpulse", delegate()
  1044. {
  1045. // Bullet adds this impulse immediately to the velocity
  1046. DetailLog("{0},BSPrim.addForceImpulse,taint,impulseforce={1}", LocalID, addImpulse);
  1047. if (PhysBody.HasPhysicalBody)
  1048. {
  1049. PhysScene.PE.ApplyCentralImpulse(PhysBody, addImpulse);
  1050. ActivateIfPhysical(false);
  1051. }
  1052. });
  1053. }
  1054. else
  1055. {
  1056. m_log.WarnFormat("{0}: AddForceImpulse: Got a NaN impulse applied to a prim. LocalID={1}", LogHeader, LocalID);
  1057. return;
  1058. }
  1059. }
  1060. }
  1061. // BSPhysObject.AddAngularForce()
  1062. public override void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime)
  1063. {
  1064. if (force.IsFinite())
  1065. {
  1066. OMV.Vector3 angForce = force;
  1067. PhysScene.TaintedObject(inTaintTime, "BSPrim.AddAngularForce", delegate()
  1068. {
  1069. if (PhysBody.HasPhysicalBody)
  1070. {
  1071. DetailLog("{0},BSPrim.AddAngularForce,taint,angForce={1}", LocalID, angForce);
  1072. PhysScene.PE.ApplyTorque(PhysBody, angForce);
  1073. ActivateIfPhysical(false);
  1074. }
  1075. });
  1076. }
  1077. else
  1078. {
  1079. m_log.WarnFormat("{0}: Got a NaN force applied to a prim. LocalID={1}", LogHeader, LocalID);
  1080. return;
  1081. }
  1082. }
  1083. // A torque impulse.
  1084. // ApplyTorqueImpulse adds torque directly to the angularVelocity.
  1085. // AddAngularForce accumulates the force and applied it to the angular velocity all at once.
  1086. // Computed as: angularVelocity += impulse * inertia;
  1087. public void ApplyTorqueImpulse(OMV.Vector3 impulse, bool inTaintTime)
  1088. {
  1089. OMV.Vector3 applyImpulse = impulse;
  1090. PhysScene.TaintedObject(inTaintTime, "BSPrim.ApplyTorqueImpulse", delegate()
  1091. {
  1092. if (PhysBody.HasPhysicalBody)
  1093. {
  1094. PhysScene.PE.ApplyTorqueImpulse(PhysBody, applyImpulse);
  1095. ActivateIfPhysical(false);
  1096. }
  1097. });
  1098. }
  1099. public override void SetMomentum(OMV.Vector3 momentum) {
  1100. // DetailLog("{0},BSPrim.SetMomentum,call,mom={1}", LocalID, momentum);
  1101. }
  1102. #region Mass Calculation
  1103. private float CalculateMass()
  1104. {
  1105. float volume = _size.X * _size.Y * _size.Z; // default
  1106. float tmp;
  1107. float returnMass = 0;
  1108. float hollowAmount = (float)BaseShape.ProfileHollow * 2.0e-5f;
  1109. float hollowVolume = hollowAmount * hollowAmount;
  1110. switch (BaseShape.ProfileShape)
  1111. {
  1112. case ProfileShape.Square:
  1113. // default box
  1114. if (BaseShape.PathCurve == (byte)Extrusion.Straight)
  1115. {
  1116. if (hollowAmount > 0.0)
  1117. {
  1118. switch (BaseShape.HollowShape)
  1119. {
  1120. case HollowShape.Square:
  1121. case HollowShape.Same:
  1122. break;
  1123. case HollowShape.Circle:
  1124. hollowVolume *= 0.78539816339f;
  1125. break;
  1126. case HollowShape.Triangle:
  1127. hollowVolume *= (0.5f * .5f);
  1128. break;
  1129. default:
  1130. hollowVolume = 0;
  1131. break;
  1132. }
  1133. volume *= (1.0f - hollowVolume);
  1134. }
  1135. }
  1136. else if (BaseShape.PathCurve == (byte)Extrusion.Curve1)
  1137. {
  1138. //a tube
  1139. volume *= 0.78539816339e-2f * (float)(200 - BaseShape.PathScaleX);
  1140. tmp= 1.0f -2.0e-2f * (float)(200 - BaseShape.PathScaleY);
  1141. volume -= volume*tmp*tmp;
  1142. if (hollowAmount > 0.0)
  1143. {
  1144. hollowVolume *= hollowAmount;
  1145. switch (BaseShape.HollowShape)
  1146. {
  1147. case HollowShape.Square:
  1148. case HollowShape.Same:
  1149. break;
  1150. case HollowShape.Circle:
  1151. hollowVolume *= 0.78539816339f;;
  1152. break;
  1153. case HollowShape.Triangle:
  1154. hollowVolume *= 0.5f * 0.5f;
  1155. break;
  1156. default:
  1157. hollowVolume = 0;
  1158. break;
  1159. }
  1160. volume *= (1.0f - hollowVolume);
  1161. }
  1162. }
  1163. break;
  1164. case ProfileShape.Circle:
  1165. if (BaseShape.PathCurve == (byte)Extrusion.Straight)
  1166. {
  1167. volume *= 0.78539816339f; // elipse base
  1168. if (hollowAmount > 0.0)
  1169. {
  1170. switch (BaseShape.HollowShape)
  1171. {
  1172. case HollowShape.Same:
  1173. case HollowShape.Circle:
  1174. break;
  1175. case HollowShape.Square:
  1176. hollowVolume *= 0.5f * 2.5984480504799f;
  1177. break;
  1178. case HollowShape.Triangle:
  1179. hollowVolume *= .5f * 1.27323954473516f;
  1180. break;
  1181. default:
  1182. hollowVolume = 0;
  1183. break;
  1184. }
  1185. volume *= (1.0f - hollowVolume);
  1186. }
  1187. }
  1188. else if (BaseShape.PathCurve == (byte)Extrusion.Curve1)
  1189. {
  1190. volume *= 0.61685027506808491367715568749226e-2f * (float)(200 - BaseShape.PathScaleX);
  1191. tmp = 1.0f - .02f * (float)(200 - BaseShape.PathScaleY);
  1192. volume *= (1.0f - tmp * tmp);
  1193. if (hollowAmount > 0.0)
  1194. {
  1195. // calculate the hollow volume by it's shape compared to the prim shape
  1196. hollowVolume *= hollowAmount;
  1197. switch (BaseShape.HollowShape)
  1198. {
  1199. case HollowShape.Same:
  1200. case HollowShape.Circle:
  1201. break;
  1202. case HollowShape.Square:
  1203. hollowVolume *= 0.5f * 2.5984480504799f;
  1204. break;
  1205. case HollowShape.Triangle:
  1206. hollowVolume *= .5f * 1.27323954473516f;
  1207. break;
  1208. default:
  1209. hollowVolume = 0;
  1210. break;
  1211. }
  1212. volume *= (1.0f - hollowVolume);
  1213. }
  1214. }
  1215. break;
  1216. case ProfileShape.HalfCircle:
  1217. if (BaseShape.PathCurve == (byte)Extrusion.Curve1)
  1218. {
  1219. volume *= 0.52359877559829887307710723054658f;
  1220. }
  1221. break;
  1222. case ProfileShape.EquilateralTriangle:
  1223. if (BaseShape.PathCurve == (byte)Extrusion.Straight)
  1224. {
  1225. volume *= 0.32475953f;
  1226. if (hollowAmount > 0.0)
  1227. {
  1228. // calculate the hollow volume by it's shape compared to the prim shape
  1229. switch (BaseShape.HollowShape)
  1230. {
  1231. case HollowShape.Same:
  1232. case HollowShape.Triangle:
  1233. hollowVolume *= .25f;
  1234. break;
  1235. case HollowShape.Square:
  1236. hollowVolume *= 0.499849f * 3.07920140172638f;
  1237. break;
  1238. case HollowShape.Circle:
  1239. // Hollow shape is a perfect cyllinder in respect to the cube's scale
  1240. // Cyllinder hollow volume calculation
  1241. hollowVolume *= 0.1963495f * 3.07920140172638f;
  1242. break;
  1243. default:
  1244. hollowVolume = 0;
  1245. break;
  1246. }
  1247. volume *= (1.0f - hollowVolume);
  1248. }
  1249. }
  1250. else if (BaseShape.PathCurve == (byte)Extrusion.Curve1)
  1251. {
  1252. volume *= 0.32475953f;
  1253. volume *= 0.01f * (float)(200 - BaseShape.PathScaleX);
  1254. tmp = 1.0f - .02f * (float)(200 - BaseShape.PathScaleY);
  1255. volume *= (1.0f - tmp * tmp);
  1256. if (hollowAmount > 0.0)
  1257. {
  1258. hollowVolume *= hollowAmount;
  1259. switch (BaseShape.HollowShape)
  1260. {
  1261. case HollowShape.Same:
  1262. case HollowShape.Triangle:
  1263. hollowVolume *= .25f;
  1264. break;
  1265. case HollowShape.Square:
  1266. hollowVolume *= 0.499849f * 3.07920140172638f;
  1267. break;
  1268. case HollowShape.Circle:
  1269. hollowVolume *= 0.1963495f * 3.07920140172638f;
  1270. break;
  1271. default:
  1272. hollowVolume = 0;
  1273. break;
  1274. }
  1275. volume *= (1.0f - hollowVolume);
  1276. }
  1277. }
  1278. break;
  1279. default:
  1280. break;
  1281. }
  1282. float taperX1;
  1283. float taperY1;
  1284. float taperX;
  1285. float taperY;
  1286. float pathBegin;
  1287. float pathEnd;
  1288. float profileBegin;
  1289. float profileEnd;
  1290. if (BaseShape.PathCurve == (byte)Extrusion.Straight || BaseShape.PathCurve == (byte)Extrusion.Flexible)
  1291. {
  1292. taperX1 = BaseShape.PathScaleX * 0.01f;
  1293. if (taperX1 > 1.0f)
  1294. taperX1 = 2.0f - taperX1;
  1295. taperX = 1.0f - taperX1;
  1296. taperY1 = BaseShape.PathScaleY * 0.01f;
  1297. if (taperY1 > 1.0f)
  1298. taperY1 = 2.0f - taperY1;
  1299. taperY = 1.0f - taperY1;
  1300. }
  1301. else
  1302. {
  1303. taperX = BaseShape.PathTaperX * 0.01f;
  1304. if (taperX < 0.0f)
  1305. taperX = -taperX;
  1306. taperX1 = 1.0f - taperX;
  1307. taperY = BaseShape.PathTaperY * 0.01f;
  1308. if (taperY < 0.0f)
  1309. taperY = -taperY;
  1310. taperY1 = 1.0f - taperY;
  1311. }
  1312. volume *= (taperX1 * taperY1 + 0.5f * (taperX1 * taperY + taperX * taperY1) + 0.3333333333f * taperX * taperY);
  1313. pathBegin = (float)BaseShape.PathBegin * 2.0e-5f;
  1314. pathEnd = 1.0f - (float)BaseShape.PathEnd * 2.0e-5f;
  1315. volume *= (pathEnd - pathBegin);
  1316. // this is crude aproximation
  1317. profileBegin = (float)BaseShape.ProfileBegin * 2.0e-5f;
  1318. profileEnd = 1.0f - (float)BaseShape.ProfileEnd * 2.0e-5f;
  1319. volume *= (profileEnd - profileBegin);
  1320. returnMass = Density * BSParam.DensityScaleFactor * volume;
  1321. returnMass = Util.Clamp(returnMass, BSParam.MinimumObjectMass, BSParam.MaximumObjectMass);
  1322. // DetailLog("{0},BSPrim.CalculateMass,den={1},vol={2},mass={3}", LocalID, Density, volume, returnMass);
  1323. DetailLog("{0},BSPrim.CalculateMass,den={1},vol={2},mass={3},pathB={4},pathE={5},profB={6},profE={7},siz={8}",
  1324. LocalID, Density, volume, returnMass, pathBegin, pathEnd, profileBegin, profileEnd, _size);
  1325. return returnMass;
  1326. }// end CalculateMass
  1327. #endregion Mass Calculation
  1328. // Rebuild the geometry and object.
  1329. // This is called when the shape changes so we need to recreate the mesh/hull.
  1330. // Called at taint-time!!!
  1331. public void CreateGeomAndObject(bool forceRebuild)
  1332. {
  1333. // Create the correct physical representation for this type of object.
  1334. // Updates base.PhysBody and base.PhysShape with the new information.
  1335. // Ignore 'forceRebuild'. 'GetBodyAndShape' makes the right choices and changes of necessary.
  1336. PhysScene.Shapes.GetBodyAndShape(false /*forceRebuild */, PhysScene.World, this, delegate(BulletBody pBody, BulletShape pShape)
  1337. {
  1338. // Called if the current prim body is about to be destroyed.
  1339. // Remove all the physical dependencies on the old body.
  1340. // (Maybe someday make the changing of BSShape an event to be subscribed to by BSLinkset, ...)
  1341. // Note: this virtual function is overloaded by BSPrimLinkable to remove linkset constraints.
  1342. RemoveDependencies();
  1343. });
  1344. // Make sure the properties are set on the new object
  1345. UpdatePhysicalParameters();
  1346. return;
  1347. }
  1348. // Called at taint-time
  1349. protected virtual void RemoveDependencies()
  1350. {
  1351. PhysicalActors.RemoveDependencies();
  1352. }
  1353. // The physics engine says that properties have updated. Update same and inform
  1354. // the world that things have changed.
  1355. // NOTE: BSPrim.UpdateProperties is overloaded by BSPrimLinkable which modifies updates from root and children prims.
  1356. // NOTE: BSPrim.UpdateProperties is overloaded by BSPrimDisplaced which handles mapping physical position to simulator position.
  1357. public override void UpdateProperties(EntityProperties entprop)
  1358. {
  1359. // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator.
  1360. TriggerPreUpdatePropertyAction(ref entprop);
  1361. // DetailLog("{0},BSPrim.UpdateProperties,entry,entprop={1}", LocalID, entprop); // DEBUG DEBUG
  1362. // Assign directly to the local variables so the normal set actions do not happen
  1363. RawPosition = entprop.Position;
  1364. RawOrientation = entprop.Rotation;
  1365. // DEBUG DEBUG DEBUG -- smooth velocity changes a bit. The simulator seems to be
  1366. // very sensitive to velocity changes.
  1367. if (entprop.Velocity == OMV.Vector3.Zero || !entprop.Velocity.ApproxEquals(RawVelocity, BSParam.UpdateVelocityChangeThreshold))
  1368. RawVelocity = entprop.Velocity;
  1369. _acceleration = entprop.Acceleration;
  1370. _rotationalVelocity = entprop.RotationalVelocity;
  1371. // DetailLog("{0},BSPrim.UpdateProperties,afterAssign,entprop={1}", LocalID, entprop); // DEBUG DEBUG
  1372. // The sanity check can change the velocity and/or position.
  1373. if (PositionSanityCheck(true /* inTaintTime */ ))
  1374. {
  1375. entprop.Position = RawPosition;
  1376. entprop.Velocity = RawVelocity;
  1377. entprop.RotationalVelocity = _rotationalVelocity;
  1378. entprop.Acceleration = _acceleration;
  1379. }
  1380. OMV.Vector3 direction = OMV.Vector3.UnitX * RawOrientation; // DEBUG DEBUG DEBUG
  1381. DetailLog("{0},BSPrim.UpdateProperties,call,entProp={1},dir={2}", LocalID, entprop, direction);
  1382. // remember the current and last set values
  1383. LastEntityProperties = CurrentEntityProperties;
  1384. CurrentEntityProperties = entprop;
  1385. PhysScene.PostUpdate(this);
  1386. }
  1387. }
  1388. }