public override void ShootBox(Vector3 camPos, Vector3 destination) { if (World != null) { const float mass = 1.0f; if (shootBoxShape == null) { shootBoxShape = new BoxShape(1.0f); shootBoxShape.InitializePolyhedralFeatures(); } RigidBody body = LocalCreateRigidBody(mass, Matrix.Translation(camPos), shootBoxShape); body.LinearFactor = new Vector3(1, 1, 1); //body->setRestitution(1); Vector3 linVel = destination - camPos; linVel.Normalize(); body.LinearVelocity = linVel * shootBoxInitialSpeed; body.AngularVelocity = Vector3.Zero; body.ContactProcessingThreshold = 1e30f; // when using m_ccdMode, disable regular CCD if (ccdMode) { body.CcdMotionThreshold = 0.0001f; body.CcdSweptSphereRadius = 0.4f; } } }
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); // ground CollisionShape groundShape = new BoxShape(50, 1, 50); CollisionShapes.Add(groundShape); CollisionObject ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape); ground.UserObject = "Ground"; // Objects //colShape = new BoxShape(1); Vector3[] points0 = { new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1) }; Vector3[] points1 = { 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) }; colShape0 = new ConvexHullShape(points0); colShape1 = new ConvexHullShape(points1); CollisionShapes.Add(colShape0); CollisionShapes.Add(colShape1); body2 = LocalCreateRigidBody(0, body2Position, colShape1); rotBody = LocalCreateRigidBody(0, rotBodyPosition, colShape0); rotBody.CollisionFlags |= CollisionFlags.KinematicObject; rotBody.ActivationState = ActivationState.DisableDeactivation; }
/* void MyContactCallback(object sender, ContactAddedEventArgs e) { if (e.CollisionObject0Wrapper.CollisionObject.CollisionShape.ShapeType == BroadphaseNativeType.CompoundShape) { CompoundShape compound = e.CollisionObject0Wrapper.CollisionObject.CollisionShape as CompoundShape; CollisionShape childShape = compound.GetChildShape(e.Index0); } if (e.CollisionObject1Wrapper.CollisionObject.CollisionShape.ShapeType == BroadphaseNativeType.CompoundShape) { CompoundShape compound = e.CollisionObject1Wrapper.CollisionObject.CollisionShape as CompoundShape; CollisionShape childShape = compound.GetChildShape(e.Index1); } e.IsContactModified = true; } */ public void SetupEmptyDynamicsWorld() { // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); CompoundCollisionAlgorithm.CompoundChildShapePairCallback = MyCompoundChildShapeCallback; convexDecompositionObjectOffset = new Vector3(10, 0, 0); Broadphase = new AxisSweep3(new Vector3(-10000, -10000, -10000), new Vector3(10000, 10000, 10000)); //Broadphase = new SimpleBroadphase(); Solver = new SequentialImpulseConstraintSolver(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf); // create the ground CollisionShape groundShape = new BoxShape(30, 2, 30); CollisionShapes.Add(groundShape); CollisionObject ground = LocalCreateRigidBody(0, Matrix.Translation(0, -4.5f, 0), groundShape); ground.UserObject = "Ground"; // create a few dynamic rigidbodies float mass = 1.0f; CollisionShape colShape = new BoxShape(1); CollisionShapes.Add(colShape); Vector3 localInertia = colShape.CalculateLocalInertia(mass); }
public Physics() { // collision configuration contains default setup for memory, collision setup collisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(collisionConf); Broadphase = new DbvtBroadphase(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, collisionConf); World.Gravity = new Vector3(0, -10, 0); CollisionShapes = new List<CollisionShape>(); // create the ground CollisionShape groundShape = new BoxShape(50, 1, 50); CollisionShapes.Add(groundShape); CollisionObject ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape); ground.UserObject = "Ground"; // create a few dynamic rigidbodies float mass = 1.0f; CollisionShape colShape = new BoxShape(1); CollisionShapes.Add(colShape); Vector3 localInertia = colShape.CalculateLocalInertia(mass); float start_x = StartPosX - ArraySizeX / 2; float start_y = StartPosY; float start_z = StartPosZ - ArraySizeZ / 2; int k, i, j; for (k = 0; k < ArraySizeY; k++) { for (i = 0; i < ArraySizeX; i++) { for (j = 0; j < ArraySizeZ; j++) { Matrix startTransform = Matrix.CreateTranslation( new Vector3( 2*i + start_x, 2*k + start_y, 2*j + start_z ) ); // using motionstate is recommended, it provides interpolation capabilities // and only synchronizes 'active' objects DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBodyConstructionInfo rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia); RigidBody body = new RigidBody(rbInfo); // make it drop from a height body.Translate(new Vector3(0, 20, 0)); World.AddRigidBody(body); } } } }
/// <summary> /// Constructs a new plane primitive, with the specified size. /// </summary> public PlanePrimitive(Renderer Renderer, float width, float length, int tessellationU, int tessellationV) { this.Renderer = Renderer; Vector3 normal = new Vector3(0, 1, 0); CollisionShape = new BoxShape(new Vector3(width / 2, 0.001f, length / 2)); for (int v = 0; v < tessellationV+1; v++) { for (int u = 0; u < tessellationU+1; u++) { GeometryData.AddVertex(new Vector3((((float)u / (float)tessellationU) * width) - (width / 2), 0, (((float)v / (float)tessellationV) * length) - (length / 2)), normal, new Vector2(((float)width / (float)tessellationU) * u, ((float)length / (float)tessellationV) * v)); } } for (int v = 0; v < tessellationV - 0; v++) { for (int u = 0; u < tessellationU - 0; u++) { GeometryData.AddIndex(u + 0 + ((tessellationU + 1) * v)); GeometryData.AddIndex(u + 1 + ((tessellationU + 1) * v)); GeometryData.AddIndex(u + 0 + tessellationU + 1 + ((tessellationU + 1) * v)); GeometryData.AddIndex(u + 0 + tessellationU + 1 + ((tessellationU + 1) * v)); GeometryData.AddIndex(u + 1 + ((tessellationU + 1) * v)); GeometryData.AddIndex(u + 1 + tessellationU + 1 + ((tessellationU + 1) * v)); } } InitializePrimitive(); }
protected override void OnInitializePhysics() { BoxShape boxA = new BoxShape(new Vector3(1, 1, 1)); boxA.Margin = 0; BoxShape boxB = new BoxShape(new Vector3(0.5f, 0.5f, 0.5f)); boxB.Margin = 0; objects[0] = new CollisionObject(); objects[1] = new CollisionObject(); objects[0].CollisionShape = boxA; objects[1].CollisionShape = boxB; // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); Broadphase = new AxisSweep3(new Vector3(-1000, -1000, -1000), new Vector3(1000, 1000, 1000)); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConf); World.Gravity = new Vector3(0, -10, 0); IsDebugDrawEnabled = true; //World.AddCollisionObject(objects[0]); World.AddCollisionObject(objects[1]); Quaternion rotA = new Quaternion(0.739f, -0.204f, 0.587f, 0.257f); rotA.Normalize(); objects[0].WorldTransform = Matrix.RotationQuaternion(rotA) * Matrix.Translation(0, 3, 0); objects[1].WorldTransform = Matrix.Translation(0, 4.248f, 0); }
private void AddVertexGraph(VertexGraph graph) { Individual = graph.Vertices.Select(vertex => { var mass = 10000; var motionState = new DefaultMotionState(); var collisionShape = new BoxShape(1); var info = new RigidBodyConstructionInfo(mass, motionState, collisionShape); var rigidBody = new VertexBoundRigidBody(vertex, info); return rigidBody; }).ToList(); foreach (var body in Individual) { // Select the 3 nearest vertices, excluding this one var nearest = Individual.OrderBy(a => a.Binding.DistanceTo(body.Binding)) .Where(a => a != body) .Take(3); foreach (var other in nearest) { // TODO: What are these matrices supposed to be? var frameInA = body.MotionState.WorldTransform; var frameInB = other.MotionState.WorldTransform; // TODO: How do you specify the spring's springiness? var constraint = new Generic6DofSpringConstraint(body, other, frameInA, frameInB, true); // TODO: Now how do I apply this to the bodies? body.AddConstraintRef(constraint); other.AddConstraintRef(constraint); } } }
public static Vector3[] CreateBox(BoxShape shape) { Vector3 size = shape.HalfExtentsWithMargin; Vector3[] vertices = new Vector3[36 * 2]; Vector3 normal; int v = 0; for (int j = 0; j < 3; j++) { for (int i = 1; i != -3; i -= 2) { normal = GetVectorByAxis(0, i, 0, j); vertices[v++] = GetVectorByAxis(i, i, i, j) * size; vertices[v++] = normal; vertices[v++] = GetVectorByAxis(1, i, -1, j) * size; vertices[v++] = normal; vertices[v++] = GetVectorByAxis(-1, i, 1, j) * size; vertices[v++] = normal; vertices[v++] = GetVectorByAxis(-i, i, -i, j) * size; vertices[v++] = normal; vertices[v++] = GetVectorByAxis(-1, i, 1, j) * size; vertices[v++] = normal; vertices[v++] = GetVectorByAxis(1, i, -1, j) * size; vertices[v++] = normal; } } return vertices; }
public override CollisionShape GetCollisionShape() { if (collisionShapePtr == null) { collisionShapePtr = new BoxShape(extents.ToBullet()); } return collisionShapePtr; }
public ConvexcastBatch(float ray_length, float z, float min_y = -1000, float max_y = 10) { boxShapeHalfExtents = new Vector3(1.0f, 1.0f, 1.0f); boxShape = new BoxShape(boxShapeHalfExtents); frame_counter = 0; ms = 0; max_ms = 0; min_ms = 9999; sum_ms_samples = 0; sum_ms = 0; dx = 10.0f; min_x = -40; max_x = 20; this.min_y = min_y; this.max_y = max_y; sign = 1.0f; const float dalpha = 4 * (float)Math.PI / NUMRAYS_IN_BAR; for (int i = 0; i < NUMRAYS_IN_BAR; i++) { float alpha = dalpha * i; // rotate around by alpha degrees y Matrix tr = Matrix.RotationQuaternion(Quaternion.RotationAxis(new Vector3(0.0f, 1.0f, 0.0f), alpha)); direction[i] = new Vector3(1.0f, 0.0f, 0.0f); direction[i] = Vector3.TransformCoordinate(direction[i], tr); source[i] = new Vector3(min_x, max_y, z); dest[i] = source[i] + direction[i] * ray_length; dest[i][1] = min_y; normal[i] = new Vector3(1.0f, 0.0f, 0.0f); } }
public ConvexcastBatch(bool unused, float ray_length, float min_z, float max_z, float min_y, float max_y) { boxShapeHalfExtents = new Vector3(1.0f, 1.0f, 1.0f); boxShape = new BoxShape(boxShapeHalfExtents); frame_counter = 0; ms = 0; max_ms = 0; min_ms = 9999; sum_ms_samples = 0; sum_ms = 0; dx = 10.0f; min_x = -40; max_x = 20; this.min_y = min_y; this.max_y = max_y; sign = 1.0f; //const float dalpha = 4 * (float)Math.PI / NUMRAYS_IN_BAR; for (int i = 0; i < NUMRAYS_IN_BAR; i++) { float z = (max_z - min_z) / NUMRAYS_IN_BAR * i + min_z; source[i] = new Vector3(min_x, max_y, z); dest[i] = new Vector3(min_x + ray_length, min_y, z); normal[i] = new Vector3(1.0f, 0.0f, 0.0f); } }
protected override void OnInitializePhysics() { // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); Vector3 worldAabbMin = new Vector3(-10000, -10000, -10000); Vector3 worldAabbMax = new Vector3(10000, 10000, 10000); Broadphase = new AxisSweep3(worldAabbMin, worldAabbMax); Solver = new SequentialImpulseConstraintSolver(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf); World.Gravity = new Vector3(0, -10, 0); World.SetInternalTickCallback(MotorPreTickCallback, this, true); // create the ground CollisionShape groundShape = new BoxShape(200, 10, 200); CollisionShapes.Add(groundShape); CollisionObject ground = LocalCreateRigidBody(0, Matrix.Translation(0, -10, 0), groundShape); ground.UserObject = "Ground"; fCyclePeriod = 2000.0f; fMuscleStrength = 0.5f; m_Time = 0; SpawnTestRig(new Vector3(1, 0.5f, 0), false); SpawnTestRig(new Vector3(-2, 0.5f, 0), true); }
Mesh CreateBoxShape(BoxShape shape) { Vector3 size = shape.HalfExtentsWithMargin; Mesh mesh = Mesh.CreateBox(device, size.X * 2, size.Y * 2, size.Z * 2); shapes.Add(shape, mesh); return mesh; }
/// <summary> /// Constructs a new box primitive, with the specified dimensions. /// </summary> public BoxPrimitive(Renderer Renderer, Vector3 dimensions) { this.Renderer = Renderer; this.Dimensions = dimensions; CollisionShape = new BoxShape(new Vector3(dimensions.X / 2, dimensions.Y / 2, dimensions.Z / 2)); GeometryData = GenerateGeometry(); }
protected override void OnInitializePhysics() { // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); Broadphase = new AxisSweep3(new Vector3(-10000, -10000, -10000), new Vector3(10000, 10000, 10000)); Solver = new SequentialImpulseConstraintSolver(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf); World.Gravity = new Vector3(0, -10, 0); //World.DispatchInfo.UseConvexConservativeDistanceUtil = true; //World.DispatchInfo.ConvexConservativeDistanceThreshold = 0.01f; // Setup a big ground box CollisionShape groundShape = new BoxShape(100, 10, 100); CollisionShapes.Add(groundShape); Matrix groundTransform = Matrix.Translation(0, -10, 0); RigidBody ground = LocalCreateRigidBody(0, groundTransform, groundShape); ground.UserObject = "Ground"; // Spawn one ragdoll SpawnRagdoll(new Vector3(1, 0.5f, 0)); SpawnRagdoll(new Vector3(-1, 0.5f, 0)); }
public override CollisionShape GetCollisionShape() { if (collisionShapePtr == null) { collisionShapePtr = new BoxShape(extents.ToBullet()); ((BoxShape)collisionShapePtr).LocalScaling = m_localScaling.ToBullet(); } return collisionShapePtr; }
/// <summary> /// Starts the component. /// </summary> protected override void OnStart(GameTime time) { this.boxShape = new BulletSharp.BoxShape( 0.5f * this.Width, 0.5f * this.Height, 0.5f * this.Length); this.boxShape.UserObject = this; }
public ConvexcastBatch() { boxShape = new BoxShape(0); ms = 0; max_ms = 0; min_ms = 9999; sum_ms_samples = 0; sum_ms = 0; }
public Physics() { CLStuff.InitCL(); cloths = new Cloth[numFlags]; for (int flagIndex = 0; flagIndex < numFlags; ++flagIndex) { cloths[flagIndex] = new Cloth(); cloths[flagIndex].CreateBuffers(clothWidth, clothHeight); } gSolver = new OpenCLSoftBodySolver(CLStuff.commandQueue, CLStuff.cxMainContext); softBodyOutput = new SoftBodySolverOutputCLToCpu(); // collision configuration contains default setup for memory, collision setup CollisionConf = new SoftBodyRigidBodyCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); Broadphase = new DbvtBroadphase(); Solver = new SequentialImpulseConstraintSolver(); World = new SoftRigidDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf, gSolver); World.Gravity = new Vector3(0, -10, 0); // create the ground CollisionShape groundShape = new BoxShape(50, 50, 50); CollisionShapes.Add(groundShape); CollisionObject ground = LocalCreateRigidBody(0, Matrix.Translation(0, -60, 0), groundShape); ground.UserObject = "Ground"; SoftWorld.WorldInfo.AirDensity = 1.2f; SoftWorld.WorldInfo.WaterDensity = 0; SoftWorld.WorldInfo.WaterOffset = 0; SoftWorld.WorldInfo.WaterNormal = Vector3.Zero; SoftWorld.WorldInfo.Gravity = new Vector3(0, -10, 0); CreateFlag(clothWidth, clothHeight, out flags); // Create output buffer descriptions for ecah flag // These describe where the simulation should send output data to for (int flagIndex = 0; flagIndex < flags.Count; ++flagIndex) { // flags[flagIndex].WindVelocity = new Vector3(0, 0, 15.0f); // In this case we have a DX11 output buffer with a vertex at index 0, 8, 16 and so on as well as a normal at 3, 11, 19 etc. // Copies will be performed GPU-side directly into the output buffer CpuVertexBufferDescriptor vertexBufferDescriptor = new CpuVertexBufferDescriptor(cloths[flagIndex].CpuBuffer, 0, 8, 3, 8); cloths[flagIndex].VertexBufferDescriptor = vertexBufferDescriptor; } gSolver.Optimize(SoftWorld.SoftBodyArray); World.StepSimulation(1.0f / 60.0f, 0); }
public static TriggerRegion CreateBoxTriggerRegion(string name, TriggerReportEvent trh, Vector3 dimensions, Vector3 position, Quaternion orientation) { var csm = LKernel.GetG<CollisionShapeManager>(); CollisionShape shape; if (!csm.TryGetShape(name, out shape)) { shape = new BoxShape(dimensions); csm.RegisterShape(name, shape); } var tr = new TriggerRegion(name, position, orientation, shape); tr.OnTrigger += trh; AddToDispose(tr, trh); return tr; }
static void TestAlignment() { const float mass = 1.0f; Vector3WriteTest vTest = new Vector3WriteTest(); vTest.Value1 = 2.0f; vTest.Value2 = 3.0f; using (BoxShape shape = new BoxShape(1)) { shape.CalculateLocalInertia(mass, out vTest.Vector); } if (vTest.Value1 != 2.0f || vTest.Value2 != 3.0f) { Console.WriteLine("Vector3 value was overwritten with padding!"); } }
/* void MyContactCallback(object sender, ContactAddedEventArgs e) { if (e.CollisionObject0Wrapper.CollisionObject.CollisionShape.ShapeType == BroadphaseNativeType.CompoundShape) { CompoundShape compound = e.CollisionObject0Wrapper.CollisionObject.CollisionShape as CompoundShape; CollisionShape childShape = compound.GetChildShape(e.Index0); } if (e.CollisionObject1Wrapper.CollisionObject.CollisionShape.ShapeType == BroadphaseNativeType.CompoundShape) { CompoundShape compound = e.CollisionObject1Wrapper.CollisionObject.CollisionShape as CompoundShape; CollisionShape childShape = compound.GetChildShape(e.Index1); } e.IsContactModified = true; } */ public void SetupEmptyDynamicsWorld() { // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); Broadphase = new AxisSweep3(new Vector3(-10000, -10000, -10000), new Vector3(10000, 10000, 10000)); Solver = new SequentialImpulseConstraintSolver(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf); // create the ground CollisionShape groundShape = new BoxShape(30, 2, 30); CollisionShapes.Add(groundShape); CollisionObject ground = LocalCreateRigidBody(0, Matrix.Translation(0, -4.5f, 0), groundShape); ground.UserObject = "Ground"; }
public PhysicsConvexSweepTestItem(Matrix4 from, Matrix4 to, int collisionFilterGroup, int collisionFilterMask, ModeEnum mode, Box box) { this.originalFrom = from; this.originalTo = to; this.CollisionFilterGroup = collisionFilterGroup; this.CollisionFilterMask = collisionFilterMask; this.Mode = mode; Matrix4 offset = new Matrix4(box.Axis, box.Center); transformedFrom = originalFrom * offset; transformedTo = originalTo * offset; Shape = new BulletSharp.BoxShape(BulletPhysicsUtility.Convert(box.Extents)); ShapeAutoDispose = true; }
public Physics() { CollisionConfiguration collisionConf = new DefaultCollisionConfiguration(); CollisionDispatcher dispatcher = new CollisionDispatcher(collisionConf); World = new DiscreteDynamicsWorld(dispatcher, new DbvtBroadphase(), null, collisionConf); World.Gravity = new Vector3(0, -10, 0); // create the ground CollisionShape groundShape = new BoxShape(50, 1, 50); CollisionObject ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape); ground.UserObject = "Ground"; // create a box CollisionShape boxShape = new BoxShape(1); LocalCreateRigidBody(1.0f, Matrix.Translation(0, 20, 0), boxShape); }
public void SetUp() { conf = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(conf); broadphase = new AxisSweep3(new Vector3(-1000, -1000, -1000), new Vector3(1000, 1000, 1000)); world = new DiscreteDynamicsWorld(dispatcher, broadphase, null, conf); broadphase.OverlappingPairUserCallback = new AxisSweepUserCallback(); boxShape = new BoxShape(1); body1 = CreateBody(10.0f, new SphereShape(1.0f), new Vector3(2, 2, 0)); body2 = CreateBody(1.0f, new SphereShape(1.0f), new Vector3(0, 2, 0)); ghostObject = new PairCachingGhostObject(); ghostObject.WorldTransform = Matrix.Translation(-1, 2, 0); ghostObject.CollisionShape = boxShape; broadphase.OverlappingPairCache.SetInternalGhostPairCallback(new GhostPairCallback()); }
public ConvexcastBatch(float rayLength, float z, float minY, float maxY) { _boxBoundMax = new Vector3(1.0f, 1.0f, 1.0f); _boxBoundMin = -_boxBoundMax; _boxShape = new BoxShape(_boxBoundMax); const float dalpha = 4 * (float)Math.PI / NumRays; for (int i = 0; i < NumRays; i++) { float alpha = dalpha * i; // rotate around by alpha degrees y Matrix transform = Matrix.RotationY(alpha); _direction[i] = new Vector3(1.0f, 0.0f, 0.0f); _direction[i] = Vector3.TransformCoordinate(_direction[i], transform); _source[i] = new Vector3(_minX, maxY, z); _destination[i] = _source[i] + _direction[i] * rayLength; _destination[i].Y = minY; _normal[i] = new Vector3(1.0f, 0.0f, 0.0f); } }
public PhysicsConvexSweepTestItem(Matrix4 from, Matrix4 to, int collisionFilterGroup, int collisionFilterMask, ModeEnum mode, Bounds bounds) { this.originalFrom = from; this.originalTo = to; this.CollisionFilterGroup = collisionFilterGroup; this.CollisionFilterMask = collisionFilterMask; this.Mode = mode; transformedFrom = originalFrom; transformedTo = originalTo; Vector3 offset = bounds.GetCenter(); if (!offset.Equals(Vector3.Zero, MathEx.Epsilon)) { transformedFrom.SetTranslation(transformedFrom.GetTranslation() + offset); transformedTo.SetTranslation(transformedTo.GetTranslation() + offset); } var halfSize = bounds.GetSize() / 2; Shape = new BulletSharp.BoxShape(BulletPhysicsUtility.Convert(halfSize)); ShapeAutoDispose = true; }
protected override void OnInitializePhysics() { int i; shootBoxInitialSpeed = 4000; // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); //Dispatcher.RegisterCollisionCreateFunc(BroadphaseNativeType.BoxShape, BroadphaseNativeType.BoxShape, // CollisionConf.GetCollisionAlgorithmCreateFunc(BroadphaseNativeType.ConvexShape, BroadphaseNativeType.ConvexShape)); Broadphase = new DbvtBroadphase(); // the default constraint solver. Solver = new SequentialImpulseConstraintSolver(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf); World.SolverInfo.SolverMode |= SolverModes.Use2FrictionDirections | SolverModes.RandomizeOrder; //World.SolverInfo.SplitImpulse = 0; World.SolverInfo.NumIterations = 20; World.DispatchInfo.UseContinuous = ccdMode; World.Gravity = new Vector3(0, -10, 0); BoxShape ground = new BoxShape(200, 1, 200); ground.InitializePolyhedralFeatures(); CollisionShapes.Add(ground); RigidBody body = LocalCreateRigidBody(0, Matrix.Identity, ground); body.Friction = 0.5f; //body.RollingFriction = 0.3f; body.UserObject = "Ground"; //CollisionShape shape = new CylinderShape(CubeHalfExtents, CubeHalfExtents, CubeHalfExtents); CollisionShape shape = new BoxShape(CubeHalfExtents, CubeHalfExtents, CubeHalfExtents); CollisionShapes.Add(shape); const int numObjects = 120; for (i = 0; i < numObjects; i++) { //stack them const int colsize = 10; int row = (int)((i * CubeHalfExtents * 2) / (colsize * 2 * CubeHalfExtents)); int row2 = row; int col = (i) % (colsize) - colsize / 2; if (col > 3) { col = 11; row2 |= 1; } Matrix trans = Matrix.Translation(col * 2 * CubeHalfExtents + (row2 % 2) * CubeHalfExtents, row * 2 * CubeHalfExtents + CubeHalfExtents + ExtraHeight, 0); body = LocalCreateRigidBody(1, trans, shape); body.SetAnisotropicFriction(shape.AnisotropicRollingFrictionDirection, AnisotropicFrictionFlags.AnisotropicRollingFriction); body.Friction = 0.5f; //body.RollingFriction = 0.3f; if (ccdMode) { body.CcdMotionThreshold = 1e-7f; body.CcdSweptSphereRadius = 0.9f * CubeHalfExtents; } } }
public virtual void ShootBox(Vector3 camPos, Vector3 destination) { if (_world == null) return; float mass = 1.0f; if (shootBoxShape == null) { shootBoxShape = new BoxShape(1.0f); shootBoxShape.InitializePolyhedralFeatures(); } RigidBody body = LocalCreateRigidBody(mass, Matrix.Translation(camPos), shootBoxShape); body.LinearFactor = new Vector3(1, 1, 1); //body.Restitution = 1; Vector3 linVel = destination - camPos; linVel.Normalize(); body.LinearVelocity = linVel * shootBoxInitialSpeed; body.CcdMotionThreshold = 0.5f; body.CcdSweptSphereRadius = 0.9f; }
protected override void OnInitializePhysics() { // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); Vector3 worldMin = new Vector3(-1000, -1000, -1000); Vector3 worldMax = new Vector3(1000, 1000, 1000); Broadphase = new AxisSweep3(worldMin, worldMax); Solver = new SequentialImpulseConstraintSolver(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf); World.SolverInfo.SplitImpulse = 1; World.Gravity = new Vector3(0, -10, 0); IsDebugDrawEnabled = true; CollisionShape colShape = new BoxShape(1); CollisionShapes.Add(colShape); for (int j = 0; j < NumDynamicBoxesX; j++) { for (int i = 0; i < NumDynamicBoxesY; i++) { //CollisionShape colShape = new CapsuleShape(0.5f,2.0f);//boxShape = new SphereShape(1.0f); Matrix startTransform = Matrix.Translation(5 * (i - NumDynamicBoxesX / 2), 10, 5 * (j - NumDynamicBoxesY / 2)); LocalCreateRigidBody(1.0f, startTransform, colShape); } } SetVertexPositions(WaveHeight, 0.0f); const bool useQuantizedAabbCompression = true; groundShape = new BvhTriangleMeshShape(indexVertexArrays, useQuantizedAabbCompression); CollisionShapes.Add(groundShape); staticBody = LocalCreateRigidBody(0.0f, Matrix.Identity, groundShape); staticBody.CollisionFlags |= CollisionFlags.StaticObject; staticBody.UserObject = "Ground"; }
public bool Build( FeatureUpdateContext updateContext, [ParentModel] Point[] Points, double Size) { //-- Upkeep //-- if( physics == null ) { physics = new Sutd.Physics( ); } else { Regenerate( ); physics.Reset( ); } //-- Set Gravity //-- physics.world.Gravity = new Vec3D( 0, 0, -10 ); //-- Create Ground //-- var body = new Sutd.Physics.Body( ); { //-- Define Infinite Plane //-- var shape = new StaticPlaneShape( new Vec3D( 0, 0, 1 ), 0 ); physics.shapes.Add( shape ); //-- Set Physics State / Bullet //-- Fixed bodies have zero mass and inertia //-- var param = new RigidBodyConstructionInfo( mass: 0.0f, motionState: new DefaultMotionState( Mat4D.Identity ), collisionShape: shape, localInertia: Vec3D.Zero ); body.rigid = new RigidBody( param ); param.Dispose( ); physics.world.AddRigidBody( body.rigid ); body.matrix = body.rigid.WorldTransform; //-- Set Visual State / Rhino //-- Create a very thin but wide finite box //-- var transform = DTransform3d.Identity; AddBox( transform, new DVector3d( 50, 50, 0.01 ) ); body.solid = geometry[geometry.Count - 1]; } physics.bodies.Add( body ); //-- Create 3D Grid of Boxes //-- float half = (float)( Size * 0.5 ); foreach( var point in Points ) { body = new Sutd.Physics.Body( ); { //-- Collision Shape //-- var shape = new BoxShape( half, half, half ); physics.shapes.Add( shape ); //-- Mass Properties //-- var inertia = Vec3D.Zero; shape.CalculateLocalInertia( mass: 1.0f, inertia: out inertia ); //-- Physics State //-- var param = new RigidBodyConstructionInfo( mass: 1.0f, motionState: new DefaultMotionState( Mat4D.Identity ), collisionShape: shape, localInertia: inertia ); body.rigid = new RigidBody( param ); param.Dispose( ); physics.world.AddRigidBody( body.rigid ); body.rigid.Translate( new Vec3D( (float)point.X, (float)point.Y, (float)point.Z ) ); body.matrix = body.rigid.WorldTransform; //-- Visual State //-- var transform = DTransform3d.Identity; transform.Translation = point.DPoint3d; AddBox( transform, new DVector3d( Size, Size, Size ) ); body.solid = geometry[geometry.Count - 1]; } physics.bodies.Add( body ); } return true; }
public override void Run() { #region Create renderers // Note: the renderers take care of creating their own // device resources and listen for DeviceManager.OnInitialize // Create a axis-grid renderer var axisGrid = ToDispose(new AxisGridRenderer()); axisGrid.Initialize(this); // Create and initialize the mesh renderer var loadedMesh = Common.Mesh.LoadFromFile("PhysicsScene1.cmo"); List <MeshRenderer> meshes = new List <MeshRenderer>(); meshes.AddRange(from mesh in loadedMesh select ToDispose(new MeshRenderer(mesh))); foreach (var m in meshes) { m.Initialize(this); m.World = Matrix.Identity; } // Set the first animation as the current animation and start clock foreach (var m in meshes) { if (m.Mesh.Animations != null && m.Mesh.Animations.Any()) { m.CurrentAnimation = m.Mesh.Animations.First().Value; } m.Clock.Start(); } loadedMesh = Common.Mesh.LoadFromFile("SubdividedPlane.cmo"); var waterMesh = ToDispose(new MeshRenderer(loadedMesh.First())); waterMesh.Initialize(this); loadedMesh = Common.Mesh.LoadFromFile("Bataux.cmo"); List <MeshRenderer> shipMeshes = new List <MeshRenderer>(); shipMeshes.AddRange((from mesh in loadedMesh select ToDispose(new MeshRenderer(mesh)))); foreach (var m in shipMeshes) { m.Initialize(this); m.World = Matrix.Scaling(3) * Matrix.RotationAxis(Vector3.UnitY, -1.57079f); } //var anchor = new SphereRenderer(0.05f); //anchor.Initialize(this); //var anchorWorld = Matrix.Identity; //var sphere = new SphereRenderer(); //sphere.Initialize(this); //var sphereWorld = Matrix.Identity; // Create and initialize a Direct2D FPS text renderer var fps = ToDispose(new Common.FpsRenderer("Calibri", Color.CornflowerBlue, new Point(8, 8), 16)); fps.Initialize(this); // Create and initialize a general purpose Direct2D text renderer // This will display some instructions and the current view and rotation offsets var textRenderer = ToDispose(new Common.TextRenderer("Calibri", Color.CornflowerBlue, new Point(8, 40), 12)); textRenderer.Initialize(this); #endregion #region Initialize physics engine CollisionConfiguration defaultConfig = new DefaultCollisionConfiguration(); ConstraintSolver solver = new SequentialImpulseConstraintSolver(); BulletSharp.Dispatcher dispatcher = new CollisionDispatcher(defaultConfig); BroadphaseInterface broadphase = new DbvtBroadphase(); DynamicsWorld world = null; Action initializePhysics = () => { RemoveAndDispose(ref world); world = ToDispose(new BulletSharp.DiscreteDynamicsWorld(dispatcher, broadphase, solver, defaultConfig)); world.Gravity = new Vector3(0, -10, 0); // For each mesh, create a RigidBody and add to "world" for simulation meshes.ForEach(m => { // We use the name of the mesh to determine the correct body if (String.IsNullOrEmpty(m.Mesh.Name)) { return; } var name = m.Mesh.Name.ToLower(); var extent = m.Mesh.Extent; BulletSharp.CollisionShape shape; #region Create collision shape if (name.Contains("box") || name.Contains("cube")) { // Assumes the box/cube has an axis-aligned neutral orientation shape = new BulletSharp.BoxShape( Math.Abs(extent.Max.Z - extent.Min.Z) / 2.0f, Math.Abs(extent.Max.Y - extent.Min.Y) / 2.0f, Math.Abs(extent.Max.X - extent.Min.X) / 2.0f); } else if (name.Contains("sphere")) { shape = new BulletSharp.SphereShape(extent.Radius); } else // use mesh vertices directly { // for each SubMesh, retrieve the vertex and index buffers // to create a TriangleMeshShape for collision detection. List <Vector3> vertices = new List <Vector3>(); List <int> indices = new List <int>(); int vertexOffset = 0; foreach (var sm in m.Mesh.SubMeshes) { vertexOffset += vertices.Count; indices.AddRange( (from indx in m.Mesh.IndexBuffers[(int)sm.IndexBufferIndex] select vertexOffset + (int)indx)); vertices.AddRange( (from v in m.Mesh .VertexBuffers[(int)sm.VertexBufferIndex] select v.Position - extent.Center)); } // Create the collision shape var iva = new BulletSharp.TriangleIndexVertexArray(indices.ToArray(), vertices.ToArray()); shape = new BulletSharp.BvhTriangleMeshShape(iva, true); } #endregion m.World = Matrix.Identity; // Reset mesh location float mass; Vector3 vec; shape.GetBoundingSphere(out vec, out mass); var body = new BulletSharp.RigidBody( new BulletSharp.RigidBodyConstructionInfo(name.Contains("static") ? 0 : mass, new MeshMotionState(m), shape, shape.CalculateLocalInertia(mass))); if (body.IsStaticObject) { body.Restitution = 1f; body.Friction = 0.4f; } // Add to the simulation world.AddRigidBody(body); }); #if DEBUG world.DebugDrawer = ToDispose(new PhysicsDebugDraw(this.DeviceManager)); world.DebugDrawer.DebugMode = DebugDrawModes.DrawAabb | DebugDrawModes.DrawWireframe; #endif }; initializePhysics(); // Newton's Cradle //var box = new Jitter.Dynamics.RigidBody(new Jitter.Collision.Shapes.BoxShape(7, 1, 2)); //box.Position = new Jitter.LinearMath.JVector(0, 8, 0); //world.AddBody(box); //box.IsStatic = true; //var anchorBody = new Jitter.Dynamics.RigidBody(new Jitter.Collision.Shapes.SphereShape(0.05f)); //anchorBody.Position = new Jitter.LinearMath.JVector(0, 4, 0); //world.AddBody(anchorBody); //anchorBody.IsStatic = true; //for (var bodyCount = -3; bodyCount < 4; bodyCount++) //{ // var testBody = new Jitter.Dynamics.RigidBody(new Jitter.Collision.Shapes.SphereShape(0.501f)); // testBody.Position = new Jitter.LinearMath.JVector(bodyCount, 0, 0); // world.AddBody(testBody); // world.AddConstraint(new Jitter.Dynamics.Constraints.PointPointDistance(box, testBody, // testBody.Position + Jitter.LinearMath.JVector.Up * 8f + Jitter.LinearMath.JVector.Forward * 3f + Jitter.LinearMath.JVector.Down * 0.5f, // testBody.Position) { Softness = 1.0f, BiasFactor = 0.8f }); // world.AddConstraint(new Jitter.Dynamics.Constraints.PointPointDistance(box, testBody, // testBody.Position + Jitter.LinearMath.JVector.Up * 8f + Jitter.LinearMath.JVector.Backward * 3f + Jitter.LinearMath.JVector.Down * 0.5f, // testBody.Position) { Softness = 1.0f, BiasFactor = 0.8f }); // testBody.Material.Restitution = 1.0f; // testBody.Material.StaticFriction = 1.0f; //} #endregion // Initialize the world matrix var worldMatrix = Matrix.Identity; // Set the camera position slightly behind (z) var cameraPosition = new Vector3(0, 1, 10); var cameraTarget = Vector3.Zero; // Looking at the origin 0,0,0 var cameraUp = Vector3.UnitY; // Y+ is Up // Prepare matrices // Create the view matrix from our camera position, look target and up direction var viewMatrix = Matrix.LookAtRH(cameraPosition, cameraTarget, cameraUp); viewMatrix.TranslationVector += new Vector3(0, -0.98f, 0); // Create the projection matrix /* FoV 60degrees = Pi/3 radians */ // Aspect ratio (based on window size), Near clip, Far clip var projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f); // Maintain the correct aspect ratio on resize Window.Resize += (s, e) => { projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f); }; bool debugDraw = false; bool paused = false; var simTime = new System.Diagnostics.Stopwatch(); simTime.Start(); float time = 0.0f; float timeStep = 0.0f; #region Rotation and window event handlers // Create a rotation vector to keep track of the rotation // around each of the axes var rotation = new Vector3(0.0f, 0.0f, 0.0f); // We will call this action to update text // for the text renderer Action updateText = () => { textRenderer.Text = String.Format("Rotation ({0}) (Up/Down Left/Right Wheel+-)\nView ({1}) (A/D, W/S, Shift+Wheel+-)" //+ "\nPress 1,2,3,4,5,6,7,8 to switch shaders" + "\nTime: {2:0.00} (P to toggle, R to reset scene)" + "\nPhysics debug draw: {3} (E to toggle)" + "\nBackspace: toggle between Physics and Waves", rotation, viewMatrix.TranslationVector, simTime.Elapsed.TotalSeconds, debugDraw); }; Dictionary <Keys, bool> keyToggles = new Dictionary <Keys, bool>(); keyToggles[Keys.Z] = false; keyToggles[Keys.F] = false; keyToggles[Keys.Back] = false; // Support keyboard/mouse input to rotate or move camera view var moveFactor = 0.02f; // how much to change on each keypress var shiftKey = false; var ctrlKey = false; var background = Color.White; var showNormals = false; var enableNormalMap = true; Window.KeyDown += (s, e) => { var context = DeviceManager.Direct3DContext; shiftKey = e.Shift; ctrlKey = e.Control; switch (e.KeyCode) { // WASD -> pans view case Keys.A: viewMatrix.TranslationVector += new Vector3(moveFactor * 2, 0f, 0f); break; case Keys.D: viewMatrix.TranslationVector -= new Vector3(moveFactor * 2, 0f, 0f); break; case Keys.S: if (shiftKey) { viewMatrix.TranslationVector += new Vector3(0f, moveFactor * 2, 0f); } else { viewMatrix.TranslationVector -= new Vector3(0f, 0f, 1) * moveFactor * 2; } break; case Keys.W: if (shiftKey) { viewMatrix.TranslationVector -= new Vector3(0f, moveFactor * 2, 0f); } else { viewMatrix.TranslationVector += new Vector3(0f, 0f, 1) * moveFactor * 2; } break; // Up/Down and Left/Right - rotates around X / Y respectively // (Mouse wheel rotates around Z) case Keys.Down: worldMatrix *= Matrix.RotationX(moveFactor); rotation += new Vector3(moveFactor, 0f, 0f); break; case Keys.Up: worldMatrix *= Matrix.RotationX(-moveFactor); rotation -= new Vector3(moveFactor, 0f, 0f); break; case Keys.Left: worldMatrix *= Matrix.RotationY(moveFactor); rotation += new Vector3(0f, moveFactor, 0f); break; case Keys.Right: worldMatrix *= Matrix.RotationY(-moveFactor); rotation -= new Vector3(0f, moveFactor, 0f); break; case Keys.T: fps.Show = !fps.Show; textRenderer.Show = !textRenderer.Show; break; case Keys.B: if (background == Color.White) { background = new Color(30, 30, 34); } else { background = Color.White; } break; case Keys.G: axisGrid.Show = !axisGrid.Show; break; case Keys.P: paused = !paused; if (paused) { simTime.Stop(); } else { simTime.Start(); } // Pause or resume mesh animation meshes.ForEach(m => { if (m.Clock.IsRunning) { m.Clock.Stop(); } else { m.Clock.Start(); } }); updateText(); break; case Keys.X: // To test for correct resource recreation // Simulate device reset or lost. System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects()); DeviceManager.Initialize(DeviceManager.Dpi); System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects()); break; case Keys.Z: keyToggles[Keys.Z] = !keyToggles[Keys.Z]; if (keyToggles[Keys.Z]) { context.PixelShader.Set(depthPixelShader); } else { context.PixelShader.Set(pixelShader); } break; case Keys.F: keyToggles[Keys.F] = !keyToggles[Keys.F]; RasterizerStateDescription rasterDesc; if (context.Rasterizer.State != null) { rasterDesc = context.Rasterizer.State.Description; } else { rasterDesc = new RasterizerStateDescription() { CullMode = CullMode.None, FillMode = FillMode.Solid } }; if (keyToggles[Keys.F]) { rasterDesc.FillMode = FillMode.Wireframe; context.Rasterizer.State = ToDispose(new RasterizerState(context.Device, rasterDesc)); } else { rasterDesc.FillMode = FillMode.Solid; context.Rasterizer.State = ToDispose(new RasterizerState(context.Device, rasterDesc)); } break; case Keys.N: if (!shiftKey) { showNormals = !showNormals; } else { enableNormalMap = !enableNormalMap; } break; case Keys.E: debugDraw = !debugDraw; break; case Keys.R: //world = new Jitter.World(new Jitter.Collision.CollisionSystemSAP()); initializePhysics(); if (simTime.IsRunning) { simTime.Restart(); } else { simTime.Reset(); } break; case Keys.D1: context.PixelShader.Set(pixelShader); break; case Keys.D2: context.PixelShader.Set(lambertShader); break; case Keys.D3: context.PixelShader.Set(phongShader); break; case Keys.D4: context.PixelShader.Set(blinnPhongShader); break; case Keys.Back: keyToggles[Keys.Back] = !keyToggles[Keys.Back]; break; } updateText(); }; Window.KeyUp += (s, e) => { // Clear the shift/ctrl keys so they aren't sticky if (e.KeyCode == Keys.ShiftKey) { shiftKey = false; } if (e.KeyCode == Keys.ControlKey) { ctrlKey = false; } }; Window.MouseWheel += (s, e) => { if (shiftKey) { // Zoom in/out viewMatrix.TranslationVector += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor * 2); } else { // rotate around Z-axis viewMatrix *= Matrix.RotationZ((e.Delta / 120f) * moveFactor); rotation += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor); } updateText(); }; var lastX = 0; var lastY = 0; Window.MouseDown += (s, e) => { if (e.Button == MouseButtons.Left) { lastX = e.X; lastY = e.Y; } }; Window.MouseMove += (s, e) => { if (e.Button == MouseButtons.Left) { var yRotate = lastX - e.X; var xRotate = lastY - e.Y; lastY = e.Y; lastX = e.X; // Mouse move changes viewMatrix *= Matrix.RotationX(-xRotate * moveFactor); viewMatrix *= Matrix.RotationY(-yRotate * moveFactor); updateText(); } }; // Display instructions with initial values updateText(); #endregion var clock = new System.Diagnostics.Stopwatch(); clock.Start(); #region Render loop // Create and run the render loop RenderLoop.Run(Window, () => { // Update simulation, at 60fps if (!paused) { if ((float)simTime.Elapsed.TotalSeconds < time) { time = 0; timeStep = 0; } timeStep = ((float)simTime.Elapsed.TotalSeconds - time); time = (float)simTime.Elapsed.TotalSeconds; world.StepSimulation(timeStep, 7); // For how to choose the maxSubSteps see: // http://www.bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World } updateText(); // Start of frame: // Retrieve immediate context var context = DeviceManager.Direct3DContext; // Clear depth stencil view context.ClearDepthStencilView(DepthStencilView, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0); // Clear render target view context.ClearRenderTargetView(RenderTargetView, background); // Create viewProjection matrix var viewProjection = Matrix.Multiply(viewMatrix, projectionMatrix); // Extract camera position from view var camPosition = Matrix.Transpose(Matrix.Invert(viewMatrix)).Column4; cameraPosition = new Vector3(camPosition.X, camPosition.Y, camPosition.Z); var perFrame = new ConstantBuffers.PerFrame(); perFrame.Light.Color = new Color(0.8f, 0.8f, 0.8f, 1.0f); var lightDir = Vector3.Transform(new Vector3(1f, -1f, -1f), worldMatrix); perFrame.Light.Direction = new Vector3(lightDir.X, lightDir.Y, lightDir.Z); perFrame.CameraPosition = cameraPosition; perFrame.Time = (float)simTime.Elapsed.TotalSeconds; // Provide simulation time to shader context.UpdateSubresource(ref perFrame, perFrameBuffer); // Render each object var perMaterial = new ConstantBuffers.PerMaterial(); perMaterial.Ambient = new Color4(0.2f); perMaterial.Diffuse = Color.White; perMaterial.Emissive = new Color4(0); perMaterial.Specular = Color.White; perMaterial.SpecularPower = 20f; perMaterial.HasTexture = 0; perMaterial.UVTransform = Matrix.Identity; context.UpdateSubresource(ref perMaterial, perMaterialBuffer); var perObject = new ConstantBuffers.PerObject(); // MESH if (!keyToggles[Keys.Back]) { meshes.ForEach((m) => { perObject.World = m.World * worldMatrix; // Provide the material constant buffer to the mesh renderer perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World)); perObject.WorldViewProjection = perObject.World * viewProjection; perObject.ViewProjection = viewProjection; perObject.Transpose(); context.UpdateSubresource(ref perObject, perObjectBuffer); m.PerMaterialBuffer = perMaterialBuffer; m.PerArmatureBuffer = perArmatureBuffer; m.Render(); if (showNormals) { using (var prevPixelShader = context.PixelShader.Get()) { perMaterial.HasTexture = 0; perMaterial.UVTransform = Matrix.Identity; context.UpdateSubresource(ref perMaterial, perMaterialBuffer); context.PixelShader.Set(pixelShader); context.GeometryShader.Set(debugNormals); m.Render(); context.PixelShader.Set(prevPixelShader); context.GeometryShader.Set(null); } } }); if (debugDraw) { perObject.World = Matrix.Identity; perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World)); perObject.WorldViewProjection = perObject.World * viewProjection; perObject.ViewProjection = viewProjection; perObject.Transpose(); context.UpdateSubresource(ref perObject, perObjectBuffer); (world.DebugDrawer as PhysicsDebugDraw).DrawDebugWorld(world); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); context.InputAssembler.InputLayout = vertexLayout; } } else { perObject.World = waterMesh.World * worldMatrix; perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World)); perObject.WorldViewProjection = perObject.World * viewProjection; perObject.ViewProjection = viewProjection; perObject.Transpose(); context.UpdateSubresource(ref perObject, perObjectBuffer); waterMesh.EnableNormalMap = enableNormalMap; waterMesh.PerMaterialBuffer = perMaterialBuffer; waterMesh.PerArmatureBuffer = perArmatureBuffer; context.VertexShader.Set(waterVertexShader); waterMesh.Render(); if (showNormals) { using (var prevPixelShader = context.PixelShader.Get()) { perMaterial.HasTexture = 0; perMaterial.UVTransform = Matrix.Identity; context.UpdateSubresource(ref perMaterial, perMaterialBuffer); context.PixelShader.Set(pixelShader); context.GeometryShader.Set(debugNormals); waterMesh.Render(); context.PixelShader.Set(prevPixelShader); context.GeometryShader.Set(null); } } context.VertexShader.Set(vertexShader); foreach (var m in shipMeshes) { perObject.World = m.World * worldMatrix; perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World)); perObject.WorldViewProjection = perObject.World * viewProjection; perObject.Transpose(); context.UpdateSubresource(ref perObject, perObjectBuffer); // Provide the material constant buffer to the mesh renderer perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World)); perObject.WorldViewProjection = perObject.World * viewProjection; perObject.ViewProjection = viewProjection; perObject.Transpose(); context.UpdateSubresource(ref perObject, perObjectBuffer); m.PerMaterialBuffer = perMaterialBuffer; m.PerArmatureBuffer = perArmatureBuffer; m.Render(); if (showNormals) { using (var prevPixelShader = context.PixelShader.Get()) { perMaterial.HasTexture = 0; perMaterial.UVTransform = Matrix.Identity; context.UpdateSubresource(ref perMaterial, perMaterialBuffer); context.PixelShader.Set(pixelShader); context.GeometryShader.Set(debugNormals); m.Render(); context.PixelShader.Set(prevPixelShader); context.GeometryShader.Set(null); } } } } perMaterial.Ambient = new Color4(0.2f); perMaterial.Diffuse = Color.White; perMaterial.Emissive = new Color4(0); perMaterial.Specular = Color.White; perMaterial.SpecularPower = 20f; perMaterial.UVTransform = Matrix.Identity; context.UpdateSubresource(ref perMaterial, perMaterialBuffer); // AXIS GRID context.HullShader.Set(null); context.DomainShader.Set(null); context.GeometryShader.Set(null); using (var prevPixelShader = context.PixelShader.Get()) using (var prevVertexShader = context.VertexShader.Get()) { context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); perObject.World = worldMatrix; perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World)); perObject.WorldViewProjection = perObject.World * viewProjection; perObject.ViewProjection = viewProjection; perObject.Transpose(); context.UpdateSubresource(ref perObject, perObjectBuffer); axisGrid.Render(); context.PixelShader.Set(prevPixelShader); context.VertexShader.Set(prevVertexShader); } // Render FPS fps.Render(); // Render instructions + position changes textRenderer.Render(); // Present the frame Present(); }); #endregion }
protected override void OnInitializePhysics() { // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); // Use the default collision dispatcher. For parallel processing you can use a diffent dispatcher. Dispatcher = new CollisionDispatcher(CollisionConf); VoronoiSimplexSolver simplex = new VoronoiSimplexSolver(); MinkowskiPenetrationDepthSolver pdSolver = new MinkowskiPenetrationDepthSolver(); Convex2DConvex2DAlgorithm.CreateFunc convexAlgo2d = new Convex2DConvex2DAlgorithm.CreateFunc(simplex, pdSolver); Dispatcher.RegisterCollisionCreateFunc(BroadphaseNativeType.Convex2DShape, BroadphaseNativeType.Convex2DShape, convexAlgo2d); Dispatcher.RegisterCollisionCreateFunc(BroadphaseNativeType.Box2DShape, BroadphaseNativeType.Convex2DShape, convexAlgo2d); Dispatcher.RegisterCollisionCreateFunc(BroadphaseNativeType.Convex2DShape, BroadphaseNativeType.Box2DShape, convexAlgo2d); Dispatcher.RegisterCollisionCreateFunc(BroadphaseNativeType.Box2DShape, BroadphaseNativeType.Box2DShape, new Box2DBox2DCollisionAlgorithm.CreateFunc()); Broadphase = new DbvtBroadphase(); // the default constraint solver. Solver = new SequentialImpulseConstraintSolver(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf); World.Gravity = new Vector3(0, -10, 0); // create a few basic rigid bodies CollisionShape groundShape = new BoxShape(150, 7, 150); CollisionShapes.Add(groundShape); RigidBody ground = LocalCreateRigidBody(0, Matrix.Identity, groundShape); ground.UserObject = "Ground"; // create a few dynamic rigidbodies // Re-using the same collision is better for memory usage and performance float u = 0.96f; Vector3[] points = { new Vector3(0, u, 0), new Vector3(-u, -u, 0), new Vector3(u, -u, 0) }; ConvexShape childShape0 = new BoxShape(1, 1, Depth); ConvexShape colShape = new Convex2DShape(childShape0); ConvexShape childShape1 = new ConvexHullShape(points); ConvexShape colShape2 = new Convex2DShape(childShape1); ConvexShape childShape2 = new CylinderShapeZ(1, 1, Depth); ConvexShape colShape3 = new Convex2DShape(childShape2); CollisionShapes.Add(colShape); CollisionShapes.Add(colShape2); CollisionShapes.Add(colShape3); CollisionShapes.Add(childShape0); CollisionShapes.Add(childShape1); CollisionShapes.Add(childShape2); colShape.Margin = 0.03f; float mass = 1.0f; Vector3 localInertia = colShape.CalculateLocalInertia(mass); Matrix startTransform; Vector3 x = new Vector3(-ArraySizeX, 8, -20); Vector3 y = Vector3.Zero; Vector3 deltaX = new Vector3(1, 2, 0); Vector3 deltaY = new Vector3(2, 0, 0); int i, j; for (i = 0; i < ArraySizeY; i++) { y = x; for (j = 0; j < ArraySizeX; j++) { startTransform = Matrix.Translation(y - new Vector3(-10, 0, 0)); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects DefaultMotionState myMotionState = new DefaultMotionState(startTransform); RigidBodyConstructionInfo rbInfo; switch (j % 3) { case 0: rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape, localInertia); break; case 1: rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape3, localInertia); break; default: rbInfo = new RigidBodyConstructionInfo(mass, myMotionState, colShape2, localInertia); break; } RigidBody body = new RigidBody(rbInfo); rbInfo.Dispose(); //body.ActivationState = ActivationState.IslandSleeping; body.LinearFactor = new Vector3(1, 1, 0); body.AngularFactor = new Vector3(0, 0, 1); World.AddRigidBody(body); y += deltaY; } x += deltaX; } }
protected override void OnInitializePhysics() { // collision configuration contains default setup for memory, collision setup CollisionConf = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConf); Vector3 worldMin = new Vector3(-1000, -1000, -1000); Vector3 worldMax = new Vector3(1000, 1000, 1000); Broadphase = new AxisSweep3(worldMin, worldMax); Solver = new SequentialImpulseConstraintSolver(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, Solver, CollisionConf); World.SolverInfo.SplitImpulse = 1; World.Gravity = new Vector3(0, -10, 0); const int totalVerts = NumVertsX * NumVertsY; const int totalTriangles = 2 * (NumVertsX - 1) * (NumVertsY - 1); indexVertexArrays = new TriangleIndexVertexArray(); IndexedMesh mesh = new IndexedMesh(); mesh.NumTriangles = totalTriangles; mesh.NumVertices = totalVerts; mesh.TriangleIndexStride = 3 * sizeof(int); mesh.VertexStride = Vector3.SizeInBytes; mesh.TriangleIndexBase = Marshal.AllocHGlobal(mesh.TriangleIndexStride * totalTriangles); mesh.VertexBase = Marshal.AllocHGlobal(mesh.VertexStride * totalVerts); var indicesStream = mesh.GetTriangleStream(); using (var indices = new BinaryWriter(indicesStream)) { for (int i = 0; i < NumVertsX - 1; i++) { for (int j = 0; j < NumVertsY - 1; j++) { indices.Write(j*NumVertsX + i); indices.Write(j*NumVertsX + i + 1); indices.Write((j + 1)*NumVertsX + i + 1); indices.Write(j*NumVertsX + i); indices.Write((j + 1)*NumVertsX + i + 1); indices.Write((j + 1)*NumVertsX + i); } } } indexVertexArrays.AddIndexedMesh(mesh); convexcastBatch = new ConvexcastBatch(40.0f, 0.0f, -10.0f, 80.0f); CollisionShape colShape = new BoxShape(1); CollisionShapes.Add(colShape); for (int j = 0; j < NumDynamicBoxesX; j++) { for (int i = 0; i < NumDynamicBoxesY; i++) { //CollisionShape colShape = new CapsuleShape(0.5f,2.0f);//boxShape = new SphereShape(1.0f); Matrix startTransform = Matrix.Translation(5 * (i - NumDynamicBoxesX / 2), 10, 5 * (j - NumDynamicBoxesY / 2)); LocalCreateRigidBody(1.0f, startTransform, colShape); } } SetVertexPositions(WaveHeight, 0.0f); const bool useQuantizedAabbCompression = true; groundShape = new BvhTriangleMeshShape(indexVertexArrays, useQuantizedAabbCompression); CollisionShapes.Add(groundShape); staticBody = LocalCreateRigidBody(0.0f, Matrix.Identity, groundShape); staticBody.CollisionFlags |= CollisionFlags.StaticObject; staticBody.UserObject = "Ground"; }
public BoxBoxDetector(BoxShape box1, BoxShape box2) : base(btBoxBoxDetector_new(box1.Native, box2.Native)) { _box1 = box1; _box2 = box2; }