void InitGImpactCollision() { // Create Torus Shape indexVertexArrays = new TriangleIndexVertexArray(TorusMesh.Indices, TorusMesh.Vertices); #if BULLET_GIMPACT #if BULLET_GIMPACT_CONVEX_DECOMPOSITION //GImpactConvexDecompositionShape trimesh = // new GImpactConvexDecompositionShape(indexVertexArrays, new Vector3(1), 0.01f); //trimesh.Margin = 0.07f; //trimesh.UpdateBound(); #else GImpactMeshShape trimesh = new GImpactMeshShape(indexVertexArrays); trimesh.LocalScaling = new Vector3(1); #if BULLET_TRIANGLE_COLLISION trimesh.Margin = 0.07f; //????? #else trimesh.Margin = 0; #endif trimesh.UpdateBound(); #endif trimeshShape = trimesh; #else //trimeshShape = new GImpactMeshData(indexVertexArrays); #endif /// Create Bunny Shape indexVertexArrays2 = new TriangleIndexVertexArray(BunnyMesh.Indices, BunnyMesh.Vertices); #if BULLET_GIMPACT #if BULLET_GIMPACT_CONVEX_DECOMPOSITION //GImpactConvexDecompositionShape trimesh2 = // new GImpactConvexDecompositionShape(indexVertexArrays, new Vector3(1), 0.01f); //trimesh.Margin = 0.07f; //trimesh.UpdateBound(); //trimeshShape = trimesh2; #else GImpactMeshShape trimesh2 = new GImpactMeshShape(indexVertexArrays2); trimesh2.LocalScaling = new Vector3(1); #if BULLET_TRIANGLE_COLLISION trimesh2.Margin = 0.07f; //????? #else trimesh2.Margin = 0; #endif trimesh2.UpdateBound(); trimeshShape2 = trimesh2; #endif #else //trimeshShape2 = new GImpactMeshData(indexVertexArrays2); #endif //register GIMPACT algorithm #if BULLET_GIMPACT GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher); #else //ConcaveConcaveCollisionAlgorithm.RegisterAlgorithm(Dispatcher); #endif }
public FisicaMundo() { //Implementación Iniciales collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration) { Gravity = new TGCVector3(0, -10f, 0).ToBulletVector3() }; var cuerpoPiso = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 0) { LocalScaling = new TGCVector3().ToBulletVector3() }; MotionState movimientoPiso = new DefaultMotionState(); piso = new RigidBody(new RigidBodyConstructionInfo(0, movimientoPiso, cuerpoPiso)) { RollingFriction = 0.3f, Restitution = 0.4f, UserObject = "floorBody" }; dynamicsWorld.AddRigidBody(piso); }
public void Init(TgcSimpleTerrain terrain) { collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); broadphaseInterface = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, broadphaseInterface, constraintSolver, collisionConfiguration); dynamicsWorld.Gravity = gravity; var ballShape = new SphereShape(50); var ballTransform = TGCMatrix.Identity; ballTransform.Origin = initialPosition; var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix); var ballInertia = ballShape.CalculateLocalInertia(1f); var ballInfo = new RigidBodyConstructionInfo(1, ballMotionState, ballShape, ballInertia); RigidCamera = new RigidBody(ballInfo); RigidCamera.SetDamping(0.9f, 0.9f); //esto es para que no le afecte la gravedad al inicio de la partida //RigidCamera.ActivationState = ActivationState.IslandSleeping; dynamicsWorld.AddRigidBody(RigidCamera); var heighmapRigid = BulletRigidBodyFactory.Instance.CreateSurfaceFromHeighMap(terrain.getData()); dynamicsWorld.AddRigidBody(heighmapRigid); }
public void Init(string MediaDir) { //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration); dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBulletVector3(); //Creamos el terreno var meshRigidBody = BulletRigidBodyFactory.Instance.CreateSurfaceFromHeighMap(triangleDataVB); dynamicsWorld.AddRigidBody(meshRigidBody); //Creamos la esfera del dragon dragonBall = BulletRigidBodyFactory.Instance.CreateBall(30f, 0.75f, new TGCVector3(100f, 500f, 100f)); dragonBall.SetDamping(0.1f, 0.5f); dragonBall.Restitution = 1f; dragonBall.Friction = 1; dynamicsWorld.AddRigidBody(dragonBall); var textureDragonBall = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\dragonball.jpg"); sphereMesh = new TGCSphere(1, textureDragonBall, TGCVector3.Empty); sphereMesh.updateValues(); director = new TGCVector3(1, 0, 0); }
private CollisionShape LoadShapeFromFile(string fileName, float mass, Vector3 scale, string baseDirectory) { string fullPath = Path.Combine(baseDirectory, fileName); string extension = Path.GetExtension(fullPath); switch (extension) { case ".obj": WavefrontObj obj = WavefrontObj.Load(fullPath); var mesh = CreateTriangleMesh(obj.Indices, obj.Vertices, scale); if (mass == 0) { const bool useQuantization = true; return(new BvhTriangleMeshShape(mesh, useQuantization)); } else { // TODO: convex decomposition GImpactCollisionAlgorithm.RegisterAlgorithm((CollisionDispatcher)World.Dispatcher); var shape = new GImpactMeshShape(mesh); shape.Margin = 0; shape.UpdateBound(); return(shape); } default: throw new NotSupportedException(); } }
public void Init() { #region MUNDO //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration) { Gravity = new TGCVector3(0, -20f, 0).ToBsVector }; #endregion #region PISO var d3dDevice = D3DDevice.Instance.Device; //El piso es un plano estatico se dice que si tiene masa 0 es estatico. var floorShape = new StaticPlaneShape(TGCVector3.Up.ToBsVector, 0); var floorMotionState = new DefaultMotionState();// Matrix.Translation(0f, 200f, -700f));//esto puede ir sin parametro y funciona var floorInfo = new RigidBodyConstructionInfo(0, floorMotionState, floorShape); floorBody = new RigidBody(floorInfo); dynamicsWorld.AddRigidBody(floorBody); //Cargamos objetos de render del framework. //var floorTexture = TgcTexture.createTexture(d3dDevice, GameModel.mediaDir + "texturas\\terrain\\TerrainTexture1.jpg"); //floorMesh = new TgcPlane(new TGCVector3(0, 0, 0), new TGCVector3(400, 0f, 400), TgcPlane.Orientations.XZplane, floorTexture); #endregion }
/// <summary> /// Called when the script instance is being initialized. /// Initializes the bullet physics environment /// </summary> public override void Awake() { Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes"); GImpactCollisionAlgorithm.RegisterAlgorithm((CollisionDispatcher)BPhysicsWorld.Get().world.Dispatcher); BPhysicsWorld.Get().DebugDrawMode = DebugDrawModes.DrawWireframe | DebugDrawModes.DrawConstraints | DebugDrawModes.DrawConstraintLimits; BPhysicsWorld.Get().DoDebugDraw = false; ((DynamicsWorld)BPhysicsWorld.Get().world).SolverInfo.NumIterations = SolverIterations; }
public void Init(string MediaDir) { #region Configuracion Basica de World //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration); dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBulletVector3(); #endregion Configuracion Basica de World foreach (var mesh in meshes) { var buildingbody = BulletRigidBodyFactory.Instance.CreateRigidBodyFromTgcMesh(mesh); dynamicsWorld.AddRigidBody(buildingbody); } //Se crea un plano ya que esta escena tiene problemas //con la definición de triangulos para el suelo var floorShape = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 10); floorShape.LocalScaling = new TGCVector3().ToBulletVector3(); var floorMotionState = new DefaultMotionState(); var floorInfo = new RigidBodyConstructionInfo(0, floorMotionState, floorShape); floorBody = new RigidBody(floorInfo); floorBody.Friction = 1; floorBody.RollingFriction = 1; floorBody.Restitution = 1f; floorBody.UserObject = "floorBody"; dynamicsWorld.AddRigidBody(floorBody); var loader = new TgcSceneLoader(); ///Se crea una caja para que haga las veces del Hummer dentro del modelo físico TgcTexture texture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"\MeshCreator\Scenes\Deposito\Textures\box4.jpg"); TGCBox boxMesh1 = TGCBox.fromSize(new TGCVector3(20, 20, 20), texture); boxMesh1.Position = new TGCVector3(0, 10, 0); hummer = boxMesh1.ToMesh("box"); boxMesh1.Dispose(); //Se crea el cuerpo rígido de la caja, en la definicio de CreateBox el ultimo parametro representa si se quiere o no //calcular el momento de inercia del cuerpo. No calcularlo lo que va a hacer es que la caja que representa el Hummer //no rote cuando colicione contra el mundo. hummerBody = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(55, 20, 80), 10, hummer.Position, 0, 0, 0, 0.55f, false); hummerBody.Restitution = 0; hummerBody.Gravity = new TGCVector3(0, -100, 0).ToBulletVector3(); dynamicsWorld.AddRigidBody(hummerBody); //Se carga el modelo del Hummer hummer = loader.loadSceneFromFile(MediaDir + @"MeshCreator\\Meshes\\Vehiculos\\Hummer\\Hummer-TgcScene.xml").Meshes[0]; leftright = new TGCVector3(1, 0, 0); fowardback = new TGCVector3(0, 0, 1); }
public virtual void Init(BulletExampleWall ctx) { Ctx = ctx; //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration); dynamicsWorld.Gravity = new TGCVector3(0, -20f, 0).ToBsVector; }
private void Init() { collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration) { Gravity = gravityZero }; }
/// <summary> /// Called when the script instance is being initialized. /// Initializes the bullet physics environment /// </summary> public override void Awake() { Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes"); GImpactCollisionAlgorithm.RegisterAlgorithm((CollisionDispatcher)BPhysicsWorld.Get().world.Dispatcher); //BPhysicsWorld.Get().DebugDrawMode = DebugDrawModes.DrawWireframe | DebugDrawModes.DrawConstraints | DebugDrawModes.DrawConstraintLimits; BPhysicsWorld.Get().DebugDrawMode = DebugDrawModes.All; BPhysicsWorld.Get().DoDebugDraw = false; ((DynamicsWorld)BPhysicsWorld.Get().world).SolverInfo.NumIterations = SolverIterations; CollisionTracker = new CollisionTracker(this); unityPacket = new UnityPacket(); SpawnedRobots = new List <SimulatorRobot>(); }
public void InitGImpactCollision() { /// Create Torus Shape { m_indexVertexArrays = new TriangleIndexVertexArray(DemoMeshes.TORUS_NUM_TRIANGLES, DemoMeshes.gTorusIndices, 3, DemoMeshes.TORUS_NUM_VERTICES, DemoMeshes.gTorusVertices, 3); #if BULLET_GIMPACT_CONVEX_DECOMPOSITION btGImpactConvexDecompositionShape *trimesh = new btGImpactConvexDecompositionShape( m_indexVertexArrays, IndexedVector3(1.f, 1.f, 1.f), btScalar(0.01)); trimesh->setMargin(0.07); trimesh->updateBound(); #else //GImpactMeshShape trimesh = new GImpactMeshShape(m_indexVertexArrays); //IndexedVector3 scaling = IndexedVector3.One; //trimesh.SetLocalScaling(ref scaling); //trimesh.SetMargin(0.07f); ///????? //trimesh.UpdateBound(); #endif //m_trimeshShape = trimesh; } /// Create Bunny Shape { m_indexVertexArrays2 = new TriangleIndexVertexArray(DemoMeshes.BUNNY_NUM_TRIANGLES, DemoMeshes.gBunnyIndices, 3, DemoMeshes.BUNNY_NUM_VERTICES, DemoMeshes.gBunnyVertices, 3); #if BULLET_GIMPACT_CONVEX_DECOMPOSITION btGImpactConvexDecompositionShape *trimesh2 = new btGImpactConvexDecompositionShape( m_indexVertexArrays2, IndexedVector3(4.f, 4.f, 4.f), btScalar(0.01)); trimesh2->setMargin(0.07); trimesh2->updateBound(); #else GImpactMeshShape trimesh2 = new GImpactMeshShape(m_indexVertexArrays2); IndexedVector3 scaling = new IndexedVector3(4.0f, 4.0f, 4.0f); trimesh2.SetLocalScaling(ref scaling); //trimesh2.SetMargin(0.07f); ///????? trimesh2.UpdateBound(); #endif m_trimeshShape2 = trimesh2; } ///register GIMPACT algorithm CollisionDispatcher dispatcher = m_dynamicsWorld.GetDispatcher() as CollisionDispatcher; GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); }
private void Init() { var collisionConfiguration = new DefaultCollisionConfiguration(); var dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); DynamicsWorld = new DiscreteDynamicsWorld( dispatcher, new DbvtBroadphase(), new SequentialImpulseConstraintSolver(), collisionConfiguration ) { Gravity = Vector3.Zero, // new TGCVector3(0, -10f, 0).ToBulletVector3(), }; }
public PhysicModel(List <TgcMesh> meshes) { #region Configuracion Basica de World //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); TGCVector3 gravity = new TGCVector3(0, -100f, 0); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration) { Gravity = gravity.ToBsVector }; #endregion Configuracion Basica de World this.meshes = meshes; }
public PhysicsGame() { //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); //broadphase = new DbvtBroadphase(); broadphase = new AxisSweep3(new Vector3(-250, -12, -15), new Vector3(250, 70, 600)); world = new DiscreteDynamicsWorld(dispatcher, broadphase, constraintSolver, collisionConfiguration) { Gravity = new TGCVector3(0, -9.8f, 0).ToBsVector }; items = new List <Item>(); bullets = new List <Bullet>(); //enemies = new List<Enemy>(); InitializeShadersAndEffects(); }
public GImpactTestDemoSimulation() { CollisionConfiguration = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConfiguration); //Broadphase = new SimpleBroadphase(); Broadphase = new AxisSweep3_32Bit(new Vector3(-10000, -10000, -10000), new Vector3(10000, 10000, 10000), 1024); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher); _torusShapeData = new TriangleIndexVertexArray(Torus.Indices, Torus.Vertices); _torusShape = CreateGImpactShape(_torusShapeData); _bunnyShapeData = new TriangleIndexVertexArray(Bunny.Indices, Bunny.Vertices); _bunnyShape = CreateGImpactShape(_bunnyShapeData); CreateStaticScene(); CreateTorusChain(); CreateBoxes(); }
/// <summary> /// Called when the script instance is being initialized. /// Initializes the bullet physics environment /// </summary> public override void Awake() { QualitySettings.SetQualityLevel(PlayerPrefs.GetInt("qualityLevel")); Screen.fullScreenMode = (FullScreenMode)PlayerPrefs.GetInt("fullscreen", 1); GameObject.Find("VersionNumber").GetComponent <Text>().text = "Version " + CurrentVersion; if (CheckConnection()) { WebClient client = new WebClient(); ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback; var json = new WebClient().DownloadString("https://raw.githubusercontent.com/Autodesk/synthesis/master/VersionManager.json"); VersionManager update = JsonConvert.DeserializeObject <VersionManager>(json); SimUI.updater = update.URL; var localVersion = new Version(CurrentVersion); var globalVersion = new Version(update.Version); var check = localVersion.CompareTo(globalVersion); if (check < 0) { Auxiliary.FindGameObject("UpdatePrompt").SetActive(true); } } robotDirectory = PlayerPrefs.GetString("RobotDirectory"); Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes"); GImpactCollisionAlgorithm.RegisterAlgorithm((CollisionDispatcher)BPhysicsWorld.Get().world.Dispatcher); //BPhysicsWorld.Get().DebugDrawMode = DebugDrawModes.DrawWireframe | DebugDrawModes.DrawConstraints | DebugDrawModes.DrawConstraintLimits; BPhysicsWorld.Get().DebugDrawMode = DebugDrawModes.All; BPhysicsWorld.Get().DoDebugDraw = false; ((DynamicsWorld)BPhysicsWorld.Get().world).SolverInfo.NumIterations = SolverIterations; CollisionTracker = new CollisionTracker(this); SpawnedRobots = new List <SimulatorRobot>(); }
private void initFisica() { //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration); dynamicsWorld.Gravity = new TGCVector3(0, -10f, 0).ToBulletVector3(); //Creamos el cuerpo del piso StaticPlaneShape floorShape = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 0); DefaultMotionState floorMotionState = new DefaultMotionState(); RigidBodyConstructionInfo floorInfo = new RigidBodyConstructionInfo(0, floorMotionState, floorShape); floorBody = new RigidBody(floorInfo); floorBody.Restitution = 1.25f; dynamicsWorld.AddRigidBody(floorBody); }
public void Init(string MediaDir) { #region Configuracion Basica de World //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration); dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBulletVector3(); #endregion Configuracion Basica de World strength = 5.8f; angle = 0.5f; foreach (var mesh in meshes) { var childTriangleMesh = construirTriangleMeshShape(mesh); var buildingbody = construirRigidBodyDeChildTriangleMeshShape(childTriangleMesh, mesh.Position, mesh.Scale); //buildingbody.Translate(mesh.Position.ToBulletVector3()); dynamicsWorld.AddRigidBody(buildingbody); } //Se crea un plano ya que esta escena tiene problemas //con la definición de triangulos para el suelo var floorShape = new StaticPlaneShape(TGCVector3.Up.ToBulletVector3(), 10); floorShape.LocalScaling = new TGCVector3().ToBulletVector3(); var floorMotionState = new DefaultMotionState(); var floorInfo = new RigidBodyConstructionInfo(0, floorMotionState, floorShape); floorBody = new RigidBody(floorInfo); floorBody.Friction = 0.5f; floorBody.RollingFriction = 1; floorBody.Restitution = 1f; floorBody.UserObject = "floorBody"; dynamicsWorld.AddRigidBody(floorBody); var meshRigidBody = BulletRigidBodyFactory.Instance.CreateSurfaceFromHeighMap(terreno.getData()); dynamicsWorld.AddRigidBody(meshRigidBody); var loader = new TgcSceneLoader(); //Se crea el cuerpo rígido de la caja, en la definicio de CreateBox el ultimo parametro representa si se quiere o no //calcular el momento de inercia del cuerpo. No calcularlo lo que va a hacer es que la caja que representa el personaje //no rote cuando colicione contra el mundo. personajeBody = BulletRigidBodyFactory.Instance.CreateCapsule(10, 10, personaje.Position, 2.55f, false); personajeBody.Gravity = new TGCVector3(0, -100, 0).ToBulletVector3(); personajeBody.SetDamping(0.3f, 0f); personajeBody.Restitution = 0.1f; personajeBody.Friction = 1; personajeBody.ActivationState = ActivationState.IslandSleeping; dynamicsWorld.AddRigidBody(personajeBody); director = new TGCVector3(-1, 0, 0); }
void Awake() { GImpactCollisionAlgorithm.RegisterAlgorithm((CollisionDispatcher)BPhysicsWorld.Get().world.Dispatcher); BPhysicsWorld.Get().DebugDrawMode = DebugDrawModes.DrawWireframe | DebugDrawModes.DrawConstraints | DebugDrawModes.DrawConstraintLimits; BPhysicsWorld.Get().DoDebugDraw = true; }
public SerializeDemoSimulation() { CollisionConfiguration = new DefaultCollisionConfiguration(); Dispatcher = new CollisionDispatcher(CollisionConfiguration); Broadphase = new DbvtBroadphase(); World = new DiscreteDynamicsWorld(Dispatcher, Broadphase, null, CollisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher); string bulletFile; string[] args = Environment.GetCommandLineArgs(); if (args.Length == 1) { bulletFile = "testFile.bullet"; } else { bulletFile = args[1]; } _fileLoader = new CustomBulletWorldImporter(World); if (!_fileLoader.LoadFile(bulletFile)) { var groundShape = new BoxShape(50); _collisionShapes.Add(groundShape); RigidBody ground = PhysicsHelper.CreateStaticBody(Matrix.Translation(0, -50, 0), groundShape, World); ground.UserObject = "Ground"; // create a few dynamic rigidbodies float mass = 1.0f; Vector3[] positions = new[] { new Vector3(0.1f, 0.2f, 0.3f), new Vector3(0.4f, 0.5f, 0.6f) }; float[] radi = new float[2] { 0.3f, 0.4f }; var colShape = new MultiSphereShape(positions, radi); //var colShape = new CapsuleShapeZ(1, 1); //var colShape = new CylinderShapeZ(1, 1, 1); //var colShape = new BoxShape(1); //var colShape = new SphereShape(1); _collisionShapes.Add(colShape); Vector3 localInertia = colShape.CalculateLocalInertia(mass); float startX = StartPosX - NumObjectsX / 2; float startY = StartPosY; float startZ = StartPosZ - NumObjectsZ / 2; for (int y = 0; y < NumObjectsY; y++) { for (int x = 0; x < NumObjectsX; x++) { for (int z = 0; z < NumObjectsZ; z++) { Matrix startTransform = Matrix.Translation( 2 * x + startX, 2 * y + startY, 2 * z + startZ ); // 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); rbInfo.Dispose(); // make it drop from a height body.Translate(new Vector3(0, 20, 0)); World.AddRigidBody(body); } } } using (var serializer = new DefaultSerializer()) { serializer.RegisterNameForObject(ground, "GroundName"); for (int i = 0; i < _collisionShapes.Count; i++) { serializer.RegisterNameForObject(_collisionShapes[i], "name" + i.ToString()); } var p2p = new Point2PointConstraint((RigidBody)World.CollisionObjectArray[2], new Vector3(0, 1, 0)); World.AddConstraint(p2p); serializer.RegisterNameForObject(p2p, "constraintje"); World.Serialize(serializer); byte[] dataBytes = new byte[serializer.CurrentBufferSize]; Marshal.Copy(serializer.BufferPointer, dataBytes, 0, dataBytes.Length); using (var file = new FileStream("testFile.bullet", FileMode.Create)) { file.Write(dataBytes, 0, dataBytes.Length); } } } }
public void Init(String MediaDir) { #region world configuration // Create a physics world using default config collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration); var gravity = new TGCVector3(0, -60f, 0).ToBsVector; dynamicsWorld.Gravity = gravity; if (UsingHeightmap) { var heightMap = BulletRigidBodyConstructor.CreateSurfaceFromHeighMap(triangleDataVB); heightMap.Restitution = 0; dynamicsWorld.AddRigidBody(heightMap); } #endregion float radius = 30f; float mass = 0.75f; var centerOfMass = new TGCVector3(-50f, 30, -200f); TGCVector3 size = TGCVector3.Empty; #region Stone Sphere ball = BulletRigidBodyConstructor.CreateBall(radius, mass, centerOfMass); ball.SetDamping(0.1f, 0.5f); ball.Restitution = 1f; ball.Friction = 1; dynamicsWorld.AddRigidBody(ball); var ballTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{MediaDir}\\Textures\\rockwall.jpg"); sphereMesh = new TGCSphere(radius, ballTexture, TGCVector3.Empty); sphereMesh.BoundingSphere.setValues(centerOfMass, radius); sphereMesh.updateValues(); director = new TGCVector3(1, 0, 0); #endregion #region BandicootRigidBody //Cuerpo rigido de una caja basica var position = new TGCVector3(0, 1, 0); mass = 1.5f; bandicootRigidBody = BulletRigidBodyConstructor.CreateCapsule(10, 5, position, mass, false); //Valores que podemos modificar a partir del RigidBody base bandicootRigidBody.SetDamping(0.1f, 0f); bandicootRigidBody.Restitution = 0f; bandicootRigidBody.Friction = 0.5f; bandicootRigidBody.InvInertiaDiagLocal = TGCVector3.Empty.ToBsVector; //Agregamos el RidigBody al World dynamicsWorld.AddRigidBody(bandicootRigidBody); #endregion #region Stairs mass = 0; size = new TGCVector3(50, 20, 30); var platformTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{MediaDir}\\textures\\rockwall.jpg"); float angle = 0.75f * FastMath.PI; for (float i = 0, x = size.Z, y = size.Y, z = -size.X; i < 10; i++) { staticPlatform = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, 0.7f); staticPlatform.CenterOfMassTransform = TGCMatrix.RotationY(angle).ToBsMatrix *TGCMatrix.Translation(x, y, z).ToBsMatrix; dynamicsWorld.AddRigidBody(staticPlatform); staticPlatformMesh = TGCBox.fromSize(2 * size, platformTexture); staticPlatformMesh.Transform = new TGCMatrix(staticPlatform.InterpolationWorldTransform); stairsMesh.Add(staticPlatformMesh); x += 35; y += 40; z -= 25; angle -= 0.1f; } #endregion #region Dynamic Platform position = new TGCVector3(0, 0, 0); mass = 1f; size = new TGCVector3(70, 10, 30); dynamicPlatform = BulletRigidBodyConstructor.CreateBox(size, mass, position, 0, 0, 0, 2f); dynamicPlatform.CenterOfMassTransform = TGCMatrix.Translation(-300, 60, -200).ToBsMatrix; dynamicPlatform.AngularFactor = (new Vector3(0, 0, 0)); dynamicsWorld.AddRigidBody(dynamicPlatform); // mesh para visualizar plataforma var platformtexture = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{MediaDir}\\textures\\rockwall.jpg"); dynamicPlatformMesh = TGCBox.fromSize(2 * size, platformtexture); dynamicPlatformMesh.Transform = new TGCMatrix(dynamicPlatform.InterpolationWorldTransform); dynamicPlatformMesh.AutoTransformEnable = false; dynamicPlatformMesh.updateValues(); #endregion }
protected override void OnInitializePhysics() { // 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); GImpactCollisionAlgorithm.RegisterAlgorithm(Dispatcher); string bulletFile; string[] args = Environment.GetCommandLineArgs(); if (args.Length == 1) { bulletFile = "testFile.bullet"; } else { bulletFile = args[1]; } fileLoader = new CustomBulletWorldImporter(World); if (!fileLoader.LoadFile(bulletFile)) { CollisionShape groundShape = new BoxShape(50); CollisionShapes.Add(groundShape); RigidBody ground = LocalCreateRigidBody(0, Matrix.Translation(0, -50, 0), groundShape); ground.UserObject = "Ground"; // create a few dynamic rigidbodies float mass = 1.0f; Vector3[] positions = new Vector3[2] { new Vector3(0.1f, 0.2f, 0.3f), new Vector3(0.4f, 0.5f, 0.6f) }; float[] radi = new float[2] { 0.3f, 0.4f }; CollisionShape colShape = new MultiSphereShape(positions, radi); //CollisionShape colShape = new CapsuleShapeZ(1, 1); //CollisionShape colShape = new CylinderShapeZ(1, 1, 1); //CollisionShape colShape = new BoxShape(1); //CollisionShape colShape = new SphereShape(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.Translation( 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); rbInfo.Dispose(); // make it drop from a height body.Translate(new Vector3(0, 20, 0)); World.AddRigidBody(body); } } } DefaultSerializer serializer = new DefaultSerializer(); serializer.RegisterNameForObject(ground, "GroundName"); for (i = 0; i < CollisionShapes.Count; i++) { serializer.RegisterNameForObject(CollisionShapes[i], "name" + i.ToString()); } Point2PointConstraint p2p = new Point2PointConstraint((RigidBody)World.CollisionObjectArray[2], new Vector3(0, 1, 0)); World.AddConstraint(p2p); serializer.RegisterNameForObject(p2p, "constraintje"); World.Serialize(serializer); BulletSharp.DataStream data = serializer.LockBuffer(); byte[] dataBytes = new byte[data.Length]; data.Read(dataBytes, 0, dataBytes.Length); FileStream file = new FileStream("testFile.bullet", FileMode.Create); file.Write(dataBytes, 0, dataBytes.Length); file.Close(); } }
protected UnityEngine.Vector3 m_eulerrotf; // euler rotation last frame // Sets up initial collision shapes and objects for the simulation. protected override void InitSim() { Debug.Log("InitSim"); // create data directory if doesn't exist Directory.CreateDirectory(dataOutDir); // get list of all objs to sim if (!BUILD_MODE) { m_baseDataDir = Application.dataPath + "/Resources/" + dataInDir + "/"; } else { m_baseDataDir = Application.dataPath + "/../../Assets/Resources/" + dataInDir + "/"; } DirectoryInfo resDirPath = new DirectoryInfo(m_baseDataDir); FileInfo[] objFileInfos = resDirPath.GetFiles("*.obj", SearchOption.AllDirectories); Debug.Log("Files to sim: " + objFileInfos.Length.ToString()); m_objFiles = new string[objFileInfos.Length]; int fileIdx = 0; foreach (FileInfo file in objFileInfos) { m_objFiles[fileIdx++] = file.Name; } // First read in all volumes m_masses = new float[m_objFiles.Length]; float maxVol = -float.MaxValue; m_inertias = new List <BulletSharp.Math.Vector3>(); for (int i = 0; i < m_masses.Length; i++) { string infoFile = dataInDir + "/" + m_objFiles[i].Replace(".obj", ""); /*if (DEBUG)*/ Debug.Log("Idx " + i.ToString() + ": " + infoFile); var jsonTextFile = Resources.Load <TextAsset>(infoFile); if (DEBUG) { Debug.Log(jsonTextFile.ToString()); } ObjInfo curInfo = ObjInfo.CreateFromJSON(jsonTextFile.ToString()); m_masses[i] = curInfo.vol; // moment of inertias assume the density is 1 (i.e. mass = volume) m_inertias.Add(new BulletSharp.Math.Vector3(curInfo.inertia[0], curInfo.inertia[1], curInfo.inertia[2])); if (DEBUG) { Debug.Log(m_masses[i].ToString()); } if (m_masses[i] > maxVol) { maxVol = m_masses[i]; } } // Normalize volumes and use as mass // float normCoeff = massMax / maxVol; // need to scale density by this much. // for (int i = 0; i < m_masses.Length; i++) { // m_masses[i] = normCoeff * m_masses[i]; // m_inertias[i] = normCoeff * m_inertias[i]; // if (DEBUG) Debug.Log(m_masses[i].ToString()); // if (DEBUG) Debug.Log(m_inertias[i].ToString()); // } // only simulate one of interest for debugging if (DEBUG_simFileIdx != -1) { string simObjFile = m_objFiles[DEBUG_simFileIdx]; float simMass = m_masses[DEBUG_simFileIdx]; BulletSharp.Math.Vector3 simInertia = m_inertias[DEBUG_simFileIdx]; m_objFiles = new string[1]; m_objFiles[0] = simObjFile; m_masses = new float[1]; m_masses[0] = simMass; m_inertias = new List <BulletSharp.Math.Vector3>(); m_inertias.Add(simInertia); Debug.Log("ONLY SIMULATING: " + simObjFile); } // create the ground, this will be the same for every sim BulletSharp.Math.Vector3 groundSize = new BulletSharp.Math.Vector3(50, 0.04f, 50); BoxShape groundShape = new BoxShape(groundSize); // groundShape.Margin = 0.07f; AddCollisionShape(groundShape); m_groundMargin = groundShape.Margin; // move down so surface is exactly y=0 Debug.Log("GROUND MARGIN: " + m_groundMargin.ToString()); // The 0.016 is dependent on the ground margin but idk why at this point m_groundInitTrans = Matrix.Translation(new BulletSharp.Math.Vector3(0, -((groundSize[1] / 2.0f) + 0.016f), 0)); m_groundRb = CreateRigidBody(0, m_groundInitTrans, groundShape, groundMat, groundFriction, viz: RENDER_MODE); // setup the camera SetEyeTarget(cameraLoc, cameraTarget); // Now load the first simulation object to start m_curObjIdx = startingObjIdx; if (m_objFiles.Length == 0) { ExitSimulation(); } else { m_curDataOutDir = Path.Combine(dataOutDir, m_objFiles[m_curObjIdx].Replace(".obj", "") + "/"); Directory.CreateDirectory(m_curDataOutDir); PrepareSimObj(m_baseDataDir + m_objFiles[m_curObjIdx], m_masses[m_curObjIdx], m_inertias[m_curObjIdx]); m_curVideoOutDir = Path.Combine(Application.dataPath, videoOutDir); m_curVideoOutDir = Path.Combine(m_curVideoOutDir, m_objFiles[m_curObjIdx].Replace(".obj", "") + "/"); Directory.CreateDirectory(m_curVideoOutDir); string simOutDir = Path.Combine(m_curVideoOutDir, "sim_0"); if (!Directory.Exists(simOutDir)) { Directory.CreateDirectory(simOutDir); } } // so we can handle object collisions, only need to do this once GImpactCollisionAlgorithm.RegisterAlgorithm(m_colDispatcher); InitStateLists(); // determine and apply the force for the first simulation SetupSim(); // take note of inital rigid body state SaveInitState(); SaveCurrentState(); m_curSimNum = 0; m_renderFrame = 1; // set up rotation tracking m_totalRot = new BulletSharp.Math.Vector3(0.0f, 0.0f, 0.0f); m_pclScale = UnityEngine.Vector3.one; m_fallenFiles = new List <string>(); m_fallCount = 0; m_stepCount = 0; m_stuckCount = 0; m_numPerturbs = 0; }
public void Init(string MediaDir) { #region Configuracion Basica de World //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); //AxisSweep3(new BsVector3(-5000f, -5000f, -5000f), new BsVector3(5000f, 5000f, 5000f), 8192); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration); dynamicsWorld.Gravity = new TGCVector3(0, -100f, 0).ToBulletVector3(); #endregion Configuracion Basica de World #region Capsula //Cuerpo rigido de una capsula basica capsuleRigidBody = BulletRigidBodyFactory.Instance.CreateCapsule(10, 50, new TGCVector3(200, 500, 200), 10, false); //Valores que podemos modificar a partir del RigidBody base capsuleRigidBody.SetDamping(0.1f, 0f); capsuleRigidBody.Restitution = 0.1f; capsuleRigidBody.Friction = 1; //Agregamos el RidigBody al World dynamicsWorld.AddRigidBody(capsuleRigidBody); #endregion Capsula #region Terreno //Creamos el RigidBody basico del Terreno var meshRigidBody = BulletRigidBodyFactory.Instance.CreateSurfaceFromHeighMap(triangleDataVB); //Agregamos algo de friccion al RigidBody ya que este va a interactuar con objetos moviles //del World meshRigidBody.Friction = 0.5f; //Agregamos el RigidBody del terreno al World dynamicsWorld.AddRigidBody(meshRigidBody); #endregion Terreno #region Esfera //Creamos una esfera para interactuar pokeball = BulletRigidBodyFactory.Instance.CreateBall(10f, 0.5f, new TGCVector3(100f, 500f, 100f)); pokeball.SetDamping(0.1f, 0.5f); pokeball.Restitution = 1f; //Agregamos la pokebola al World dynamicsWorld.AddRigidBody(pokeball); //Textura de pokebola var texturePokeball = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\pokeball.jpg"); //Se crea una esfera de tamaño 1 para escalarla luego (en render) sphereMesh = new TGCSphere(1, texturePokeball, TGCVector3.Empty); //Tgc no crea el vertex buffer hasta invocar a update values. sphereMesh.updateValues(); #endregion Esfera #region Personaje //Cargamos personaje var skeletalLoader = new TgcSkeletalLoader(); personaje = skeletalLoader.loadMeshAndAnimationsFromFile( MediaDir + "SkeletalAnimations\\Robot\\Robot-TgcSkeletalMesh.xml", MediaDir + "SkeletalAnimations\\Robot\\", new[] { MediaDir + "SkeletalAnimations\\Robot\\Caminando-TgcSkeletalAnim.xml", MediaDir + "SkeletalAnimations\\Robot\\Parado-TgcSkeletalAnim.xml" }); //Le cambiamos la textura para diferenciarlo un poco personaje.changeDiffuseMaps(new[] { TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "SkeletalAnimations\\Robot\\Textures\\uvwGreen.jpg") }); //Configurar animacion inicial personaje.playAnimation("Parado", true); #endregion Personaje #region Cajas var sizeBox = 20f; //Textura de caja var textureBox = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"MeshCreator\Textures\Madera\cajaMadera2.jpg"); box = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(0, 12, 0), 0, 0, 0, 0.5f, true); dynamicsWorld.AddRigidBody(box); boxMesh = TGCBox.fromSize(new TGCVector3(40f, 40f, 40f), textureBox); boxMesh.updateValues(); sizeBox = 40f; boxB = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(100, 40, 0), 0, 0, 0, 0.5f, true); dynamicsWorld.AddRigidBody(boxB); boxMeshB = TGCBox.fromSize(new TGCVector3(80f, 80f, 80f), textureBox); boxMeshB.updateValues(); box45 = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0, new TGCVector3(200, 40, 0), BulletSharp.MathUtil.SIMD_QUARTER_PI, 0, 0, 0.5f, true); dynamicsWorld.AddRigidBody(box45); boxPush = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(sizeBox, sizeBox, sizeBox), 0.5f, new TGCVector3(-200, 60, 0), BulletSharp.MathUtil.SIMD_QUARTER_PI, 0, 0, 0.25f, true); dynamicsWorld.AddRigidBody(boxPush); boxMeshPush = TGCBox.fromSize(new TGCVector3(80f, 80f, 80f), textureBox); boxMeshPush.updateValues(); #endregion Cajas #region Escalera var a = 0; var textureStones = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\stones.bmp"); //la altura de cualquier cubo que quiera subir una capsula debe ser menor a la mitad del radio var size = new TGCVector3(50, 4, 20); escalon = TGCBox.fromSize(size, textureStones); //Se crean 10 escalonescd d while (a < 10) { escalonRigidBody = BulletRigidBodyFactory.Instance.CreateBox(size, 0, new TGCVector3(200, a * 4 + 10, a * 20 + 100), 0, 0, 0, 0.1f, true); escalonesRigidBodies.Add(escalonRigidBody); dynamicsWorld.AddRigidBody(escalonRigidBody); a++; } #endregion Escalera #region Plataforma textureStones = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + @"Texturas\cobblestone_quad.jpg"); rigidBodyPlataforma = BulletRigidBodyFactory.Instance.CreateBox(new TGCVector3(50f, 15f, 50f), 0, new TGCVector3(200, 42.5f, 315), 0, 0, 0, 0.5f, true); dynamicsWorld.AddRigidBody(rigidBodyPlataforma); plataforma = TGCBox.fromSize(new TGCVector3(50f, 15f, 50f), textureStones); plataforma.updateValues(); #endregion Plataforma #region Columna columnaRigidBody = BulletRigidBodyFactory.Instance.CreateCylinder(new TGCVector3(10, 50, 10), new TGCVector3(100, 50, 100), 0); dynamicsWorld.AddRigidBody(columnaRigidBody); var columnaLoader = new TgcSceneLoader(); columnaMesh = columnaLoader.loadSceneFromFile(MediaDir + @"MeshCreator\Meshes\Cimientos\PilarEgipcio\PilarEgipcio-TgcScene.xml", MediaDir + @"MeshCreator\Meshes\Cimientos\PilarEgipcio\").Meshes[0]; columnaMesh.Position = new TGCVector3(100, 7.5f, 100); columnaMesh.UpdateMeshTransform(); #endregion Columna director = new TGCVector3(0, 0, 1); }
public void Init() { #region MUNDO_FISICO //Creamos el mundo fisico por defecto. collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration) { Gravity = new TGCVector3(0, -20f, 0).ToBsVector }; #endregion var texture = TgcTexture.createTexture(D3DDevice.Instance.Device, GameModel.mediaDir + "texturas\\terrain\\NormalMapMar.png"); //Creamos shapes y bodies. #region PISO //El piso es un plano estatico se dice que si tiene masa 0 es estatico. var floorShape = new StaticPlaneShape(TGCVector3.Up.ToBsVector, 0); var floorMotionState = new DefaultMotionState(); var floorInfo = new RigidBodyConstructionInfo(0, floorMotionState, floorShape); floorBody = new RigidBody(floorInfo); dynamicsWorld.AddRigidBody(floorBody); //Cargamos objetos de render del framework. var floorTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, GameModel.mediaDir + "modelos\\Textures\\Canionero.jpg"); floorMesh = new TgcPlane(new TGCVector3(0, 500, 0), new TGCVector3(400, 0f, 400), TgcPlane.Orientations.XZplane, floorTexture); #endregion #region CAJA //Se crea una caja de tamaño 20 con rotaciones y origien en 10,100,10 y 1kg de masa. var boxShape = new BoxShape(10, 10, 10); var boxTransform = TGCMatrix.RotationYawPitchRoll(MathUtil.SIMD_HALF_PI, MathUtil.SIMD_QUARTER_PI, MathUtil.SIMD_2_PI).ToBsMatrix; boxTransform.Origin = new TGCVector3(0, 600, 0).ToBsVector; DefaultMotionState boxMotionState = new DefaultMotionState(boxTransform); //Es importante calcular la inercia caso contrario el objeto no rotara. var boxLocalInertia = boxShape.CalculateLocalInertia(1f); var boxInfo = new RigidBodyConstructionInfo(1f, boxMotionState, boxShape, boxLocalInertia); boxBody = new RigidBody(boxInfo); dynamicsWorld.AddRigidBody(boxBody); //Es importante crear todos los mesh con centro en el 0,0,0 y que este coincida con el centro de masa definido caso contrario rotaria de otra forma diferente a la dada por el motor de fisica. boxMesh = TGCBox.fromSize(new TGCVector3(20, 20, 20), texture); #endregion #region BOLA //Se crea una esfera de tamaño 1 para escalarla luego (en render) //Crea una bola de radio 10 origen 50 de 1 kg. var ballShape = new SphereShape(10); var ballTransform = TGCMatrix.Identity; ballTransform.Origin = new TGCVector3(0, 200, 0); var ballMotionState = new DefaultMotionState(ballTransform.ToBsMatrix); //Podriamos no calcular la inercia para que no rote, pero es correcto que rote tambien. var ballLocalInertia = ballShape.CalculateLocalInertia(1f); var ballInfo = new RigidBodyConstructionInfo(1, ballMotionState, ballShape, ballLocalInertia); ballBody = new RigidBody(ballInfo); dynamicsWorld.AddRigidBody(ballBody); sphereMesh = new TGCSphere(1, texture.Clone(), TGCVector3.Empty); //Tgc no crea el vertex buffer hasta invocar a update values. sphereMesh.updateValues(); #endregion callback = new MyContactResultCallback(dispatcher, dynamicsWorld, floorBody);// boxBody); }
public void Init(IGameModel ctx) { #region World configuration this.ctx = ctx; // Create a physics world using default config collisionConfiguration = new DefaultCollisionConfiguration(); dispatcher = new CollisionDispatcher(collisionConfiguration); GImpactCollisionAlgorithm.RegisterAlgorithm(dispatcher); constraintSolver = new SequentialImpulseConstraintSolver(); overlappingPairCache = new DbvtBroadphase(); dynamicsWorld = new DiscreteDynamicsWorld(dispatcher, overlappingPairCache, constraintSolver, collisionConfiguration) { Gravity = new TGCVector3(0, -15f, 0).ToBsVector }; var heightMap = BulletRigidBodyConstructor.CreateSurfaceFromHeighMap(ctx.Terrain.getData()); heightMap.Restitution = 0; dynamicsWorld.AddRigidBody(heightMap); #endregion #region BandicootRigidBody var position = new TGCVector3(0, 1, 0); var mass = 1.5f; var radius = 10; var height = 5; BandicootRigidBody = BulletRigidBodyConstructor.CreateCapsule(radius, height, position, mass, false); BandicootRigidBody.SetDamping(0.1f, 0); BandicootRigidBody.Restitution = 0f; BandicootRigidBody.Friction = 0.15f; BandicootRigidBody.InvInertiaDiagLocal = TGCVector3.Empty.ToBsVector; BandicootRigidBody.CenterOfMassTransform = TGCMatrix.Translation(-900, 1000, 900).ToBsMatrix; dynamicsWorld.AddRigidBody(BandicootRigidBody); #endregion #region Rocks var size = new TGCVector3(200, 150, 200); mass = 0; var centerOfMass = TGCVector3.Empty; var rockFriction = 1.5f; var translation = TGCMatrix.Translation(-900, size.Y, 900); // Rock1 Body Rock1Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, rockFriction); Rock1Body.CenterOfMassTransform = translation.ToBsMatrix; dynamicsWorld.AddRigidBody(Rock1Body); // Rock1 Mesh var canyonTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{ctx.MediaDir}\\Textures\\canyon-horizontal.png"); Rock1Mesh = TGCBox.fromSize(centerOfMass, 2 * size, canyonTexture); Rock1Mesh.Transform = new TGCMatrix(Rock1Body.InterpolationWorldTransform); // Rock2 Body size = new TGCVector3(100, 150, 100); Rock2Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, rockFriction); translation *= TGCMatrix.Translation(400, 1, 1); Rock2Body.CenterOfMassTransform = translation.ToBsMatrix; dynamicsWorld.AddRigidBody(Rock2Body); // Rock2 Mesh Rock2Mesh = TGCBox.fromSize(centerOfMass, 2 * size, canyonTexture); Rock2Mesh.Transform = new TGCMatrix(Rock2Body.InterpolationWorldTransform); // Rock3 Body Rock3Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, rockFriction); translation *= TGCMatrix.Translation(800, 1, 1); Rock3Body.CenterOfMassTransform = translation.ToBsMatrix; dynamicsWorld.AddRigidBody(Rock3Body); // Rock3 Mesh Rock3Mesh = TGCBox.fromSize(centerOfMass, 2 * size, canyonTexture); Rock3Mesh.Transform = new TGCMatrix(Rock3Body.InterpolationWorldTransform); // Rock4 Body size = new TGCVector3(100, 200, 100); Rock4Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, rockFriction); translation *= TGCMatrix.Translation(0, 1, -700); Rock4Body.CenterOfMassTransform = translation.ToBsMatrix; dynamicsWorld.AddRigidBody(Rock4Body); // Rock4 Mesh Rock4Mesh = TGCBox.fromSize(centerOfMass, 2 * size, canyonTexture); Rock4Mesh.Transform = new TGCMatrix(Rock4Body.InterpolationWorldTransform); // Rock5 Body Rock5Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, rockFriction); translation *= TGCMatrix.Translation(1, 1, -900); Rock5Body.CenterOfMassTransform = translation.ToBsMatrix; dynamicsWorld.AddRigidBody(Rock5Body); // Rock5 Mesh Rock5Mesh = TGCBox.fromSize(centerOfMass, 2 * size, canyonTexture); Rock5Mesh.Transform = new TGCMatrix(Rock5Body.InterpolationWorldTransform); #endregion #region Dynamic Platforms mass = 1f; size = new TGCVector3(70, 10, 40); var platformFriction = 2.5f; // DynamicPlatform1 Body DynamicPlatform1Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, platformFriction); DynamicPlatform1Body.AngularFactor = new Vector3(0, 0, 0); DynamicPlatform1Body.CenterOfMassTransform = TGCMatrix.RotationY(FastMath.PI_HALF).ToBsMatrix *TGCMatrix.Translation(distance, 300, 900).ToBsMatrix; dynamicsWorld.AddRigidBody(DynamicPlatform1Body); // DynamicPlatform1 Mesh var platformtexture = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{ctx.MediaDir}\\textures\\rockwall.jpg"); DynamicPlatform1Mesh = TGCBox.fromSize(2 * size, platformtexture); DynamicPlatform1Mesh.Transform = new TGCMatrix(DynamicPlatform1Body.InterpolationWorldTransform); // DynamicPlatform2 Body DynamicPlatform2Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, platformFriction); DynamicPlatform2Body.AngularFactor = new Vector3(0, 0, 0); DynamicPlatform2Body.CenterOfMassTransform = TGCMatrix.Translation(300, 300, 700).ToBsMatrix; dynamicsWorld.AddRigidBody(DynamicPlatform2Body); // DynamicPlatform2 Mesh var platformtexture2 = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{ctx.MediaDir}\\textures\\rockwall.jpg"); DynamicPlatform2Mesh = TGCBox.fromSize(2 * size, platformtexture); DynamicPlatform2Mesh.Transform = new TGCMatrix(DynamicPlatform2Body.InterpolationWorldTransform); // DynamicPlatform3 Body DynamicPlatform3Body = BulletRigidBodyConstructor.CreateBox(size, mass, centerOfMass, 0, 0, 0, platformFriction); DynamicPlatform3Body.AngularFactor = new Vector3(0, 0, 0); DynamicPlatform3Body.CenterOfMassTransform = TGCMatrix.Translation(300, 350, 0).ToBsMatrix; dynamicsWorld.AddRigidBody(DynamicPlatform3Body); // DynamicPlatform3 Mesh platformtexture2 = TgcTexture.createTexture(D3DDevice.Instance.Device, $"{ctx.MediaDir}\\textures\\rockwall.jpg"); DynamicPlatform3Mesh = TGCBox.fromSize(2 * size, platformtexture); DynamicPlatform3Mesh.Transform = new TGCMatrix(DynamicPlatform3Body.InterpolationWorldTransform); #endregion }