private void UpdateTelemetry() { if (dataStream.Connected) { bool dataIsDirty = isTelemetryDataDirty; // lock the queues and flush their contents to our render data lock (receiver.LockObject) { while (receiver.ReceivedFrameSnapshots.Count > 0) { frameData.Frames.Add(receiver.ReceivedFrameSnapshots.Dequeue()); isTelemetryDataDirty = true; } while (receiver.ReceivedFrameStats.Count > 0) { frameData.FrameStats.Add(receiver.ReceivedFrameStats.Dequeue()); isTelemetryDataDirty = true; } while (receiver.ReceivedShapes.Count > 0) { PacketTranslator.CollectedFrameShapes collectedShapes = receiver.ReceivedShapes.Dequeue(); isTelemetryDataDirty = true; foreach (BaseShape addedShape in collectedShapes.Shapes) { switch (addedShape.ShapeType) { case ShapeType.eConvexHull: ConvexHullShape convexShape = (ConvexHullShape)addedShape; int shapeRenderHandle = GenerateMeshForConvexHull(convexShape); ShapeFrameIdPair pair = frameData.ShapeData.AddNewShape(collectedShapes.FrameId, convexShape); // store a binding for this mesh version shapeRenderMeshBindings.Add(pair, shapeRenderHandle); break; case ShapeType.eObb: case ShapeType.eSphere: case ShapeType.eCone: case ShapeType.eTetrahedron: default: frameData.ShapeData.AddNewShape(collectedShapes.FrameId, addedShape); break; } } } } if (dataIsDirty != isTelemetryDataDirty) { BuildAndSetApplicationTitleString(); } FramesAdded(); } }
public static void CreateConvexHull(ConvexHullShape shape, Mesh mesh) { ShapeHull hull = new ShapeHull(shape); hull.BuildHull(shape.Margin); List <UnityEngine.Vector3> verts = new List <UnityEngine.Vector3>(); List <int> tris = new List <int>(); //int vertexCount = hull.NumVertices; UIntArray indices = hull.Indices; Vector3Array points = hull.Vertices; for (int i = 0; i < indices.Count; i += 3) { verts.Add(points[(int)indices[i]].ToUnity()); verts.Add(points[(int)indices[i + 1]].ToUnity()); verts.Add(points[(int)indices[i + 2]].ToUnity()); tris.Add(i); tris.Add(i + 1); tris.Add(i + 2); } mesh.vertices = verts.ToArray(); mesh.triangles = tris.ToArray(); mesh.RecalculateBounds(); mesh.RecalculateNormals(); }
protected override void OnInitializePhysics() { CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); Broadphase = new DbvtBroadphase(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf); World.Gravity = new Vector3(0, -10, 0); CreateGround(); Vector3[] rotatingPoints = { new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1) }; _rotatingShape = new ConvexHullShape(rotatingPoints); _rotatingBody = LocalCreateRigidBody(0, _rotBodyPosition, _rotatingShape); _rotatingBody.CollisionFlags |= CollisionFlags.KinematicObject; _rotatingBody.ActivationState = ActivationState.DisableDeactivation; Vector3[] staticPoints = { new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(-1, -1, 0) }; _staticShape = new ConvexHullShape(staticPoints); _staticBody = LocalCreateRigidBody(0, _staticBodyPosition, _staticShape); }
/// <summary> /// Generates a convex hull collision mesh from the given original mesh. /// </summary> /// <param name="original"></param> /// <returns></returns> public static Mesh GenerateCollisionMesh(Mesh original, Vector3 offset = default(Vector3)) { ConvexHullShape tempShape = new ConvexHullShape(Array.ConvertAll(original.vertices, x => x.ToBullet()), original.vertices.Length); tempShape.Margin = 0f; ShapeHull shapeHull = new ShapeHull(tempShape); bool b = shapeHull.BuildHull(0f); Mesh collisionMesh = new Mesh(); Vector3[] vertices = new Vector3[shapeHull.NumVertices]; for (int i = 0; i < vertices.Length; i++) { vertices[i] = shapeHull.Vertices[i].ToUnity() - offset; } int[] triangles = new int[shapeHull.NumIndices]; for (int i = 0; i < triangles.Length; i++) { triangles[i] = (int)shapeHull.Indices[i]; } collisionMesh.vertices = vertices; collisionMesh.triangles = triangles; collisionMesh.RecalculateNormals(); collisionMesh.RecalculateBounds(); // TODO: Find a way to implement embedded margins. See https://www.bulletphysics.org/Bullet/phpBB3/viewtopic.php?f=9&t=2358 return(collisionMesh); }
public override void OnDrawGizmosSelected() { if (!drawGizmo) { return; } Gizmos.color = Color.yellow; CollisionShape shape = GetCollisionShape(); ConvexHullShape convexShape = shape as ConvexHullShape; Gizmos.matrix = transform.localToWorldMatrix * Matrix4x4.Scale(transform.lossyScale).inverse; if (convexShape != null) { //BulletSharp.Math.Matrix childShapeTransform = this.transform; //childShapeTransform.Invert(); //BulletSharp.Math.Matrix shapeTransform = childShapeTransform * this.transform.localToWorldMatrix.ToBullet(); int nbEdges = convexShape.NumEdges; for (int j = 0; j < nbEdges; j++) { BulletSharp.Math.Vector3 vertex1; BulletSharp.Math.Vector3 vertex2; convexShape.GetEdge(j, out vertex1, out vertex2); Vector3 vertexUnity1 = BSExtensionMethods2.ToUnity(vertex1); Vector3 vertexUnity2 = BSExtensionMethods2.ToUnity(vertex2); Gizmos.DrawLine(vertexUnity1, vertexUnity2); } } BvhTriangleMeshShape triangleShape = shape as BvhTriangleMeshShape; if (triangleShape != null) { DisplayTriangleCallback cb = new DisplayTriangleCallback(); triangleShape.MeshInterface.InternalProcessAllTriangles(cb, triangleShape.LocalAabbMin, triangleShape.LocalAabbMax); } }
private static void CreateHullGizmoMesh(ConvexHullShape shape, ref Mesh mesh) { if (mesh == null) { mesh = new Mesh(); } else { mesh.Clear(); } Vector3[] vertexBuffer; int[] triangleBuffer; using (ShapeHull hull = new ShapeHull(shape)) { hull.BuildHull(0.0f); vertexBuffer = hull.Vertices .Select(v => v.ToUnity()) .ToArray(); triangleBuffer = hull.Indices .Select(i => (int)i) .ToArray(); } MergeVertices(vertexBuffer, 0.05f); mesh.vertices = vertexBuffer; mesh.triangles = triangleBuffer; mesh.RecalculateBounds(); mesh.RecalculateNormals(); }
public static libTechCollisionShape FromVertices(IEnumerable <Vector3> Verts) { ConvexHullShape HullShape = new ConvexHullShape(Verts); HullShape.InitializePolyhedralFeatures(); return(new libTechCollisionShape(HullShape)); }
public DistanceDemoSimulation() { CollisionConfiguration = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConfiguration); Broadphase = new DbvtBroadphase(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConfiguration); CreateGround(); Vector3[] rotatingPoints = { new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1) }; _rotatingShape = new ConvexHullShape(rotatingPoints); _rotatingBody = PhysicsHelper.CreateStaticBody(_rotBodyPosition, _rotatingShape, World); _rotatingBody.CollisionFlags |= CollisionFlags.KinematicObject; _rotatingBody.ActivationState = ActivationState.DisableDeactivation; Vector3[] staticPoints = { new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1), new Vector3(0, 0, -1), new Vector3(-1, -1, 0) }; _staticShape = new ConvexHullShape(staticPoints); Matrix staticBodyPosition = Matrix.Translation(0, 5, 0); _staticBody = PhysicsHelper.CreateStaticBody(staticBodyPosition, _staticShape, World); }
public override void AddConvexVerticesCollider(AlignedVector3Array vertices, bool isEntity, Vector3 entityTargetLocation) { // perhaps we can do something special with entities (isEntity) // like adding a collision Triggering (as example) if (vertices.Count == 0) { return; } const float mass = 0.0f; //can use a shift Matrix startTransform = Matrix.Translation(0, -10.0f, 0); //this create an internal copy of the vertices for (int i = 0; i < vertices.Count; i++) { Vector3 v = vertices[i] * 0.5f; vertices[i] = new Vector3(v.X, v.Z * 0.75f, -v.Y); } CollisionShape shape = new ConvexHullShape(vertices); demo.CollisionShapes.Add(shape); demo.LocalCreateRigidBody(mass, startTransform, shape); }
public override void Draw(GameTime gameTime) { ConvexHullShape hullShape = body.Shape as ConvexHullShape; Matrix world = Conversion.ToXNAMatrix(body.Orientation); // RigidBody.Position gives you the position of the center of mass of the shape. // But this is not the center of our graphical represantion, use the // "shift" property of the more complex shapes to deal with this. world.Translation = Conversion.ToXNAVector(body.Position + JVector.Transform(hullShape.Shift, body.Orientation)); Matrix[] boneTransforms = new Matrix[model.Bones.Count]; model.CopyAbsoluteBoneTransformsTo(boneTransforms); foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.View = ((JitterDemo)Game).Camera.View; effect.EnableDefaultLighting(); effect.Projection = ((JitterDemo)Game).Camera.Projection; //effect.DiffuseColor = Color.Gray.ToVector3(); effect.World = boneTransforms[mesh.ParentBone.Index] * world; } mesh.Draw(); } base.Draw(gameTime); }
public void MakeModelPhysicsConvexHull(Model model) { GeometryMesh mesh = model.Batch.MeshSource as GeometryMesh; Geometry geometry = mesh.Geometry; var pointLocations = geometry.PointAttributes.Find <Vector3>("point_locations"); List <Vector3> positions = new List <Vector3>(); BoundingBox box = new BoundingBox(); for (int i = 0; i < geometry.Points.Count; ++i) { Point point = geometry.Points[i]; Vector3 p = pointLocations[point]; positions.Add(p); box.ExtendBy(p); } ConvexHullShape shape = new ConvexHullShape(positions); model.PhysicsShape = shape; /*System.Diagnostics.Trace.TraceInformation( * "ConvexHull" + " Shift = " + shape.Shift.ToString() + " BoundingBox = " + box.ToString() + );*/ }
public ConvexDecompositionDemoSimulation(bool enableSat) { _enableSat = enableSat; CollisionConfiguration = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConfiguration); Broadphase = new AxisSweep3(new Vector3(-10000, -10000, -10000), new Vector3(10000, 10000, 10000)); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConfiguration); CreateGround(); ManifoldPoint.ContactAdded += MyContactCallback; //CompoundCollisionAlgorithm.CompoundChildShapePairCallback = MyCompoundChildShapeCallback; string path = Path.Combine("data", "file.obj"); var wavefrontModel = WavefrontObj.Load(path); if (wavefrontModel.Indices.Count == 0) { return; } var localScaling = new Vector3(6, 6, 6); _triangleMesh = CreateTriangleMesh(wavefrontModel.Indices, wavefrontModel.Vertices, localScaling); // Convex hull approximation ConvexHullShape convexShape = CreateHullApproximation(_triangleMesh); float mass = 1.0f; PhysicsHelper.CreateBody(mass, Matrix.Translation(0, 2, 14), convexShape, World); // Non-moving body var objectOffset = new Vector3(10, 0, 0); const bool useQuantization = true; var concaveShape = new BvhTriangleMeshShape(_triangleMesh, useQuantization); PhysicsHelper.CreateStaticBody(Matrix.Translation(objectOffset), concaveShape, World); Hacd hacd = ComputeHacd(wavefrontModel); hacd.Save("output.wrl", false); var compoundShape = CreateCompoundShape(hacd, localScaling); mass = 10.0f; objectOffset = new Vector3(-10, 0, -6); var body2 = PhysicsHelper.CreateBody(mass, Matrix.Translation(objectOffset), compoundShape, World); body2.CollisionFlags |= CollisionFlags.CustomMaterialCallback; objectOffset.Z += 6; body2 = PhysicsHelper.CreateBody(mass, Matrix.Translation(objectOffset), compoundShape, World); body2.CollisionFlags |= CollisionFlags.CustomMaterialCallback; objectOffset.Z += 6; body2 = PhysicsHelper.CreateBody(mass, Matrix.Translation(objectOffset), compoundShape, World); body2.CollisionFlags |= CollisionFlags.CustomMaterialCallback; }
protected override void LoadContent() { model = Game.Content.Load <Model>("convexhull"); if (cvhs == null) { List <JVector> jvecs = new List <JVector>(); List <TriangleVertexIndices> indices = new List <TriangleVertexIndices>(); ExtractData(jvecs, indices, model); int[] convexHullIndices = JConvexHull.Build(jvecs, JConvexHull.Approximation.Level6); List <JVector> hullPoints = new List <JVector>(); for (int i = 0; i < convexHullIndices.Length; i++) { hullPoints.Add(jvecs[convexHullIndices[i]]); } cvhs = new ConvexHullShape(hullPoints); } body = new RigidBody(cvhs); body.Tag = BodyTag.DontDrawMe; }
/// <summary> /// Rescales a convex hull shape. /// </summary> /// <param name="shape">The shape.</param> /// <param name="scaleFactor">The scaling factor.</param> /// <returns>The new hull.</returns> public static ConvexHullShape Rescale(this ConvexHullShape shape, Vector3 scaleFactor) { ReadOnlyList <Vector3> verts = shape.Vertices; List <Vector3> newlist = new List <Vector3>(verts.Count); foreach (Vector3 vert in verts) { newlist.Add(vert * scaleFactor); } double len = scaleFactor.Length(); RawList <int> triangles = CommonResources.GetIntList(); ConvexHullHelper.GetConvexHull(newlist, triangles); InertiaHelper.ComputeShapeDistribution(newlist, triangles, out double volume, out Matrix3x3 volumeDistribution); ConvexShapeDescription csd = new ConvexShapeDescription() { CollisionMargin = shape.CollisionMargin, EntityShapeVolume = new BEPUphysics.CollisionShapes.EntityShapeVolumeDescription() { Volume = volume, VolumeDistribution = volumeDistribution }, MaximumRadius = shape.MaximumRadius * len, MinimumRadius = shape.MinimumRadius * len }; CommonResources.GiveBack(triangles); return(new ConvexHullShape(newlist, csd)); }
public static void CreateConvexHull(ConvexHullShape shape, Mesh mesh) { ShapeHull hull = new ShapeHull(shape); hull.BuildHull(shape.Margin); int vertexCount = hull.NumIndices; UIntArray indices = hull.Indices; Vector3Array points = hull.Vertices; UnityEngine.Vector3[] vertices = new UnityEngine.Vector3[vertexCount]; for (int i = 0; i < vertexCount; i++) { vertices[i] = points[(int)indices[i]].ToUnity(); } int[] tris = new int[indices.Count]; for (int i = 0; i < indices.Count; i++) { tris[i] = (int)indices[i]; } mesh.vertices = vertices; mesh.triangles = tris; mesh.RecalculateBounds(); mesh.RecalculateNormals(); }
public override CollisionShape GetCollisionShape() { if (collisionShapePtr == null) { /* * btShapeHull* hull = new btShapeHull(originalConvexShape); * btScalar margin = originalConvexShape->getMargin(); * hull->buildHull(margin); * btConvexHullShape* simplifiedConvexShape = new btConvexHullShape(hull->getVertexPointer(), hull->numVertices()); */ Vector3[] verts = hullMesh.vertices; //todo remove duplicate verts //todo use vertex reduction utility float[] points = new float[verts.Length * 3]; for (int i = 0; i < verts.Length; i++) { int idx = i * 3; points[idx] = verts[i].x; points[idx + 1] = verts[i].y; points[idx + 2] = verts[i].z; } collisionShapePtr = new ConvexHullShape(points); ((ConvexHullShape)collisionShapePtr).LocalScaling = m_localScaling.ToBullet(); } return(collisionShapePtr); }
public override void SetupFromMesh(Mesh mesh) { var triMesh = new TriangleMesh(); int i = 0; var vertices = mesh.Vertices; while (i < mesh.Indices.Length) { triMesh.AddTriangle( vertices[mesh.Indices[i++]], vertices[mesh.Indices[i++]], vertices[mesh.Indices[i++]] ); } var tempShape = new ConvexTriangleMeshShape(triMesh); using var tempHull = new ShapeHull(tempShape); tempHull.BuildHull(tempShape.Margin); collisionShape = new ConvexHullShape(tempHull.Vertices); }
public static Vector3[] CreateConvexHull(ConvexHullShape shape) { var hull = new ShapeHull(shape); hull.BuildHull(shape.Margin); int vertexCount = hull.NumIndices; UIntArray indices = hull.Indices; Vector3Array points = hull.Vertices; var vertices = new Vector3[vertexCount * 2]; int v = 0; for (int i = 0; i < vertexCount; i += 3) { Vector3 v0 = points[(int)indices[i]]; Vector3 v1 = points[(int)indices[i + 1]]; Vector3 v2 = points[(int)indices[i + 2]]; Vector3 v01 = v0 - v1; Vector3 v02 = v0 - v2; Vector3 normal = Vector3.Cross(v01, v02); normal.Normalize(); vertices[v++] = v0; vertices[v++] = normal; vertices[v++] = v1; vertices[v++] = normal; vertices[v++] = v2; vertices[v++] = normal; } return(vertices); }
private void constructPhysicsBody() { ConvexHullShape hull = new ConvexHullShape(importPhysicsHull()); hull.CollisionMargin = 0.6f; var bodies = new List <CompoundShapeEntry>() { new CompoundShapeEntry(hull, Vector3.Zero, 25f) }; physicsEntityBody = new CompoundBody(bodies, 60f); //body.CollisionInformation.LocalPosition = new Vector3(0, .5f, 0);//Moves center of gravity position to adjust stability. physicsEntityBody.IsAlwaysActive = true; //physicsBody.CenterOfMassOffset = new Vector3(0, 0f, 0);//Becareful with this as forces/impulses act from here including raycasts physicsEntityBody.LinearDamping = 0.5f;//As there is rarely friction must slow ship down every update physicsEntityBody.AngularDamping = 0.94f; physicsEntityBody.Material.KineticFriction = 2f; physicsEntityBody.PositionUpdateMode = PositionUpdateMode.Continuous; physicsEntityBody.CollisionInformation.Events.ContactCreated += new ContactCreatedEventHandler <EntityCollidable>(Events_InitialCollisionDetected); Physics.space.Add(physicsEntityBody); }
public ConvexHullShape GetConvexHull(float scale = 1.0f) { //if (CachedBvhTriangleMeshShape != null) return CachedBvhTriangleMeshShape; List <Vector3> vectors = GetRawVertexList(); var convex = new ConvexHullShape(vectors.ToArray()); return(convex); }
public override void Update(GameTime gameTime) { base.Update(gameTime); if (body.Shape is ConvexHullShape) { ConvexHullShape convexHullShape = body.Shape as ConvexHullShape; //((DrawingObject)parent).Center = -Helper.ToXNAVector(convexHullShape.Shift); } }
public void setPhysMesh(string pMeshName, JMatrix mOrientation) { pBoxList.Add(pMeshName); Mesh pboxMesh = gameWindow.meshLoader.getMesh(pMeshName); ConvexHullShape objShape = new ConvexHullShape(GenericMethods.FromOpenTKVecArToJVecList(pboxMesh.positionVboData)); setPhysMesh(objShape); }
Mesh CreateConvexHullShape(ConvexHullShape shape) { ShapeHull hull = new ShapeHull(shape); hull.BuildHull(shape.Margin); UIntArray hullIndices = hull.Indices; Vector3Array points = hull.Vertices; int vertexCount = hull.NumIndices; int faceCount = hull.NumTriangles; bool index32 = vertexCount > 65536; Mesh mesh = new Mesh(device, faceCount, vertexCount, MeshFlags.SystemMemory | (index32 ? MeshFlags.Use32Bit : 0), VertexFormat.Position | VertexFormat.Normal); SlimDX.DataStream indices = mesh.LockIndexBuffer(LockFlags.Discard); int i; if (index32) { for (i = 0; i < vertexCount; i++) { indices.Write(i); } } else { for (i = 0; i < vertexCount; i++) { indices.Write((short)i); } } mesh.UnlockIndexBuffer(); SlimDX.DataStream verts = mesh.LockVertexBuffer(LockFlags.Discard); Vector3 scale = Vector3.Multiply(shape.LocalScaling, 1.0f + shape.Margin); for (i = 0; i < vertexCount; i += 3) { verts.Write(Vector3.Modulate(points[(int)hullIndices[i]], scale)); verts.Position += 12; verts.Write(Vector3.Modulate(points[(int)hullIndices[i + 1]], scale)); verts.Position += 12; verts.Write(Vector3.Modulate(points[(int)hullIndices[i + 2]], scale)); verts.Position += 12; } mesh.UnlockVertexBuffer(); mesh.ComputeNormals(); shapes.Add(shape, mesh); return(mesh); }
protected override CollisionShape CreateShape() { ConvexHullShape shape = new ConvexHullShape(this.vertices); //BvhTriangleMeshShape bvh = new BvhTriangleMeshShape( //StridingMeshInterface smi = new StridingMeshInterface(); //TriangleIndexVertexArray tiv = new TriangleIndexVertexArray( //StridingMeshInterface return(shape); }
/// <summary> /// Removes a <see cref="ConvexHullShape"/> from the multi hull shape. /// </summary> /// <param name="hullShape"></param> public void RemoveHullShape(ConvexHullShape hullShape) { if (!hullShapes.Contains(hullShape)) { return; } hullShapes.Remove(hullShape); compoundShape.RemoveChildShape(hullShape); }
/// <summary> /// Adds a <see cref="ConvexHullShape"/> to the multi hull shape. /// </summary> /// <param name="hullShape"></param> /// <param name="offset"></param> public void AddHullShape(ConvexHullShape hullShape, BulletSharp.Math.Matrix offset) { if (hullShapes.Contains(hullShape)) { return; } hullShapes.Add(hullShape); compoundShape.AddChildShape(offset, hullShape); }
void IConstructable.Construct(IDictionary <string, string> param) { var type = param["type"]; switch (type) { case "trimesh": var physData = ResourceFactory.LoadAsset <PhysicsData>(param["physData"]); Shape shape = new TriangleMeshShape(physData.Octree); Body = new RigidBody(shape) { Material = { Restitution = 0f, KineticFriction = 0f } }; break; case "hull": physData = ResourceFactory.LoadAsset <PhysicsData>(param["physData"]); shape = new ConvexHullShape(physData.Vertices); Body = new RigidBody(shape); break; case "sphere": shape = new SphereShape(float.Parse(param["radius"], CultureInfo.InvariantCulture)); Body = new RigidBody(shape); break; case "box": var d = param["size"].ConvertToVector(); var offset = param.Get("offset", "0;0;0").ConvertToVector(); shape = new BoxShape(2.0f * d.ToJVector()); Body = new RigidBody(shape) { Position = offset.ToJVector() }; break; case "capsule": var height = float.Parse(param["height"], CultureInfo.InvariantCulture); var radius = float.Parse(param["radius"], CultureInfo.InvariantCulture); shape = new CapsuleShape(height, radius); Body = new RigidBody(shape) { Position = JVector.Backward * (0.5f * height + radius), Orientation = JMatrix.CreateRotationX(MathHelper.PiOver2) }; break; default: throw new Exception("Unknown shape: " + type); } Body.IsStatic = Convert.ToBoolean(param.Get("static", "false")); Body.Material.KineticFriction = 0.5f; Body.Material.StaticFriction = 0.5f; Body.Material.Restitution = 0.5f; }
public MeshCollider(Mesh mesh) : base() { Mesh = mesh; bepu.Vector3[] vertices = new bepu.Vector3[Mesh.vertices.Length]; for (int i = 0; i < Mesh.vertices.Length; i++) { vertices[i] = Physics.VectorT2B(Mesh.vertices[i].Xyz); } shape = new ConvexHullShape(vertices); }
protected override void OnInitializePhysics() { ManifoldPoint.ContactAdded += MyContactCallback; SetupEmptyDynamicsWorld(); //CompoundCollisionAlgorithm.CompoundChildShapePairCallback = MyCompoundChildShapeCallback; string path = Path.Combine("data", "file.obj"); var wavefrontModel = WavefrontObj.Load(path); if (wavefrontModel.Indices.Count == 0) { return; } var localScaling = new Vector3(6, 6, 6); _triangleMesh = CreateTriangleMesh(wavefrontModel.Indices, wavefrontModel.Vertices, localScaling); // Convex hull approximation ConvexHullShape convexShape = CreateHullApproximation(_triangleMesh); float mass = 1.0f; LocalCreateRigidBody(mass, Matrix.Translation(0, 2, 14), convexShape); // Non-moving body var objectOffset = new Vector3(10, 0, 0); const bool useQuantization = true; var concaveShape = new BvhTriangleMeshShape(_triangleMesh, useQuantization); LocalCreateRigidBody(0, Matrix.Translation(objectOffset), concaveShape); Hacd hacd = ComputeHacd(wavefrontModel); hacd.Save("output.wrl", false); var compoundShape = CreateCompoundShape(hacd, localScaling); mass = 10.0f; objectOffset = new Vector3(-10, 0, -6); var body2 = LocalCreateRigidBody(mass, Matrix.Translation(objectOffset), compoundShape); body2.CollisionFlags |= CollisionFlags.CustomMaterialCallback; objectOffset.Z += 6; body2 = LocalCreateRigidBody(mass, Matrix.Translation(objectOffset), compoundShape); body2.CollisionFlags |= CollisionFlags.CustomMaterialCallback; objectOffset.Z += 6; body2 = LocalCreateRigidBody(mass, Matrix.Translation(objectOffset), compoundShape); body2.CollisionFlags |= CollisionFlags.CustomMaterialCallback; }
public ConvexHullAdapter(Game game, BaseObject parent, World physicsWorld, Model drawingModel, RigidBody body, bool hasCharacterController = false) : base(game, parent, physicsWorld, body) { this.drawingModel = drawingModel; ConvexHullShape shape = ConvexHullHelper.BuildConvexHullShape(drawingModel, parent.Scale); body.Shape = shape; //((DrawingObject)parent).Center = -Helper.ToXNAVector(shape.Shift); }
public IConvexHullShapeImp AddConvexHullShape() { var btConvexHullShape = new ConvexHullShape(); BtCollisionShapes.Add(btConvexHullShape); var retval = new ConvexHullShapeImp(); retval.BtConvexHullShape = btConvexHullShape; btConvexHullShape.UserObject = retval; return retval; }
public IConvexHullShapeImp AddConvexHullShape(float3[] points, bool optimized) { var btPoints = new Vector3[points.Count()]; for (int i = 0; i < btPoints.Count(); i++) { var point = Translater.Float3ToBtVector3(points[i]); btPoints[i] = point; } var btConvexHullShape = new ConvexHullShape(btPoints); //btConvexHullShape.LocalScaling = new Vector3(3, 3, 3); if (optimized == true) { var btShapeHull = new ShapeHull(btConvexHullShape); var margin = btConvexHullShape.Margin; btShapeHull.BuildHull(margin); ConvexHullShape simplifiedConvexShape = new ConvexHullShape(btShapeHull.Vertices); BtCollisionShapes.Add(simplifiedConvexShape); var retval = new ConvexHullShapeImp(); retval.BtConvexHullShape = simplifiedConvexShape; simplifiedConvexShape.UserObject = retval; return retval; } else { BtCollisionShapes.Add(btConvexHullShape); var retval = new ConvexHullShapeImp(); retval.BtConvexHullShape = btConvexHullShape; btConvexHullShape.UserObject = retval; return retval; } }
/*private void MyTickCallBack(ManifoldPoint cp, CollisionObjectWrapper colobj0wrap, int partid0, int index0, CollisionObjectWrapper colobj1wrap, int partid1, int index1) { Debug.WriteLine("MyTickCallBack"); int numManifolds = BtWorld.Dispatcher.NumManifolds; RigidBodyImp myRb; //Debug.WriteLine("numManifolds: " + numManifolds); for (int i = 0; i < numManifolds; i++) { PersistentManifold contactManifold = BtWorld.Dispatcher.GetManifoldByIndexInternal(i); int numContacts = contactManifold.NumContacts; if (numContacts > 0) { CollisionObject obA = (CollisionObject) contactManifold.Body0; CollisionObject obB = (CollisionObject) contactManifold.Body1; // Debug.WriteLine(numContacts); var pnA = obA.UserObject; for (int j = 0; j < numContacts; j++) { ManifoldPoint pt = contactManifold.GetContactPoint(j); } } } }*/ public IRigidBodyImp AddRigidBody(float mass, float3 worldTransform, float3 orientation, ICollisionShapeImp colShape/*, float3 intertia*/) { // Use bullet to do what needs to be done: var btMatrix = Matrix.RotationX(orientation.x) * Matrix.RotationY(orientation.y) * Matrix.RotationZ(orientation.z) * Matrix.Translation(worldTransform.x, worldTransform.y, worldTransform.z); var btMotionState = new DefaultMotionState(btMatrix); var shapeType = colShape.GetType().ToString(); CollisionShape btColShape; var isStatic = false; switch (shapeType) { //Primitives case "Fusee.Engine.BoxShapeImp": var box = (BoxShapeImp) colShape; var btBoxHalfExtents = Translater.Float3ToBtVector3(box.HalfExtents); btColShape = new BoxShape(btBoxHalfExtents); break; case "Fusee.Engine.CapsuleShapeImp": var capsule = (CapsuleShapeImp) colShape; btColShape = new CapsuleShape(capsule.Radius, capsule.HalfHeight); break; case "Fusee.Engine.ConeShapeImp": var cone = (ConeShapeImp) colShape; btColShape = new ConeShape(cone.Radius, cone.Height); break; case "Fusee.Engine.CylinderShapeImp": var cylinider = (CylinderShapeImp) colShape; var btCylinderHalfExtents = Translater.Float3ToBtVector3(cylinider.HalfExtents); btColShape = new CylinderShape(btCylinderHalfExtents); break; case "Fusee.Engine.MultiSphereShapeImp": var multiSphere = (MultiSphereShapeImp) colShape; var btPositions = new Vector3[multiSphere.SphereCount]; var btRadi = new float[multiSphere.SphereCount]; for (int i = 0; i < multiSphere.SphereCount; i++) { var pos = Translater.Float3ToBtVector3(multiSphere.GetSpherePosition(i)); btPositions[i] = pos; btRadi[i] = multiSphere.GetSphereRadius(i); } btColShape = new MultiSphereShape(btPositions, btRadi); break; case "Fusee.Engine.SphereShapeImp": var sphere = (SphereShapeImp) colShape; var btRadius = sphere.Radius; btColShape = new SphereShape(btRadius); break; //Misc case "Fusee.Engine.CompoundShapeImp": var compShape = (CompoundShapeImp) colShape; btColShape = new CompoundShape(true); btColShape = compShape.BtCompoundShape; break; case "Fusee.Engine.EmptyShapeImp": btColShape = new EmptyShape(); break; //Meshes case "Fusee.Engine.ConvexHullShapeImp": var convHull = (ConvexHullShapeImp) colShape; var btPoints= new Vector3[convHull.GetNumPoints()]; for (int i = 0; i < convHull.GetNumPoints(); i++) { var point = convHull.GetScaledPoint(i); btPoints[i] = Translater.Float3ToBtVector3(point); } btColShape = new ConvexHullShape(btPoints); //btColShape.LocalScaling = new Vector3(3,3,3); break; case "Fusee.Engine.StaticPlaneShapeImp": var staticPlane = (StaticPlaneShapeImp) colShape; Debug.WriteLine("staticplane: " + staticPlane.Margin); var btNormal = Translater.Float3ToBtVector3(staticPlane.PlaneNormal); btColShape = new StaticPlaneShape(btNormal, staticPlane.PlaneConstant); isStatic = true; //btColShape.Margin = 0.04f; //Debug.WriteLine("btColshape" + btColShape.Margin); break; case "Fusee.Engine.GImpactMeshShapeImp": var gImpMesh = (GImpactMeshShapeImp)colShape; gImpMesh.BtGImpactMeshShape.UpdateBound(); var btGimp = new GImpactMeshShape(gImpMesh.BtGImpactMeshShape.MeshInterface); btGimp.UpdateBound(); btColShape = btGimp; break; //Default default: Debug.WriteLine("defaultImp"); btColShape = new EmptyShape(); break; } var btLocalInertia = btColShape.CalculateLocalInertia(mass); // btLocalInertia *= (10.0f*10); RigidBodyConstructionInfo btRbcInfo = new RigidBodyConstructionInfo(mass, btMotionState, btColShape, btLocalInertia); var btRigidBody = new RigidBody(btRbcInfo); btRigidBody.Restitution = 0.2f; btRigidBody.Friction = 0.2f; btRigidBody.CollisionFlags = CollisionFlags.CustomMaterialCallback; BtWorld.AddRigidBody(btRigidBody); btRbcInfo.Dispose(); var retval = new RigidBodyImp(); retval._rbi = btRigidBody; btRigidBody.UserObject = retval; return retval; }