BSCharacter.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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.Reflection;
  30. using log4net;
  31. using OMV = OpenMetaverse;
  32. using OpenSim.Framework;
  33. using OpenSim.Region.PhysicsModules.SharedBase;
  34. namespace OpenSim.Region.PhysicsModule.BulletS
  35. {
  36. public sealed class BSCharacter : BSPhysObject
  37. {
  38. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  39. private static readonly string LogHeader = "[BULLETS CHAR]";
  40. // private bool _stopped;
  41. private bool _grabbed;
  42. private bool _selected;
  43. private float _mass;
  44. private float _avatarVolume;
  45. private float _collisionScore;
  46. private OMV.Vector3 _acceleration;
  47. private int _physicsActorType;
  48. private bool _isPhysical;
  49. private bool _flying;
  50. private bool _setAlwaysRun;
  51. private bool _throttleUpdates;
  52. private bool _floatOnWater;
  53. private bool _kinematic;
  54. private float _buoyancy;
  55. private OMV.Vector3 _size;
  56. private float _footOffset;
  57. private BSActorAvatarMove m_moveActor;
  58. private const string AvatarMoveActorName = "BSCharacter.AvatarMove";
  59. private OMV.Vector3 _PIDTarget;
  60. private float _PIDTau;
  61. // public override OMV.Vector3 RawVelocity
  62. // { get { return base.RawVelocity; }
  63. // set {
  64. // if (value != base.RawVelocity)
  65. // Util.PrintCallStack();
  66. // Console.WriteLine("Set rawvel to {0}", value);
  67. // base.RawVelocity = value; }
  68. // }
  69. // Avatars are always complete (in the physics engine sense)
  70. public override bool IsIncomplete { get { return false; } }
  71. public BSCharacter(
  72. uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 vel, OMV.Vector3 size, float footOffset, bool isFlying)
  73. : base(parent_scene, localID, avName, "BSCharacter")
  74. {
  75. _physicsActorType = (int)ActorTypes.Agent;
  76. RawPosition = pos;
  77. _flying = isFlying;
  78. RawOrientation = OMV.Quaternion.Identity;
  79. RawVelocity = vel;
  80. _buoyancy = ComputeBuoyancyFromFlying(isFlying);
  81. Friction = BSParam.AvatarStandingFriction;
  82. Density = BSParam.AvatarDensity;
  83. _isPhysical = true;
  84. // Adjustments for zero X and Y made in Size()
  85. // This also computes avatar scale, volume, and mass
  86. SetAvatarSize(size, footOffset, true /* initializing */);
  87. DetailLog(
  88. "{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5},pos={6},vel={7}",
  89. LocalID, Size, Scale, Density, _avatarVolume, RawMass, pos, vel);
  90. // do actual creation in taint time
  91. PhysScene.TaintedObject(LocalID, "BSCharacter.create", delegate()
  92. {
  93. DetailLog("{0},BSCharacter.create,taint", LocalID);
  94. // New body and shape into PhysBody and PhysShape
  95. PhysScene.Shapes.GetBodyAndShape(true, PhysScene.World, this);
  96. // The avatar's movement is controlled by this motor that speeds up and slows down
  97. // the avatar seeking to reach the motor's target speed.
  98. // This motor runs as a prestep action for the avatar so it will keep the avatar
  99. // standing as well as moving. Destruction of the avatar will destroy the pre-step action.
  100. m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName);
  101. PhysicalActors.Add(AvatarMoveActorName, m_moveActor);
  102. SetPhysicalProperties();
  103. IsInitialized = true;
  104. });
  105. return;
  106. }
  107. // called when this character is being destroyed and the resources should be released
  108. public override void Destroy()
  109. {
  110. IsInitialized = false;
  111. base.Destroy();
  112. DetailLog("{0},BSCharacter.Destroy", LocalID);
  113. PhysScene.TaintedObject(LocalID, "BSCharacter.destroy", delegate()
  114. {
  115. PhysScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */);
  116. PhysBody.Clear();
  117. PhysShape.Dereference(PhysScene);
  118. PhysShape = new BSShapeNull();
  119. });
  120. }
  121. private void SetPhysicalProperties()
  122. {
  123. PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody);
  124. ForcePosition = RawPosition;
  125. // Set the velocity
  126. if (m_moveActor != null)
  127. m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false);
  128. ForceVelocity = RawVelocity;
  129. TargetVelocity = RawVelocity;
  130. // This will enable or disable the flying buoyancy of the avatar.
  131. // Needs to be reset especially when an avatar is recreated after crossing a region boundry.
  132. Flying = _flying;
  133. PhysScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution);
  134. PhysScene.PE.SetMargin(PhysShape.physShapeInfo, PhysScene.Params.collisionMargin);
  135. PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
  136. PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold);
  137. if (BSParam.CcdMotionThreshold > 0f)
  138. {
  139. PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold);
  140. PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius);
  141. }
  142. UpdatePhysicalMassProperties(RawMass, false);
  143. // Make so capsule does not fall over
  144. PhysScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero);
  145. // The avatar mover sets some parameters.
  146. PhysicalActors.Refresh();
  147. PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT);
  148. PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody);
  149. // PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG);
  150. PhysScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION);
  151. PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody);
  152. // Do this after the object has been added to the world
  153. if (BSParam.AvatarToAvatarCollisionsByDefault)
  154. PhysBody.collisionType = CollisionType.Avatar;
  155. else
  156. PhysBody.collisionType = CollisionType.PhantomToOthersAvatar;
  157. PhysBody.ApplyCollisionMask(PhysScene);
  158. }
  159. public override void RequestPhysicsterseUpdate()
  160. {
  161. base.RequestPhysicsterseUpdate();
  162. }
  163. // No one calls this method so I don't know what it could possibly mean
  164. public override bool Stopped { get { return false; } }
  165. public override OMV.Vector3 Size {
  166. get
  167. {
  168. return _size;
  169. }
  170. set {
  171. setAvatarSize(value, _footOffset);
  172. }
  173. }
  174. // OpenSim 0.9 introduces a common avatar size computation
  175. public override void setAvatarSize(OMV.Vector3 size, float feetOffset)
  176. {
  177. SetAvatarSize(size, feetOffset, false /* initializing */);
  178. }
  179. // Internal version that, if initializing, doesn't do all the updating of the physics engine
  180. public void SetAvatarSize(OMV.Vector3 size, float feetOffset, bool initializing)
  181. {
  182. OMV.Vector3 newSize = size;
  183. if (newSize.IsFinite())
  184. {
  185. // Old versions of ScenePresence passed only the height. If width and/or depth are zero,
  186. // replace with the default values.
  187. if (newSize.X == 0f) newSize.X = BSParam.AvatarCapsuleDepth;
  188. if (newSize.Y == 0f) newSize.Y = BSParam.AvatarCapsuleWidth;
  189. if (newSize.X < 0.01f) newSize.X = 0.01f;
  190. if (newSize.Y < 0.01f) newSize.Y = 0.01f;
  191. if (newSize.Z < 0.01f) newSize.Z = BSParam.AvatarCapsuleHeight;
  192. }
  193. else
  194. {
  195. newSize = new OMV.Vector3(BSParam.AvatarCapsuleDepth, BSParam.AvatarCapsuleWidth, BSParam.AvatarCapsuleHeight);
  196. }
  197. // This is how much the avatar size is changing. Positive means getting bigger.
  198. // The avatar altitude must be adjusted for this change.
  199. float heightChange = newSize.Z - Size.Z;
  200. _size = newSize;
  201. Scale = ComputeAvatarScale(Size);
  202. ComputeAvatarVolumeAndMass();
  203. DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}",
  204. LocalID, _size, Scale, Density, _avatarVolume, RawMass);
  205. PhysScene.TaintedObject(LocalID, "BSCharacter.setSize", delegate()
  206. {
  207. if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape)
  208. {
  209. PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale);
  210. UpdatePhysicalMassProperties(RawMass, true);
  211. // Adjust the avatar's position to account for the increase/decrease in size
  212. ForcePosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, RawPosition.Z + heightChange / 2f);
  213. // Make sure this change appears as a property update event
  214. PhysScene.PE.PushUpdate(PhysBody);
  215. }
  216. });
  217. }
  218. public override PrimitiveBaseShape Shape
  219. {
  220. set { BaseShape = value; }
  221. }
  222. public override bool Grabbed {
  223. set { _grabbed = value; }
  224. }
  225. public override bool Selected {
  226. set { _selected = value; }
  227. }
  228. public override bool IsSelected
  229. {
  230. get { return _selected; }
  231. }
  232. public override void CrossingFailure() { return; }
  233. public override void link(PhysicsActor obj) { return; }
  234. public override void delink() { return; }
  235. // Set motion values to zero.
  236. // Do it to the properties so the values get set in the physics engine.
  237. // Push the setting of the values to the viewer.
  238. // Called at taint time!
  239. public override void ZeroMotion(bool inTaintTime)
  240. {
  241. RawVelocity = OMV.Vector3.Zero;
  242. _acceleration = OMV.Vector3.Zero;
  243. RawRotationalVelocity = OMV.Vector3.Zero;
  244. // Zero some other properties directly into the physics engine
  245. PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
  246. {
  247. if (PhysBody.HasPhysicalBody)
  248. PhysScene.PE.ClearAllForces(PhysBody);
  249. });
  250. }
  251. public override void ZeroAngularMotion(bool inTaintTime)
  252. {
  253. RawRotationalVelocity = OMV.Vector3.Zero;
  254. PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate()
  255. {
  256. if (PhysBody.HasPhysicalBody)
  257. {
  258. PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero);
  259. PhysScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero);
  260. // The next also get rid of applied linear force but the linear velocity is untouched.
  261. PhysScene.PE.ClearForces(PhysBody);
  262. }
  263. });
  264. }
  265. public override void LockAngularMotion(byte axislocks) { return; }
  266. public override OMV.Vector3 Position {
  267. get {
  268. // Don't refetch the position because this function is called a zillion times
  269. // RawPosition = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID);
  270. return RawPosition;
  271. }
  272. set {
  273. RawPosition = value;
  274. PhysScene.TaintedObject(LocalID, "BSCharacter.setPosition", delegate()
  275. {
  276. DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
  277. PositionSanityCheck();
  278. ForcePosition = RawPosition;
  279. });
  280. }
  281. }
  282. public override OMV.Vector3 ForcePosition {
  283. get {
  284. RawPosition = PhysScene.PE.GetPosition(PhysBody);
  285. return RawPosition;
  286. }
  287. set {
  288. RawPosition = value;
  289. if (PhysBody.HasPhysicalBody)
  290. {
  291. PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
  292. }
  293. }
  294. }
  295. // Check that the current position is sane and, if not, modify the position to make it so.
  296. // Check for being below terrain or on water.
  297. // Returns 'true' of the position was made sane by some action.
  298. private bool PositionSanityCheck()
  299. {
  300. bool ret = false;
  301. // TODO: check for out of bounds
  302. if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition))
  303. {
  304. // The character is out of the known/simulated area.
  305. // Force the avatar position to be within known. ScenePresence will use the position
  306. // plus the velocity to decide if the avatar is moving out of the region.
  307. RawPosition = PhysScene.TerrainManager.ClampPositionIntoKnownTerrain(RawPosition);
  308. DetailLog("{0},BSCharacter.PositionSanityCheck,notWithinKnownTerrain,clampedPos={1}", LocalID, RawPosition);
  309. return true;
  310. }
  311. // If below the ground, move the avatar up
  312. float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition);
  313. if (Position.Z < terrainHeight)
  314. {
  315. DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight);
  316. RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters);
  317. ret = true;
  318. }
  319. if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0)
  320. {
  321. float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition);
  322. if (Position.Z < waterHeight)
  323. {
  324. RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, waterHeight);
  325. ret = true;
  326. }
  327. }
  328. return ret;
  329. }
  330. // A version of the sanity check that also makes sure a new position value is
  331. // pushed back to the physics engine. This routine would be used by anyone
  332. // who is not already pushing the value.
  333. private bool PositionSanityCheck(bool inTaintTime)
  334. {
  335. bool ret = false;
  336. if (PositionSanityCheck())
  337. {
  338. // The new position value must be pushed into the physics engine but we can't
  339. // just assign to "Position" because of potential call loops.
  340. PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.PositionSanityCheck", delegate()
  341. {
  342. DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation);
  343. ForcePosition = RawPosition;
  344. });
  345. ret = true;
  346. }
  347. return ret;
  348. }
  349. public override float Mass { get { return _mass; } }
  350. // used when we only want this prim's mass and not the linkset thing
  351. public override float RawMass {
  352. get {return _mass; }
  353. }
  354. public override void UpdatePhysicalMassProperties(float physMass, bool inWorld)
  355. {
  356. OMV.Vector3 localInertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass);
  357. PhysScene.PE.SetMassProps(PhysBody, physMass, localInertia);
  358. }
  359. public override OMV.Vector3 Force {
  360. get { return RawForce; }
  361. set {
  362. RawForce = value;
  363. // m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force);
  364. PhysScene.TaintedObject(LocalID, "BSCharacter.SetForce", delegate()
  365. {
  366. DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce);
  367. if (PhysBody.HasPhysicalBody)
  368. PhysScene.PE.SetObjectForce(PhysBody, RawForce);
  369. });
  370. }
  371. }
  372. // Avatars don't do vehicles
  373. public override int VehicleType { get { return (int)Vehicle.TYPE_NONE; } set { return; } }
  374. public override void VehicleFloatParam(int param, float value) { }
  375. public override void VehicleVectorParam(int param, OMV.Vector3 value) {}
  376. public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { }
  377. public override void VehicleFlags(int param, bool remove) { }
  378. // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more
  379. public override void SetVolumeDetect(int param) { return; }
  380. public override bool IsVolumeDetect { get { return false; } }
  381. public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } }
  382. public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } }
  383. // PhysicsActor.TargetVelocity
  384. // Sets the target in the motor. This starts the changing of the avatar's velocity.
  385. public override OMV.Vector3 TargetVelocity
  386. {
  387. get
  388. {
  389. return base.m_targetVelocity;
  390. }
  391. set
  392. {
  393. DetailLog("{0},BSCharacter.setTargetVelocity,call,vel={1}", LocalID, value);
  394. OMV.Vector3 targetVel = value;
  395. if (!_flying)
  396. {
  397. if (_setAlwaysRun)
  398. targetVel *= new OMV.Vector3(BSParam.AvatarAlwaysRunFactor, BSParam.AvatarAlwaysRunFactor, 1f);
  399. else
  400. if (BSParam.AvatarWalkVelocityFactor != 1f)
  401. targetVel *= new OMV.Vector3(BSParam.AvatarWalkVelocityFactor, BSParam.AvatarWalkVelocityFactor, 1f);
  402. }
  403. base.m_targetVelocity = targetVel;
  404. if (m_moveActor != null)
  405. m_moveActor.SetVelocityAndTarget(RawVelocity, base.m_targetVelocity, false /* inTaintTime */);
  406. }
  407. }
  408. // Directly setting velocity means this is what the user really wants now.
  409. public override OMV.Vector3 Velocity {
  410. get { return RawVelocity; }
  411. set {
  412. if (m_moveActor != null)
  413. {
  414. // m_moveActor.SetVelocityAndTarget(OMV.Vector3.Zero, OMV.Vector3.Zero, false /* inTaintTime */);
  415. m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false /* inTaintTime */);
  416. }
  417. base.Velocity = value;
  418. }
  419. }
  420. // SetMomentum just sets the velocity without a target. We need to stop the movement actor if a character.
  421. public override void SetMomentum(OMV.Vector3 momentum)
  422. {
  423. if (m_moveActor != null)
  424. {
  425. // m_moveActor.SetVelocityAndTarget(OMV.Vector3.Zero, OMV.Vector3.Zero, false /* inTaintTime */);
  426. m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false /* inTaintTime */);
  427. }
  428. base.SetMomentum(momentum);
  429. }
  430. public override OMV.Vector3 ForceVelocity {
  431. get { return RawVelocity; }
  432. set {
  433. DetailLog("{0},BSCharacter.ForceVelocity.set={1}", LocalID, value);
  434. RawVelocity = Util.ClampV(value, BSParam.MaxLinearVelocity);
  435. PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity);
  436. PhysScene.PE.Activate(PhysBody, true);
  437. }
  438. }
  439. public override OMV.Vector3 Torque {
  440. get { return RawTorque; }
  441. set { RawTorque = value;
  442. }
  443. }
  444. public override float CollisionScore {
  445. get { return _collisionScore; }
  446. set { _collisionScore = value;
  447. }
  448. }
  449. public override OMV.Vector3 Acceleration {
  450. get { return _acceleration; }
  451. set { _acceleration = value; }
  452. }
  453. public override OMV.Quaternion Orientation {
  454. get { return RawOrientation; }
  455. set {
  456. // Orientation is set zillions of times when an avatar is walking. It's like
  457. // the viewer doesn't trust us.
  458. if (RawOrientation != value)
  459. {
  460. RawOrientation = value;
  461. PhysScene.TaintedObject(LocalID, "BSCharacter.setOrientation", delegate()
  462. {
  463. // Bullet assumes we know what we are doing when forcing orientation
  464. // so it lets us go against all the rules and just compensates for them later.
  465. // This forces rotation to be only around the Z axis and doesn't change any of the other axis.
  466. // This keeps us from flipping the capsule over which the veiwer does not understand.
  467. float oRoll, oPitch, oYaw;
  468. RawOrientation.GetEulerAngles(out oRoll, out oPitch, out oYaw);
  469. OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw);
  470. // DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}",
  471. // LocalID, RawOrientation, OMV.Vector3.UnitX * RawOrientation,
  472. // trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation);
  473. ForceOrientation = trimmedOrientation;
  474. });
  475. }
  476. }
  477. }
  478. // Go directly to Bullet to get/set the value.
  479. public override OMV.Quaternion ForceOrientation
  480. {
  481. get
  482. {
  483. RawOrientation = PhysScene.PE.GetOrientation(PhysBody);
  484. return RawOrientation;
  485. }
  486. set
  487. {
  488. RawOrientation = value;
  489. if (PhysBody.HasPhysicalBody)
  490. {
  491. // RawPosition = PhysicsScene.PE.GetPosition(BSBody);
  492. PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation);
  493. }
  494. }
  495. }
  496. public override int PhysicsActorType {
  497. get { return _physicsActorType; }
  498. set { _physicsActorType = value;
  499. }
  500. }
  501. public override bool IsPhysical {
  502. get { return _isPhysical; }
  503. set { _isPhysical = value;
  504. }
  505. }
  506. public override bool IsSolid {
  507. get { return true; }
  508. }
  509. public override bool IsStatic {
  510. get { return false; }
  511. }
  512. public override bool IsPhysicallyActive {
  513. get { return true; }
  514. }
  515. public override bool Flying {
  516. get { return _flying; }
  517. set {
  518. _flying = value;
  519. // simulate flying by changing the effect of gravity
  520. Buoyancy = ComputeBuoyancyFromFlying(_flying);
  521. }
  522. }
  523. // Flying is implimented by changing the avatar's buoyancy.
  524. // Would this be done better with a vehicle type?
  525. private float ComputeBuoyancyFromFlying(bool ifFlying) {
  526. return ifFlying ? 1f : 0f;
  527. }
  528. public override bool
  529. SetAlwaysRun {
  530. get { return _setAlwaysRun; }
  531. set { _setAlwaysRun = value; }
  532. }
  533. public override bool ThrottleUpdates {
  534. get { return _throttleUpdates; }
  535. set { _throttleUpdates = value; }
  536. }
  537. public override bool FloatOnWater {
  538. set {
  539. _floatOnWater = value;
  540. PhysScene.TaintedObject(LocalID, "BSCharacter.setFloatOnWater", delegate()
  541. {
  542. if (PhysBody.HasPhysicalBody)
  543. {
  544. if (_floatOnWater)
  545. CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
  546. else
  547. CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER);
  548. }
  549. });
  550. }
  551. }
  552. public override bool Kinematic {
  553. get { return _kinematic; }
  554. set { _kinematic = value; }
  555. }
  556. // neg=fall quickly, 0=1g, 1=0g, pos=float up
  557. public override float Buoyancy {
  558. get { return _buoyancy; }
  559. set { _buoyancy = value;
  560. PhysScene.TaintedObject(LocalID, "BSCharacter.setBuoyancy", delegate()
  561. {
  562. DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
  563. ForceBuoyancy = _buoyancy;
  564. });
  565. }
  566. }
  567. public override float ForceBuoyancy {
  568. get { return _buoyancy; }
  569. set {
  570. _buoyancy = value;
  571. DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy);
  572. // Buoyancy is faked by changing the gravity applied to the object
  573. float grav = BSParam.Gravity * (1f - _buoyancy);
  574. Gravity = new OMV.Vector3(0f, 0f, grav);
  575. if (PhysBody.HasPhysicalBody)
  576. PhysScene.PE.SetGravity(PhysBody, Gravity);
  577. }
  578. }
  579. // Used for MoveTo
  580. public override OMV.Vector3 PIDTarget {
  581. set { _PIDTarget = value; }
  582. }
  583. public override bool PIDActive { get; set; }
  584. public override float PIDTau {
  585. set { _PIDTau = value; }
  586. }
  587. public override void AddForce(OMV.Vector3 force, bool pushforce)
  588. {
  589. // Since this force is being applied in only one step, make this a force per second.
  590. OMV.Vector3 addForce = force;
  591. // The interaction of this force with the simulator rate and collision occurance is tricky.
  592. // ODE multiplies the force by 100
  593. // ubODE multiplies the force by 5.3
  594. // BulletSim, after much in-world testing, thinks it gets a similar effect by multiplying mass*0.315f
  595. // This number could be a feature of friction or timing, but it seems to move avatars the same as ubODE
  596. addForce *= Mass * BSParam.AvatarAddForcePushFactor;
  597. DetailLog("{0},BSCharacter.addForce,call,force={1},addForce={2},push={3},mass={4}", LocalID, force, addForce, pushforce, Mass);
  598. AddForce(false, addForce);
  599. }
  600. public override void AddForce(bool inTaintTime, OMV.Vector3 force) {
  601. if (force.IsFinite())
  602. {
  603. OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude);
  604. // DetailLog("{0},BSCharacter.addForce,call,force={1},push={2},inTaint={3}", LocalID, addForce, pushforce, inTaintTime);
  605. PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.AddForce", delegate()
  606. {
  607. // Bullet adds this central force to the total force for this tick
  608. // DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce);
  609. if (PhysBody.HasPhysicalBody)
  610. {
  611. // Bullet adds this central force to the total force for this tick.
  612. // Deep down in Bullet:
  613. // linearVelocity += totalForce / mass * timeStep;
  614. PhysScene.PE.ApplyCentralForce(PhysBody, addForce);
  615. PhysScene.PE.Activate(PhysBody, true);
  616. }
  617. if (m_moveActor != null)
  618. {
  619. m_moveActor.SuppressStationayCheckUntilLowVelocity();
  620. }
  621. });
  622. }
  623. else
  624. {
  625. m_log.WarnFormat("{0}: Got a NaN force applied to a character. LocalID={1}", LogHeader, LocalID);
  626. return;
  627. }
  628. }
  629. public override void AddAngularForce(bool inTaintTime, OMV.Vector3 force) {
  630. }
  631. // The avatar's physical shape (whether capsule or cube) is unit sized. BulletSim sets
  632. // the scale of that unit shape to create the avatars full size.
  633. private OMV.Vector3 ComputeAvatarScale(OMV.Vector3 size)
  634. {
  635. OMV.Vector3 newScale = size;
  636. if (BSParam.AvatarUseBefore09SizeComputation)
  637. {
  638. // Bullet's capsule total height is the "passed height + radius * 2";
  639. // The base capsule is 1 unit in diameter and 2 units in height (passed radius=0.5, passed height = 1)
  640. // The number we pass in for 'scaling' is the multiplier to get that base
  641. // shape to be the size desired.
  642. // So, when creating the scale for the avatar height, we take the passed height
  643. // (size.Z) and remove the caps.
  644. // An oddity of the Bullet capsule implementation is that it presumes the Y
  645. // dimension is the radius of the capsule. Even though some of the code allows
  646. // for a asymmetrical capsule, other parts of the code presume it is cylindrical.
  647. // Scale is multiplier of radius with one of "0.5"
  648. float heightAdjust = BSParam.AvatarHeightMidFudge;
  649. if (BSParam.AvatarHeightLowFudge != 0f || BSParam.AvatarHeightHighFudge != 0f)
  650. {
  651. const float AVATAR_LOW = 1.1f;
  652. const float AVATAR_MID = 1.775f; // 1.87f
  653. const float AVATAR_HI = 2.45f;
  654. // An avatar is between 1.1 and 2.45 meters. Midpoint is 1.775m.
  655. float midHeightOffset = size.Z - AVATAR_MID;
  656. if (midHeightOffset < 0f)
  657. {
  658. // Small avatar. Add the adjustment based on the distance from midheight
  659. heightAdjust += ((-1f * midHeightOffset) / (AVATAR_MID - AVATAR_LOW)) * BSParam.AvatarHeightLowFudge;
  660. }
  661. else
  662. {
  663. // Large avatar. Add the adjustment based on the distance from midheight
  664. heightAdjust += ((midHeightOffset) / (AVATAR_HI - AVATAR_MID)) * BSParam.AvatarHeightHighFudge;
  665. }
  666. }
  667. if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule)
  668. {
  669. newScale.X = size.X / 2f;
  670. newScale.Y = size.Y / 2f;
  671. // The total scale height is the central cylindar plus the caps on the two ends.
  672. newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2) + heightAdjust) / 2f;
  673. }
  674. else
  675. {
  676. newScale.Z = size.Z + heightAdjust;
  677. }
  678. // m_log.DebugFormat("{0} ComputeAvatarScale: size={1},adj={2},scale={3}", LogHeader, size, heightAdjust, newScale);
  679. // If smaller than the endcaps, just fake like we're almost that small
  680. if (newScale.Z < 0)
  681. newScale.Z = 0.1f;
  682. DetailLog("{0},BSCharacter.ComputeAvatarScale,size={1},lowF={2},midF={3},hiF={4},adj={5},newScale={6}",
  683. LocalID, size, BSParam.AvatarHeightLowFudge, BSParam.AvatarHeightMidFudge, BSParam.AvatarHeightHighFudge, heightAdjust, newScale);
  684. }
  685. else
  686. {
  687. newScale.Z = size.Z + _footOffset;
  688. DetailLog("{0},BSCharacter.ComputeAvatarScale,using newScale={1}, footOffset={2}", LocalID, newScale, _footOffset);
  689. }
  690. return newScale;
  691. }
  692. // set _avatarVolume and _mass based on capsule size, _density and Scale
  693. private void ComputeAvatarVolumeAndMass()
  694. {
  695. if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule)
  696. {
  697. _avatarVolume = (float)(
  698. Math.PI
  699. * Size.X / 2f
  700. * Size.Y / 2f // the area of capsule cylinder
  701. * Size.Z // times height of capsule cylinder
  702. + 1.33333333f
  703. * Math.PI
  704. * Size.X / 2f
  705. * Math.Min(Size.X, Size.Y) / 2
  706. * Size.Y / 2f // plus the volume of the capsule end caps
  707. );
  708. }
  709. else
  710. {
  711. _avatarVolume = Size.X * Size.Y * Size.Z;
  712. }
  713. _mass = Density * BSParam.DensityScaleFactor * _avatarVolume;
  714. }
  715. // The physics engine says that properties have updated. Update same and inform
  716. // the world that things have changed.
  717. public override void UpdateProperties(EntityProperties entprop)
  718. {
  719. // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator.
  720. TriggerPreUpdatePropertyAction(ref entprop);
  721. RawPosition = entprop.Position;
  722. RawOrientation = entprop.Rotation;
  723. // Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar
  724. // and will send agent updates to the clients if velocity changes by more than
  725. // 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many
  726. // extra updates.
  727. //
  728. // XXX: Contrary to the above comment, setting an update threshold here above 0.4 actually introduces jitter to
  729. // avatar movement rather than removes it. The larger the threshold, the bigger the jitter.
  730. // This is most noticeable in level flight and can be seen with
  731. // the "show updates" option in a viewer. With an update threshold, the RawVelocity cycles between a lower
  732. // bound and an upper bound, where the difference between the two is enough to trigger a large delta v update
  733. // and subsequently trigger an update in ScenePresence.SendTerseUpdateToAllClients(). The cause of this cycle (feedback?)
  734. // has not yet been identified.
  735. //
  736. // If there is a threshold below 0.4 or no threshold check at all (as in ODE), then RawVelocity stays constant and extra
  737. // updates are not triggered in ScenePresence.SendTerseUpdateToAllClients().
  738. // if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f))
  739. RawVelocity = entprop.Velocity;
  740. _acceleration = entprop.Acceleration;
  741. RawRotationalVelocity = entprop.RotationalVelocity;
  742. // Do some sanity checking for the avatar. Make sure it's above ground and inbounds.
  743. if (PositionSanityCheck(true))
  744. {
  745. DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, RawPosition);
  746. entprop.Position = RawPosition;
  747. }
  748. // remember the current and last set values
  749. LastEntityProperties = CurrentEntityProperties;
  750. CurrentEntityProperties = entprop;
  751. // Tell the linkset about value changes
  752. // Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this);
  753. // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop.
  754. // PhysScene.PostUpdate(this);
  755. DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}",
  756. LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, RawRotationalVelocity);
  757. }
  758. }
  759. }