BulletXPlugin.cs 61 KB

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