BSPrim.cs 57 KB

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