BulletXPlugin.cs 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  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 copyright
  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 OpenSim 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. */
  28. #region Copyright
  29. /*
  30. * Copyright (c) Contributors, http://www.openmetaverse.org/
  31. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  32. *
  33. * Redistribution and use in source and binary forms, with or without
  34. * modification, are permitted provided that the following conditions are met:
  35. * * Redistributions of source code must retain the above copyright
  36. * notice, this list of conditions and the following disclaimer.
  37. * * Redistributions in binary form must reproduce the above copyright
  38. * notice, this list of conditions and the following disclaimer in the
  39. * documentation and/or other materials provided with the distribution.
  40. * * Neither the name of the OpenSim Project nor the
  41. * names of its contributors may be used to endorse or promote products
  42. * derived from this software without specific prior written permission.
  43. *
  44. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  45. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  46. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  47. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  48. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  49. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  50. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  51. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  52. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  53. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  54. *
  55. */
  56. #endregion
  57. #region References
  58. using System;
  59. using System.Collections.Generic;
  60. using MonoXnaCompactMaths;
  61. using OpenSim.Framework;
  62. using OpenSim.Framework.Console;
  63. using OpenSim.Region.Physics.Manager;
  64. using XnaDevRu.BulletX;
  65. using XnaDevRu.BulletX.Dynamics;
  66. using AxiomQuaternion = Axiom.Math.Quaternion;
  67. using BoxShape=XnaDevRu.BulletX.BoxShape;
  68. #endregion
  69. namespace OpenSim.Region.Physics.BulletXPlugin
  70. {
  71. /// <summary>
  72. /// BulletXConversions are called now BulletXMaths
  73. /// This Class converts objects and types for BulletX and give some operations
  74. /// </summary>
  75. public class BulletXMaths
  76. {
  77. //Vector3
  78. public static Vector3 PhysicsVectorToXnaVector3(PhysicsVector physicsVector)
  79. {
  80. return new Vector3(physicsVector.X, physicsVector.Y, physicsVector.Z);
  81. }
  82. public static PhysicsVector XnaVector3ToPhysicsVector(Vector3 xnaVector3)
  83. {
  84. return new PhysicsVector(xnaVector3.X, xnaVector3.Y, xnaVector3.Z);
  85. }
  86. //Quaternion
  87. public static Quaternion AxiomQuaternionToXnaQuaternion(AxiomQuaternion axiomQuaternion)
  88. {
  89. return new Quaternion(axiomQuaternion.x, axiomQuaternion.y, axiomQuaternion.z, axiomQuaternion.w);
  90. }
  91. public static AxiomQuaternion XnaQuaternionToAxiomQuaternion(Quaternion xnaQuaternion)
  92. {
  93. return new AxiomQuaternion(xnaQuaternion.W, xnaQuaternion.X, xnaQuaternion.Y, xnaQuaternion.Z);
  94. }
  95. //Next methods are extracted from XnaDevRu.BulletX(See 3rd party license):
  96. //- SetRotation (class MatrixOperations)
  97. //- GetRotation (class MatrixOperations)
  98. //- GetElement (class MathHelper)
  99. //- SetElement (class MathHelper)
  100. internal static void SetRotation(ref Matrix m, Quaternion q)
  101. {
  102. float d = q.LengthSquared();
  103. float s = 2f/d;
  104. float xs = q.X*s, ys = q.Y*s, zs = q.Z*s;
  105. float wx = q.W*xs, wy = q.W*ys, wz = q.W*zs;
  106. float xx = q.X*xs, xy = q.X*ys, xz = q.X*zs;
  107. float yy = q.Y*ys, yz = q.Y*zs, zz = q.Z*zs;
  108. m = new Matrix(1 - (yy + zz), xy - wz, xz + wy, 0,
  109. xy + wz, 1 - (xx + zz), yz - wx, 0,
  110. xz - wy, yz + wx, 1 - (xx + yy), 0,
  111. m.M41, m.M42, m.M43, 1);
  112. }
  113. internal static Quaternion GetRotation(Matrix m)
  114. {
  115. Quaternion q = new Quaternion();
  116. float trace = m.M11 + m.M22 + m.M33;
  117. if (trace > 0)
  118. {
  119. float s = (float) Math.Sqrt(trace + 1);
  120. q.W = s*0.5f;
  121. s = 0.5f/s;
  122. q.X = (m.M32 - m.M23)*s;
  123. q.Y = (m.M13 - m.M31)*s;
  124. q.Z = (m.M21 - m.M12)*s;
  125. }
  126. else
  127. {
  128. int i = m.M11 < m.M22
  129. ?
  130. (m.M22 < m.M33 ? 2 : 1)
  131. :
  132. (m.M11 < m.M33 ? 2 : 0);
  133. int j = (i + 1)%3;
  134. int k = (i + 2)%3;
  135. float s = (float) Math.Sqrt(GetElement(m, i, i) - GetElement(m, j, j) - GetElement(m, k, k) + 1);
  136. SetElement(ref q, i, s*0.5f);
  137. s = 0.5f/s;
  138. q.W = (GetElement(m, k, j) - GetElement(m, j, k))*s;
  139. SetElement(ref q, j, (GetElement(m, j, i) + GetElement(m, i, j))*s);
  140. SetElement(ref q, k, (GetElement(m, k, i) + GetElement(m, i, k))*s);
  141. }
  142. return q;
  143. }
  144. internal static float SetElement(ref Quaternion q, int index, float value)
  145. {
  146. switch (index)
  147. {
  148. case 0:
  149. q.X = value;
  150. break;
  151. case 1:
  152. q.Y = value;
  153. break;
  154. case 2:
  155. q.Z = value;
  156. break;
  157. case 3:
  158. q.W = value;
  159. break;
  160. }
  161. return 0;
  162. }
  163. internal static float GetElement(Matrix mat, int row, int col)
  164. {
  165. switch (row)
  166. {
  167. case 0:
  168. switch (col)
  169. {
  170. case 0:
  171. return mat.M11;
  172. case 1:
  173. return mat.M12;
  174. case 2:
  175. return mat.M13;
  176. }
  177. break;
  178. case 1:
  179. switch (col)
  180. {
  181. case 0:
  182. return mat.M21;
  183. case 1:
  184. return mat.M22;
  185. case 2:
  186. return mat.M23;
  187. }
  188. break;
  189. case 2:
  190. switch (col)
  191. {
  192. case 0:
  193. return mat.M31;
  194. case 1:
  195. return mat.M32;
  196. case 2:
  197. return mat.M33;
  198. }
  199. break;
  200. }
  201. return 0;
  202. }
  203. }
  204. /// <summary>
  205. /// PhysicsPlugin Class for BulletX
  206. /// </summary>
  207. public class BulletXPlugin : IPhysicsPlugin
  208. {
  209. private BulletXScene _mScene;
  210. public BulletXPlugin()
  211. {
  212. }
  213. public bool Init()
  214. {
  215. return true;
  216. }
  217. public PhysicsScene GetScene()
  218. {
  219. if (_mScene == null)
  220. {
  221. _mScene = new BulletXScene();
  222. }
  223. return (_mScene);
  224. }
  225. public string GetName()
  226. {
  227. return ("modified_BulletX"); //Changed!! "BulletXEngine" To "modified_BulletX"
  228. }
  229. public void Dispose()
  230. {
  231. }
  232. }
  233. // Class to detect and debug collisions
  234. // Mainly used for debugging purposes
  235. internal class CollisionDispatcherLocal : CollisionDispatcher
  236. {
  237. private BulletXScene relatedScene;
  238. public CollisionDispatcherLocal(BulletXScene s)
  239. : base()
  240. {
  241. relatedScene = s;
  242. }
  243. public override bool NeedsCollision(CollisionObject bodyA, CollisionObject bodyB)
  244. {
  245. RigidBody rb;
  246. BulletXCharacter bxcA = null;
  247. BulletXPrim bxpA = null;
  248. Type t = bodyA.GetType();
  249. if (t == typeof (RigidBody))
  250. {
  251. rb = (RigidBody) bodyA;
  252. relatedScene._characters.TryGetValue(rb, out bxcA);
  253. relatedScene._prims.TryGetValue(rb, out bxpA);
  254. }
  255. String nameA;
  256. if (bxcA != null)
  257. nameA = bxcA._name;
  258. else if (bxpA != null)
  259. nameA = bxpA._name;
  260. else
  261. nameA = "null";
  262. BulletXCharacter bxcB = null;
  263. BulletXPrim bxpB = null;
  264. t = bodyB.GetType();
  265. if (t == typeof (RigidBody))
  266. {
  267. rb = (RigidBody) bodyB;
  268. relatedScene._characters.TryGetValue(rb, out bxcB);
  269. relatedScene._prims.TryGetValue(rb, out bxpB);
  270. }
  271. String nameB;
  272. if (bxcB != null)
  273. nameB = bxcB._name;
  274. else if (bxpB != null)
  275. nameB = bxpB._name;
  276. else
  277. nameB = "null";
  278. bool needsCollision = base.NeedsCollision(bodyA, bodyB);
  279. MainLog.Instance.Debug("BulletX", "A collision was detected between {0} and {1} --> {2}", nameA, nameB,
  280. needsCollision);
  281. return needsCollision;
  282. }
  283. }
  284. /// <summary>
  285. /// PhysicsScene Class for BulletX
  286. /// </summary>
  287. public class BulletXScene : PhysicsScene
  288. {
  289. #region BulletXScene Fields
  290. public DiscreteDynamicsWorld ddWorld;
  291. private CollisionDispatcher cDispatcher;
  292. private OverlappingPairCache opCache;
  293. private SequentialImpulseConstraintSolver sicSolver;
  294. public static Object BulletXLock = new Object();
  295. private const int minXY = 0;
  296. private const int minZ = 0;
  297. private const int maxXY = 256;
  298. private const int maxZ = 4096;
  299. private const int maxHandles = 32766; //Why? I don't know
  300. private const float gravity = 9.8f;
  301. private const float heightLevel0 = 77.0f;
  302. private const float heightLevel1 = 200.0f;
  303. private const float lowGravityFactor = 0.2f;
  304. //OpenSim calls Simulate 10 times per seconds. So FPS = "Simulate Calls" * simulationSubSteps = 100 FPS
  305. private const int simulationSubSteps = 10;
  306. //private float[] _heightmap;
  307. private BulletXPlanet _simFlatPlanet;
  308. internal Dictionary<RigidBody, BulletXCharacter> _characters = new Dictionary<RigidBody, BulletXCharacter>();
  309. internal Dictionary<RigidBody, BulletXPrim> _prims = new Dictionary<RigidBody, BulletXPrim>();
  310. public IMesher mesher;
  311. public static float Gravity
  312. {
  313. get { return gravity; }
  314. }
  315. public static float HeightLevel0
  316. {
  317. get { return heightLevel0; }
  318. }
  319. public static float HeightLevel1
  320. {
  321. get { return heightLevel1; }
  322. }
  323. public static float LowGravityFactor
  324. {
  325. get { return lowGravityFactor; }
  326. }
  327. public static int MaxXY
  328. {
  329. get { return maxXY; }
  330. }
  331. public static int MaxZ
  332. {
  333. get { return maxZ; }
  334. }
  335. private List<RigidBody> _forgottenRigidBodies = new List<RigidBody>();
  336. internal string is_ex_message = "Can't remove rigidBody!: ";
  337. #endregion
  338. public BulletXScene()
  339. {
  340. cDispatcher = new CollisionDispatcherLocal(this);
  341. Vector3 worldMinDim = new Vector3((float) minXY, (float) minXY, (float) minZ);
  342. Vector3 worldMaxDim = new Vector3((float) maxXY, (float) maxXY, (float) maxZ);
  343. opCache = new AxisSweep3(worldMinDim, worldMaxDim, maxHandles);
  344. sicSolver = new SequentialImpulseConstraintSolver();
  345. lock (BulletXLock)
  346. {
  347. ddWorld = new DiscreteDynamicsWorld(cDispatcher, opCache, sicSolver);
  348. ddWorld.Gravity = new Vector3(0, 0, -gravity);
  349. }
  350. //this._heightmap = new float[65536];
  351. }
  352. public override void Initialise(IMesher meshmerizer)
  353. {
  354. mesher = meshmerizer;
  355. }
  356. public override PhysicsActor AddAvatar(string avName, PhysicsVector position, uint localID)
  357. {
  358. PhysicsVector pos = new PhysicsVector();
  359. pos.X = position.X;
  360. pos.Y = position.Y;
  361. pos.Z = position.Z + 20;
  362. BulletXCharacter newAv = null;
  363. lock (BulletXLock)
  364. {
  365. newAv = new BulletXCharacter(avName, this, pos);
  366. _characters.Add(newAv.RigidBody, newAv);
  367. }
  368. return newAv;
  369. }
  370. public override void RemoveAvatar(PhysicsActor actor)
  371. {
  372. if (actor is BulletXCharacter)
  373. {
  374. lock (BulletXLock)
  375. {
  376. try
  377. {
  378. ddWorld.RemoveRigidBody(((BulletXCharacter) actor).RigidBody);
  379. }
  380. catch (Exception ex)
  381. {
  382. BulletXMessage(is_ex_message + ex.Message, true);
  383. ((BulletXCharacter) actor).RigidBody.ActivationState = ActivationState.DisableSimulation;
  384. AddForgottenRigidBody(((BulletXCharacter) actor).RigidBody);
  385. }
  386. _characters.Remove(((BulletXCharacter) actor).RigidBody);
  387. }
  388. GC.Collect();
  389. }
  390. }
  391. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, PhysicsVector position,
  392. PhysicsVector size, AxiomQuaternion rotation, uint localID)
  393. {
  394. return AddPrimShape(primName, pbs, position, size, rotation, false,localID);
  395. }
  396. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, PhysicsVector position,
  397. PhysicsVector size, AxiomQuaternion rotation, bool isPhysical, uint LocalID)
  398. {
  399. PhysicsActor result;
  400. switch (pbs.ProfileShape)
  401. {
  402. case ProfileShape.Square:
  403. /// support simple box & hollow box now; later, more shapes
  404. if (pbs.ProfileHollow == 0)
  405. {
  406. result = AddPrim(primName, position, size, rotation, null, null, isPhysical, LocalID);
  407. }
  408. else
  409. {
  410. IMesh mesh = mesher.CreateMesh(primName, pbs, size);
  411. result = AddPrim(primName, position, size, rotation, mesh, pbs, isPhysical, LocalID);
  412. }
  413. break;
  414. default:
  415. result = AddPrim(primName, position, size, rotation, null, null, isPhysical, LocalID);
  416. break;
  417. }
  418. return result;
  419. }
  420. public PhysicsActor AddPrim(String name, PhysicsVector position, PhysicsVector size, AxiomQuaternion rotation,
  421. IMesh mesh, PrimitiveBaseShape pbs, bool isPhysical, uint localID)
  422. {
  423. BulletXPrim newPrim = null;
  424. lock (BulletXLock)
  425. {
  426. newPrim = new BulletXPrim(name, this, position, size, rotation, mesh, pbs, isPhysical);
  427. _prims.Add(newPrim.RigidBody, newPrim);
  428. }
  429. return newPrim;
  430. }
  431. public override void RemovePrim(PhysicsActor prim)
  432. {
  433. if (prim is BulletXPrim)
  434. {
  435. lock (BulletXLock)
  436. {
  437. try
  438. {
  439. ddWorld.RemoveRigidBody(((BulletXPrim) prim).RigidBody);
  440. }
  441. catch (Exception ex)
  442. {
  443. BulletXMessage(is_ex_message + ex.Message, true);
  444. ((BulletXPrim) prim).RigidBody.ActivationState = ActivationState.DisableSimulation;
  445. AddForgottenRigidBody(((BulletXPrim) prim).RigidBody);
  446. }
  447. _prims.Remove(((BulletXPrim) prim).RigidBody);
  448. }
  449. GC.Collect();
  450. }
  451. }
  452. public override void AddPhysicsActorTaint(PhysicsActor prim)
  453. {
  454. }
  455. public override float Simulate(float timeStep)
  456. {
  457. float fps = 0;
  458. lock (BulletXLock)
  459. {
  460. //Try to remove garbage
  461. RemoveForgottenRigidBodies();
  462. //End of remove
  463. MoveAllObjects(timeStep);
  464. fps = (timeStep*simulationSubSteps);
  465. ddWorld.StepSimulation(timeStep, simulationSubSteps, timeStep);
  466. //Extra Heightmap Validation: BulletX's HeightFieldTerrain somestimes doesn't work so fine.
  467. ValidateHeightForAll();
  468. //End heightmap validation.
  469. UpdateKineticsForAll();
  470. }
  471. return fps;
  472. }
  473. private void MoveAllObjects(float timeStep)
  474. {
  475. foreach (BulletXCharacter actor in _characters.Values)
  476. {
  477. actor.Move(timeStep);
  478. }
  479. foreach (BulletXPrim prim in _prims.Values)
  480. {
  481. }
  482. }
  483. private void ValidateHeightForAll()
  484. {
  485. float _height;
  486. foreach (BulletXCharacter actor in _characters.Values)
  487. {
  488. //_height = HeightValue(actor.RigidBodyPosition);
  489. _height = _simFlatPlanet.HeightValue(actor.RigidBodyPosition);
  490. actor.ValidateHeight(_height);
  491. //if (_simFlatPlanet.heightIsNotValid(actor.RigidBodyPosition, out _height)) actor.ValidateHeight(_height);
  492. }
  493. foreach (BulletXPrim prim in _prims.Values)
  494. {
  495. //_height = HeightValue(prim.RigidBodyPosition);
  496. _height = _simFlatPlanet.HeightValue(prim.RigidBodyPosition);
  497. prim.ValidateHeight(_height);
  498. //if (_simFlatPlanet.heightIsNotValid(prim.RigidBodyPosition, out _height)) prim.ValidateHeight(_height);
  499. }
  500. //foreach (BulletXCharacter actor in _characters)
  501. //{
  502. // actor.ValidateHeight(0);
  503. //}
  504. //foreach (BulletXPrim prim in _prims)
  505. //{
  506. // prim.ValidateHeight(0);
  507. //}
  508. }
  509. private void UpdateKineticsForAll()
  510. {
  511. //UpdatePosition > UpdateKinetics.
  512. //Not only position will be updated, also velocity cause acceleration.
  513. foreach (BulletXCharacter actor in _characters.Values)
  514. {
  515. actor.UpdateKinetics();
  516. }
  517. foreach (BulletXPrim prim in _prims.Values)
  518. {
  519. prim.UpdateKinetics();
  520. }
  521. //if(this._simFlatPlanet!=null) this._simFlatPlanet.Restore();
  522. }
  523. public override void GetResults()
  524. {
  525. }
  526. public override bool IsThreaded
  527. {
  528. get { return (false); // for now we won't be multithreaded
  529. }
  530. }
  531. public override void SetTerrain(float[] heightMap)
  532. {
  533. ////As the same as ODE, heightmap (x,y) must be swapped for BulletX
  534. //for (int i = 0; i < 65536; i++)
  535. //{
  536. // // this._heightmap[i] = (double)heightMap[i];
  537. // // dbm (danx0r) -- heightmap x,y must be swapped for Ode (should fix ODE, but for now...)
  538. // int x = i & 0xff;
  539. // int y = i >> 8;
  540. // this._heightmap[i] = heightMap[x * 256 + y];
  541. //}
  542. //float[] swappedHeightMap = new float[65536];
  543. ////As the same as ODE, heightmap (x,y) must be swapped for BulletX
  544. //for (int i = 0; i < 65536; i++)
  545. //{
  546. // // this._heightmap[i] = (double)heightMap[i];
  547. // // dbm (danx0r) -- heightmap x,y must be swapped for Ode (should fix ODE, but for now...)
  548. // int x = i & 0xff;
  549. // int y = i >> 8;
  550. // swappedHeightMap[i] = heightMap[x * 256 + y];
  551. //}
  552. DeleteTerrain();
  553. //There is a BulletXLock inside the constructor of BulletXPlanet
  554. //this._simFlatPlanet = new BulletXPlanet(this, swappedHeightMap);
  555. _simFlatPlanet = new BulletXPlanet(this, heightMap);
  556. //this._heightmap = heightMap;
  557. }
  558. public override void DeleteTerrain()
  559. {
  560. if (_simFlatPlanet != null)
  561. {
  562. lock (BulletXLock)
  563. {
  564. try
  565. {
  566. ddWorld.RemoveRigidBody(_simFlatPlanet.RigidBody);
  567. }
  568. catch (Exception ex)
  569. {
  570. BulletXMessage(is_ex_message + ex.Message, true);
  571. _simFlatPlanet.RigidBody.ActivationState = ActivationState.DisableSimulation;
  572. AddForgottenRigidBody(_simFlatPlanet.RigidBody);
  573. }
  574. }
  575. _simFlatPlanet = null;
  576. GC.Collect();
  577. BulletXMessage("Terrain erased!", false);
  578. }
  579. //this._heightmap = null;
  580. }
  581. internal void AddForgottenRigidBody(RigidBody forgottenRigidBody)
  582. {
  583. _forgottenRigidBodies.Add(forgottenRigidBody);
  584. }
  585. private void RemoveForgottenRigidBodies()
  586. {
  587. RigidBody forgottenRigidBody;
  588. int nRigidBodies = _forgottenRigidBodies.Count;
  589. for (int i = nRigidBodies - 1; i >= 0; i--)
  590. {
  591. forgottenRigidBody = _forgottenRigidBodies[i];
  592. try
  593. {
  594. ddWorld.RemoveRigidBody(forgottenRigidBody);
  595. _forgottenRigidBodies.Remove(forgottenRigidBody);
  596. BulletXMessage("Forgotten Rigid Body Removed", false);
  597. }
  598. catch (Exception ex)
  599. {
  600. BulletXMessage("Can't remove forgottenRigidBody!: " + ex.Message, false);
  601. }
  602. }
  603. GC.Collect();
  604. }
  605. internal void BulletXMessage(string message, bool isWarning)
  606. {
  607. PhysicsPluginManager.PhysicsPluginMessage("[Modified BulletX]:\t" + message, isWarning);
  608. }
  609. //temp
  610. //private float HeightValue(MonoXnaCompactMaths.Vector3 position)
  611. //{
  612. // int li_x, li_y;
  613. // float height;
  614. // li_x = (int)Math.Round(position.X); if (li_x < 0) li_x = 0;
  615. // li_y = (int)Math.Round(position.Y); if (li_y < 0) li_y = 0;
  616. // height = this._heightmap[li_y * 256 + li_x];
  617. // if (height < 0) height = 0;
  618. // else if (height > maxZ) height = maxZ;
  619. // return height;
  620. //}
  621. }
  622. /// <summary>
  623. /// Generic Physics Actor for BulletX inherit from PhysicActor
  624. /// </summary>
  625. public class BulletXActor : PhysicsActor
  626. {
  627. protected bool flying = false;
  628. protected bool _physical = false;
  629. protected PhysicsVector _position;
  630. protected PhysicsVector _velocity;
  631. protected PhysicsVector _size;
  632. protected PhysicsVector _acceleration;
  633. protected AxiomQuaternion _orientation;
  634. protected PhysicsVector m_rotationalVelocity = PhysicsVector.Zero;
  635. protected RigidBody rigidBody;
  636. protected int m_PhysicsActorType;
  637. private Boolean iscolliding = false;
  638. internal string _name;
  639. public BulletXActor(String name)
  640. {
  641. _name = name;
  642. }
  643. public override PhysicsVector Position
  644. {
  645. get { return _position; }
  646. set
  647. {
  648. lock (BulletXScene.BulletXLock)
  649. {
  650. _position = value;
  651. Translate();
  652. }
  653. }
  654. }
  655. public override PhysicsVector RotationalVelocity
  656. {
  657. get { return m_rotationalVelocity; }
  658. set { m_rotationalVelocity = value; }
  659. }
  660. public override PhysicsVector Velocity
  661. {
  662. get { return _velocity; }
  663. set
  664. {
  665. lock (BulletXScene.BulletXLock)
  666. {
  667. //Static objects don' have linear velocity
  668. if (_physical)
  669. {
  670. _velocity = value;
  671. Speed();
  672. }
  673. else
  674. {
  675. _velocity = new PhysicsVector();
  676. }
  677. }
  678. }
  679. }
  680. public override PhysicsVector Size
  681. {
  682. get { return _size; }
  683. set
  684. {
  685. lock (BulletXScene.BulletXLock)
  686. {
  687. _size = value;
  688. }
  689. }
  690. }
  691. public override PhysicsVector Force
  692. {
  693. get { return PhysicsVector.Zero; }
  694. }
  695. public override PhysicsVector CenterOfMass
  696. {
  697. get { return PhysicsVector.Zero; }
  698. }
  699. public override PhysicsVector GeometricCenter
  700. {
  701. get { return PhysicsVector.Zero; }
  702. }
  703. public override PrimitiveBaseShape Shape
  704. {
  705. set { return; }
  706. }
  707. public override bool SetAlwaysRun
  708. {
  709. get { return false; }
  710. set { return; }
  711. }
  712. public override PhysicsVector Acceleration
  713. {
  714. get { return _acceleration; }
  715. }
  716. public override AxiomQuaternion Orientation
  717. {
  718. get { return _orientation; }
  719. set
  720. {
  721. lock (BulletXScene.BulletXLock)
  722. {
  723. _orientation = value;
  724. ReOrient();
  725. }
  726. }
  727. }
  728. public override float Mass
  729. {
  730. get { return ActorMass; }
  731. }
  732. public virtual float ActorMass
  733. {
  734. get { return 0; }
  735. }
  736. public override int PhysicsActorType
  737. {
  738. get { return (int) m_PhysicsActorType; }
  739. set { m_PhysicsActorType = value; }
  740. }
  741. public RigidBody RigidBody
  742. {
  743. get { return rigidBody; }
  744. }
  745. public Vector3 RigidBodyPosition
  746. {
  747. get { return rigidBody.CenterOfMassPosition; }
  748. }
  749. public override bool IsPhysical
  750. {
  751. get { return _physical; }
  752. set { _physical = value; }
  753. }
  754. public override bool Flying
  755. {
  756. get { return flying; }
  757. set { flying = value; }
  758. }
  759. public override bool ThrottleUpdates
  760. {
  761. get { return false; }
  762. set { return; }
  763. }
  764. public override bool IsColliding
  765. {
  766. get { return iscolliding; }
  767. set { iscolliding = value; }
  768. }
  769. public override bool CollidingGround
  770. {
  771. get { return false; }
  772. set { return; }
  773. }
  774. public override bool CollidingObj
  775. {
  776. get { return false; }
  777. set { return; }
  778. }
  779. public virtual void SetAcceleration(PhysicsVector accel)
  780. {
  781. lock (BulletXScene.BulletXLock)
  782. {
  783. _acceleration = accel;
  784. }
  785. }
  786. public override bool Kinematic
  787. {
  788. get { return false; }
  789. set { }
  790. }
  791. public override void AddForce(PhysicsVector force)
  792. {
  793. }
  794. public override void SetMomentum(PhysicsVector momentum)
  795. {
  796. }
  797. internal virtual void ValidateHeight(float heighmapPositionValue)
  798. {
  799. }
  800. internal virtual void UpdateKinetics()
  801. {
  802. }
  803. #region Methods for updating values of RigidBody
  804. protected internal void Translate()
  805. {
  806. Translate(_position);
  807. }
  808. protected internal void Translate(PhysicsVector _newPos)
  809. {
  810. Vector3 _translation;
  811. _translation = BulletXMaths.PhysicsVectorToXnaVector3(_newPos) - rigidBody.CenterOfMassPosition;
  812. rigidBody.Translate(_translation);
  813. }
  814. protected internal void Speed()
  815. {
  816. Speed(_velocity);
  817. }
  818. protected internal void Speed(PhysicsVector _newSpeed)
  819. {
  820. Vector3 _speed;
  821. _speed = BulletXMaths.PhysicsVectorToXnaVector3(_newSpeed);
  822. rigidBody.LinearVelocity = _speed;
  823. }
  824. protected internal void ReOrient()
  825. {
  826. ReOrient(_orientation);
  827. }
  828. protected internal void ReOrient(AxiomQuaternion _newOrient)
  829. {
  830. Quaternion _newOrientation;
  831. _newOrientation = BulletXMaths.AxiomQuaternionToXnaQuaternion(_newOrient);
  832. Matrix _comTransform = rigidBody.CenterOfMassTransform;
  833. BulletXMaths.SetRotation(ref _comTransform, _newOrientation);
  834. rigidBody.CenterOfMassTransform = _comTransform;
  835. }
  836. protected internal void ReSize()
  837. {
  838. ReSize(_size);
  839. }
  840. protected internal virtual void ReSize(PhysicsVector _newSize)
  841. {
  842. }
  843. public virtual void ScheduleTerseUpdate()
  844. {
  845. base.RequestPhysicsterseUpdate();
  846. }
  847. #endregion
  848. }
  849. /// <summary>
  850. /// PhysicsActor Character Class for BulletX
  851. /// </summary>
  852. public class BulletXCharacter : BulletXActor
  853. {
  854. public BulletXCharacter(BulletXScene parent_scene, PhysicsVector pos)
  855. : this("", parent_scene, pos)
  856. {
  857. }
  858. public BulletXCharacter(String avName, BulletXScene parent_scene, PhysicsVector pos)
  859. : this(avName, parent_scene, pos, new PhysicsVector(), new PhysicsVector(), new PhysicsVector(),
  860. AxiomQuaternion.Identity)
  861. {
  862. }
  863. public BulletXCharacter(String avName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector velocity,
  864. PhysicsVector size, PhysicsVector acceleration, AxiomQuaternion orientation)
  865. : base(avName)
  866. {
  867. //This fields will be removed. They're temporal
  868. float _sizeX = 0.5f;
  869. float _sizeY = 0.5f;
  870. float _sizeZ = 1.6f;
  871. //.
  872. _position = pos;
  873. _velocity = velocity;
  874. _size = size;
  875. //---
  876. _size.X = _sizeX;
  877. _size.Y = _sizeY;
  878. _size.Z = _sizeZ;
  879. //.
  880. _acceleration = acceleration;
  881. _orientation = orientation;
  882. _physical = true;
  883. float _mass = 50.0f; //This depends of avatar's dimensions
  884. //For RigidBody Constructor. The next values might change
  885. float _linearDamping = 0.0f;
  886. float _angularDamping = 0.0f;
  887. float _friction = 0.5f;
  888. float _restitution = 0.0f;
  889. Matrix _startTransform = Matrix.Identity;
  890. Matrix _centerOfMassOffset = Matrix.Identity;
  891. lock (BulletXScene.BulletXLock)
  892. {
  893. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(pos);
  894. //CollisionShape _collisionShape = new BoxShape(new MonoXnaCompactMaths.Vector3(1.0f, 1.0f, 1.60f));
  895. //For now, like ODE, collisionShape = sphere of radious = 1.0
  896. CollisionShape _collisionShape = new SphereShape(1.0f);
  897. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  898. Vector3 _localInertia = new Vector3();
  899. _collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0
  900. rigidBody =
  901. new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping,
  902. _friction, _restitution);
  903. //rigidBody.ActivationState = ActivationState.DisableDeactivation;
  904. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  905. Vector3 _vDebugTranslation;
  906. _vDebugTranslation = _startTransform.Translation - rigidBody.CenterOfMassPosition;
  907. rigidBody.Translate(_vDebugTranslation);
  908. parent_scene.ddWorld.AddRigidBody(rigidBody);
  909. }
  910. }
  911. public override int PhysicsActorType
  912. {
  913. get { return (int) ActorTypes.Agent; }
  914. set { return; }
  915. }
  916. public override PhysicsVector Position
  917. {
  918. get { return base.Position; }
  919. set { base.Position = value; }
  920. }
  921. public override PhysicsVector Velocity
  922. {
  923. get { return base.Velocity; }
  924. set { base.Velocity = value; }
  925. }
  926. public override PhysicsVector Size
  927. {
  928. get { return base.Size; }
  929. set { base.Size = value; }
  930. }
  931. public override PhysicsVector Acceleration
  932. {
  933. get { return base.Acceleration; }
  934. }
  935. public override AxiomQuaternion Orientation
  936. {
  937. get { return base.Orientation; }
  938. set { base.Orientation = value; }
  939. }
  940. public override bool Flying
  941. {
  942. get { return base.Flying; }
  943. set { base.Flying = value; }
  944. }
  945. public override bool IsColliding
  946. {
  947. get { return base.IsColliding; }
  948. set { base.IsColliding = value; }
  949. }
  950. public override bool Kinematic
  951. {
  952. get { return base.Kinematic; }
  953. set { base.Kinematic = value; }
  954. }
  955. public override void SetAcceleration(PhysicsVector accel)
  956. {
  957. base.SetAcceleration(accel);
  958. }
  959. public override void AddForce(PhysicsVector force)
  960. {
  961. base.AddForce(force);
  962. }
  963. public override void SetMomentum(PhysicsVector momentum)
  964. {
  965. base.SetMomentum(momentum);
  966. }
  967. internal void Move(float timeStep)
  968. {
  969. Vector3 vec = new Vector3();
  970. //At this point it's supossed that:
  971. //_velocity == rigidBody.LinearVelocity
  972. vec.X = _velocity.X;
  973. vec.Y = _velocity.Y;
  974. vec.Z = _velocity.Z;
  975. if ((vec.X != 0.0f) || (vec.Y != 0.0f) || (vec.Z != 0.0f)) rigidBody.Activate();
  976. if (flying)
  977. {
  978. //Antigravity with movement
  979. if (_position.Z <= BulletXScene.HeightLevel0)
  980. {
  981. vec.Z += BulletXScene.Gravity*timeStep;
  982. }
  983. //Lowgravity with movement
  984. else if ((_position.Z > BulletXScene.HeightLevel0)
  985. && (_position.Z <= BulletXScene.HeightLevel1))
  986. {
  987. vec.Z += BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  988. }
  989. //Lowgravity with...
  990. else if (_position.Z > BulletXScene.HeightLevel1)
  991. {
  992. if (vec.Z > 0) //no movement
  993. vec.Z = BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  994. else
  995. vec.Z += BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  996. }
  997. }
  998. rigidBody.LinearVelocity = vec;
  999. }
  1000. //This validation is very basic
  1001. internal override void ValidateHeight(float heighmapPositionValue)
  1002. {
  1003. if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue + _size.Z/2.0f)
  1004. {
  1005. Matrix m = rigidBody.WorldTransform;
  1006. Vector3 v3 = m.Translation;
  1007. v3.Z = heighmapPositionValue + _size.Z/2.0f;
  1008. m.Translation = v3;
  1009. rigidBody.WorldTransform = m;
  1010. //When an Avie touch the ground it's vertical velocity it's reduced to ZERO
  1011. Speed(new PhysicsVector(rigidBody.LinearVelocity.X, rigidBody.LinearVelocity.Y, 0.0f));
  1012. }
  1013. }
  1014. internal override void UpdateKinetics()
  1015. {
  1016. _position = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition);
  1017. _velocity = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.LinearVelocity);
  1018. //Orientation it seems that it will be the default.
  1019. ReOrient();
  1020. }
  1021. }
  1022. /// <summary>
  1023. /// PhysicsActor Prim Class for BulletX
  1024. /// </summary>
  1025. public class BulletXPrim : BulletXActor
  1026. {
  1027. //Density it will depends of material.
  1028. //For now all prims have the same density, all prims are made of water. Be water my friend! :D
  1029. private const float _density = 1000.0f;
  1030. private BulletXScene _parent_scene;
  1031. private PhysicsVector m_prev_position = new PhysicsVector(0, 0, 0);
  1032. private bool m_lastUpdateSent = false;
  1033. public BulletXPrim(String primName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector size,
  1034. AxiomQuaternion rotation, IMesh mesh, PrimitiveBaseShape pbs, bool isPhysical)
  1035. : this(
  1036. primName, parent_scene, pos, new PhysicsVector(), size, new PhysicsVector(), rotation, mesh, pbs,
  1037. isPhysical)
  1038. {
  1039. }
  1040. public BulletXPrim(String primName, BulletXScene parent_scene, PhysicsVector pos, PhysicsVector velocity,
  1041. PhysicsVector size,
  1042. PhysicsVector acceleration, AxiomQuaternion rotation, IMesh mesh, PrimitiveBaseShape pbs,
  1043. bool isPhysical)
  1044. : base(primName)
  1045. {
  1046. if ((size.X == 0) || (size.Y == 0) || (size.Z == 0)) throw new Exception("Size 0");
  1047. if (rotation.Norm == 0f) rotation = AxiomQuaternion.Identity;
  1048. _position = pos;
  1049. _physical = isPhysical;
  1050. _velocity = _physical ? velocity : new PhysicsVector();
  1051. _size = size;
  1052. _acceleration = acceleration;
  1053. _orientation = rotation;
  1054. _parent_scene = parent_scene;
  1055. CreateRigidBody(parent_scene, mesh, pos, size);
  1056. }
  1057. public override int PhysicsActorType
  1058. {
  1059. get { return (int) ActorTypes.Prim; }
  1060. set { return; }
  1061. }
  1062. public override PhysicsVector Position
  1063. {
  1064. get { return base.Position; }
  1065. set { base.Position = value; }
  1066. }
  1067. public override PhysicsVector Velocity
  1068. {
  1069. get { return base.Velocity; }
  1070. set { base.Velocity = value; }
  1071. }
  1072. public override PhysicsVector Size
  1073. {
  1074. get { return _size; }
  1075. set
  1076. {
  1077. lock (BulletXScene.BulletXLock)
  1078. {
  1079. _size = value;
  1080. ReSize();
  1081. }
  1082. }
  1083. }
  1084. public override PhysicsVector Acceleration
  1085. {
  1086. get { return base.Acceleration; }
  1087. }
  1088. public override AxiomQuaternion Orientation
  1089. {
  1090. get { return base.Orientation; }
  1091. set { base.Orientation = value; }
  1092. }
  1093. public override float ActorMass
  1094. {
  1095. get
  1096. {
  1097. //For now all prims are boxes
  1098. return (_physical ? 1 : 0)*_density*_size.X*_size.Y*_size.Z;
  1099. }
  1100. }
  1101. public override bool IsPhysical
  1102. {
  1103. get { return base.IsPhysical; }
  1104. set
  1105. {
  1106. base.IsPhysical = value;
  1107. if (value)
  1108. {
  1109. //---
  1110. PhysicsPluginManager.PhysicsPluginMessage("Physical - Recreate", true);
  1111. //---
  1112. ReCreateRigidBody(_size);
  1113. }
  1114. else
  1115. {
  1116. //---
  1117. PhysicsPluginManager.PhysicsPluginMessage("Physical - SetMassProps", true);
  1118. //---
  1119. rigidBody.SetMassProps(Mass, new Vector3());
  1120. }
  1121. }
  1122. }
  1123. public override bool Flying
  1124. {
  1125. get { return base.Flying; }
  1126. set { base.Flying = value; }
  1127. }
  1128. public override bool IsColliding
  1129. {
  1130. get { return base.IsColliding; }
  1131. set { base.IsColliding = value; }
  1132. }
  1133. public override bool Kinematic
  1134. {
  1135. get { return base.Kinematic; }
  1136. set { base.Kinematic = value; }
  1137. }
  1138. public override void SetAcceleration(PhysicsVector accel)
  1139. {
  1140. lock (BulletXScene.BulletXLock)
  1141. {
  1142. _acceleration = accel;
  1143. }
  1144. }
  1145. public override void AddForce(PhysicsVector force)
  1146. {
  1147. base.AddForce(force);
  1148. }
  1149. public override void SetMomentum(PhysicsVector momentum)
  1150. {
  1151. base.SetMomentum(momentum);
  1152. }
  1153. internal override void ValidateHeight(float heighmapPositionValue)
  1154. {
  1155. if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue + _size.Z/2.0f)
  1156. {
  1157. Matrix m = rigidBody.WorldTransform;
  1158. Vector3 v3 = m.Translation;
  1159. v3.Z = heighmapPositionValue + _size.Z/2.0f;
  1160. m.Translation = v3;
  1161. rigidBody.WorldTransform = m;
  1162. //When a Prim touch the ground it's vertical velocity it's reduced to ZERO
  1163. //Static objects don't have linear velocity
  1164. if (_physical)
  1165. Speed(new PhysicsVector(rigidBody.LinearVelocity.X, rigidBody.LinearVelocity.Y, 0.0f));
  1166. }
  1167. }
  1168. internal override void UpdateKinetics()
  1169. {
  1170. if (_physical) //Updates properties. Prim updates its properties physically
  1171. {
  1172. _position = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition);
  1173. _velocity = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.LinearVelocity);
  1174. _orientation = BulletXMaths.XnaQuaternionToAxiomQuaternion(rigidBody.Orientation);
  1175. if ((Math.Abs(m_prev_position.X - _position.X) < 0.03)
  1176. && (Math.Abs(m_prev_position.Y - _position.Y) < 0.03)
  1177. && (Math.Abs(m_prev_position.Z - _position.Z) < 0.03))
  1178. {
  1179. if (!m_lastUpdateSent)
  1180. {
  1181. _velocity = new PhysicsVector(0, 0, 0);
  1182. base.ScheduleTerseUpdate();
  1183. m_lastUpdateSent = true;
  1184. }
  1185. }
  1186. else
  1187. {
  1188. m_lastUpdateSent = false;
  1189. base.ScheduleTerseUpdate();
  1190. }
  1191. m_prev_position = _position;
  1192. }
  1193. else //Doesn't updates properties. That's a cancel
  1194. {
  1195. Translate();
  1196. //Speed(); //<- Static objects don't have linear velocity
  1197. ReOrient();
  1198. }
  1199. }
  1200. #region Methods for updating values of RigidBody
  1201. protected internal void CreateRigidBody(BulletXScene parent_scene, IMesh mesh, PhysicsVector pos,
  1202. PhysicsVector size)
  1203. {
  1204. //For RigidBody Constructor. The next values might change
  1205. float _linearDamping = 0.0f;
  1206. float _angularDamping = 0.0f;
  1207. float _friction = 1.0f;
  1208. float _restitution = 0.0f;
  1209. Matrix _startTransform = Matrix.Identity;
  1210. Matrix _centerOfMassOffset = Matrix.Identity;
  1211. lock (BulletXScene.BulletXLock)
  1212. {
  1213. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(pos);
  1214. //For now all prims are boxes
  1215. CollisionShape _collisionShape;
  1216. if (mesh == null)
  1217. {
  1218. _collisionShape = new BoxShape(BulletXMaths.PhysicsVectorToXnaVector3(size)/2.0f);
  1219. }
  1220. else
  1221. {
  1222. int iVertexCount = mesh.getVertexList().Count;
  1223. int[] indices = mesh.getIndexListAsInt();
  1224. Vector3[] v3Vertices = new Vector3[iVertexCount];
  1225. for (int i = 0; i < iVertexCount; i++)
  1226. {
  1227. PhysicsVector v = mesh.getVertexList()[i];
  1228. if (v != null) // Note, null has special meaning. See meshing code for details
  1229. v3Vertices[i] = BulletXMaths.PhysicsVectorToXnaVector3(v);
  1230. else
  1231. v3Vertices[i] = Vector3.Zero;
  1232. }
  1233. TriangleIndexVertexArray triMesh = new TriangleIndexVertexArray(indices, v3Vertices);
  1234. _collisionShape = new TriangleMeshShape(triMesh);
  1235. }
  1236. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1237. Vector3 _localInertia = new Vector3();
  1238. if (_physical) _collisionShape.CalculateLocalInertia(Mass, out _localInertia); //Always when mass > 0
  1239. rigidBody =
  1240. new RigidBody(Mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping,
  1241. _friction, _restitution);
  1242. //rigidBody.ActivationState = ActivationState.DisableDeactivation;
  1243. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1244. Vector3 _vDebugTranslation;
  1245. _vDebugTranslation = _startTransform.Translation - rigidBody.CenterOfMassPosition;
  1246. rigidBody.Translate(_vDebugTranslation);
  1247. //---
  1248. parent_scene.ddWorld.AddRigidBody(rigidBody);
  1249. }
  1250. }
  1251. protected internal void ReCreateRigidBody(PhysicsVector size)
  1252. {
  1253. //There is a bug when trying to remove a rigidBody that is colliding with something..
  1254. try
  1255. {
  1256. _parent_scene.ddWorld.RemoveRigidBody(rigidBody);
  1257. }
  1258. catch (Exception ex)
  1259. {
  1260. _parent_scene.BulletXMessage(_parent_scene.is_ex_message + ex.Message, true);
  1261. rigidBody.ActivationState = ActivationState.DisableSimulation;
  1262. _parent_scene.AddForgottenRigidBody(rigidBody);
  1263. }
  1264. CreateRigidBody(_parent_scene, null, _position, size);
  1265. // Note, null for the meshing definitely is wrong. It's here for the moment to apease the compiler
  1266. if (_physical) Speed(); //Static objects don't have linear velocity
  1267. ReOrient();
  1268. GC.Collect();
  1269. }
  1270. protected internal override void ReSize(PhysicsVector _newSize)
  1271. {
  1272. //I wonder to know how to resize with a simple instruction in BulletX. It seems that for now there isn't
  1273. //so i have to do it manually. That's recreating rigidbody
  1274. ReCreateRigidBody(_newSize);
  1275. }
  1276. #endregion
  1277. }
  1278. /// <summary>
  1279. /// This Class manage a HeighField as a RigidBody. This is for to be added in the BulletXScene
  1280. /// </summary>
  1281. internal class BulletXPlanet
  1282. {
  1283. private PhysicsVector _staticPosition;
  1284. private PhysicsVector _staticVelocity;
  1285. private AxiomQuaternion _staticOrientation;
  1286. private float _mass;
  1287. private BulletXScene _parentscene;
  1288. internal float[] _heightField;
  1289. private RigidBody _flatPlanet;
  1290. internal RigidBody RigidBody
  1291. {
  1292. get { return _flatPlanet; }
  1293. }
  1294. internal BulletXPlanet(BulletXScene parent_scene, float[] heightField)
  1295. {
  1296. _staticPosition = new PhysicsVector(BulletXScene.MaxXY/2, BulletXScene.MaxXY/2, 0);
  1297. _staticVelocity = new PhysicsVector();
  1298. _staticOrientation = AxiomQuaternion.Identity;
  1299. _mass = 0; //No active
  1300. _parentscene = parent_scene;
  1301. _heightField = heightField;
  1302. float _linearDamping = 0.0f;
  1303. float _angularDamping = 0.0f;
  1304. float _friction = 0.5f;
  1305. float _restitution = 0.0f;
  1306. Matrix _startTransform = Matrix.Identity;
  1307. Matrix _centerOfMassOffset = Matrix.Identity;
  1308. lock (BulletXScene.BulletXLock)
  1309. {
  1310. try
  1311. {
  1312. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(_staticPosition);
  1313. CollisionShape _collisionShape =
  1314. new HeightfieldTerrainShape(BulletXScene.MaxXY, BulletXScene.MaxXY, _heightField,
  1315. (float) BulletXScene.MaxZ, 2, true, false);
  1316. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1317. Vector3 _localInertia = new Vector3();
  1318. //_collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0
  1319. _flatPlanet =
  1320. new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping,
  1321. _angularDamping, _friction, _restitution);
  1322. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1323. Vector3 _vDebugTranslation;
  1324. _vDebugTranslation = _startTransform.Translation - _flatPlanet.CenterOfMassPosition;
  1325. _flatPlanet.Translate(_vDebugTranslation);
  1326. parent_scene.ddWorld.AddRigidBody(_flatPlanet);
  1327. }
  1328. catch (Exception ex)
  1329. {
  1330. _parentscene.BulletXMessage(ex.Message, true);
  1331. }
  1332. }
  1333. _parentscene.BulletXMessage("BulletXPlanet created.", false);
  1334. }
  1335. internal float HeightValue(Vector3 position)
  1336. {
  1337. int li_x, li_y;
  1338. float height;
  1339. li_x = (int) Math.Round(position.X);
  1340. if (li_x < 0) li_x = 0;
  1341. if (li_x >= BulletXScene.MaxXY) li_x = BulletXScene.MaxXY - 1;
  1342. li_y = (int) Math.Round(position.Y);
  1343. if (li_y < 0) li_y = 0;
  1344. if (li_y >= BulletXScene.MaxXY) li_y = BulletXScene.MaxXY - 1;
  1345. height = ((HeightfieldTerrainShape) _flatPlanet.CollisionShape).getHeightFieldValue(li_x, li_y);
  1346. if (height < 0) height = 0;
  1347. else if (height > BulletXScene.MaxZ) height = BulletXScene.MaxZ;
  1348. return height;
  1349. }
  1350. }
  1351. }