BSPrim.cs 62 KB

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