BSPhysObject.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  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.Collections.Generic;
  29. using System.Text;
  30. using OMV = OpenMetaverse;
  31. using OpenSim.Framework;
  32. using OpenSim.Region.PhysicsModules.SharedBase;
  33. namespace OpenSim.Region.PhysicsModule.BulletS
  34. {
  35. /*
  36. * Class to wrap all objects.
  37. * The rest of BulletSim doesn't need to keep checking for avatars or prims
  38. * unless the difference is significant.
  39. *
  40. * Variables in the physicsl objects are in three forms:
  41. * VariableName: used by the simulator and performs taint operations, etc
  42. * RawVariableName: direct reference to the BulletSim storage for the variable value
  43. * ForceVariableName: direct reference (store and fetch) to the value in the physics engine.
  44. * The last one should only be referenced in taint-time.
  45. */
  46. /*
  47. * As of 20121221, the following are the call sequences (going down) for different script physical functions:
  48. * llApplyImpulse llApplyRotImpulse llSetTorque llSetForce
  49. * SOP.ApplyImpulse SOP.ApplyAngularImpulse SOP.SetAngularImpulse SOP.SetForce
  50. * SOG.ApplyImpulse SOG.ApplyAngularImpulse SOG.SetAngularImpulse
  51. * PA.AddForce PA.AddAngularForce PA.Torque = v PA.Force = v
  52. * BS.ApplyCentralForce BS.ApplyTorque
  53. */
  54. // Flags used to denote which properties updates when making UpdateProperties calls to linksets, etc.
  55. public enum UpdatedProperties : uint
  56. {
  57. Position = 1 << 0,
  58. Orientation = 1 << 1,
  59. Velocity = 1 << 2,
  60. Acceleration = 1 << 3,
  61. RotationalVelocity = 1 << 4,
  62. EntPropUpdates = Position | Orientation | Velocity | Acceleration | RotationalVelocity,
  63. }
  64. public abstract class BSPhysObject : PhysicsActor
  65. {
  66. protected BSPhysObject()
  67. {
  68. }
  69. protected BSPhysObject(BSScene parentScene, uint localID, string name, string typeName)
  70. {
  71. IsInitialized = false;
  72. PhysScene = parentScene;
  73. LocalID = localID;
  74. PhysObjectName = name;
  75. Name = name; // PhysicsActor also has the name of the object. Someday consolidate.
  76. TypeName = typeName;
  77. // Oddity if object is destroyed and recreated very quickly it could still have the old body.
  78. if (!PhysBody.HasPhysicalBody)
  79. PhysBody = new BulletBody(localID);
  80. // Clean out anything that might be in the physical actor list.
  81. // Again, a workaround for destroying and recreating an object very quickly.
  82. PhysicalActors.Dispose();
  83. UserSetCenterOfMassDisplacement = null;
  84. PrimAssetState = PrimAssetCondition.Unknown;
  85. // Initialize variables kept in base.
  86. // Beware that these cause taints to be queued whch can cause race conditions on startup.
  87. GravModifier = 1.0f;
  88. Gravity = new OMV.Vector3(0f, 0f, BSParam.Gravity);
  89. HoverActive = false;
  90. // Default material type. Also sets Friction, Restitution and Density.
  91. SetMaterial((int)MaterialAttributes.Material.Wood);
  92. CollisionsLastTickStep = -1;
  93. SubscribedEventsMs = 0;
  94. // Crazy values that will never be true
  95. CollidingStep = BSScene.NotASimulationStep;
  96. CollidingGroundStep = BSScene.NotASimulationStep;
  97. CollisionAccumulation = BSScene.NotASimulationStep;
  98. ColliderIsMoving = false;
  99. CollisionScore = 0;
  100. // All axis free.
  101. LockedLinearAxis = LockedAxisFree;
  102. LockedAngularAxis = LockedAxisFree;
  103. }
  104. // Tell the object to clean up.
  105. public virtual void Destroy()
  106. {
  107. PhysicalActors.Enable(false);
  108. PhysScene.TaintedObject(LocalID, "BSPhysObject.Destroy", delegate()
  109. {
  110. PhysicalActors.Dispose();
  111. });
  112. }
  113. public BSScene PhysScene { get; protected set; }
  114. // public override uint LocalID { get; set; } // Use the LocalID definition in PhysicsActor
  115. public string PhysObjectName { get; protected set; }
  116. public string TypeName { get; protected set; }
  117. // Set to 'true' when the object is completely initialized.
  118. // This mostly prevents property updates and collisions until the object is completely here.
  119. public bool IsInitialized { get; protected set; }
  120. // Set to 'true' if an object (mesh/linkset/sculpty) is not completely constructed.
  121. // This test is used to prevent some updates to the object when it only partially exists.
  122. // There are several reasons and object might be incomplete:
  123. // Its underlying mesh/sculpty is an asset which must be fetched from the asset store
  124. // It is a linkset who is being added to or removed from
  125. // It is changing state (static to physical, for instance) which requires rebuilding
  126. // This is a computed value based on the underlying physical object construction
  127. abstract public bool IsIncomplete { get; }
  128. // Return the object mass without calculating it or having side effects
  129. public abstract float RawMass { get; }
  130. // Set the raw mass but also update physical mass properties (inertia, ...)
  131. // 'inWorld' true if the object has already been added to the dynamic world.
  132. public abstract void UpdatePhysicalMassProperties(float mass, bool inWorld);
  133. // The gravity being applied to the object. A function of default grav, GravityModifier and Buoyancy.
  134. public virtual OMV.Vector3 Gravity { get; set; }
  135. // The last value calculated for the prim's inertia
  136. public OMV.Vector3 Inertia { get; set; }
  137. // Reference to the physical body (btCollisionObject) of this object
  138. public BulletBody PhysBody = new BulletBody(0);
  139. // Reference to the physical shape (btCollisionShape) of this object
  140. public BSShape PhysShape = new BSShapeNull();
  141. // The physical representation of the prim might require an asset fetch.
  142. // The asset state is first 'Unknown' then 'Waiting' then either 'Failed' or 'Fetched'.
  143. public enum PrimAssetCondition
  144. {
  145. Unknown, Waiting, FailedAssetFetch, FailedMeshing, Fetched
  146. }
  147. public PrimAssetCondition PrimAssetState { get; set; }
  148. public virtual bool AssetFailed()
  149. {
  150. return ( (this.PrimAssetState == PrimAssetCondition.FailedAssetFetch)
  151. || (this.PrimAssetState == PrimAssetCondition.FailedMeshing) );
  152. }
  153. // The objects base shape information. Null if not a prim type shape.
  154. public PrimitiveBaseShape BaseShape { get; protected set; }
  155. // When the physical properties are updated, an EntityProperty holds the update values.
  156. // Keep the current and last EntityProperties to enable computation of differences
  157. // between the current update and the previous values.
  158. public EntityProperties CurrentEntityProperties { get; set; }
  159. public EntityProperties LastEntityProperties { get; set; }
  160. public virtual OMV.Vector3 Scale { get; set; }
  161. // It can be confusing for an actor to know if it should move or update an object
  162. // depeneding on the setting of 'selected', 'physical, ...
  163. // This flag is the true test -- if true, the object is being acted on in the physical world
  164. public abstract bool IsPhysicallyActive { get; }
  165. // Detailed state of the object.
  166. public abstract bool IsSolid { get; }
  167. public abstract bool IsStatic { get; }
  168. public abstract bool IsSelected { get; }
  169. public abstract bool IsVolumeDetect { get; }
  170. // Materialness
  171. public MaterialAttributes.Material Material { get; private set; }
  172. public override void SetMaterial(int material)
  173. {
  174. Material = (MaterialAttributes.Material)material;
  175. // Setting the material sets the material attributes also.
  176. // TODO: decide if this is necessary -- the simulator does this.
  177. MaterialAttributes matAttrib = BSMaterials.GetAttributes(Material, false);
  178. Friction = matAttrib.friction;
  179. Restitution = matAttrib.restitution;
  180. Density = matAttrib.density;
  181. // DetailLog("{0},{1}.SetMaterial,Mat={2},frict={3},rest={4},den={5}", LocalID, TypeName, Material, Friction, Restitution, Density);
  182. }
  183. public override float Density
  184. {
  185. get
  186. {
  187. return base.Density;
  188. }
  189. set
  190. {
  191. DetailLog("{0},BSPhysObject.Density,set,den={1}", LocalID, value);
  192. base.Density = value;
  193. }
  194. }
  195. // Stop all physical motion.
  196. public abstract void ZeroMotion(bool inTaintTime);
  197. public abstract void ZeroAngularMotion(bool inTaintTime);
  198. // Update the physical location and motion of the object. Called with data from Bullet.
  199. public abstract void UpdateProperties(EntityProperties entprop);
  200. // The position value as known by BulletSim. Does not effect the physics engine.
  201. public virtual OMV.Vector3 RawPosition { get; set; }
  202. // Set position in BulletSim and the physics engined to a value immediately. Must be called at taint time.
  203. public abstract OMV.Vector3 ForcePosition { get; set; }
  204. // The orientation value as known by BulletSim. Does not effect the physics engine.
  205. public virtual OMV.Quaternion RawOrientation { get; set; }
  206. // Set orientation in BulletSim and the physics engine to a value immediately. Must be called at taint time.
  207. public abstract OMV.Quaternion ForceOrientation { get; set; }
  208. // The velocity value as known by BulletSim. Does not effect the physics engine.
  209. public virtual OMV.Vector3 RawVelocity { get; set; }
  210. // Set velocity in BulletSim and the physics engined to a value immediately. Must be called at taint time.
  211. public abstract OMV.Vector3 ForceVelocity { get; set; }
  212. // The rotational velocity value as known by BulletSim. Does not effect the physics engine.
  213. public OMV.Vector3 RawRotationalVelocity { get; set; }
  214. // RawForce is a constant force applied to object (see Force { set; } )
  215. public OMV.Vector3 RawForce { get; set; }
  216. public OMV.Vector3 RawTorque { get; set; }
  217. public override void AddAngularForce(OMV.Vector3 force, bool pushforce)
  218. {
  219. AddAngularForce(false, force);
  220. }
  221. public abstract void AddAngularForce(bool inTaintTime, OMV.Vector3 force);
  222. public abstract void AddForce(bool inTaintTime, OMV.Vector3 force);
  223. // PhysicsActor.Velocity
  224. public override OMV.Vector3 Velocity
  225. {
  226. get { return RawVelocity; }
  227. set
  228. {
  229. // This sets the velocity now. BSCharacter will override to clear target velocity
  230. // before calling this.
  231. RawVelocity = value;
  232. PhysScene.TaintedObject(LocalID, TypeName + ".SetVelocity", delegate () {
  233. // DetailLog("{0},BSPhysObject.Velocity.set,vel={1}", LocalID, RawVelocity);
  234. ForceVelocity = RawVelocity;
  235. });
  236. }
  237. }
  238. // PhysicsActor.SetMomentum
  239. // All the physics engines use this as a way of forcing the velocity to something.
  240. // BSCharacter overrides this so it can set the target velocity to zero before calling this.
  241. public override void SetMomentum(OMV.Vector3 momentum)
  242. {
  243. this.Velocity = momentum;
  244. }
  245. public override OMV.Vector3 RotationalVelocity {
  246. get {
  247. return RawRotationalVelocity;
  248. }
  249. set {
  250. RawRotationalVelocity = value;
  251. Util.ClampV(RawRotationalVelocity, BSParam.MaxAngularVelocity);
  252. // m_log.DebugFormat("{0}: RotationalVelocity={1}", LogHeader, _rotationalVelocity);
  253. PhysScene.TaintedObject(LocalID, TypeName + ".setRotationalVelocity", delegate()
  254. {
  255. ForceRotationalVelocity = RawRotationalVelocity;
  256. });
  257. }
  258. }
  259. public OMV.Vector3 ForceRotationalVelocity {
  260. get {
  261. return RawRotationalVelocity;
  262. }
  263. set {
  264. RawRotationalVelocity = Util.ClampV(value, BSParam.MaxAngularVelocity);
  265. if (PhysBody.HasPhysicalBody)
  266. {
  267. DetailLog("{0},{1}.ForceRotationalVel,taint,rotvel={2}", LocalID, TypeName, RawRotationalVelocity);
  268. PhysScene.PE.SetAngularVelocity(PhysBody, RawRotationalVelocity);
  269. // PhysicsScene.PE.SetInterpolationAngularVelocity(PhysBody, _rotationalVelocity);
  270. ActivateIfPhysical(false);
  271. }
  272. }
  273. }
  274. public abstract float ForceBuoyancy { get; set; }
  275. public virtual bool ForceBodyShapeRebuild(bool inTaintTime) { return false; }
  276. public override bool PIDActive
  277. {
  278. get { return MoveToTargetActive; }
  279. set { MoveToTargetActive = value; }
  280. }
  281. public override OMV.Vector3 PIDTarget { set { MoveToTargetTarget = value; } }
  282. public override float PIDTau { set { MoveToTargetTau = value; } }
  283. public bool MoveToTargetActive { get; set; }
  284. public OMV.Vector3 MoveToTargetTarget { get; set; }
  285. public float MoveToTargetTau { get; set; }
  286. // Used for llSetHoverHeight and maybe vehicle height. Hover Height will override MoveTo target's Z
  287. public override bool PIDHoverActive {get {return HoverActive;} set { HoverActive = value; } }
  288. public override float PIDHoverHeight { set { HoverHeight = value; } }
  289. public override PIDHoverType PIDHoverType { set { HoverType = value; } }
  290. public override float PIDHoverTau { set { HoverTau = value; } }
  291. public bool HoverActive { get; set; }
  292. public float HoverHeight { get; set; }
  293. public PIDHoverType HoverType { get; set; }
  294. public float HoverTau { get; set; }
  295. // For RotLookAt
  296. public override OMV.Quaternion APIDTarget { set { return; } }
  297. public override bool APIDActive { set { return; } }
  298. public override float APIDStrength { set { return; } }
  299. public override float APIDDamping { set { return; } }
  300. // The current velocity forward
  301. public virtual float ForwardSpeed
  302. {
  303. get
  304. {
  305. OMV.Vector3 characterOrientedVelocity = RawVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation));
  306. return characterOrientedVelocity.X;
  307. }
  308. }
  309. // The forward speed we are trying to achieve (TargetVelocity)
  310. public virtual float TargetVelocitySpeed
  311. {
  312. get
  313. {
  314. OMV.Vector3 characterOrientedVelocity = TargetVelocity * OMV.Quaternion.Inverse(OMV.Quaternion.Normalize(RawOrientation));
  315. return characterOrientedVelocity.X;
  316. }
  317. }
  318. // The user can optionally set the center of mass. The user's setting will override any
  319. // computed center-of-mass (like in linksets).
  320. // Note this is a displacement from the root's coordinates. Zero means use the root prim as center-of-mass.
  321. public OMV.Vector3? UserSetCenterOfMassDisplacement { get; set; }
  322. public OMV.Vector3 LockedLinearAxis; // zero means locked. one means free.
  323. public OMV.Vector3 LockedAngularAxis; // zero means locked. one means free.
  324. public const float FreeAxis = 1f;
  325. public const float LockedAxis = 0f;
  326. public readonly OMV.Vector3 LockedAxisFree = new OMV.Vector3(FreeAxis, FreeAxis, FreeAxis); // All axis are free
  327. // If an axis is locked (flagged above) then the limits of that axis are specified here.
  328. // Linear axis limits are relative to the object's starting coordinates.
  329. // Angular limits are limited to -PI to +PI
  330. public OMV.Vector3 LockedLinearAxisLow;
  331. public OMV.Vector3 LockedLinearAxisHigh;
  332. public OMV.Vector3 LockedAngularAxisLow;
  333. public OMV.Vector3 LockedAngularAxisHigh;
  334. // Enable physical actions. Bullet will keep sleeping non-moving physical objects so
  335. // they need waking up when parameters are changed.
  336. // Called in taint-time!!
  337. public void ActivateIfPhysical(bool forceIt)
  338. {
  339. if (PhysBody.HasPhysicalBody)
  340. {
  341. if (IsPhysical)
  342. {
  343. // Physical objects might need activating
  344. PhysScene.PE.Activate(PhysBody, forceIt);
  345. }
  346. else
  347. {
  348. // Clear the collision cache since we've changed some properties.
  349. PhysScene.PE.ClearCollisionProxyCache(PhysScene.World, PhysBody);
  350. }
  351. }
  352. }
  353. // 'actors' act on the physical object to change or constrain its motion. These can range from
  354. // hovering to complex vehicle motion.
  355. // May be called at non-taint time as this just adds the actor to the action list and the real
  356. // work is done during the simulation step.
  357. // Note that, if the actor is already in the list and we are disabling same, the actor is just left
  358. // in the list disabled.
  359. public delegate BSActor CreateActor();
  360. public void EnableActor(bool enableActor, string actorName, CreateActor creator)
  361. {
  362. lock (PhysicalActors)
  363. {
  364. BSActor theActor;
  365. if (PhysicalActors.TryGetActor(actorName, out theActor))
  366. {
  367. // The actor already exists so just turn it on or off
  368. DetailLog("{0},BSPhysObject.EnableActor,enablingExistingActor,name={1},enable={2}", LocalID, actorName, enableActor);
  369. theActor.Enabled = enableActor;
  370. }
  371. else
  372. {
  373. // The actor does not exist. If it should, create it.
  374. if (enableActor)
  375. {
  376. DetailLog("{0},BSPhysObject.EnableActor,creatingActor,name={1}", LocalID, actorName);
  377. theActor = creator();
  378. PhysicalActors.Add(actorName, theActor);
  379. theActor.Enabled = true;
  380. }
  381. else
  382. {
  383. DetailLog("{0},BSPhysObject.EnableActor,notCreatingActorSinceNotEnabled,name={1}", LocalID, actorName);
  384. }
  385. }
  386. }
  387. }
  388. #region Collisions
  389. // Requested number of milliseconds between collision events. Zero means disabled.
  390. protected int SubscribedEventsMs { get; set; }
  391. // Given subscription, the time that a collision may be passed up
  392. protected int NextCollisionOkTime { get; set; }
  393. // The simulation step that last had a collision
  394. protected long CollidingStep { get; set; }
  395. // The simulation step that last had a collision with the ground
  396. protected long CollidingGroundStep { get; set; }
  397. // The simulation step that last collided with an object
  398. protected long CollidingObjectStep { get; set; }
  399. // The collision flags we think are set in Bullet
  400. protected CollisionFlags CurrentCollisionFlags { get; set; }
  401. // On a collision, check the collider and remember if the last collider was moving
  402. // Used to modify the standing of avatars (avatars on stationary things stand still)
  403. public bool ColliderIsMoving;
  404. // 'true' if the last collider was a volume detect object
  405. public bool ColliderIsVolumeDetect;
  406. // Used by BSCharacter to manage standing (and not slipping)
  407. public bool IsStationary;
  408. // Count of collisions for this object
  409. protected long CollisionAccumulation { get; set; }
  410. public override bool IsColliding {
  411. get { return (CollidingStep == PhysScene.SimulationStep); }
  412. set {
  413. if (value)
  414. CollidingStep = PhysScene.SimulationStep;
  415. else
  416. CollidingStep = BSScene.NotASimulationStep;
  417. }
  418. }
  419. // Complex objects (like linksets) need to know if there is a collision on any part of
  420. // their shape. 'IsColliding' has an existing definition of reporting a collision on
  421. // only this specific prim or component of linksets.
  422. // 'HasSomeCollision' is defined as reporting if there is a collision on any part of
  423. // the complex body that this prim is the root of.
  424. public virtual bool HasSomeCollision
  425. {
  426. get { return IsColliding; }
  427. set { IsColliding = value; }
  428. }
  429. public override bool CollidingGround {
  430. get { return (CollidingGroundStep == PhysScene.SimulationStep); }
  431. set
  432. {
  433. if (value)
  434. CollidingGroundStep = PhysScene.SimulationStep;
  435. else
  436. CollidingGroundStep = BSScene.NotASimulationStep;
  437. }
  438. }
  439. public override bool CollidingObj {
  440. get { return (CollidingObjectStep == PhysScene.SimulationStep); }
  441. set {
  442. if (value)
  443. CollidingObjectStep = PhysScene.SimulationStep;
  444. else
  445. CollidingObjectStep = BSScene.NotASimulationStep;
  446. }
  447. }
  448. // The collisions that have been collected for the next collision reporting (throttled by subscription)
  449. protected CollisionEventUpdate CollisionCollection = new CollisionEventUpdate();
  450. // This is the collision collection last reported to the Simulator.
  451. public CollisionEventUpdate CollisionsLastReported = new CollisionEventUpdate();
  452. // Remember the collisions recorded in the last tick for fancy collision checking
  453. // (like a BSCharacter walking up stairs).
  454. public CollisionEventUpdate CollisionsLastTick = new CollisionEventUpdate();
  455. private long CollisionsLastTickStep = -1;
  456. // The simulation step is telling this object about a collision.
  457. // I'm the 'collider', the thing I'm colliding with is the 'collidee'.
  458. // Return 'true' if a collision was processed and should be sent up.
  459. // Return 'false' if this object is not enabled/subscribed/appropriate for or has already seen this collision.
  460. // Called at taint time from within the Step() function
  461. public virtual bool Collide(BSPhysObject collidee, OMV.Vector3 contactPoint, OMV.Vector3 contactNormal, float pentrationDepth)
  462. {
  463. bool ret = false;
  464. // if 'collidee' is null, that means it is terrain
  465. uint collideeLocalID = (collidee == null) ? BSScene.TERRAIN_ID : collidee.LocalID;
  466. // All terrain goes by the TERRAIN_ID id when passed up as a collision
  467. if (collideeLocalID <= PhysScene.TerrainManager.HighestTerrainID) {
  468. collideeLocalID = BSScene.TERRAIN_ID;
  469. }
  470. // The following lines make IsColliding(), CollidingGround() and CollidingObj work
  471. CollidingStep = PhysScene.SimulationStep;
  472. if (collideeLocalID == BSScene.TERRAIN_ID)
  473. {
  474. CollidingGroundStep = PhysScene.SimulationStep;
  475. }
  476. else
  477. {
  478. CollidingObjectStep = PhysScene.SimulationStep;
  479. }
  480. CollisionAccumulation++;
  481. // For movement tests, if the collider is me, remember if we are colliding with an object that is moving.
  482. // Here the 'collider'/'collidee' thing gets messed up. In the larger context, when something is checking
  483. // if the thing it is colliding with is moving, for instance, it asks if the its collider is moving.
  484. ColliderIsMoving = collidee != null ? (collidee.RawVelocity != OMV.Vector3.Zero || collidee.RotationalVelocity != OMV.Vector3.Zero) : false;
  485. ColliderIsVolumeDetect = collidee != null ? (collidee.IsVolumeDetect) : false;
  486. // Make a collection of the collisions that happened the last simulation tick.
  487. // This is different than the collection created for sending up to the simulator as it is cleared every tick.
  488. if (CollisionsLastTickStep != PhysScene.SimulationStep)
  489. {
  490. CollisionsLastTick = new CollisionEventUpdate();
  491. CollisionsLastTickStep = PhysScene.SimulationStep;
  492. }
  493. CollisionsLastTick.AddCollider(collideeLocalID, new ContactPoint(contactPoint, contactNormal, pentrationDepth));
  494. // If someone has subscribed for collision events log the collision so it will be reported up
  495. if (SubscribedEvents()) {
  496. ContactPoint newContact = new ContactPoint(contactPoint, contactNormal, pentrationDepth);
  497. // Collision sound requires a velocity to know it should happen. This is a lot of computation for a little used feature.
  498. OMV.Vector3 relvel = OMV.Vector3.Zero;
  499. if (IsPhysical)
  500. relvel = RawVelocity;
  501. if (collidee != null && collidee.IsPhysical)
  502. relvel -= collidee.RawVelocity;
  503. newContact.RelativeSpeed = -OMV.Vector3.Dot(relvel, contactNormal);
  504. // DetailLog("{0},{1}.Collision.AddCollider,vel={2},contee.vel={3},relvel={4},relspeed={5}",
  505. // LocalID, TypeName, RawVelocity, (collidee == null ? OMV.Vector3.Zero : collidee.RawVelocity), relvel, newContact.RelativeSpeed);
  506. lock (PhysScene.CollisionLock)
  507. {
  508. CollisionCollection.AddCollider(collideeLocalID, newContact);
  509. }
  510. DetailLog("{0},{1}.Collision.AddCollider,call,with={2},point={3},normal={4},depth={5},speed={6},colliderMoving={7}",
  511. LocalID, TypeName, collideeLocalID, contactPoint, contactNormal, pentrationDepth,
  512. newContact.RelativeSpeed, ColliderIsMoving);
  513. ret = true;
  514. }
  515. return ret;
  516. }
  517. // Send the collected collisions into the simulator.
  518. // Called at taint time from within the Step() function thus no locking problems
  519. // with CollisionCollection and ObjectsWithNoMoreCollisions.
  520. // Called with BSScene.CollisionLock locked to protect the collision lists.
  521. // Return 'true' if there were some actual collisions passed up
  522. public virtual bool SendCollisions()
  523. {
  524. bool ret = true;
  525. // If no collisions this call but there were collisions last call, force the collision
  526. // event to be happen right now so quick collision_end.
  527. bool force = (CollisionCollection.Count == 0 && CollisionsLastReported.Count != 0);
  528. // throttle the collisions to the number of milliseconds specified in the subscription
  529. if (force || (PhysScene.SimulationNowTime >= NextCollisionOkTime))
  530. {
  531. NextCollisionOkTime = PhysScene.SimulationNowTime + SubscribedEventsMs;
  532. // We are called if we previously had collisions. If there are no collisions
  533. // this time, send up one last empty event so OpenSim can sense collision end.
  534. if (CollisionCollection.Count == 0)
  535. {
  536. // If I have no collisions this time, remove me from the list of objects with collisions.
  537. ret = false;
  538. }
  539. DetailLog("{0},{1}.SendCollisionUpdate,call,numCollisions={2}", LocalID, TypeName, CollisionCollection.Count);
  540. base.SendCollisionUpdate(CollisionCollection);
  541. // Remember the collisions from this tick for some collision specific processing.
  542. CollisionsLastReported = CollisionCollection;
  543. // The CollisionCollection instance is passed around in the simulator.
  544. // Make sure we don't have a handle to that one and that a new one is used for next time.
  545. // This fixes an interesting 'gotcha'. If we call CollisionCollection.Clear() here,
  546. // a race condition is created for the other users of this instance.
  547. CollisionCollection = new CollisionEventUpdate();
  548. }
  549. return ret;
  550. }
  551. // Subscribe for collision events.
  552. // Parameter is the millisecond rate the caller wishes collision events to occur.
  553. public override void SubscribeEvents(int ms) {
  554. // DetailLog("{0},{1}.SubscribeEvents,subscribing,ms={2}", LocalID, TypeName, ms);
  555. SubscribedEventsMs = ms;
  556. if (ms > 0)
  557. {
  558. // make sure first collision happens
  559. NextCollisionOkTime = Util.EnvironmentTickCountSubtract(SubscribedEventsMs);
  560. PhysScene.TaintedObject(LocalID, TypeName+".SubscribeEvents", delegate()
  561. {
  562. if (PhysBody.HasPhysicalBody)
  563. {
  564. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
  565. DetailLog("{0},{1}.SubscribeEvents,setting collision. ms={2}, collisionFlags={3:x}",
  566. LocalID, TypeName, SubscribedEventsMs, CurrentCollisionFlags);
  567. }
  568. });
  569. }
  570. else
  571. {
  572. // Subscribing for zero or less is the same as unsubscribing
  573. UnSubscribeEvents();
  574. }
  575. }
  576. public override void UnSubscribeEvents() {
  577. // DetailLog("{0},{1}.UnSubscribeEvents,unsubscribing", LocalID, TypeName);
  578. SubscribedEventsMs = 0;
  579. PhysScene.TaintedObject(LocalID, TypeName+".UnSubscribeEvents", delegate()
  580. {
  581. // Make sure there is a body there because sometimes destruction happens in an un-ideal order.
  582. if (PhysBody.HasPhysicalBody)
  583. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
  584. });
  585. }
  586. // Return 'true' if the simulator wants collision events
  587. public override bool SubscribedEvents() {
  588. return (SubscribedEventsMs > 0);
  589. }
  590. // Because 'CollisionScore' is called many times while sorting, it should not be recomputed
  591. // each time called. So this is built to be light weight for each collision and to do
  592. // all the processing when the user asks for the info.
  593. public void ComputeCollisionScore()
  594. {
  595. // Scale the collision count by the time since the last collision.
  596. // The "+1" prevents dividing by zero.
  597. long timeAgo = PhysScene.SimulationStep - CollidingStep + 1;
  598. CollisionScore = CollisionAccumulation / timeAgo;
  599. }
  600. public override float CollisionScore { get; set; }
  601. #endregion // Collisions
  602. #region Per Simulation Step actions
  603. public BSActorCollection PhysicalActors = new BSActorCollection();
  604. // When an update to the physical properties happens, this event is fired to let
  605. // different actors to modify the update before it is passed around
  606. public delegate void PreUpdatePropertyAction(ref EntityProperties entprop);
  607. public event PreUpdatePropertyAction OnPreUpdateProperty;
  608. protected void TriggerPreUpdatePropertyAction(ref EntityProperties entprop)
  609. {
  610. PreUpdatePropertyAction actions = OnPreUpdateProperty;
  611. if (actions != null)
  612. actions(ref entprop);
  613. }
  614. #endregion // Per Simulation Step actions
  615. // High performance detailed logging routine used by the physical objects.
  616. protected void DetailLog(string msg, params Object[] args)
  617. {
  618. if (PhysScene.PhysicsLogging.Enabled)
  619. PhysScene.DetailLog(msg, args);
  620. }
  621. }
  622. }