1
0

BSPrim.cs 60 KB

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