BSPrim.cs 61 KB

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