BulletXPlugin.cs 52 KB

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