BSPrim.cs 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyrightD
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Reflection;
  29. using System.Collections.Generic;
  30. using System.Xml;
  31. using log4net;
  32. using OMV = OpenMetaverse;
  33. using OpenSim.Framework;
  34. using OpenSim.Region.Physics.Manager;
  35. using OpenSim.Region.Physics.ConvexDecompositionDotNet;
  36. namespace OpenSim.Region.Physics.BulletSPlugin
  37. {
  38. [Serializable]
  39. public class BSPrim : BSPhysObject
  40. {
  41. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  42. private static readonly string LogHeader = "[BULLETS PRIM]";
  43. // _size is what the user passed. Scale is what we pass to the physics engine with the mesh.
  44. private OMV.Vector3 _size; // the multiplier for each mesh dimension as passed by the user
  45. private bool _grabbed;
  46. private bool _isSelected;
  47. private bool _isVolumeDetect;
  48. private float _mass; // the mass of this object
  49. private OMV.Vector3 _acceleration;
  50. private int _physicsActorType;
  51. private bool _isPhysical;
  52. private bool _flying;
  53. private bool _setAlwaysRun;
  54. private bool _throttleUpdates;
  55. private bool _floatOnWater;
  56. private OMV.Vector3 _rotationalVelocity;
  57. private bool _kinematic;
  58. private float _buoyancy;
  59. private int CrossingFailures { get; set; }
  60. // Keep a handle to the vehicle actor so it is easy to set parameters on same.
  61. public const string VehicleActorName = "BasicVehicle";
  62. // Parameters for the hover actor
  63. public const string HoverActorName = "BSPrim.HoverActor";
  64. // Parameters for the axis lock actor
  65. public const String LockedAxisActorName = "BSPrim.LockedAxis";
  66. // Parameters for the move to target actor
  67. public const string MoveToTargetActorName = "BSPrim.MoveToTargetActor";
  68. // Parameters for the setForce and setTorque actors
  69. public const string SetForceActorName = "BSPrim.SetForceActor";
  70. public const string SetTorqueActorName = "BSPrim.SetTorqueActor";
  71. public BSPrim(uint localID, String primName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 size,
  72. OMV.Quaternion rotation, PrimitiveBaseShape pbs, bool pisPhysical)
  73. : base(parent_scene, localID, primName, "BSPrim")
  74. {
  75. // m_log.DebugFormat("{0}: BSPrim creation of {1}, id={2}", LogHeader, primName, localID);
  76. _physicsActorType = (int)ActorTypes.Prim;
  77. RawPosition = pos;
  78. _size = size;
  79. Scale = size; // prims are the size the user wants them to be (different for BSCharactes).
  80. RawOrientation = rotation;
  81. _buoyancy = 0f;
  82. RawVelocity = OMV.Vector3.Zero;
  83. _rotationalVelocity = OMV.Vector3.Zero;
  84. BaseShape = pbs;
  85. _isPhysical = pisPhysical;
  86. _isVolumeDetect = false;
  87. // Add a dynamic vehicle to our set of actors that can move this prim.
  88. // PhysicalActors.Add(VehicleActorName, new BSDynamics(PhysScene, this, VehicleActorName));
  89. _mass = CalculateMass();
  90. // DetailLog("{0},BSPrim.constructor,call", LocalID);
  91. // do the actual object creation at taint time
  92. PhysScene.TaintedObject("BSPrim.create", delegate()
  93. {
  94. // Make sure the object is being created with some sanity.
  95. ExtremeSanityCheck(true /* inTaintTime */);
  96. CreateGeomAndObject(true);
  97. CurrentCollisionFlags = PhysScene.PE.GetCollisionFlags(PhysBody);
  98. 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("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, "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("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, "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, "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("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("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("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("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("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("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("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("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("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("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("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("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("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("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("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("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("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("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("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, "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, "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, "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, "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. object ret = null;
  1384. switch (pFunct)
  1385. {
  1386. case BSScene.PhysFunctGetLinksetType:
  1387. {
  1388. BSPrimLinkable myHandle = this as BSPrimLinkable;
  1389. if (myHandle != null)
  1390. {
  1391. ret = (object)myHandle.LinksetType;
  1392. }
  1393. m_log.DebugFormat("{0} Extension.physGetLinksetType, type={1}", LogHeader, ret);
  1394. break;
  1395. }
  1396. case BSScene.PhysFunctSetLinksetType:
  1397. {
  1398. if (pParams.Length > 0)
  1399. {
  1400. BSLinkset.LinksetImplementation linksetType = (BSLinkset.LinksetImplementation)pParams[0];
  1401. BSPrimLinkable myHandle = this as BSPrimLinkable;
  1402. if (myHandle != null && myHandle.Linkset.IsRoot(myHandle))
  1403. {
  1404. PhysScene.TaintedObject("BSPrim.PhysFunctSetLinksetType", delegate()
  1405. {
  1406. // Cause the linkset type to change
  1407. m_log.DebugFormat("{0} Extension.physSetLinksetType, oldType={1}, newType={2}",
  1408. LogHeader, myHandle.Linkset.LinksetImpl, linksetType);
  1409. myHandle.ConvertLinkset(linksetType);
  1410. });
  1411. }
  1412. ret = (object)(int)linksetType;
  1413. }
  1414. break;
  1415. }
  1416. default:
  1417. ret = base.Extension(pFunct, pParams);
  1418. break;
  1419. }
  1420. return ret;
  1421. }
  1422. #endregion // Extension
  1423. // The physics engine says that properties have updated. Update same and inform
  1424. // the world that things have changed.
  1425. // NOTE: BSPrim.UpdateProperties is overloaded by BSPrimLinkable which modifies updates from root and children prims.
  1426. // NOTE: BSPrim.UpdateProperties is overloaded by BSPrimDisplaced which handles mapping physical position to simulator position.
  1427. public override void UpdateProperties(EntityProperties entprop)
  1428. {
  1429. // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator.
  1430. TriggerPreUpdatePropertyAction(ref entprop);
  1431. // DetailLog("{0},BSPrim.UpdateProperties,entry,entprop={1}", LocalID, entprop); // DEBUG DEBUG
  1432. // Assign directly to the local variables so the normal set actions do not happen
  1433. RawPosition = entprop.Position;
  1434. RawOrientation = entprop.Rotation;
  1435. // DEBUG DEBUG DEBUG -- smooth velocity changes a bit. The simulator seems to be
  1436. // very sensitive to velocity changes.
  1437. if (entprop.Velocity == OMV.Vector3.Zero || !entprop.Velocity.ApproxEquals(RawVelocity, BSParam.UpdateVelocityChangeThreshold))
  1438. RawVelocity = entprop.Velocity;
  1439. _acceleration = entprop.Acceleration;
  1440. _rotationalVelocity = entprop.RotationalVelocity;
  1441. // DetailLog("{0},BSPrim.UpdateProperties,afterAssign,entprop={1}", LocalID, entprop); // DEBUG DEBUG
  1442. // The sanity check can change the velocity and/or position.
  1443. if (PositionSanityCheck(true /* inTaintTime */ ))
  1444. {
  1445. entprop.Position = RawPosition;
  1446. entprop.Velocity = RawVelocity;
  1447. entprop.RotationalVelocity = _rotationalVelocity;
  1448. entprop.Acceleration = _acceleration;
  1449. }
  1450. OMV.Vector3 direction = OMV.Vector3.UnitX * RawOrientation; // DEBUG DEBUG DEBUG
  1451. DetailLog("{0},BSPrim.UpdateProperties,call,entProp={1},dir={2}", LocalID, entprop, direction);
  1452. // remember the current and last set values
  1453. LastEntityProperties = CurrentEntityProperties;
  1454. CurrentEntityProperties = entprop;
  1455. PhysScene.PostUpdate(this);
  1456. }
  1457. }
  1458. }