BSShapeCollection.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 copyrightD
  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. using System;
  28. using System.Collections.Generic;
  29. using System.Text;
  30. using OMV = OpenMetaverse;
  31. using OpenSim.Framework;
  32. using OpenSim.Region.PhysicsModules.SharedBase;
  33. namespace OpenSim.Region.PhysicsModule.BulletS
  34. {
  35. public sealed class BSShapeCollection : IDisposable
  36. {
  37. #pragma warning disable 414
  38. private static string LogHeader = "[BULLETSIM SHAPE COLLECTION]";
  39. #pragma warning restore 414
  40. private BSScene m_physicsScene { get; set; }
  41. private Object m_collectionActivityLock = new Object();
  42. private bool DDetail = false;
  43. public BSShapeCollection(BSScene physScene)
  44. {
  45. m_physicsScene = physScene;
  46. // Set the next to 'true' for very detailed shape update detailed logging (detailed details?)
  47. // While detailed debugging is still active, this is better than commenting out all the
  48. // DetailLog statements. When debugging slows down, this and the protected logging
  49. // statements can be commented/removed.
  50. DDetail = true;
  51. }
  52. public void Dispose()
  53. {
  54. // TODO!!!!!!!!!
  55. }
  56. // Callbacks called just before either the body or shape is destroyed.
  57. // Mostly used for changing bodies out from under Linksets.
  58. // Useful for other cases where parameters need saving.
  59. // Passing 'null' says no callback.
  60. public delegate void PhysicalDestructionCallback(BulletBody pBody, BulletShape pShape);
  61. // Called to update/change the body and shape for an object.
  62. // The object has some shape and body on it. Here we decide if that is the correct shape
  63. // for the current state of the object (static/dynamic/...).
  64. // If bodyCallback is not null, it is called if either the body or the shape are changed
  65. // so dependencies (like constraints) can be removed before the physical object is dereferenced.
  66. // Return 'true' if either the body or the shape changed.
  67. // Called at taint-time.
  68. public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim, PhysicalDestructionCallback bodyCallback)
  69. {
  70. m_physicsScene.AssertInTaintTime("BSShapeCollection.GetBodyAndShape");
  71. bool ret = false;
  72. // This lock could probably be pushed down lower but building shouldn't take long
  73. lock (m_collectionActivityLock)
  74. {
  75. // Do we have the correct geometry for this type of object?
  76. // Updates prim.BSShape with information/pointers to shape.
  77. // Returns 'true' of BSShape is changed to a new shape.
  78. bool newGeom = CreateGeom(forceRebuild, prim, bodyCallback);
  79. // If we had to select a new shape geometry for the object,
  80. // rebuild the body around it.
  81. // Updates prim.BSBody with information/pointers to requested body
  82. // Returns 'true' if BSBody was changed.
  83. bool newBody = CreateBody((newGeom || forceRebuild), prim, m_physicsScene.World, bodyCallback);
  84. ret = newGeom || newBody;
  85. }
  86. DetailLog("{0},BSShapeCollection.GetBodyAndShape,taintExit,force={1},ret={2},body={3},shape={4}",
  87. prim.LocalID, forceRebuild, ret, prim.PhysBody, prim.PhysShape);
  88. return ret;
  89. }
  90. public bool GetBodyAndShape(bool forceRebuild, BulletWorld sim, BSPhysObject prim)
  91. {
  92. return GetBodyAndShape(forceRebuild, sim, prim, null);
  93. }
  94. // If the existing prim's shape is to be replaced, remove the tie to the existing shape
  95. // before replacing it.
  96. private void DereferenceExistingShape(BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
  97. {
  98. if (prim.PhysShape.HasPhysicalShape)
  99. {
  100. if (shapeCallback != null)
  101. shapeCallback(prim.PhysBody, prim.PhysShape.physShapeInfo);
  102. prim.PhysShape.Dereference(m_physicsScene);
  103. }
  104. prim.PhysShape = new BSShapeNull();
  105. }
  106. // Create the geometry information in Bullet for later use.
  107. // The objects needs a hull if it's physical otherwise a mesh is enough.
  108. // if 'forceRebuild' is true, the geometry is unconditionally rebuilt. For meshes and hulls,
  109. // shared geometries will be used. If the parameters of the existing shape are the same
  110. // as this request, the shape is not rebuilt.
  111. // Info in prim.BSShape is updated to the new shape.
  112. // Returns 'true' if the geometry was rebuilt.
  113. // Called at taint-time!
  114. public const int AvatarShapeCapsule = 0;
  115. public const int AvatarShapeCube = 1;
  116. public const int AvatarShapeOvoid = 2;
  117. public const int AvatarShapeMesh = 3;
  118. private bool CreateGeom(bool forceRebuild, BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
  119. {
  120. bool ret = false;
  121. bool haveShape = false;
  122. bool nativeShapePossible = true;
  123. PrimitiveBaseShape pbs = prim.BaseShape;
  124. // Kludge to create the capsule for the avatar.
  125. // TDOD: Remove/redo this when BSShapeAvatar is working!!
  126. BSCharacter theChar = prim as BSCharacter;
  127. if (theChar != null)
  128. {
  129. DereferenceExistingShape(prim, shapeCallback);
  130. switch (BSParam.AvatarShape)
  131. {
  132. case AvatarShapeCapsule:
  133. prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
  134. BSPhysicsShapeType.SHAPE_CAPSULE, FixedShapeKey.KEY_CAPSULE);
  135. ret = true;
  136. haveShape = true;
  137. break;
  138. case AvatarShapeCube:
  139. prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
  140. BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_CAPSULE);
  141. ret = true;
  142. haveShape = true;
  143. break;
  144. case AvatarShapeOvoid:
  145. // Saddly, Bullet doesn't scale spheres so this doesn't work as an avatar shape
  146. prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
  147. BSPhysicsShapeType.SHAPE_SPHERE, FixedShapeKey.KEY_CAPSULE);
  148. ret = true;
  149. haveShape = true;
  150. break;
  151. case AvatarShapeMesh:
  152. break;
  153. default:
  154. break;
  155. }
  156. }
  157. // If the prim attributes are simple, this could be a simple Bullet native shape
  158. // Native shapes work whether to object is static or physical.
  159. if (!haveShape
  160. && nativeShapePossible
  161. && pbs != null
  162. && PrimHasNoCuts(pbs)
  163. && ( !pbs.SculptEntry || (pbs.SculptEntry && !BSParam.ShouldMeshSculptedPrim) )
  164. )
  165. {
  166. // Get the scale of any existing shape so we can see if the new shape is same native type and same size.
  167. OMV.Vector3 scaleOfExistingShape = OMV.Vector3.Zero;
  168. if (prim.PhysShape.HasPhysicalShape)
  169. scaleOfExistingShape = m_physicsScene.PE.GetLocalScaling(prim.PhysShape.physShapeInfo);
  170. if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,maybeNative,force={1},primScale={2},primSize={3},primShape={4}",
  171. prim.LocalID, forceRebuild, prim.Scale, prim.Size, prim.PhysShape.physShapeInfo.shapeType);
  172. // It doesn't look like Bullet scales native spheres so make sure the scales are all equal
  173. if ((pbs.ProfileShape == ProfileShape.HalfCircle && pbs.PathCurve == (byte)Extrusion.Curve1)
  174. && pbs.Scale.X == pbs.Scale.Y && pbs.Scale.Y == pbs.Scale.Z)
  175. {
  176. haveShape = true;
  177. if (forceRebuild
  178. || prim.PhysShape.ShapeType != BSPhysicsShapeType.SHAPE_SPHERE
  179. )
  180. {
  181. DereferenceExistingShape(prim, shapeCallback);
  182. prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
  183. BSPhysicsShapeType.SHAPE_SPHERE, FixedShapeKey.KEY_SPHERE);
  184. ret = true;
  185. }
  186. if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,sphere,force={1},rebuilt={2},shape={3}",
  187. prim.LocalID, forceRebuild, ret, prim.PhysShape);
  188. }
  189. // If we didn't make a sphere, maybe a box will work.
  190. if (!haveShape && pbs.ProfileShape == ProfileShape.Square && pbs.PathCurve == (byte)Extrusion.Straight)
  191. {
  192. haveShape = true;
  193. if (forceRebuild
  194. || prim.Scale != scaleOfExistingShape
  195. || prim.PhysShape.ShapeType != BSPhysicsShapeType.SHAPE_BOX
  196. )
  197. {
  198. DereferenceExistingShape(prim, shapeCallback);
  199. prim.PhysShape = BSShapeNative.GetReference(m_physicsScene, prim,
  200. BSPhysicsShapeType.SHAPE_BOX, FixedShapeKey.KEY_BOX);
  201. ret = true;
  202. }
  203. if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,box,force={1},rebuilt={2},shape={3}",
  204. prim.LocalID, forceRebuild, ret, prim.PhysShape);
  205. }
  206. }
  207. // If a simple shape is not happening, create a mesh and possibly a hull.
  208. if (!haveShape && pbs != null)
  209. {
  210. ret = CreateGeomMeshOrHull(prim, shapeCallback);
  211. }
  212. return ret;
  213. }
  214. // return 'true' if this shape description does not include any cutting or twisting.
  215. public static bool PrimHasNoCuts(PrimitiveBaseShape pbs)
  216. {
  217. return pbs.ProfileBegin == 0 && pbs.ProfileEnd == 0
  218. && pbs.ProfileHollow == 0
  219. && pbs.PathTwist == 0 && pbs.PathTwistBegin == 0
  220. && pbs.PathBegin == 0 && pbs.PathEnd == 0
  221. && pbs.PathTaperX == 0 && pbs.PathTaperY == 0
  222. && pbs.PathScaleX == 100 && pbs.PathScaleY == 100
  223. && pbs.PathShearX == 0 && pbs.PathShearY == 0;
  224. }
  225. // return 'true' if the prim's shape was changed.
  226. private bool CreateGeomMeshOrHull(BSPhysObject prim, PhysicalDestructionCallback shapeCallback)
  227. {
  228. bool ret = false;
  229. // Note that if it's a native shape, the check for physical/non-physical is not
  230. // made. Native shapes work in either case.
  231. if (prim.IsPhysical && BSParam.ShouldUseHullsForPhysicalObjects)
  232. {
  233. // Use a simple, single mesh convex hull shape if the object is simple enough
  234. BSShape potentialHull = null;
  235. PrimitiveBaseShape pbs = prim.BaseShape;
  236. // Use a simple, one section convex shape for prims that are probably convex (no cuts or twists)
  237. if (BSParam.ShouldUseSingleConvexHullForPrims
  238. && pbs != null
  239. && !pbs.SculptEntry
  240. && PrimHasNoCuts(pbs)
  241. )
  242. {
  243. potentialHull = BSShapeConvexHull.GetReference(m_physicsScene, false /* forceRebuild */, prim);
  244. }
  245. // Use the GImpact shape if it is a prim that has some concaveness
  246. if (potentialHull == null
  247. && BSParam.ShouldUseGImpactShapeForPrims
  248. && pbs != null
  249. && !pbs.SculptEntry
  250. )
  251. {
  252. potentialHull = BSShapeGImpact.GetReference(m_physicsScene, false /* forceRebuild */, prim);
  253. }
  254. // If not any of the simple cases, just make a hull
  255. if (potentialHull == null)
  256. {
  257. potentialHull = BSShapeHull.GetReference(m_physicsScene, false /*forceRebuild*/, prim);
  258. }
  259. // If the current shape is not what is on the prim at the moment, time to change.
  260. if (!prim.PhysShape.HasPhysicalShape
  261. || potentialHull.ShapeType != prim.PhysShape.ShapeType
  262. || potentialHull.physShapeInfo.shapeKey != prim.PhysShape.physShapeInfo.shapeKey)
  263. {
  264. DereferenceExistingShape(prim, shapeCallback);
  265. prim.PhysShape = potentialHull;
  266. ret = true;
  267. }
  268. else
  269. {
  270. // The current shape on the prim is the correct one. We don't need the potential reference.
  271. potentialHull.Dereference(m_physicsScene);
  272. }
  273. if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,hull,shape={1}", prim.LocalID, prim.PhysShape);
  274. }
  275. else
  276. {
  277. // Non-physical objects should be just meshes.
  278. BSShape potentialMesh = BSShapeMesh.GetReference(m_physicsScene, false /*forceRebuild*/, prim);
  279. // If the current shape is not what is on the prim at the moment, time to change.
  280. if (!prim.PhysShape.HasPhysicalShape
  281. || potentialMesh.ShapeType != prim.PhysShape.ShapeType
  282. || potentialMesh.physShapeInfo.shapeKey != prim.PhysShape.physShapeInfo.shapeKey)
  283. {
  284. DereferenceExistingShape(prim, shapeCallback);
  285. prim.PhysShape = potentialMesh;
  286. ret = true;
  287. }
  288. else
  289. {
  290. // We don't need this reference to the mesh that is already being using.
  291. potentialMesh.Dereference(m_physicsScene);
  292. }
  293. if (DDetail) DetailLog("{0},BSShapeCollection.CreateGeom,mesh,shape={1}", prim.LocalID, prim.PhysShape);
  294. }
  295. return ret;
  296. }
  297. // Track another user of a body.
  298. // We presume the caller has allocated the body.
  299. // Bodies only have one user so the body is just put into the world if not already there.
  300. private void ReferenceBody(BulletBody body)
  301. {
  302. lock (m_collectionActivityLock)
  303. {
  304. if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,newBody,body={1}", body.ID, body);
  305. if (!m_physicsScene.PE.IsInWorld(m_physicsScene.World, body))
  306. {
  307. m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, body);
  308. if (DDetail) DetailLog("{0},BSShapeCollection.ReferenceBody,addedToWorld,ref={1}", body.ID, body);
  309. }
  310. }
  311. }
  312. // Release the usage of a body.
  313. // Called when releasing use of a BSBody. BSShape is handled separately.
  314. // Called in taint time.
  315. public void DereferenceBody(BulletBody body, PhysicalDestructionCallback bodyCallback )
  316. {
  317. if (!body.HasPhysicalBody)
  318. return;
  319. m_physicsScene.AssertInTaintTime("BSShapeCollection.DereferenceBody");
  320. lock (m_collectionActivityLock)
  321. {
  322. if (DDetail) DetailLog("{0},BSShapeCollection.DereferenceBody,DestroyingBody,body={1}", body.ID, body);
  323. // If the caller needs to know the old body is going away, pass the event up.
  324. if (bodyCallback != null)
  325. bodyCallback(body, null);
  326. // Removing an object not in the world is a NOOP
  327. m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, body);
  328. // Zero any reference to the shape so it is not freed when the body is deleted.
  329. m_physicsScene.PE.SetCollisionShape(m_physicsScene.World, body, null);
  330. m_physicsScene.PE.DestroyObject(m_physicsScene.World, body);
  331. }
  332. }
  333. // Create a body object in Bullet.
  334. // Updates prim.BSBody with the information about the new body if one is created.
  335. // Returns 'true' if an object was actually created.
  336. // Called at taint-time.
  337. private bool CreateBody(bool forceRebuild, BSPhysObject prim, BulletWorld sim, PhysicalDestructionCallback bodyCallback)
  338. {
  339. bool ret = false;
  340. // the mesh, hull or native shape must have already been created in Bullet
  341. bool mustRebuild = !prim.PhysBody.HasPhysicalBody;
  342. // If there is an existing body, verify it's of an acceptable type.
  343. // If not a solid object, body is a GhostObject. Otherwise a RigidBody.
  344. if (!mustRebuild)
  345. {
  346. CollisionObjectTypes bodyType = (CollisionObjectTypes)m_physicsScene.PE.GetBodyType(prim.PhysBody);
  347. if (prim.IsSolid && bodyType != CollisionObjectTypes.CO_RIGID_BODY
  348. || !prim.IsSolid && bodyType != CollisionObjectTypes.CO_GHOST_OBJECT)
  349. {
  350. // If the collisionObject is not the correct type for solidness, rebuild what's there
  351. mustRebuild = true;
  352. if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,forceRebuildBecauseChangingBodyType,bodyType={1}", prim.LocalID, bodyType);
  353. }
  354. }
  355. if (mustRebuild || forceRebuild)
  356. {
  357. // Free any old body
  358. DereferenceBody(prim.PhysBody, bodyCallback);
  359. BulletBody aBody;
  360. if (prim.IsSolid)
  361. {
  362. aBody = m_physicsScene.PE.CreateBodyFromShape(sim, prim.PhysShape.physShapeInfo, prim.LocalID, prim.RawPosition, prim.RawOrientation);
  363. if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,rigid,body={1}", prim.LocalID, aBody);
  364. }
  365. else
  366. {
  367. aBody = m_physicsScene.PE.CreateGhostFromShape(sim, prim.PhysShape.physShapeInfo, prim.LocalID, prim.RawPosition, prim.RawOrientation);
  368. if (DDetail) DetailLog("{0},BSShapeCollection.CreateBody,ghost,body={1}", prim.LocalID, aBody);
  369. }
  370. ReferenceBody(aBody);
  371. prim.PhysBody = aBody;
  372. ret = true;
  373. }
  374. return ret;
  375. }
  376. private void DetailLog(string msg, params Object[] args)
  377. {
  378. if (m_physicsScene.PhysicsLogging.Enabled)
  379. m_physicsScene.DetailLog(msg, args);
  380. }
  381. }
  382. }