1
0

BulletXPlugin.cs 53 KB

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