1
0

BSCharacter.cs 35 KB

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