BulletXPlugin.cs 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844
  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(OpenMetaverse.Vector3 physicsVector)
  51. {
  52. return new Vector3(physicsVector.X, physicsVector.Y, physicsVector.Z);
  53. }
  54. public static OpenMetaverse.Vector3 XnaVector3ToPhysicsVector(Vector3 xnaVector3)
  55. {
  56. return new OpenMetaverse.Vector3(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. OpenMetaverse.Vector3 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. OpenMetaverse.Vector3 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. OpenMetaverse.Vector3 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, OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 size, bool isFlying)
  488. {
  489. OpenMetaverse.Vector3 pos = OpenMetaverse.Vector3.Zero;
  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, OpenMetaverse.Vector3 position,
  524. OpenMetaverse.Vector3 size, OpenMetaverse.Quaternion rotation)
  525. {
  526. return AddPrimShape(primName, pbs, position, size, rotation, false);
  527. }
  528. public override PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, OpenMetaverse.Vector3 position,
  529. OpenMetaverse.Vector3 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, OpenMetaverse.Vector3 position, OpenMetaverse.Vector3 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 OpenMetaverse.Vector3 _position;
  761. protected OpenMetaverse.Vector3 _velocity;
  762. protected OpenMetaverse.Vector3 _size;
  763. protected OpenMetaverse.Vector3 _acceleration;
  764. protected OpenMetaverse.Quaternion _orientation;
  765. protected OpenMetaverse.Vector3 m_rotationalVelocity;
  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 OpenMetaverse.Vector3 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 OpenMetaverse.Vector3 RotationalVelocity
  791. {
  792. get { return m_rotationalVelocity; }
  793. set { m_rotationalVelocity = value; }
  794. }
  795. public override OpenMetaverse.Vector3 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 = OpenMetaverse.Vector3.Zero;
  811. }
  812. }
  813. }
  814. }
  815. public override float CollisionScore
  816. {
  817. get { return 0f; }
  818. set { }
  819. }
  820. public override OpenMetaverse.Vector3 Size
  821. {
  822. get { return _size; }
  823. set
  824. {
  825. lock (BulletXScene.BulletXLock)
  826. {
  827. _size = value;
  828. }
  829. }
  830. }
  831. public override OpenMetaverse.Vector3 Force
  832. {
  833. get { return OpenMetaverse.Vector3.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, OpenMetaverse.Vector3 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 OpenMetaverse.Vector3 CenterOfMass
  854. {
  855. get { return OpenMetaverse.Vector3.Zero; }
  856. }
  857. public override OpenMetaverse.Vector3 GeometricCenter
  858. {
  859. get { return OpenMetaverse.Vector3.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 OpenMetaverse.Vector3 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(OpenMetaverse.Vector3 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(OpenMetaverse.Vector3 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(OpenMetaverse.Vector3 force, bool pushforce)
  980. {
  981. }
  982. public override OpenMetaverse.Vector3 Torque
  983. {
  984. get { return OpenMetaverse.Vector3.Zero; }
  985. set { return; }
  986. }
  987. public override void AddAngularForce(OpenMetaverse.Vector3 force, bool pushforce)
  988. {
  989. }
  990. public override void SetMomentum(OpenMetaverse.Vector3 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(OpenMetaverse.Vector3 _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(OpenMetaverse.Vector3 _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(OpenMetaverse.Vector3 _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 OpenMetaverse.Vector3 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 OpenMetaverse.Quaternion APIDTarget
  1055. {
  1056. set { return; }
  1057. }
  1058. public override bool APIDActive
  1059. {
  1060. set { return; }
  1061. }
  1062. public override float APIDStrength
  1063. {
  1064. set { return; }
  1065. }
  1066. public override float APIDDamping
  1067. {
  1068. set { return; }
  1069. }
  1070. public override void SubscribeEvents(int ms)
  1071. {
  1072. }
  1073. public override void UnSubscribeEvents()
  1074. {
  1075. }
  1076. public override bool SubscribedEvents()
  1077. {
  1078. return false;
  1079. }
  1080. }
  1081. /// <summary>
  1082. /// PhysicsActor Character Class for BulletX
  1083. /// </summary>
  1084. public class BulletXCharacter : BulletXActor
  1085. {
  1086. public BulletXCharacter(BulletXScene parent_scene, OpenMetaverse.Vector3 pos)
  1087. : this(String.Empty, parent_scene, pos)
  1088. {
  1089. }
  1090. public BulletXCharacter(String avName, BulletXScene parent_scene, OpenMetaverse.Vector3 pos)
  1091. : this(avName, parent_scene, pos, OpenMetaverse.Vector3.Zero, OpenMetaverse.Vector3.Zero, OpenMetaverse.Vector3.Zero,
  1092. OpenMetaverse.Quaternion.Identity)
  1093. {
  1094. }
  1095. public BulletXCharacter(String avName, BulletXScene parent_scene, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 velocity,
  1096. OpenMetaverse.Vector3 size, OpenMetaverse.Vector3 acceleration, OpenMetaverse.Quaternion orientation)
  1097. : base(avName)
  1098. {
  1099. //This fields will be removed. They're temporal
  1100. float _sizeX = 0.5f;
  1101. float _sizeY = 0.5f;
  1102. float _sizeZ = 1.6f;
  1103. //.
  1104. _position = pos;
  1105. _velocity = velocity;
  1106. _size = size;
  1107. //---
  1108. _size.X = _sizeX;
  1109. _size.Y = _sizeY;
  1110. _size.Z = _sizeZ;
  1111. //.
  1112. _acceleration = acceleration;
  1113. _orientation = orientation;
  1114. _physical = true;
  1115. float _mass = 50.0f; //This depends of avatar's dimensions
  1116. //For RigidBody Constructor. The next values might change
  1117. float _linearDamping = 0.0f;
  1118. float _angularDamping = 0.0f;
  1119. float _friction = 0.5f;
  1120. float _restitution = 0.0f;
  1121. Matrix _startTransform = Matrix.Identity;
  1122. Matrix _centerOfMassOffset = Matrix.Identity;
  1123. lock (BulletXScene.BulletXLock)
  1124. {
  1125. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(pos);
  1126. //CollisionShape _collisionShape = new BoxShape(new MonoXnaCompactMaths.Vector3(1.0f, 1.0f, 1.60f));
  1127. //For now, like ODE, collisionShape = sphere of radious = 1.0
  1128. CollisionShape _collisionShape = new SphereShape(1.0f);
  1129. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1130. Vector3 _localInertia = new Vector3();
  1131. _collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0
  1132. rigidBody =
  1133. new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping,
  1134. _friction, _restitution);
  1135. //rigidBody.ActivationState = ActivationState.DisableDeactivation;
  1136. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1137. Vector3 _vDebugTranslation;
  1138. _vDebugTranslation = _startTransform.Translation - rigidBody.CenterOfMassPosition;
  1139. rigidBody.Translate(_vDebugTranslation);
  1140. parent_scene.ddWorld.AddRigidBody(rigidBody);
  1141. }
  1142. }
  1143. public override int PhysicsActorType
  1144. {
  1145. get { return (int) ActorTypes.Agent; }
  1146. set { return; }
  1147. }
  1148. public override OpenMetaverse.Vector3 Position
  1149. {
  1150. get { return base.Position; }
  1151. set { base.Position = value; }
  1152. }
  1153. public override OpenMetaverse.Vector3 Velocity
  1154. {
  1155. get { return base.Velocity; }
  1156. set { base.Velocity = value; }
  1157. }
  1158. public override OpenMetaverse.Vector3 Size
  1159. {
  1160. get { return base.Size; }
  1161. set { base.Size = value; }
  1162. }
  1163. public override OpenMetaverse.Vector3 Acceleration
  1164. {
  1165. get { return base.Acceleration; }
  1166. }
  1167. public override OpenMetaverse.Quaternion Orientation
  1168. {
  1169. get { return base.Orientation; }
  1170. set { base.Orientation = value; }
  1171. }
  1172. public override bool Flying
  1173. {
  1174. get { return base.Flying; }
  1175. set { base.Flying = value; }
  1176. }
  1177. public override bool IsColliding
  1178. {
  1179. get { return base.IsColliding; }
  1180. set { base.IsColliding = value; }
  1181. }
  1182. public override bool Kinematic
  1183. {
  1184. get { return base.Kinematic; }
  1185. set { base.Kinematic = value; }
  1186. }
  1187. public override void SetAcceleration(OpenMetaverse.Vector3 accel)
  1188. {
  1189. base.SetAcceleration(accel);
  1190. }
  1191. public override void AddForce(OpenMetaverse.Vector3 force, bool pushforce)
  1192. {
  1193. base.AddForce(force, pushforce);
  1194. }
  1195. public override void SetMomentum(OpenMetaverse.Vector3 momentum)
  1196. {
  1197. base.SetMomentum(momentum);
  1198. }
  1199. internal void Move(float timeStep)
  1200. {
  1201. Vector3 vec = new Vector3();
  1202. //At this point it's supossed that:
  1203. //_velocity == rigidBody.LinearVelocity
  1204. vec.X = _velocity.X;
  1205. vec.Y = _velocity.Y;
  1206. vec.Z = _velocity.Z;
  1207. if ((vec.X != 0.0f) || (vec.Y != 0.0f) || (vec.Z != 0.0f)) rigidBody.Activate();
  1208. if (flying)
  1209. {
  1210. //Antigravity with movement
  1211. if (_position.Z <= BulletXScene.HeightLevel0)
  1212. {
  1213. vec.Z += BulletXScene.Gravity*timeStep;
  1214. }
  1215. //Lowgravity with movement
  1216. else if ((_position.Z > BulletXScene.HeightLevel0)
  1217. && (_position.Z <= BulletXScene.HeightLevel1))
  1218. {
  1219. vec.Z += BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  1220. }
  1221. //Lowgravity with...
  1222. else if (_position.Z > BulletXScene.HeightLevel1)
  1223. {
  1224. if (vec.Z > 0) //no movement
  1225. vec.Z = BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  1226. else
  1227. vec.Z += BulletXScene.Gravity*timeStep*(1.0f - BulletXScene.LowGravityFactor);
  1228. }
  1229. }
  1230. rigidBody.LinearVelocity = vec;
  1231. }
  1232. //This validation is very basic
  1233. internal override void ValidateHeight(float heighmapPositionValue)
  1234. {
  1235. if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue + _size.Z/2.0f)
  1236. {
  1237. Matrix m = rigidBody.WorldTransform;
  1238. Vector3 v3 = m.Translation;
  1239. v3.Z = heighmapPositionValue + _size.Z/2.0f;
  1240. m.Translation = v3;
  1241. rigidBody.WorldTransform = m;
  1242. //When an Avie touch the ground it's vertical velocity it's reduced to ZERO
  1243. Speed(new OpenMetaverse.Vector3(rigidBody.LinearVelocity.X, rigidBody.LinearVelocity.Y, 0.0f));
  1244. }
  1245. }
  1246. internal override void UpdateKinetics()
  1247. {
  1248. _position = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition);
  1249. _velocity = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.LinearVelocity);
  1250. //Orientation it seems that it will be the default.
  1251. ReOrient();
  1252. }
  1253. }
  1254. /// <summary>
  1255. /// PhysicsActor Prim Class for BulletX
  1256. /// </summary>
  1257. public class BulletXPrim : BulletXActor
  1258. {
  1259. //Density it will depends of material.
  1260. //For now all prims have the same density, all prims are made of water. Be water my friend! :D
  1261. private const float _density = 1000.0f;
  1262. private BulletXScene _parent_scene;
  1263. private OpenMetaverse.Vector3 m_prev_position;
  1264. private bool m_lastUpdateSent = false;
  1265. //added by jed zhu
  1266. private IMesh _mesh;
  1267. public IMesh GetMesh() { return _mesh; }
  1268. public BulletXPrim(String primName, BulletXScene parent_scene, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 size,
  1269. OpenMetaverse.Quaternion rotation, IMesh mesh, PrimitiveBaseShape pbs, bool isPhysical)
  1270. : this(
  1271. primName, parent_scene, pos, OpenMetaverse.Vector3.Zero, size, OpenMetaverse.Vector3.Zero, rotation, mesh, pbs,
  1272. isPhysical)
  1273. {
  1274. }
  1275. public BulletXPrim(String primName, BulletXScene parent_scene, OpenMetaverse.Vector3 pos, OpenMetaverse.Vector3 velocity,
  1276. OpenMetaverse.Vector3 size,
  1277. OpenMetaverse.Vector3 acceleration, OpenMetaverse.Quaternion rotation, IMesh mesh, PrimitiveBaseShape pbs,
  1278. bool isPhysical)
  1279. : base(primName)
  1280. {
  1281. if ((size.X == 0) || (size.Y == 0) || (size.Z == 0))
  1282. throw new Exception("Size 0");
  1283. if (OpenMetaverse.Quaternion.Normalize(rotation).Length() == 0f)
  1284. rotation = OpenMetaverse.Quaternion.Identity;
  1285. _position = pos;
  1286. _physical = isPhysical;
  1287. _velocity = _physical ? velocity : OpenMetaverse.Vector3.Zero;
  1288. _size = size;
  1289. _acceleration = acceleration;
  1290. _orientation = rotation;
  1291. _parent_scene = parent_scene;
  1292. CreateRigidBody(parent_scene, mesh, pos, size);
  1293. }
  1294. public override int PhysicsActorType
  1295. {
  1296. get { return (int) ActorTypes.Prim; }
  1297. set { return; }
  1298. }
  1299. public override OpenMetaverse.Vector3 Position
  1300. {
  1301. get { return base.Position; }
  1302. set { base.Position = value; }
  1303. }
  1304. public override OpenMetaverse.Vector3 Velocity
  1305. {
  1306. get { return base.Velocity; }
  1307. set { base.Velocity = value; }
  1308. }
  1309. public override OpenMetaverse.Vector3 Size
  1310. {
  1311. get { return _size; }
  1312. set
  1313. {
  1314. lock (BulletXScene.BulletXLock)
  1315. {
  1316. _size = value;
  1317. ReSize();
  1318. }
  1319. }
  1320. }
  1321. public override OpenMetaverse.Vector3 Acceleration
  1322. {
  1323. get { return base.Acceleration; }
  1324. }
  1325. public override OpenMetaverse.Quaternion Orientation
  1326. {
  1327. get { return base.Orientation; }
  1328. set { base.Orientation = value; }
  1329. }
  1330. public override float ActorMass
  1331. {
  1332. get
  1333. {
  1334. //For now all prims are boxes
  1335. return (_physical ? 1 : 0)*_density*_size.X*_size.Y*_size.Z;
  1336. }
  1337. }
  1338. public override bool IsPhysical
  1339. {
  1340. get { return base.IsPhysical; }
  1341. set
  1342. {
  1343. base.IsPhysical = value;
  1344. if (value)
  1345. {
  1346. //---
  1347. PhysicsPluginManager.PhysicsPluginMessage("Physical - Recreate", true);
  1348. //---
  1349. ReCreateRigidBody(_size);
  1350. }
  1351. else
  1352. {
  1353. //---
  1354. PhysicsPluginManager.PhysicsPluginMessage("Physical - SetMassProps", true);
  1355. //---
  1356. rigidBody.SetMassProps(Mass, new Vector3());
  1357. }
  1358. }
  1359. }
  1360. public override bool Flying
  1361. {
  1362. get { return base.Flying; }
  1363. set { base.Flying = value; }
  1364. }
  1365. public override bool IsColliding
  1366. {
  1367. get { return base.IsColliding; }
  1368. set { base.IsColliding = value; }
  1369. }
  1370. public override bool Kinematic
  1371. {
  1372. get { return base.Kinematic; }
  1373. set { base.Kinematic = value; }
  1374. }
  1375. public override void SetAcceleration(OpenMetaverse.Vector3 accel)
  1376. {
  1377. lock (BulletXScene.BulletXLock)
  1378. {
  1379. _acceleration = accel;
  1380. }
  1381. }
  1382. public override void AddForce(OpenMetaverse.Vector3 force, bool pushforce)
  1383. {
  1384. base.AddForce(force,pushforce);
  1385. }
  1386. public override void SetMomentum(OpenMetaverse.Vector3 momentum)
  1387. {
  1388. base.SetMomentum(momentum);
  1389. }
  1390. internal override void ValidateHeight(float heighmapPositionValue)
  1391. {
  1392. if (rigidBody.CenterOfMassPosition.Z < heighmapPositionValue + _size.Z/2.0f)
  1393. {
  1394. Matrix m = rigidBody.WorldTransform;
  1395. Vector3 v3 = m.Translation;
  1396. v3.Z = heighmapPositionValue + _size.Z/2.0f;
  1397. m.Translation = v3;
  1398. rigidBody.WorldTransform = m;
  1399. //When a Prim touch the ground it's vertical velocity it's reduced to ZERO
  1400. //Static objects don't have linear velocity
  1401. if (_physical)
  1402. Speed(new OpenMetaverse.Vector3(rigidBody.LinearVelocity.X, rigidBody.LinearVelocity.Y, 0.0f));
  1403. }
  1404. }
  1405. internal override void UpdateKinetics()
  1406. {
  1407. if (_physical) //Updates properties. Prim updates its properties physically
  1408. {
  1409. _position = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.CenterOfMassPosition);
  1410. _velocity = BulletXMaths.XnaVector3ToPhysicsVector(rigidBody.LinearVelocity);
  1411. _orientation = BulletXMaths.XnaQuaternionToQuaternion(rigidBody.Orientation);
  1412. if ((Math.Abs(m_prev_position.X - _position.X) < 0.03)
  1413. && (Math.Abs(m_prev_position.Y - _position.Y) < 0.03)
  1414. && (Math.Abs(m_prev_position.Z - _position.Z) < 0.03))
  1415. {
  1416. if (!m_lastUpdateSent)
  1417. {
  1418. _velocity = OpenMetaverse.Vector3.Zero;
  1419. base.ScheduleTerseUpdate();
  1420. m_lastUpdateSent = true;
  1421. }
  1422. }
  1423. else
  1424. {
  1425. m_lastUpdateSent = false;
  1426. base.ScheduleTerseUpdate();
  1427. }
  1428. m_prev_position = _position;
  1429. }
  1430. else //Doesn't updates properties. That's a cancel
  1431. {
  1432. Translate();
  1433. //Speed(); //<- Static objects don't have linear velocity
  1434. ReOrient();
  1435. }
  1436. }
  1437. #region Methods for updating values of RigidBody
  1438. protected internal void CreateRigidBody(BulletXScene parent_scene, IMesh mesh, OpenMetaverse.Vector3 pos,
  1439. OpenMetaverse.Vector3 size)
  1440. {
  1441. //For RigidBody Constructor. The next values might change
  1442. float _linearDamping = 0.0f;
  1443. float _angularDamping = 0.0f;
  1444. float _friction = 1.0f;
  1445. float _restitution = 0.0f;
  1446. Matrix _startTransform = Matrix.Identity;
  1447. Matrix _centerOfMassOffset = Matrix.Identity;
  1448. //added by jed zhu
  1449. _mesh = mesh;
  1450. lock (BulletXScene.BulletXLock)
  1451. {
  1452. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(pos);
  1453. //For now all prims are boxes
  1454. CollisionShape _collisionShape;
  1455. if (mesh == null)
  1456. {
  1457. _collisionShape = new BoxShape(BulletXMaths.PhysicsVectorToXnaVector3(size)/2.0f);
  1458. }
  1459. else
  1460. {
  1461. int iVertexCount = mesh.getVertexList().Count;
  1462. int[] indices = mesh.getIndexListAsInt();
  1463. Vector3[] v3Vertices = new Vector3[iVertexCount];
  1464. for (int i = 0; i < iVertexCount; i++)
  1465. {
  1466. OpenMetaverse.Vector3 v = mesh.getVertexList()[i];
  1467. if (v != null) // Note, null has special meaning. See meshing code for details
  1468. v3Vertices[i] = BulletXMaths.PhysicsVectorToXnaVector3(v);
  1469. else
  1470. v3Vertices[i] = Vector3.Zero;
  1471. }
  1472. TriangleIndexVertexArray triMesh = new TriangleIndexVertexArray(indices, v3Vertices);
  1473. _collisionShape = new TriangleMeshShape(triMesh);
  1474. }
  1475. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1476. Vector3 _localInertia = new Vector3();
  1477. if (_physical) _collisionShape.CalculateLocalInertia(Mass, out _localInertia); //Always when mass > 0
  1478. rigidBody =
  1479. new RigidBody(Mass, _motionState, _collisionShape, _localInertia, _linearDamping, _angularDamping,
  1480. _friction, _restitution);
  1481. //rigidBody.ActivationState = ActivationState.DisableDeactivation;
  1482. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1483. Vector3 _vDebugTranslation;
  1484. _vDebugTranslation = _startTransform.Translation - rigidBody.CenterOfMassPosition;
  1485. rigidBody.Translate(_vDebugTranslation);
  1486. //---
  1487. parent_scene.ddWorld.AddRigidBody(rigidBody);
  1488. }
  1489. }
  1490. protected internal void ReCreateRigidBody(OpenMetaverse.Vector3 size)
  1491. {
  1492. //There is a bug when trying to remove a rigidBody that is colliding with something..
  1493. try
  1494. {
  1495. _parent_scene.ddWorld.RemoveRigidBody(rigidBody);
  1496. }
  1497. catch (Exception ex)
  1498. {
  1499. BulletXScene.BulletXMessage(_parent_scene.is_ex_message + ex.Message, true);
  1500. rigidBody.ActivationState = ActivationState.DisableSimulation;
  1501. _parent_scene.AddForgottenRigidBody(rigidBody);
  1502. }
  1503. CreateRigidBody(_parent_scene, null, _position, size);
  1504. // Note, null for the meshing definitely is wrong. It's here for the moment to apease the compiler
  1505. if (_physical) Speed(); //Static objects don't have linear velocity
  1506. ReOrient();
  1507. GC.Collect();
  1508. }
  1509. protected internal override void ReSize(OpenMetaverse.Vector3 _newSize)
  1510. {
  1511. //I wonder to know how to resize with a simple instruction in BulletX. It seems that for now there isn't
  1512. //so i have to do it manually. That's recreating rigidbody
  1513. ReCreateRigidBody(_newSize);
  1514. }
  1515. #endregion
  1516. }
  1517. /// <summary>
  1518. /// This Class manage a HeighField as a RigidBody. This is for to be added in the BulletXScene
  1519. /// </summary>
  1520. internal class BulletXPlanet
  1521. {
  1522. private OpenMetaverse.Vector3 _staticPosition;
  1523. // private Vector3 _staticVelocity;
  1524. // private OpenMetaverse.Quaternion _staticOrientation;
  1525. private float _mass;
  1526. // private BulletXScene _parentscene;
  1527. internal float[] _heightField;
  1528. private RigidBody _flatPlanet;
  1529. internal RigidBody RigidBody
  1530. {
  1531. get { return _flatPlanet; }
  1532. }
  1533. internal BulletXPlanet(BulletXScene parent_scene, float[] heightField)
  1534. {
  1535. _staticPosition = new OpenMetaverse.Vector3(BulletXScene.MaxXY / 2, BulletXScene.MaxXY / 2, 0);
  1536. // _staticVelocity = new PhysicsVector();
  1537. // _staticOrientation = OpenMetaverse.Quaternion.Identity;
  1538. _mass = 0; //No active
  1539. // _parentscene = parent_scene;
  1540. _heightField = heightField;
  1541. float _linearDamping = 0.0f;
  1542. float _angularDamping = 0.0f;
  1543. float _friction = 0.5f;
  1544. float _restitution = 0.0f;
  1545. Matrix _startTransform = Matrix.Identity;
  1546. Matrix _centerOfMassOffset = Matrix.Identity;
  1547. lock (BulletXScene.BulletXLock)
  1548. {
  1549. try
  1550. {
  1551. _startTransform.Translation = BulletXMaths.PhysicsVectorToXnaVector3(_staticPosition);
  1552. CollisionShape _collisionShape =
  1553. new HeightfieldTerrainShape(BulletXScene.MaxXY, BulletXScene.MaxXY, _heightField,
  1554. (float) BulletXScene.MaxZ, 2, true, false);
  1555. DefaultMotionState _motionState = new DefaultMotionState(_startTransform, _centerOfMassOffset);
  1556. Vector3 _localInertia = new Vector3();
  1557. //_collisionShape.CalculateLocalInertia(_mass, out _localInertia); //Always when mass > 0
  1558. _flatPlanet =
  1559. new RigidBody(_mass, _motionState, _collisionShape, _localInertia, _linearDamping,
  1560. _angularDamping, _friction, _restitution);
  1561. //It's seems that there are a bug with rigidBody constructor and its CenterOfMassPosition
  1562. Vector3 _vDebugTranslation;
  1563. _vDebugTranslation = _startTransform.Translation - _flatPlanet.CenterOfMassPosition;
  1564. _flatPlanet.Translate(_vDebugTranslation);
  1565. parent_scene.ddWorld.AddRigidBody(_flatPlanet);
  1566. }
  1567. catch (Exception ex)
  1568. {
  1569. BulletXScene.BulletXMessage(ex.Message, true);
  1570. }
  1571. }
  1572. BulletXScene.BulletXMessage("BulletXPlanet created.", false);
  1573. }
  1574. internal float HeightValue(Vector3 position)
  1575. {
  1576. int li_x, li_y;
  1577. float height;
  1578. li_x = (int) Math.Round(position.X);
  1579. if (li_x < 0) li_x = 0;
  1580. if (li_x >= BulletXScene.MaxXY) li_x = BulletXScene.MaxXY - 1;
  1581. li_y = (int) Math.Round(position.Y);
  1582. if (li_y < 0) li_y = 0;
  1583. if (li_y >= BulletXScene.MaxXY) li_y = BulletXScene.MaxXY - 1;
  1584. height = ((HeightfieldTerrainShape) _flatPlanet.CollisionShape).getHeightFieldValue(li_x, li_y);
  1585. if (height < 0) height = 0;
  1586. else if (height > BulletXScene.MaxZ) height = BulletXScene.MaxZ;
  1587. return height;
  1588. }
  1589. }
  1590. }