/// <summary> /// Builds and spawns the body into the world. /// </summary> public virtual void SpawnBody() { if (Body != null) { DestroyBody(); } Body = new BEPUphysics.Entities.Entity(Shape, Mass); Body.CollisionInformation.CollisionRules.Group = CGroup; InternalOffset = new Location(Body.Position); Body.AngularVelocity = new Vector3((float)AVel.X, (float)AVel.Y, (float)AVel.Z); Body.LinearVelocity = new Vector3((float)LVel.X, (float)LVel.Y, (float)LVel.Z); Body.WorldTransform = WorldTransform; // TODO: Position + Quaternion Body.PositionUpdateMode = BEPUphysics.PositionUpdating.PositionUpdateMode.Passive; if (!CanRotate) { Body.AngularDamping = 1; } // TODO: Other settings // TODO: Gravity Body.Tag = this; SetFriction(Friction); SetBounciness(Bounciness); TheRegion.PhysicsWorld.Add(Body); for (int i = 0; i < Joints.Count; i++) { if (Joints[i] is BaseJoint joint) { joint.CurrentJoint = joint.GetBaseJoint(); TheRegion.PhysicsWorld.Add(joint.CurrentJoint); } } ShadowCastShape = Shape.GetCollidableInstance().BoundingBox; ShadowMainDupe = Shape.GetCollidableInstance().BoundingBox; ShadowCenter = GetPosition(); }
/// <summary> /// Builds and spawns the body into the world. /// </summary> public virtual void SpawnBody() { if (Body != null) { DestroyBody(); } Body = new BEPUphysics.Entities.Entity(Shape, Mass); Body.CollisionInformation.CollisionRules.Group = CGroup; InternalOffset = new Location(Body.Position); Body.AngularVelocity = new Vector3((double)AVel.X, (double)AVel.Y, (double)AVel.Z); Body.LinearVelocity = new Vector3((double)LVel.X, (double)LVel.Y, (double)LVel.Z); Body.WorldTransform = WorldTransform; // TODO: Position, Orientation Body.Tag = this; Body.PositionUpdateMode = BEPUphysics.PositionUpdating.PositionUpdateMode.Passive; if (!CanRotate) { Body.AngularDamping = 1; } // TODO: Other settings // TODO: Gravity SetFriction(Friction); SetBounciness(Bounciness); TheRegion.PhysicsWorld.Add(Body); for (int i = 0; i < Joints.Count; i++) { if (Joints[i] is BaseJoint) { BaseJoint joint = (BaseJoint)Joints[i]; joint.CurrentJoint = joint.GetBaseJoint(); TheRegion.PhysicsWorld.Add(joint.CurrentJoint); } } }
/// <summary> /// Create a Physics box prefab from a model. /// </summary> /// <param name="m">model to create from</param> /// <param name="position">position in world</param> /// <param name="mass">mass of box</param> /// <returns></returns> /*BEPUphysics.Entities.Prefabs.Box*/ public static BEPUphysics.Entities.Entity ModelToPhysicsBox(Model m, Vector3 position, float mass, float pitch, float yaw, float roll) { Vector3[] vertices; int[] indices; BEPUphysics.DataStructures.TriangleMesh.GetVerticesAndIndicesFromModel(m, out vertices, out indices); BoundingBox box = BoundingBox.CreateFromPoints(vertices); // calculate dimensions Vector3 difference = box.Max - box.Min; float length = difference.Z; float height = difference.Y; float width = difference.X; BEPUphysics.Entities.Entity e; if ( mass == -1.0f) { e = new BEPUphysics.Entities.Entity(new BEPUphysics.CollisionShapes.ConvexShapes.BoxShape(width, height, length)); } else { e = new BEPUphysics.Entities.Entity(new BEPUphysics.CollisionShapes.ConvexShapes.BoxShape(width, height, length), mass); } e.Orientation = Quaternion.CreateFromYawPitchRoll(yaw, pitch, roll); e.Position = position; return e; //return new BEPUphysics.Entities.Prefabs.Box(position, width, height, length, mass); }
void Events_ContactCreated(EntityCollidable sender, Collidable other, CollidablePairHandler pair, ContactData contact) { if (TheRegion.GlobalTickTimeLocal - lastSoundTime < soundmaxrate) { return; } lastSoundTime = TheRegion.GlobalTickTimeLocal; if (other is FullChunkObject) { ((ConvexFCOPairHandler)pair).ContactInfo(/*contact.Id*/ 0, out ContactInformation info); float vellen = (float)(Math.Abs(info.RelativeVelocity.X) + Math.Abs(info.RelativeVelocity.Y) + Math.Abs(info.RelativeVelocity.Z)); float mod = vellen / 5; if (mod > 2) { mod = 2; } Location block = new Location(contact.Position - contact.Normal * 0.01f); BlockInternal bi = TheRegion.GetBlockInternal(block); MaterialSound sound = ((Material)bi.BlockMaterial).Sound(); if (sound != MaterialSound.NONE) { new DefaultSoundPacketIn() { TheClient = TheClient }.PlayDefaultBlockSound(block, sound, mod, 0.5f * mod); } MaterialSound sound2 = Mat.Sound(); if (sound2 != MaterialSound.NONE) { new DefaultSoundPacketIn() { TheClient = TheClient }.PlayDefaultBlockSound(block, sound2, mod, 0.5f * mod); } } else if (other is EntityCollidable) { BEPUphysics.Entities.Entity e = ((EntityCollidable)other).Entity; BEPUutilities.Vector3 velocity = BEPUutilities.Vector3.Zero; if (e != null) { velocity = e.LinearVelocity; } BEPUutilities.Vector3 relvel = Body.LinearVelocity - velocity; float vellen = (float)(Math.Abs(relvel.X) + Math.Abs(relvel.Y) + Math.Abs(relvel.Z)); float mod = vellen / 5; if (mod > 2) { mod = 2; } MaterialSound sound = Mat.Sound(); if (sound != MaterialSound.NONE) { new DefaultSoundPacketIn() { TheClient = TheClient }.PlayDefaultBlockSound(new Location(contact.Position), sound, mod, 0.5f * mod); } } }
/// <summary> /// Destroys the body, removing it from the physics world. /// </summary> public virtual void DestroyBody() { if (Body == null) { return; } if (Body.Space == null) { Body = null; return; } LVel = new Location(Body.LinearVelocity); AVel = new Location(Body.AngularVelocity); Friction = GetFriction(); // TODO: Gravity = new Location(Body.Gravity.X, Body.Gravity.Y, Body.Gravity.Z); WorldTransform = Body.WorldTransform; for (int i = 0; i < Joints.Count; i++) { if (Joints[i] is BaseJoint joint && joint.CurrentJoint != null) { TheRegion.PhysicsWorld.Remove(joint.CurrentJoint); joint.CurrentJoint = null; } } TheRegion.PhysicsWorld.Remove(Body); Body = null; }
public ISpaceObject CreateJoint(BEPUphysics.Entities.Entity entity1, BEPUphysics.Entities.Entity entity2, Vector3 pos, Vector3 direction, Vector3 anchor) { // entity1 is us // entity2 is the main map we are attaching to this.physicsEntity = entity1; Vector3 originalPos = entity1.Position; Quaternion originalRotation = entity1.Orientation; entity1.Position = pos; entity1.Orientation = this.OriginalRotation; this.joint = new RevoluteJoint(entity1, entity2, anchor, direction); entity1.Position = originalPos; entity1.Orientation = originalRotation; float multiplier = Math.Max(1.0f, entity1.Mass); this.joint.AngularJoint.SpringSettings.StiffnessConstant *= multiplier; this.joint.Limit.SpringSettings.StiffnessConstant *= multiplier; this.joint.Motor.Settings.Mode = MotorMode.Servomechanism; this.setLimits(); this.setLocked(); this.setSpeed(); this.setMode(); this.setGoal(); return(joint); }
/// <summary> /// Destroys the body, removing it from the physics world. /// </summary> public virtual void DestroyBody() { if (Seats != null) { foreach (Seat seat in Seats) { if (seat.Sitter != null) { seat.Kick(); } } } LVel = new Location(Body.LinearVelocity.X, Body.LinearVelocity.Y, Body.LinearVelocity.Z); AVel = new Location(Body.AngularVelocity.X, Body.AngularVelocity.Y, Body.AngularVelocity.Z); Friction = GetFriction(); // TODO: Gravity = new Location(Body.Gravity.X, Body.Gravity.Y, Body.Gravity.Z); WorldTransform = Body.WorldTransform; for (int i = 0; i < Joints.Count; i++) { if (Joints[i] is BaseJoint joint) { try { TheRegion.PhysicsWorld.Remove(joint.CurrentJoint); } catch (Exception ex) { // We don't actually care if this errors. Utilities.CheckException(ex); } } } TheRegion.PhysicsWorld.Remove(Body); Body = null; }
public static void SetBox(Vector3 p, Vector3 n) { if (box == null) { box = new BEPUphysics.Entities.Prefabs.Box(BEPUutilities.Vector3.Zero, 1, 1, 1, 50); box.BecomeDynamic(50); World.Add(box); } box.Position = new BEPUutilities.Vector3(p.X, p.Y, p.Z); box.Orientation = BEPUutilities.Quaternion.Identity; box.LinearVelocity = new BEPUutilities.Vector3(n.X, n.Y, n.Z); }
/// <summary> /// Calculates the gravitational force to apply to the entity. /// </summary> /// <param name="e">Target of the impulse.</param> /// <param name="dt">Time since the last frame in simulation seconds.</param> /// <param name="impulse">Force to apply at the given position.</param> protected override void CalculateImpulse(BEPUphysics.Entities.Entity e, float dt, out Vector3 impulse) { Vector3 r = e.Position - Origin; float length = r.Length(); float force = dt * Math.Min(MaxForce, Multiplier * e.Mass / (length * length * length)); impulse = -force * r; //Could use a linear dropoff for a slightly faster calculation (divide by length^2 instead of length^3). //Vector3 r = e.Position - Origin; //float force = dt * Math.Min(MaxForce, Multiplier * e.Mass / (r.LengthSquared())); //impulse = -force * r; }
public RigidBody(Shape shape) { entity = new BEPUphysics.Entities.Entity(shape.shape); this.shape = shape; UpdateMassProperties(shape.Mass); //Helper.Check(shape.massDistribution); entity.BecomeDynamic(Mass, shape.massDistribution); //Check(); material = new Material(entity.Material); }
internal void CollisionEntityCreated(BEPUphysics.Entities.Entity collisionEntity) { if (collisionEntity == null) { return; } collisionEntity.Tag = this; PhysicsUsage.PhysicsManager.instance.Add(collisionEntity); collisionEntity.CollisionInformation.Events.ContactCreated += Events_ContactCreated; collisionEntity.CollisionInformation.Events.ContactRemoved += Events_ContactRemoved; collisionEntity_generic = collisionEntity; }
public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color) { MobileMeshShape shape = DisplayedObject.CollisionInformation.Shape as MobileMeshShape; var tempVertices = new VertexPositionNormalTexture[shape.TriangleMesh.Data.Vertices.Length]; for (int i = 0; i < shape.TriangleMesh.Data.Vertices.Length; i++) { Vector3 position; shape.TriangleMesh.Data.GetVertexPosition(i, out position); tempVertices[i] = new VertexPositionNormalTexture( position, Vector3.Zero, Vector2.Zero); } List <VertexPositionColor> vertices = new List <VertexPositionColor>(); List <short> indices = new List <short>(); for (int i = 0; i < shape.TriangleMesh.Data.Indices.Length; i++) { indices.Add((short)shape.TriangleMesh.Data.Indices[i]); } for (int i = 0; i < indices.Count; i += 3) { int a = indices[i]; int b = indices[i + 1]; int c = indices[i + 2]; Vector3 normal = Vector3.Normalize(Vector3.Cross( tempVertices[c].Position - tempVertices[a].Position, tempVertices[b].Position - tempVertices[a].Position)); tempVertices[a].Normal += normal; tempVertices[b].Normal += normal; tempVertices[c].Normal += normal; } for (int i = 0; i < tempVertices.Length; i++) { tempVertices[i].Normal.Normalize(); vertices.Add(new VertexPositionColor(tempVertices[i].Position, color)); } DebugInfo DebugInfo = new DebugInfo(); DebugInfo.vertices = vertices.ToArray(); DebugInfo.indices = indices.ToArray(); return(DebugInfo); }
public ISpaceObject CreateJoint(BEPUphysics.Entities.Entity entity1, BEPUphysics.Entities.Entity entity2, Vector3 pos, Vector3 direction, Vector3 anchor) { // entity1 is us // entity2 is the main map we are attaching to Vector3 originalPos = entity1.Position; entity1.Position = pos; this.joint = new NoRotationJoint(entity2, entity1); entity1.Position = originalPos; if (this.mover != null && this.mover.Space != null) { this.main.Space.Remove(this.mover); } this.mover = new EntityMover(entity1); this.main.Space.Add(this.mover); this.physicsUpdated(entity1.Mass, entity1.Volume); return(this.joint); }
public ISpaceObject CreateJoint(BEPUphysics.Entities.Entity entity1, BEPUphysics.Entities.Entity entity2, Vector3 pos, Vector3 direction, Vector3 anchor) { // entity1 is us // entity2 is the main map we are attaching to Vector3 originalPos = entity1.Position; entity1.Position = pos; this.joint = new PrismaticJoint(entity2, entity1, pos, direction, pos); entity1.Position = originalPos; this.setLimits(); this.setLocked(); this.setSpeed(); this.setGoal(); this.setMode(); this.setMaxForce(); this.joint.Motor.Settings.Servo.SpringSettings.StiffnessConstant = 0.03f; this.joint.Limit.Update(0.0f); return(this.joint); }
public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color) { var convexHullShape = DisplayedObject.CollisionInformation.Shape as ConvexHullShape; if (convexHullShape == null) { throw new ArgumentException("Wrong shape type."); } var hullTriangleVertices = new List <Vector3>(); var hullTriangleIndices = new List <int>(); Toolbox.GetConvexHull(convexHullShape.Vertices, hullTriangleIndices, hullTriangleVertices); //The hull triangle vertices are used as a dummy to get the unnecessary hull vertices, which are cleared afterwards. hullTriangleVertices.Clear(); foreach (int i in hullTriangleIndices) { hullTriangleVertices.Add(convexHullShape.Vertices[i]); } List <VertexPositionColor> vertices = new List <VertexPositionColor>(); List <short> indices = new List <short>(); Vector3 normal; for (short i = 0; i < hullTriangleVertices.Count; i += 3) { normal = Vector3.Normalize(Vector3.Cross(hullTriangleVertices[i + 2] - hullTriangleVertices[i], hullTriangleVertices[i + 1] - hullTriangleVertices[i])); vertices.Add(new VertexPositionColor(hullTriangleVertices[i], color)); vertices.Add(new VertexPositionColor(hullTriangleVertices[i + 1], color)); vertices.Add(new VertexPositionColor(hullTriangleVertices[i + 2], color)); indices.Add(i); indices.Add((short)(i + 1)); indices.Add((short)(i + 2)); } DebugInfo DebugInfo = new DebugInfo(); DebugInfo.vertices = vertices.ToArray(); DebugInfo.indices = indices.ToArray(); return(DebugInfo); }
public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color) { var sphereShape = DisplayedObject.CollisionInformation.Shape as SphereShape; if (sphereShape == null) { throw new ArgumentException("Wrong shape type"); } var n = new Vector3(); float angleBetweenFacets = MathHelper.TwoPi / NumSides; float radius = sphereShape.Radius; List <VertexPositionColor> vertices = new List <VertexPositionColor>(); List <short> indices = new List <short>(); //Create the vertex list vertices.Add(new VertexPositionColor(new Vector3(0, radius, 0), color)); for (int i = 1; i < NumSides / 2; i++) { float phi = MathHelper.PiOver2 - i * angleBetweenFacets; var sinPhi = (float)Math.Sin(phi); var cosPhi = (float)Math.Cos(phi); for (int j = 0; j < NumSides; j++) { float theta = j * angleBetweenFacets; n.X = (float)Math.Cos(theta) * cosPhi; n.Y = sinPhi; n.Z = (float)Math.Sin(theta) * cosPhi; vertices.Add(new VertexPositionColor(n * radius, color)); } } vertices.Add(new VertexPositionColor(new Vector3(0, -radius, 0), color)); //Create the index list for (int i = 0; i < NumSides; i++) { indices.Add((short)(vertices.Count - 1)); indices.Add((short)(vertices.Count - 2 - i)); indices.Add((short)(vertices.Count - 2 - (i + 1) % NumSides)); } for (int i = 0; i < NumSides / 2 - 2; i++) { for (int j = 0; j < NumSides; j++) { int nextColumn = (j + 1) % NumSides; indices.Add((short)(i * NumSides + nextColumn + 1)); indices.Add((short)(i * NumSides + j + 1)); indices.Add((short)((i + 1) * NumSides + j + 1)); indices.Add((short)((i + 1) * NumSides + nextColumn + 1)); indices.Add((short)(i * NumSides + nextColumn + 1)); indices.Add((short)((i + 1) * NumSides + j + 1)); } } for (int i = 0; i < NumSides; i++) { indices.Add(0); indices.Add((short)(i + 1)); indices.Add((short)((i + 1) % NumSides + 1)); } DebugInfo DebugInfo = new DebugInfo(); DebugInfo.vertices = vertices.ToArray(); DebugInfo.indices = indices.ToArray(); return(DebugInfo); }
protected override void Update(GameTime gameTime) { // Allows the game to exit float timeDelta = (float)gameTime.ElapsedGameTime.TotalSeconds; KeyboardState keyState = Keyboard.GetState(); MouseState mouseState = Mouse.GetState(); if (keyState.IsKeyDown(Keys.Escape)) { this.Exit(); } if (keyState.IsKeyDown(Keys.F1)) { if (!didSpawn) { Ray ray; ray.Position = Camera.Position; ray.Direction = Camera.Look; Vector3 point; if (ground.rayIntersects(ray, out point)) { point.Y = 10; createFromMesh(point, "fish", 10); didSpawn = true; } } } else if (keyState.IsKeyDown(Keys.F2)) { if (!didSpawn) { Ray ray; ray.Position = Camera.Position; ray.Direction = Camera.Look; Vector3 point; if (ground.rayIntersects(ray, out point)) { point.Y = 10; createFromMesh(point, "tube", 1); didSpawn = true; } } } else if (keyState.IsKeyDown(Keys.F3)) { if (!didSpawn) { Ray ray; ray.Position = Camera.Position; ray.Direction = Camera.Look; Vector3 point; if (ground.rayIntersects(ray, out point)) { point.Y = 10; createVehicle(point); didSpawn = true; } } } else if (keyState.IsKeyDown(Keys.F4)) { if (!didSpawn) { Ray ray; ray.Position = Camera.Position; ray.Direction = Camera.Look; Vector3 point; if (ground.rayIntersects(ray, out point)) { point.Y = 10; createFromMesh(point, "guy", 10); didSpawn = true; } } } else if (keyState.IsKeyDown(Keys.F5)) { if (!didSpawn) { Ray ray; ray.Position = Camera.Position; ray.Direction = Camera.Look; Vector3 point; if (ground.rayIntersects(ray, out point)) { point.Y = 25; BepuEntity cog1 = createCog(point, 10, 20); //BepuEntity cog2 = createCog(point, 10, 20); didSpawn = true; } } } else if (keyState.IsKeyDown(Keys.F12)) { resetScene(); didSpawn = true; } else { didSpawn = false; } if (mouseState.LeftButton == ButtonState.Pressed) { if (pickedUp == null) { Ray ray; ray.Position = Camera.Position; ray.Direction = Camera.Look; RayCastResult result; bool didDit = space.RayCast(ray, out result); if (didDit) { pickedUp = ((EntityCollidable)result.HitObject).Entity; if (pickedUp == groundBox) { pickedUp = null; } } } if (pickedUp != null) { float fDistance = 15.0f; float powerfactor = 50.0f; // Higher values causes the targets moving faster to the holding point. float maxVel = 40.0f; // Lower values prevent objects flying through walls. // Calculate the hold point in front of the camera Vector3 holdPos = Camera.Position + (Camera.Look * fDistance); Vector3 v = holdPos - pickedUp.Position; // direction to move the Target v *= powerfactor; // powerfactor of the GravityGun if (v.Length() > maxVel) { // if the correction-velocity is bigger than maximum v.Normalize(); v *= maxVel; // just set correction-velocity to the maximum } pickedUp.LinearVelocity = v; } } else { pickedUp = null; } if (keyState.IsKeyDown(Keys.F) & pickedUp != null) { pickedUp.LinearVelocity = Vector3.Zero; pickedUp.ApplyImpulse(pickedUp.Position, Camera.Look * 100.0f); pickedUp = null; } if (keyState.IsKeyDown(Keys.B) & lastFired > 0.25f) { fireBall(); lastFired = 0.0f; } lastFired += timeDelta; for (int i = 0; i < children.Count; i++) { children[i].Update(gameTime); } cameraCylindar.Position = camera.Position; space.Update(); base.Update(gameTime); }
internal void OnPhysicsUpdate(BEPUphysics.Entities.Entity obj) { this.position = obj.Position; this.rotation = obj.Orientation; }
/// <summary> /// Destroys the body, removing it from the physics world. /// </summary> public virtual void DestroyBody() { if (Seats != null) { foreach (Seat seat in Seats) { if (seat.Sitter != null) { seat.Kick(); } } } LVel = new Location(Body.LinearVelocity.X, Body.LinearVelocity.Y, Body.LinearVelocity.Z); AVel = new Location(Body.AngularVelocity.X, Body.AngularVelocity.Y, Body.AngularVelocity.Z); Friction = GetFriction(); // TODO: Gravity = new Location(Body.Gravity.X, Body.Gravity.Y, Body.Gravity.Z); WorldTransform = Body.WorldTransform; for (int i = 0; i < Joints.Count; i++) { if (Joints[i] is BaseJoint) { BaseJoint joint = (BaseJoint)Joints[i]; try { TheRegion.PhysicsWorld.Remove(joint.CurrentJoint); } catch (Exception ex) { // We don't actually care if this errors. Utilities.CheckException(ex); } } } TheRegion.PhysicsWorld.Remove(Body); Body = null; }
public override void Create(Vector3 position, Quaternion orientation, Vector3 velocity, BEPUphysics.Entities.Entity target) { throw new NotImplementedException(); }
public override void Click(Entity ent, ItemStack item) { if (!(ent is PlayerEntity)) { // TODO: update to generic entity return; } PlayerEntity player = (PlayerEntity)ent; Location eye = player.GetEyePosition(); Location forw = player.ForwardVector(); RayCastResult rcr; bool h = player.TheRegion.SpecialCaseRayTrace(eye, forw, 5, MaterialSolidity.FULLSOLID, player.IgnoreThis, out rcr); if (h) { bool hitIt = (player.TheRegion.GlobalTickTime - player.LastBlockBreak) > 0.5f; // TODO: Arbitrary constant! if (hitIt && rcr.HitObject != null && rcr.HitObject is EntityCollidable && ((EntityCollidable)rcr.HitObject).Entity != null) { BEPUphysics.Entities.Entity hitent = ((EntityCollidable)rcr.HitObject).Entity; Vector3 force = forw.ToBVector() * 75; // TODO: Arbitrary constant! hitent.ApplyImpulse(ref rcr.HitData.Location, ref force); // TODO: Damage player.LastBlockBreak = player.TheRegion.GlobalTickTime; return; } if (!player.Mode.GetDetails().CanBreak) { return; } bool breakIt = false; Location block = (new Location(rcr.HitData.Location) - new Location(rcr.HitData.Normal).Normalize() * 0.01).GetBlockLocation(); if (block != player.BlockBreakTarget) { player.BlockBreakStarted = 0; player.BlockBreakTarget = block; } Material mat = player.TheRegion.GetBlockMaterial(block); if (player.Mode.GetDetails().FastBreak) { breakIt = player.TheRegion.GlobalTickTime - player.LastBlockBreak >= 0.2; // TODO: Arbitrary constant! } else { if (player.BlockBreakStarted <= 0) { player.BlockBreakStarted = player.TheRegion.GlobalTickTime; } double bt = mat.GetBreakTime(); MaterialBreaker breaker = GetBreaker(); MaterialBreaker matbreaker = mat.GetBreaker(); if (matbreaker == MaterialBreaker.NON_BREAKABLE) { return; } // TODO: arbitrary constants! if (breaker == MaterialBreaker.PICKAXE) { if (matbreaker == MaterialBreaker.PICKAXE) { bt *= 0.3f; } else if (!mat.GetBreaksFromOtherTools()) { return; } else if (matbreaker == MaterialBreaker.AXE) { bt *= 0.7f; } else if (matbreaker == MaterialBreaker.SHOVEL) { bt *= 1.2f; } else if (matbreaker == MaterialBreaker.HAND) { bt *= 0.87f; } } // else: hand! Default values! breakIt = (player.TheRegion.GlobalTickTime - player.BlockBreakStarted) > bt; } if (breakIt) { if (player.TheRegion.IsAllowedToBreak(player, block, mat)) { player.TheRegion.BreakNaturally(block); player.Network.SendPacket(new DefaultSoundPacketOut(block, DefaultSound.BREAK, (byte)mat.Sound())); player.LastBlockBreak = player.TheRegion.GlobalTickTime; } player.BlockBreakStarted = 0; } } }
public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color) { var boxShape = DisplayedObject.CollisionInformation.Shape as BoxShape; var boundingBox = new BoundingBox( new Vector3(-boxShape.HalfWidth, -boxShape.HalfHeight, -boxShape.HalfLength), new Vector3(boxShape.HalfWidth, boxShape.HalfHeight, boxShape.HalfLength)); Vector3[] corners = boundingBox.GetCorners(); List <VertexPositionColor> vertices = new List <VertexPositionColor>(); List <short> indices = new List <short>(); vertices.Add(new VertexPositionColor(corners[0], color)); vertices.Add(new VertexPositionColor(corners[1], color)); vertices.Add(new VertexPositionColor(corners[2], color)); vertices.Add(new VertexPositionColor(corners[3], color)); indices.Add(0); indices.Add(1); indices.Add(2); indices.Add(0); indices.Add(2); indices.Add(3); vertices.Add(new VertexPositionColor(corners[1], color)); vertices.Add(new VertexPositionColor(corners[2], color)); vertices.Add(new VertexPositionColor(corners[5], color)); vertices.Add(new VertexPositionColor(corners[6], color)); indices.Add(4); indices.Add(6); indices.Add(7); indices.Add(4); indices.Add(7); indices.Add(5); vertices.Add(new VertexPositionColor(corners[4], color)); vertices.Add(new VertexPositionColor(corners[5], color)); vertices.Add(new VertexPositionColor(corners[6], color)); vertices.Add(new VertexPositionColor(corners[7], color)); indices.Add(9); indices.Add(8); indices.Add(11); indices.Add(9); indices.Add(11); indices.Add(10); vertices.Add(new VertexPositionColor(corners[0], color)); vertices.Add(new VertexPositionColor(corners[3], color)); vertices.Add(new VertexPositionColor(corners[4], color)); vertices.Add(new VertexPositionColor(corners[7], color)); indices.Add(14); indices.Add(12); indices.Add(13); indices.Add(14); indices.Add(13); indices.Add(15); vertices.Add(new VertexPositionColor(corners[0], color)); vertices.Add(new VertexPositionColor(corners[1], color)); vertices.Add(new VertexPositionColor(corners[4], color)); vertices.Add(new VertexPositionColor(corners[5], color)); indices.Add(16); indices.Add(19); indices.Add(17); indices.Add(16); indices.Add(18); indices.Add(19); vertices.Add(new VertexPositionColor(corners[2], color)); vertices.Add(new VertexPositionColor(corners[3], color)); vertices.Add(new VertexPositionColor(corners[6], color)); vertices.Add(new VertexPositionColor(corners[7], color)); indices.Add(21); indices.Add(20); indices.Add(22); indices.Add(21); indices.Add(22); indices.Add(23); DebugInfo DebugInfo = new DebugInfo(); DebugInfo.vertices = vertices.ToArray(); DebugInfo.indices = indices.ToArray(); return(DebugInfo); }
public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color) { ConeShape coneShape = DisplayedObject.CollisionInformation.Shape as ConeShape; if (coneShape == null) { throw new ArgumentException("Wrong shape type."); } float verticalOffset = -coneShape.Height / 4; float angleBetweenFacets = MathHelper.TwoPi / NumSides; float radius = coneShape.Radius; //Create the vertex list var topVertexPosition = new Vector3(0, coneShape.Height + verticalOffset, 0); List <VertexPositionColor> vertices = new List <VertexPositionColor>(); List <short> indices = new List <short>(); for (int i = 0; i < NumSides; i++) { float theta = i * angleBetweenFacets; var position = new Vector3((float)Math.Cos(theta) * radius, verticalOffset, (float)Math.Sin(theta) * radius); Vector3 offset = topVertexPosition - position; Vector3 normal = Vector3.Normalize(Vector3.Cross(Vector3.Cross(offset, Vector3.Up), offset)); //Top vertex vertices.Add(new VertexPositionColor(topVertexPosition, color)); //Sloped vertices vertices.Add(new VertexPositionColor(position, color)); //Bottom vertices vertices.Add(new VertexPositionColor(position, color)); } //Create the index list for (short i = 0; i < vertices.Count; i += 3) { //Each iteration, the loop advances to the next vertex 'column.' //Four triangles per column (except for the four degenerate cap triangles). //Sloped Triangles indices.Add(i); indices.Add((short)(i + 1)); indices.Add((short)((i + 4) % vertices.Count)); //Bottom cap triangles. var nextIndex = (short)((i + 5) % vertices.Count); if (nextIndex != 2) //Don't add cap indices if it's going to be a degenerate triangle. { indices.Add((short)(i + 2)); indices.Add(2); indices.Add(nextIndex); } } DebugInfo DebugInfo = new DebugInfo(); DebugInfo.vertices = vertices.ToArray(); DebugInfo.indices = indices.ToArray(); return(DebugInfo); }
public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color) { var transformableShape = DisplayedObject.CollisionInformation.Shape as TransformableShape; if (transformableShape == null) { throw new ArgumentException("Wrong shape type."); } var points = new List <Vector3>(); Vector3 max; var direction = new Vector3(); float angleChange = MathHelper.TwoPi / NumSamples; for (int i = 1; i < NumSamples / 2 - 1; i++) { float phi = MathHelper.PiOver2 - i * angleChange; var sinPhi = (float)Math.Sin(phi); var cosPhi = (float)Math.Cos(phi); for (int j = 0; j < NumSamples; j++) { float theta = j * angleChange; direction.X = (float)Math.Cos(theta) * cosPhi; direction.Y = sinPhi; direction.Z = (float)Math.Sin(theta) * cosPhi; transformableShape.GetLocalExtremePoint(direction, out max); points.Add(max); } } transformableShape.GetLocalExtremePoint(Toolbox.UpVector, out max); points.Add(max); transformableShape.GetLocalExtremePoint(Toolbox.DownVector, out max); points.Add(max); var hullTriangleVertices = new List <Vector3>(); var hullTriangleIndices = new List <int>(); Toolbox.GetConvexHull(points, hullTriangleIndices, hullTriangleVertices); //The hull triangle vertices are used as a dummy to get the unnecessary hull vertices, which are cleared afterwards. hullTriangleVertices.Clear(); foreach (int i in hullTriangleIndices) { hullTriangleVertices.Add(points[i]); } List <VertexPositionColor> vertices = new List <VertexPositionColor>(); List <short> indices = new List <short>(); Vector3 normal; for (short i = 0; i < hullTriangleVertices.Count; i += 3) { normal = Vector3.Normalize(Vector3.Cross(hullTriangleVertices[i + 2] - hullTriangleVertices[i], hullTriangleVertices[i + 1] - hullTriangleVertices[i])); vertices.Add(new VertexPositionColor(hullTriangleVertices[i], color)); vertices.Add(new VertexPositionColor(hullTriangleVertices[i + 1], color)); vertices.Add(new VertexPositionColor(hullTriangleVertices[i + 2], color)); indices.Add(i); indices.Add((short)(i + 1)); indices.Add((short)(i + 2)); } DebugInfo DebugInfo = new DebugInfo(); DebugInfo.vertices = vertices.ToArray(); DebugInfo.indices = indices.ToArray(); return(DebugInfo); }
void PositionUpdated(BEPUphysics.Entities.Entity entity) { transform.m_rotation = entity.Orientation; transform.m_position = (Vector3)entity.Position - center.RotateBy(transform.rotation); }
public static DebugInfo GetDebugInfo(BEPUphysics.Entities.Entity DisplayedObject, Color color) { var cylinderShape = DisplayedObject.CollisionInformation.Shape as CylinderShape; if (cylinderShape == null) { throw new ArgumentException("Wrong shape type."); } float verticalOffset = cylinderShape.Height / 2; float angleBetweenFacets = MathHelper.TwoPi / NumSides; float radius = cylinderShape.Radius; List <VertexPositionColor> vertices = new List <VertexPositionColor>(); List <short> indices = new List <short>(); //Create the vertex list for (int i = 0; i < NumSides; i++) { float theta = i * angleBetweenFacets; float x = (float)Math.Cos(theta) * radius; float z = (float)Math.Sin(theta) * radius; //Top cap vertices.Add(new VertexPositionColor(new Vector3(x, verticalOffset, z), color)); //Top part of body vertices.Add(new VertexPositionColor(new Vector3(x, verticalOffset, z), color)); //Bottom part of body vertices.Add(new VertexPositionColor(new Vector3(x, -verticalOffset, z), color)); //Bottom cap vertices.Add(new VertexPositionColor(new Vector3(x, -verticalOffset, z), color)); } //Create the index list //The vertices are arranged a little nonintuitively. //0 is part of the top cap, 1 is the upper body, 2 is lower body, and 3 is bottom cap. for (short i = 0; i < vertices.Count; i += 4) { //Each iteration, the loop advances to the next vertex 'column.' //Four triangles per column (except for the four degenerate cap triangles). //Top cap triangles var nextIndex = (short)((i + 4) % vertices.Count); if (nextIndex != 0) //Don't add cap indices if it's going to be a degenerate triangle. { indices.Add(i); indices.Add(nextIndex); indices.Add(0); } //Body triangles nextIndex = (short)((i + 5) % vertices.Count); indices.Add((short)(i + 1)); indices.Add((short)(i + 2)); indices.Add(nextIndex); indices.Add(nextIndex); indices.Add((short)(i + 2)); indices.Add((short)((i + 6) % vertices.Count)); //Bottom cap triangles. nextIndex = (short)((i + 7) % vertices.Count); if (nextIndex != 3) //Don't add cap indices if it's going to be a degenerate triangle. { indices.Add((short)(i + 3)); indices.Add(3); indices.Add(nextIndex); } } DebugInfo DebugInfo = new DebugInfo(); DebugInfo.vertices = vertices.ToArray(); DebugInfo.indices = indices.ToArray(); return(DebugInfo); }
/// <summary> /// Builds and spawns the body into the world. /// </summary> public virtual void SpawnBody() { if (Body != null) { DestroyBody(); } Body = new BEPUphysics.Entities.Entity(Shape, Mass); Body.CollisionInformation.CollisionRules.Group = CGroup; InternalOffset = new Location(Body.Position); Body.AngularVelocity = new Vector3((float)AVel.X, (float)AVel.Y, (float)AVel.Z); Body.LinearVelocity = new Vector3((float)LVel.X, (float)LVel.Y, (float)LVel.Z); Body.WorldTransform = WorldTransform; // TODO: Position + Quaternion Body.PositionUpdateMode = BEPUphysics.PositionUpdating.PositionUpdateMode.Passive; if (!CanRotate) { Body.AngularDamping = 1; } // TODO: Other settings // TODO: Gravity Body.Tag = this; SetFriction(Friction); SetBounciness(Bounciness); TheRegion.PhysicsWorld.Add(Body); for (int i = 0; i < Joints.Count; i++) { if (Joints[i] is BaseJoint) { BaseJoint joint = (BaseJoint)Joints[i]; joint.CurrentJoint = joint.GetBaseJoint(); TheRegion.PhysicsWorld.Add(joint.CurrentJoint); } } ShadowCastShape = Shape.GetCollidableInstance().BoundingBox; ShadowMainDupe = Shape.GetCollidableInstance().BoundingBox; ShadowCenter = GetPosition(); }
/// <summary> /// /// </summary> /// <param name="modelManager"></param> /// <param name="descriptor"></param> /// <param name="scene"></param> /// <param name="entity"></param> public KinematicModel(PhysicsManager physicsManager, ModelDescriptor descriptor, Scene scene, Entity entity) { this.entity = entity; this.physicsManager = physicsManager; this.scene = scene; this.preTransform = descriptor.ComputePreTransformMatrix(); this.nodeCount = scene.Nodes.Count; convexHulls = new BepuEntity[nodeCount]; var transforms = new Matrix[nodeCount]; animSnapshot = new Matrix[nodeCount]; offsets = new Vector3[nodeCount]; movers = new EntityMover[nodeCount]; rotators = new EntityRotator[nodeCount]; scene.ComputeAbsoluteTransforms(transforms); for (int i = 0; i < scene.Nodes.Count; i++) { var node = scene.Nodes[i]; if (node.MeshIndex < 0) { continue; } var mesh = scene.Meshes[node.MeshIndex]; var indices = mesh.GetIndices(); var vertices = mesh.Vertices .Select(v2 => MathConverter.Convert(v2.Position)) .ToList(); var ms = new MotionState(); var transform = transforms[i] * preTransform *entity.GetWorldMatrix(1); var p = transform.TranslationVector; var q = Fusion.Core.Mathematics.Quaternion.RotationMatrix(transform); ms.AngularVelocity = MathConverter.Convert(Vector3.Zero); ms.LinearVelocity = MathConverter.Convert(Vector3.Zero); ms.Orientation = MathConverter.Convert(q); ms.Position = MathConverter.Convert(p); // recenter shape : // https://bepuphysics.codeplex.com/wikipage?title=Shape%20Recentering var offset = BEPUVector3.Zero; var convexShape = new ConvexHullShape(vertices, out offset); var convexHull = new BepuEntity(convexShape, 0); offsets[i] = MathConverter.Convert(offset); convexHull.Tag = entity; convexHulls[i] = convexHull; movers[i] = new EntityMover(convexHull); rotators[i] = new EntityRotator(convexHull); physicsManager.PhysSpace.Add(convexHull); physicsManager.PhysSpace.Add(movers[i]); physicsManager.PhysSpace.Add(rotators[i]); } }
void detectorVolume_EntityBeginsTouching(BEPUphysics.Entities.Entity toucher, DetectorVolume volume) { contactEntity = BepuEntityObject.RecoverObjectFromEntity(toucher); evt.Code = FireBeginsTouching; evt.FireEvent(this); }
/// <summary> /// Destroys the body, removing it from the physics world. /// </summary> public virtual void DestroyBody() { LVel = new Location(Body.LinearVelocity); AVel = new Location(Body.AngularVelocity); Friction = GetFriction(); // TODO: Gravity = new Location(Body.Gravity.X, Body.Gravity.Y, Body.Gravity.Z); WorldTransform = Body.WorldTransform; for (int i = 0; i < Joints.Count; i++) { if (Joints[i] is BaseJoint) { BaseJoint joint = (BaseJoint)Joints[i]; TheRegion.PhysicsWorld.Remove(joint.CurrentJoint); } } TheRegion.PhysicsWorld.Remove(Body); Body = null; }
void detectorVolume_VolumeStopsContainingEntity(DetectorVolume volume, BEPUphysics.Entities.Entity entity) { contactEntity = BepuEntityObject.RecoverObjectFromEntity(entity); evt.Code = FireEndsContaining; evt.FireEvent(this); }
public void ApplyHook(PlayerEntity player, ItemStack item, Location Position, BEPUphysics.Entities.Entity HitEnt) { RemoveHook(player); PhysicsEntity pe; double len = (double)(Position - player.GetCenter()).Length(); Location step = (player.GetCenter() - Position) / len; Location forw = Utilities.VectorToAngles(step); forw.Yaw += 180; BEPUutilities.Quaternion quat = BEPUutilities.Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), (double)(forw.Pitch * Utilities.PI180)) * BEPUutilities.Quaternion.CreateFromAxisAngle(new Vector3(0, 0, 1), (double)(forw.Yaw * Utilities.PI180)); if (HitEnt == null) { ModelEntity mod = new ModelEntity("cube", player.TheRegion) { Mass = 0, CanSave = false, scale = new Location(0.023, 0.05, 0.05), mode = ModelCollisionMode.AABB }; mod.SetPosition(Position); mod.SetOrientation(quat); player.TheRegion.SpawnEntity(mod); pe = mod; player.Hooks.Add(new HookInfo() { Joint = null, Hit = pe, IsBar = true }); } else { pe = (PhysicsEntity)HitEnt.Tag; } JointDistance jd; //jd = new JointDistance(player, pe, 0.01f, len + 0.01f, player.GetCenter(), Position); //player.TheRegion.AddJoint(jd); //player.Hooks.Add(new HookInfo() { Joint = jd, Hit = pe, IsBar = false }); PhysicsEntity cent = pe; for (double f = 0; f < len - 1f; f += 0.5f) { Location cpos = Position + step * f; ModelEntity ce = new ModelEntity("cube", player.TheRegion) { Mass = 15, CanSave = false, scale = new Location(0.023, 0.05, 0.05), mode = ModelCollisionMode.AABB }; ce.SetPosition(cpos + step * 0.5); ce.SetOrientation(quat); player.TheRegion.SpawnEntity(ce); jd = new JointDistance(ce, cent, 0.01f, 0.5f, ce.GetPosition(), (ReferenceEquals(cent, pe) ? Position: cent.GetPosition())); CollisionRules.AddRule(player.Body, ce.Body, CollisionRule.NoBroadPhase); player.TheRegion.AddJoint(jd); player.Hooks.Add(new HookInfo() { Joint = jd, Hit = ce, IsBar = true }); cent = ce; } jd = new JointDistance(cent, player, 0.01f, 0.5f, cent.GetPosition(), player.GetCenter()); player.TheRegion.AddJoint(jd); player.Hooks.Add(new HookInfo() { Joint = jd, Hit = player, IsBar = false }); }
public override void Create(Vector3 position, Quaternion orientation, Vector3 velocity, BEPUphysics.Entities.Entity target) { Create(position, orientation, velocity); }