Example #1
0
        /// <summary>
        /// Creates an actor using shape info and information from the parent BaseEntity.
        /// </summary>
        /// <param name="PhysicsScene">Reference to the physics scene</param>
        protected override void CreateActor(IPhysicsScene PhysicsScene)
        {
            // Character physics have custom physics bodies that have gravity and other
            // forces manually applied, but they're still considered dynamic so they can
            // collide with other objects
            this.isDynamic = true;

            ActorDesc desc = new ActorDesc();

            desc.Orientation       = this.parentEntity.Rotation;
            desc.Mass              = this.mass;
            desc.Dynamic           = this.isDynamic;
            desc.AffectedByGravity = this.affectedByGravity;
            desc.Position          = this.parentEntity.Position;
            desc.EntityID          = this.parentEntity.UniqueID;
            desc.Game              = this.parentEntity.Game;
            desc.Type              = ActorType.Character;

            this.actor = PhysicsScene.CreateActor(desc);

            if (this.actor != null)
            {
                this.actor.EnableCollisionListening();
            }
        }
Example #2
0
        /// <summary>
        /// Creates an actor using shape info and information from the parent BaseEntity.
        /// </summary>
        /// <param name="PhysicsScene">Reference to the physics scene</param>
        protected override void CreateActor(IPhysicsScene PhysicsScene)
        {
            ShapeDesc newShape = CreateShapeFromType(shapeType);

            // Phantoms cannot currently have dynamic physics
            this.isDynamic = false;

            var desc = new ActorDesc();

            desc.Orientation       = this.parentEntity.Rotation;
            desc.Mass              = this.mass;
            desc.Dynamic           = this.isDynamic;
            desc.AffectedByGravity = this.affectedByGravity;
            desc.Position          = this.parentEntity.Position;
            desc.Shapes.Add(newShape);
            desc.EntityID = this.parentEntity.UniqueID;
            desc.Game     = this.parentEntity.Game;
            desc.Type     = ActorType.Static;

            this.actor = PhysicsScene.CreateActor(desc);

            if (this.actor != null)
            {
                this.actor.EnableCollisionListening();
            }
        }
Example #3
0
        /// <summary>
        /// Creates an actor using shape info and information from the parent BaseEntity.
        /// </summary>
        /// <param name="PhysicsScene">Reference to the physics scene</param>
        protected virtual void CreateActor(IPhysicsScene PhysicsScene)
        {
            ShapeDesc newShape = CreateShapeFromType(shapeType);

            if (newShape == null)
            {
                throw new Exception("Shape did not load properly");
            }

            ActorDesc desc = new ActorDesc();

            desc.Orientation       = this.parentEntity.Rotation;
            desc.Mass              = this.mass;
            desc.Dynamic           = this.isDynamic;
            desc.AffectedByGravity = this.affectedByGravity;
            desc.Position          = this.parentEntity.Position;
            desc.Shapes.Add(newShape);
            desc.EntityID = this.parentEntity.UniqueID;
            desc.Game     = this.parentEntity.Game;
            desc.Type     = ActorType.Basic;

            if (newShape is TriangleMeshShapeDesc)
            {
                var triDesc = newShape as TriangleMeshShapeDesc;
                if (triDesc.Vertices.Count > 100)
                {
                    desc.Type = ActorType.Static;
                }
            }

            this.actor = PhysicsScene.CreateActor(desc);
        }
Example #4
0
        /// <summary>
        /// Constructs a new static physics actor.
        /// </summary>
        /// <param name="desc">Descriptor for the actor.</param>
        public TerrainBEPUActor(ActorDesc desc) : base(desc)
        {
            if (desc.Shapes.Count != 1)
            {
                throw new Exception("Terrain actors can only consist of one shape");
            }

            ShapeDesc shapeDesc = desc.Shapes[0];

            if (shapeDesc is HeightFieldShapeDesc)
            {
                // For height fields, we need to copy the data into an Array2D.
                var heightFieldDesc = shapeDesc as HeightFieldShapeDesc;

                float spacing = heightFieldDesc.SizeX / heightFieldDesc.HeightField.GetLength(0);

                this.collidable = new Terrain(heightFieldDesc.HeightField, new AffineTransform(
                                                  new Vector3(spacing, 1, spacing),
                                                  Quaternion.Identity,
                                                  Vector3.Zero));
            }
            else
            {
                throw new Exception("Shape description for a Terrain actor must be HeightFieldShapeDesc.");
            }

            // Tag the physics with data needed by the engine
            var tag = new EntityTag(this.ownerEntityID);

            this.collidable.Tag = tag;

            this.spaceObject = this.collidable;
        }
Example #5
0
        private void AddCube()
        {
            double d = 0.1 + 0.2 * rnd.NextDouble();

            Mogre.Vector3 pos = new Mogre.Vector3((float)(-10 * d), (float)d, 0);;

            for (int j = 0; j < 10; j++)
            {
                float tempy = pos.y;

                pos.x += 2 * (float)(d - physx.Parameters.SkinWidth);
                pos.z += 1f * (float)(d + physx.Parameters.SkinWidth);

                for (int i = 0; i < 1 + j; i++)
                {
                    var ad = new ActorDesc(new BodyDesc(), 10, new BoxShapeDesc(new Mogre.Vector3((float)d, (float)d, (float)d)));
                    ad.GlobalPosition = new Mogre.Vector3(pos.x, pos.y, pos.z);
                    pos.y            += 2 * (float)(d - physx.Parameters.SkinWidth);
                    var a = scene.CreateActor(ad);
                    cubeActors.Add(a);

                    string id       = "MaunalObject_" + Guid.NewGuid().ToString();
                    string cubeName = "CUSTOME_CUBE_" + Guid.NewGuid().ToString();
                    createCube(cubeName, ad.GlobalPosition, d);
                    Entity    mo          = m_pSceneMgr.CreateEntity(id, cubeName);
                    SceneNode moSceneNode = m_pSceneMgr.RootSceneNode.CreateChildSceneNode();
                    moSceneNode.AttachObject(mo);

                    cubes.Add(mo);
                }
                pos.y = tempy;
            }
            return;
        }
Example #6
0
        /// <summary>
        /// Constructs a new physics actor.
        /// </summary>
        /// <param name="desc">Descriptor for the actor.</param>
        public CharacterBEPUActor(ActorDesc desc) : base(desc)
        {
            character     = new CharacterController(desc.Position, 17f, 17f * 0.6f, 6.0f, 4500.0f);
            characterBody = character.Body;

            // Tag the physics with data needed by the engine
            var tag = new CharacterTag(this.ownerEntityID, characterBody);

            this.characterBody.Tag = tag;
            this.characterBody.CollisionInformation.Tag = tag;

            this.Position    = desc.Position;
            this.Orientation = desc.Orientation;

            Debug.Assert(this.characterBody != null, "A physics entity was not properly created.");

            this.spaceObject = this.character;

            this.characterBody.IsAffectedByGravity = desc.AffectedByGravity;

#if WINDOWS
            // We add the character's cylinder body to the physics viewer.
            var msgAddPhys = ObjectPool.Aquire <MsgAddPhysicsToModelViewer>();
            msgAddPhys.SpaceObject = this.characterBody;
            this.game.SendInterfaceMessage(msgAddPhys, InterfaceType.Physics);
#endif //WINDOW
        }
Example #7
0
        public override void Spawn(Vector3 position, Quaternion orientation)
        {
            // create scene node
            SceneNode sceneNode = this.CreateSceneNode(position, orientation);
            Entity    entity    = sceneNode.GetAttachedObject(0) as Entity;

            // physics
            BodyDesc bodyDesc = new BodyDesc();

            bodyDesc.LinearVelocity = this.Velocity;

            ActorDesc actorDesc = Engine.Physics.CreateActorDesc(this, entity, position, orientation, this.Scale);

            actorDesc.Density           = this.Density;
            actorDesc.Body              = bodyDesc;
            actorDesc.GlobalPosition    = position;
            actorDesc.GlobalOrientation = orientation.ToRotationMatrix();

            if (this.EnableCCD)
            {
                foreach (ShapeDesc shapeDesc in actorDesc.Shapes)
                {
                    shapeDesc.ShapeFlags = ShapeFlags.DynamicDynamicCCD;
                }
            }

            Actor actor = Engine.Physics.Scene.CreateActor(actorDesc);

            actor.UserData = this;

            ActorNode actorNode = new ActorNode(sceneNode, actor);

            Engine.World.ActorNodes.Add(actorNode);
        }
Example #8
0
        /// <summary>
        /// These can be specified in several different ways:
        ///
        ///1) actorDesc.density == 0, bodyDesc.mass > 0, bodyDesc.massSpaceInertia.magnitude() > 0
        ///
        ///Here the mass properties are specified explicitly, there is nothing to compute.
        ///
        ///2) actorDesc.density > 0, actorDesc.shapes.size() > 0, bodyDesc.mass == 0, bodyDesc.massSpaceInertia.magnitude() == 0
        ///
        ///Here a density and the shapes are given. From this both the mass and the inertia tensor is computed.
        ///
        ///3) actorDesc.density == 0, actorDesc.shapes.size() > 0, bodyDesc.mass > 0, bodyDesc.massSpaceInertia.magnitude() == 0
        ///
        ///Here a mass and shapes are given. From this the inertia tensor is computed.
        ///
        ///Other combinations of settings are illegal.
        /// </summary>
        /// <param name="node"></param>
        /// <param name="dynamic"></param>
        /// <param name="shapeBuilder"></param>
        /// <param name="density"></param>
        /// <param name="mass"></param>
        /// <returns></returns>
        public Actor CreateActor(Physic physic, bool dynamic, Func <Frame, ActorShapeDesc> shapeBuilder, float density = 0, float mass = 0)
        {
            if (physic != null)
            {
                throw new NullReferenceException("Physics");
            }

            ActorDesc actorDesc = _CreateActorDescription(dynamic, density, mass);

            if (shapeBuilder != null)
            {
                foreach (var child in EnumerateNodesPosOrden())
                {
                    var shapeDesc = shapeBuilder(child);
                    if (shapeDesc != null)
                    {
                        actorDesc.Shapes.Add(shapeDesc);
                    }
                }
            }

            var actor = physic.CreateActor(actorDesc);

            this.BindTo(actor);

            return(actor);
        }
Example #9
0
        private ActorDesc _CreateActorDescription(bool dynamic, float density = 0, float mass = 0)
        {
            if (Engine.Scene == null || Engine.Scene.Physics == null)
            {
                throw new InvalidOperationException("No Scene");
            }

            ActorDesc actorDesc = new ActorDesc();

            actorDesc.Name       = Name;
            actorDesc.GlobalPose = _worldTransform;

            if (density > 0)
            {
                actorDesc.Density = density;
                mass = 0;
            }

            if (dynamic)
            {
                actorDesc.Body = new BodyDesc()
                {
                };
                if (mass > 0)
                {
                    actorDesc.Body.Mass = mass;
                }
            }

            return(actorDesc);
        }
Example #10
0
 public void ToNxActor(ref ActorDesc actorDesc)
 {
     actorDesc.ContactReportFlags = contactReportFlags;
     actorDesc.Density            = density;
     actorDesc.DominanceGroup     = dominanceGroup;
     actorDesc.ForceFieldMaterial = forceFieldMaterial;
     actorDesc.Group = group;
     actorDesc.Name  = name;
 }
Example #11
0
        /// <summary>
        /// Constructs a new physics actor.
        /// </summary>
        /// <param name="desc">Descriptor for the actor.</param>
        internal BEPUActor(ActorDesc desc)
        {
            this.actorType     = desc.Type;
            this.shapes        = desc.Shapes;
            this.ownerEntityID = desc.EntityID;
            this.game          = desc.Game;

            this.body = new QSBody(this);
        }
Example #12
0
        public void CreateStatic(Vector3 pose, RigidBodyDescription description, Scene scene, ShapeDesc shape)
        {
            ActorDesc actorDesc = new ActorDesc();

            actorDesc.GlobalPosition = pose;
            actorDesc.Body           = null;
            description.ToNxActor(ref actorDesc);
            actorDesc.Shapes.Add(shape);
            Actor = scene.CreateActor(actorDesc);
        }
Example #13
0
        public override void enter()
        {
            m_pSceneMgr = AdvancedMogreFramework.Singleton.m_pRoot.CreateSceneManager(SceneType.ST_GENERIC, "PhysxBasicCubeMgr");
            ColourValue cvAmbineLight = new ColourValue(0.7f, 0.7f, 0.7f);

            m_pSceneMgr.AmbientLight = cvAmbineLight;//(Ogre::ColourValue(0.7f, 0.7f, 0.7f));

            m_pCamera = m_pSceneMgr.CreateCamera("PhysxBasicCubeCamera");
            Mogre.Vector3 vectCameraPostion = new Mogre.Vector3(-10, 40, 10);
            m_pCamera.Position = vectCameraPostion;
            Mogre.Vector3 vectorCameraLookAt = new Mogre.Vector3(5, 20, 0);
            m_pCamera.LookAt(vectorCameraLookAt);
            m_pCamera.NearClipDistance = 5;

            m_pCamera.AspectRatio = AdvancedMogreFramework.Singleton.m_pViewport.ActualWidth / AdvancedMogreFramework.Singleton.m_pViewport.ActualHeight;

            AdvancedMogreFramework.Singleton.m_pViewport.Camera = m_pCamera;

            createPanel(m_pSceneMgr);

            trayMgr.destroyAllWidgets();

            for (int i = 0; i < 10; i++)
            {
                double        d     = 0.1 + 0.2 * rnd.NextDouble() * 10;
                var           ad    = new ActorDesc(new BodyDesc(), 10, new BoxShapeDesc(new Mogre.Vector3((float)d, (float)d, (float)d)));
                Mogre.Vector3 gpose = new Mogre.Vector3((float)(10 * (rnd.NextDouble() - rnd.NextDouble())), (float)(10 * rnd.NextDouble()), (float)(5 * rnd.NextDouble()));
                ad.GlobalPosition = gpose;

                var a = scene.CreateActor(ad);
                cubeActors.Add(a);
                a.AddTorque(new Mogre.Vector3(0, 0, (float)(15 * d * (rnd.NextDouble() - rnd.NextDouble()))), ForceModes.Impulse);

                string id       = "MaunalObject_" + Guid.NewGuid().ToString();
                string cubeName = "CUSTOME_CUBE_" + Guid.NewGuid().ToString();
                createCube(cubeName, gpose, d);
                Entity    mo          = m_pSceneMgr.CreateEntity(id, cubeName);
                SceneNode moSceneNode = m_pSceneMgr.RootSceneNode.CreateChildSceneNode();
                moSceneNode.AttachObject(mo);

                cubes.Add(mo);
            }

            scene.Simulate(0);

            AdvancedMogreFramework.Singleton.m_pMouse.MouseMoved     += mouseMoved;
            AdvancedMogreFramework.Singleton.m_pMouse.MousePressed   += mousePressed;
            AdvancedMogreFramework.Singleton.m_pMouse.MouseReleased  += mouseReleased;
            AdvancedMogreFramework.Singleton.m_pKeyboard.KeyPressed  += keyPressed;
            AdvancedMogreFramework.Singleton.m_pKeyboard.KeyReleased += keyReleased;
        }
Example #14
0
        protected override void create()
        {
            itemEnt  = camera.SceneManager.CreateEntity(itemName, itemMeshName);
            itemNode = camera.SceneManager.RootSceneNode.CreateChildSceneNode();
            itemNode.AttachObject(itemEnt);

            ActorDesc actorDesc = new ActorDesc();

            actorDesc.Density = 4;
            actorDesc.Body    = null;
            actorDesc.Shapes.Add(physics.CreateTriangleMesh(new
                                                            StaticMeshData(itemEnt.GetMesh())));
            itemActor = physicsScene.CreateActor(actorDesc);
        }
Example #15
0
        protected override void create()
        {
            renderable.Entity     = renderable.SceneManager.CreateEntity(Guid.NewGuid().ToString(), itemData.MeshName);
            renderable.EntityNode = renderable.SceneManager.RootSceneNode.CreateChildSceneNode();
            renderable.EntityNode.AttachObject(renderable.Entity);

            ActorDesc actorDesc = new ActorDesc();

            actorDesc.Density = 4;
            actorDesc.Body    = null;
            actorDesc.Shapes.Add(physics.CreateTriangleMesh(new
                                                            StaticMeshData(renderable.Entity.GetMesh())));
            itemActor = physicsScene.CreateActor(actorDesc);
        }
Example #16
0
        protected override void create(GameWorld world)
        {
            base.create(world);
            renderable.Entity     = renderable.SceneManager.CreateEntity(itemName, itemMeshName);
            renderable.EntityNode = renderable.SceneManager.RootSceneNode.CreateChildSceneNode();
            renderable.EntityNode.AttachObject(renderable.Entity);

            ActorDesc actorDesc = new ActorDesc();

            actorDesc.Density = 4;
            actorDesc.Body    = null;
            actorDesc.Shapes.Add(physics.CreateTriangleMesh(new
                                                            StaticMeshData(renderable.Entity.GetMesh())));
            itemActor = physicsScene.CreateActor(actorDesc);
        }
Example #17
0
        public void CreateDynamic(
            Vector3 pose,
            Matrix3 oritentaion,
            RigidBodyDescription description,
            Scene scene,
            ShapeDesc shape)
        {
            BodyDesc  bodyDesc  = new BodyDesc();
            ActorDesc actorDesc = new ActorDesc();

            description.ToNxActor(ref actorDesc, ref bodyDesc);
            actorDesc.Body              = bodyDesc;
            actorDesc.GlobalPosition    = pose;
            actorDesc.GlobalOrientation = oritentaion;
            actorDesc.Shapes.Add(shape);
            Actor = scene.CreateActor(actorDesc);
        }
Example #18
0
        public ActorDesc CreateActorDesc(EntityWorldEntity entityNode, Entity entity, Vector3 position, Quaternion orientation, Vector3 scale)
        {
            ActorDesc actorDesc = new ActorDesc();

            actorDesc.GlobalPosition    = position;
            actorDesc.GlobalOrientation = orientation.ToRotationMatrix();

            if (entityNode.CollisionMode == CollisionMode.ConvexHull || entityNode.CollisionMode == CollisionMode.TriangleMesh)
            {
                StaticMeshData meshData = new StaticMeshData(entity.GetMesh(), scale);

                if (entityNode.CollisionMode == CollisionMode.TriangleMesh)
                {
                    actorDesc.Shapes.Add(Engine.Physics.CreateTriangleMesh(meshData));
                }
                else
                {
                    actorDesc.Shapes.Add(Engine.Physics.CreateConvexHull(meshData));
                }
            }
            else
            {
                switch (entityNode.CollisionMode)
                {
                case CollisionMode.BoundingBox:
                    actorDesc.Shapes.Add(new BoxShapeDesc(entity.BoundingBox.HalfSize * scale, entity.BoundingBox.Center * scale));
                    break;

                case CollisionMode.BoundingSphere:
                    actorDesc.Shapes.Add(new SphereShapeDesc(Engine.MaxAxis(entity.BoundingBox.HalfSize), entity.BoundingBox.Center * scale));
                    break;

                case CollisionMode.Shapes:
                    foreach (ShapeDesc shapeDesc in entityNode.Shapes)
                    {
                        actorDesc.Shapes.Add(shapeDesc);
                    }
                    break;

                default:
                    throw new Exception(entityNode.CollisionMode.ToString() + " not implemented");
                }
            }

            return(actorDesc);
        }
Example #19
0
        private void createPanel(SceneManager scm)
        {
            MeshManager.Singleton.CreatePlane("floor", ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                                              new Plane(Mogre.Vector3.UNIT_Y, 0), 100, 100, 10, 10, true, 1, 10, 10, Mogre.Vector3.UNIT_Z);
            Entity floor = scm.CreateEntity("Floor", "floor");

            floor.SetMaterialName("Examples/Rockwall");
            floor.CastShadows = (false);
            scm.RootSceneNode.AttachObject(floor);
            ActorDesc actorDesc = new ActorDesc();

            actorDesc.Density = 4;
            actorDesc.Body    = null;
            actorDesc.Shapes.Add(physx.CreateTriangleMesh(new
                                                          StaticMeshData(floor.GetMesh())));
            Actor floorActor = scene.CreateActor(actorDesc);
        }
Example #20
0
        /// <summary>
        /// Creates a new physics actor.
        /// </summary>
        /// <param name="desc">The actor descriptor.</param>
        /// <returns>The new actor instance.</returns>
        public IPhysicsActor CreateActor(ActorDesc desc)
        {
            if (this.bFixedTimeMet)
            {
                // This should pause the physics frame ever so slightly so we can add the
                // actor to the physics scene.
                this.startFrame.Reset();
            }

            IPhysicsActor actor;

            switch (desc.Type)
            {
            case ActorType.Basic:
                actor = new BasicBEPUActor(desc);
                break;

            case ActorType.Character:
                actor = new CharacterBEPUActor(desc);
                break;

            case ActorType.Terrain:
                actor = new TerrainBEPUActor(desc);
                break;

            case ActorType.Water:
                actor = new WaterVolumeBEPUActor(desc);
                break;

            case ActorType.Static:
                actor = new StaticBEPUActor(desc);
                break;

            default:
                throw new ArgumentException("Unknown actor type, new type was added and this switch wasn't updated to handle it.");
            }

            if (this.bFixedTimeMet)
            {
                // Unpause physics now that new actor is in the physics scene
                this.startFrame.Set();
            }

            return(actor);
        }
Example #21
0
        public Actor CreateActor(Physic physic, bool dynamic, ActorShapeDesc[] shapes, float density = 0, float mass = 0)
        {
            if (physic != null)
            {
                throw new ArgumentNullException("physic");
            }

            ActorDesc actorDesc = _CreateActorDescription(dynamic, density, mass);

            foreach (var item in shapes)
            {
                actorDesc.Shapes.Add(item);
            }

            var actor = physic.CreateActor(actorDesc);

            this.BindTo(actor);

            return(actor);
        }
Example #22
0
        public void ToNxActor(ref ActorDesc actorDesc, ref BodyDesc bodyDesc)
        {
            ToNxActor(ref actorDesc);

            bodyDesc.AngularDamping     = angularDamping;
            bodyDesc.AngularVelocity    = angularVelocity;
            bodyDesc.CCDMotionThreshold = ccdMotionThreshold;
            bodyDesc.LinearDamping      = linearDamping;
            bodyDesc.LinearVelocity     = linearVelocity;
            bodyDesc.Mass                 = mass;
            bodyDesc.MassLocalPose        = massLocalPose;
            bodyDesc.MassSpaceInertia     = massSpaceInertia;
            bodyDesc.MaxAngularVelocity   = maxAngularVelocity;
            bodyDesc.SleepAngularVelocity = sleepAngularVelocity;
            bodyDesc.SleepDamping         = sleepDamping;
            bodyDesc.SleepEnergyThreshold = sleepEnergyThreshold;
            bodyDesc.SleepLinearVelocity  = sleepLinearVelocity;
            bodyDesc.SolverIterationCount = solverIterationCount;
            bodyDesc.WakeUpCounter        = wakeUpCounter;
        }
Example #23
0
        protected override void create()
        {
            string name = Guid.NewGuid().ToString();

            MeshManager.Singleton.CreatePlane(name, groupName,
                                              new Plane(rkNormal, fConstanst), width, height, xsegments, ysegments, normals, numTexCoordSets, uTile, vTile, upVector);
            entity = sceneManager.CreateEntity(Guid.NewGuid().ToString(), name);
            entity.SetMaterialName(materialName);
            entity.CastShadows = false;
            entNode            = sceneManager.RootSceneNode.CreateChildSceneNode();
            entNode.AttachObject(entity);
            entNode.Position = position;
            ActorDesc actorDesc = new ActorDesc();

            actorDesc.Density = 4;
            actorDesc.Body    = null;
            actorDesc.Shapes.Add(physics.CreateTriangleMesh(new
                                                            StaticMeshData(entity.GetMesh())));
            Actor entityActor = physicsScene.CreateActor(actorDesc);
        }
Example #24
0
        internal override void Initialize(ActorContext context, ActorDesc actorDesc)
        {
            base.Initialize(context, actorDesc);

            var desc = (PhysicsSceneDesc)actorDesc;

            // TODO: Enable custom initialization of physics world
            collisionConf = new DefaultCollisionConfiguration();
            dispatcher    = new CollisionDispatcher(collisionConf);
            broadphase    = new DbvtBroadphase();
            world         = new DiscreteDynamicsWorld(dispatcher, broadphase, null, collisionConf);
            world.Gravity = desc.Gravity;

            if (desc.Colliders != null)
            {
                foreach (var collider in desc.Colliders)
                {
                    AddCollider(collider);
                }
            }
        }
Example #25
0
        public override void Spawn(Vector3 position, Quaternion orientation)
        {
            // create entity
            Entity entity = this.CreateEntity();

            // add it to the static geometry
            if (this.CastShadows)
            {
                Engine.World.StaticGeometryCaster.AddEntity(entity, position, orientation, scale);
            }
            else
            {
                Engine.World.StaticGeometryReceiver.AddEntity(entity, position, orientation, scale);
            }

            // create the physics mesh
            ActorDesc actorDesc = Engine.Physics.CreateActorDesc(this, entity, position, orientation, scale);
            Actor     actor     = Engine.Physics.Scene.CreateActor(actorDesc);

            actor.UserData = this;
        }
Example #26
0
        /// <summary>
        /// Creates an actor using shape info and information from the parent BaseEntity.
        /// </summary>
        /// <param name="PhysicsScene">Reference to the physics scene</param>
        /// <param name="density">Density of physics object</param>
        private void CreateHeightfieldActor(IPhysicsScene PhysicsScene, float[,] heightData, float scaleFactor)
        {
            HeightFieldShapeDesc heightfieldShape = CreateHeightfieldShape(heightData, scaleFactor);

            if (heightfieldShape == null)
            {
                throw new Exception("Shape did not load properly");
            }

            var desc = new ActorDesc();

            desc.Orientation       = parentEntity.Rotation;
            desc.Mass              = 1.0f;
            desc.Dynamic           = false;
            desc.AffectedByGravity = false;
            desc.Position          = parentEntity.Position;
            desc.EntityID          = this.parentEntity.UniqueID;
            desc.Shapes.Add(heightfieldShape);
            desc.Type = ActorType.Terrain;

            actor = PhysicsScene.CreateActor(desc);
        }
Example #27
0
        internal override void Initialize(ActorContext context, ActorDesc actorDesc)
        {
            base.Initialize(context, actorDesc);

            var desc     = (RigidBodyDesc)actorDesc;
            var snapshot = (RigidBodySnapshot)Snapshot;

            var localInertia = Vector3.Zero;

            if (!desc.IsKinematic)
            {
                desc.Shape.CalculateLocalInertia(desc.Mass, out localInertia);
            }

            var motionState = new DefaultMotionState(desc.StartTransform, desc.CenterOfMassOffset);

            using (var rbInfo = new RigidBodyConstructionInfo(desc.Mass, motionState, desc.Shape, localInertia))
            {
                rbInfo.Friction        = desc.Friction;
                rbInfo.RollingFriction = desc.RollingFriction;
                rbInfo.Restitution     = desc.Restitution;
                rbInfo.LinearDamping   = desc.LinearDamping;
                rbInfo.AngularDamping  = desc.AngularDamping;

                rigidBody            = new RigidBody(rbInfo);
                rigidBody.UserObject = this;

                if (desc.IsKinematic)
                {
                    rigidBody.CollisionFlags |= CollisionFlags.KinematicObject;
                }

                Scene.World.AddRigidBody(rigidBody);

                logger.Debug("Create RigidBody for {0}: Mass: {1}, Shape: {2}, Friction: {3}, RollingFriction: {4}, Restitution: {5}, LinearDamping: {6}, AngularDamping: {7}"
                             , this, 1 / rigidBody.InvMass, rigidBody.CollisionShape, rigidBody.Friction, rigidBody.RollingFriction, rigidBody.Restitution, rigidBody.LinearDamping, rigidBody.AngularDamping);
            }
        }
Example #28
0
        /// <summary>
        /// Creates an actor using shape info and information from the parent BaseEntity.
        /// </summary>
        /// <param name="PhysicsScene">Reference to the physics scene</param>
        protected override void CreateActor(IPhysicsScene PhysicsScene)
        {
            ShapeDesc newShape = CreateShapeFromType(shapeType);

            if (newShape == null)
            {
                throw new Exception("Shape did not load properly");
            }

            ActorDesc desc = new ActorDesc();

            desc.Orientation       = this.parentEntity.Rotation;
            desc.Mass              = this.mass;
            desc.Dynamic           = false;
            desc.AffectedByGravity = false;
            desc.Position          = this.parentEntity.Position;
            desc.Shapes.Add(newShape);
            desc.EntityID = this.parentEntity.UniqueID;
            desc.Game     = this.parentEntity.Game;
            desc.Type     = ActorType.Water;

            this.actor = PhysicsScene.CreateActor(desc);
        }
Example #29
0
        public ActorDesc CreateActorDesc(EntityWorldEntity entityNode, Entity entity, Vector3 position, Quaternion orientation, Vector3 scale)
        {
            ActorDesc actorDesc = new ActorDesc();
            actorDesc.GlobalPosition = position;
            actorDesc.GlobalOrientation = orientation.ToRotationMatrix();

            if (entityNode.CollisionMode == CollisionMode.ConvexHull || entityNode.CollisionMode == CollisionMode.TriangleMesh)
            {
                StaticMeshData meshData = new StaticMeshData(entity.GetMesh(), scale);

                if (entityNode.CollisionMode == CollisionMode.TriangleMesh)
                    actorDesc.Shapes.Add(Engine.Physics.CreateTriangleMesh(meshData));
                else
                    actorDesc.Shapes.Add(Engine.Physics.CreateConvexHull(meshData));
            }
            else
            {
                switch (entityNode.CollisionMode)
                {
                    case CollisionMode.BoundingBox:
                        actorDesc.Shapes.Add(new BoxShapeDesc(entity.BoundingBox.HalfSize * scale, entity.BoundingBox.Center * scale));
                        break;
                    case CollisionMode.BoundingSphere:
                        actorDesc.Shapes.Add(new SphereShapeDesc(Engine.MaxAxis(entity.BoundingBox.HalfSize), entity.BoundingBox.Center * scale));
                        break;
                    case CollisionMode.Shapes:
                        foreach (ShapeDesc shapeDesc in entityNode.Shapes)
                            actorDesc.Shapes.Add(shapeDesc);
                        break;
                    default:
                        throw new Exception(entityNode.CollisionMode.ToString() + " not implemented");
                }
            }

            return actorDesc;
        }
Example #30
0
        public override void init()
        {
            #region ground
            MeshManager.Singleton.CreatePlane("ground",
                                              ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                                              new Plane(Mogre.Vector3.UNIT_Y, 0),
                                              1500, 1500, 20, 20, true, 1, 5, 5, Mogre.Vector3.UNIT_Z);
            // Create a ground plane
            entities.Add(OgreWindow.Instance.mSceneMgr.CreateEntity("GroundEntity", "ground"));
            entities["GroundEntity"].CastShadows = false;
            entities["GroundEntity"].SetMaterialName("dirt");
            nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("ground"));
            nodes["ground"].AttachObject(entities["GroundEntity"]);
            nodes["ground"].Position = new Mogre.Vector3(0f, 0f, 0f) + Location().toMogre;

            // the actor properties control the mass, position and orientation
            // if you leave the body set to null it will become a static actor and wont move
            ActorDesc actorDesc2 = new ActorDesc();
            actorDesc2.Density           = 4;
            actorDesc2.Body              = null;
            actorDesc2.GlobalPosition    = nodes["ground"].Position;
            actorDesc2.GlobalOrientation = nodes["ground"].Orientation.ToRotationMatrix();


            PhysXHelpers.StaticMeshData meshdata = new PhysXHelpers.StaticMeshData(entities["GroundEntity"].GetMesh());
            actorDesc2.Shapes.Add(PhysXHelpers.CreateTriangleMesh(meshdata));
            Actor actor2 = null;
            try { actor2 = OgreWindow.Instance.scene.CreateActor(actorDesc2); }
            catch (System.AccessViolationException ex) { log(ex.ToString()); }
            if (actor2 != null)
            {
                // create our special actor node to tie together the scene node and actor that we can update its position later
                ActorNode actorNode2 = new ActorNode(nodes["ground"], actor2);
                actors.Add(actorNode2);
            }
            #endregion



            lights.Add(OgreWindow.Instance.mSceneMgr.CreateLight("playerLight"));
            lights["playerLight"].Type           = Light.LightTypes.LT_POINT;
            lights["playerLight"].Position       = Location().toMogre;
            lights["playerLight"].DiffuseColour  = ColourValue.White;
            lights["playerLight"].SpecularColour = ColourValue.White;

            #region drone

            OgreWindow.Instance.skeletons["\\Drone.skeleton"].Load();
            OgreWindow.Instance.meshes["\\Drone.mesh"].Load();
            OgreWindow.Instance.meshes["\\Drone.mesh"].SkeletonName = "\\Drone.skeleton";

            entities.Add(OgreWindow.Instance.mSceneMgr.CreateEntity("drone", "\\Drone.mesh"));

            entities["drone"].CastShadows = true;
            walkState         = entities["drone"].GetAnimationState("walk");
            walkState.Enabled = true;
            walkState.Loop    = true;
            entities["drone"].SetMaterialName("metal");
            nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("drone"));
            nodes["drone"].AttachObject(entities["drone"]);
            nodes["drone"].Position = new Mogre.Vector3(0f, 40f, 0f) + Location().toMogre;
            nodes["drone"].Scale(new Mogre.Vector3(.3f));

            nodes.Add(nodes["drone"].CreateChildSceneNode("orbit0"));
            nodes.Add(nodes["orbit0"].CreateChildSceneNode("orbit"));
            nodes["orbit"].Position = Location().toMogre;
            nodes["orbit"].AttachObject(OgreWindow.Instance.mCamera);
            nodes["drone"].SetFixedYawAxis(true);



            #endregion


            //#region baseball
            //entities.Add(OgreWindow.Instance.mSceneMgr.CreateEntity("baseball", "\\baseball.mesh"));
            //entities["baseball"].SetMaterialName("baseball");
            ////nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("baseball"));
            //nodes.Add(nodes["drone"].CreateChildSceneNode("baseball"));
            //nodes["baseball"].AttachObject(entities["baseball"]);
            //nodes["baseball"].SetScale(.5f, .5f, .5f);
            //nodes["baseball"].SetPosition(-3f, 7f, 3f);
            //// nodes["baseball"].SetScale(5f, 5f, 5f);
            //#endregion

            #region player physics
            bcd     = new BoxControllerDesc();
            control = OgreWindow.Instance.physics.ControllerManager.CreateController(OgreWindow.Instance.scene, bcd); //System.NullReferenceException
            #endregion

            nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("suspensionY"));

            OgreWindow.g_m.MouseMoved += new MouseListener.MouseMovedHandler(mouseMoved);
            middlemousetimer.reset();
            middlemousetimer.start();

            this.btnLimiter_F.reset();
            this.btnLimiter_F.start();

            ready = true;
            new Thread(new ThreadStart(controlThread)).Start();
            new Thread(new ThreadStart(statusUpdaterThread)).Start();

            localY = nodes["drone"]._getDerivedOrientation() * Mogre.Vector3.UNIT_Y;
            localZ = nodes["drone"]._getDerivedOrientation() * Mogre.Vector3.UNIT_Z;
            localX = nodes["drone"]._getDerivedOrientation() * Mogre.Vector3.UNIT_X;

            OgreWindow.Instance.tbTextToSend.GotFocus  += new EventHandler(tbTextToSend_GotFocus);
            OgreWindow.Instance.tbTextToSend.LostFocus += new EventHandler(tbTextToSend_LostFocus);
            OgreWindow.Instance.tbConsole.GotFocus     += new EventHandler(tbConsole_GotFocus);
            OgreWindow.Instance.tbConsole.LostFocus    += new EventHandler(tbConsole_LostFocus);
        }
Example #31
0
        /// <summary>
        /// Constructs a new physics actor.
        /// </summary>
        /// <param name="desc">Descriptor for the actor.</param>
        public StaticBEPUActor(ActorDesc desc) : base(desc)
        {
            // Build all shapes that make up the actor.
            for (int i = 0; i < desc.Shapes.Count; ++i)
            {
                ShapeDesc shapeDesc = desc.Shapes[i];

                var tag = new EntityTag(this.ownerEntityID);

                if (shapeDesc is BoxShapeDesc)
                {
                    var boxDesc = shapeDesc as BoxShapeDesc;
                    this.body.PhysicsEntity = new Box(desc.Position, boxDesc.Extents.X, boxDesc.Extents.Y, boxDesc.Extents.Z);
                }
                else if (shapeDesc is SphereShapeDesc)
                {
                    var sphereDesc = shapeDesc as SphereShapeDesc;
                    this.body.PhysicsEntity = new Sphere(desc.Position, sphereDesc.Radius);
                }
                else if (shapeDesc is CapsuleShapeDesc)
                {
                    var capDesc = shapeDesc as CapsuleShapeDesc;
                    this.body.PhysicsEntity = new Capsule(desc.Position, capDesc.Length, capDesc.Radius);
                }
                else if (shapeDesc is CylinderShapeDesc)
                {
                    var cylDesc = shapeDesc as CylinderShapeDesc;
                    this.body.PhysicsEntity = new Cylinder(desc.Position, cylDesc.Height, cylDesc.Radius);
                }
                else if (shapeDesc is TriangleMeshShapeDesc)
                {
                    var triDesc = shapeDesc as TriangleMeshShapeDesc;

                    this.collidable = new StaticMesh(triDesc.Vertices.ToArray(),
                                                     triDesc.Indices.ToArray(),
                                                     new AffineTransform(Quaternion.CreateFromRotationMatrix(desc.Orientation), desc.Position));

                    this.collidable.Tag = tag;
                    this.spaceObject    = this.collidable;
                }
                else if (shapeDesc is HeightFieldShapeDesc)
                {
                    throw new Exception("To load terrain physics you must use a TerrainBEPUActor.");
                }
                else
                {
                    throw new Exception("Bad shape.");
                }

                if (null != this.body.PhysicsEntity)
                {
                    SetMovable(false);
                    this.body.PhysicsEntity.Tag = tag;
                    this.body.PhysicsEntity.CollisionInformation.Tag = tag;
                    this.spaceObject = this.body.PhysicsEntity;
                }
            }

            if (this.body.PhysicsEntity != null)
            {
                this.spaceObject = this.body.PhysicsEntity;
                this.body.PhysicsEntity.BecomeKinematic();
                this.body.PhysicsEntity.IsAffectedByGravity = desc.Dynamic;
            }

            Debug.Assert(this.spaceObject != null, "A physics entity was not properly created.");
        }
        public override void init()
        {
            #region ground
            MeshManager.Singleton.CreatePlane("ground",
                ResourceGroupManager.DEFAULT_RESOURCE_GROUP_NAME,
                new Plane(Mogre.Vector3.UNIT_Y, 0),
                1500, 1500, 20, 20, true, 1, 5, 5, Mogre.Vector3.UNIT_Z);
            // Create a ground plane
            entities.Add(OgreWindow.Instance.mSceneMgr.CreateEntity("GroundEntity", "ground"));
            entities["GroundEntity"].CastShadows = false;
            entities["GroundEntity"].SetMaterialName("dirt");
            nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("ground"));
            nodes["ground"].AttachObject(entities["GroundEntity"]);
            nodes["ground"].Position = new Mogre.Vector3(0f, 0f, 0f) + Location().toMogre;

            // the actor properties control the mass, position and orientation
            // if you leave the body set to null it will become a static actor and wont move
            ActorDesc actorDesc2 = new ActorDesc();
            actorDesc2.Density = 4;
            actorDesc2.Body = null;
            actorDesc2.GlobalPosition = nodes["ground"].Position;
            actorDesc2.GlobalOrientation = nodes["ground"].Orientation.ToRotationMatrix();

            PhysXHelpers.StaticMeshData meshdata = new PhysXHelpers.StaticMeshData(entities["GroundEntity"].GetMesh());
            actorDesc2.Shapes.Add(PhysXHelpers.CreateTriangleMesh(meshdata));
            Actor actor2 = null;
            try { actor2 = OgreWindow.Instance.scene.CreateActor(actorDesc2); }
            catch (System.AccessViolationException ex) { log(ex.ToString()); }
            if (actor2 != null)
            {
                // create our special actor node to tie together the scene node and actor that we can update its position later
                ActorNode actorNode2 = new ActorNode(nodes["ground"], actor2);
                actors.Add(actorNode2);
            }
            #endregion

            lights.Add(OgreWindow.Instance.mSceneMgr.CreateLight("playerLight"));
            lights["playerLight"].Type = Light.LightTypes.LT_POINT;
            lights["playerLight"].Position = Location().toMogre;
            lights["playerLight"].DiffuseColour = ColourValue.White;
            lights["playerLight"].SpecularColour = ColourValue.White;

            #region drone

            OgreWindow.Instance.skeletons["\\Drone.skeleton"].Load();
            OgreWindow.Instance.meshes["\\Drone.mesh"].Load();
            OgreWindow.Instance.meshes["\\Drone.mesh"].SkeletonName = "\\Drone.skeleton";

            entities.Add(OgreWindow.Instance.mSceneMgr.CreateEntity("drone", "\\Drone.mesh"));

            entities["drone"].CastShadows = true;
            walkState = entities["drone"].GetAnimationState("walk");
            walkState.Enabled = true;
            walkState.Loop = true;
            entities["drone"].SetMaterialName("metal");
            nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("drone"));
            nodes["drone"].AttachObject(entities["drone"]);
            nodes["drone"].Position = new Mogre.Vector3(0f, 40f, 0f) + Location().toMogre;
            nodes["drone"].Scale(new Mogre.Vector3(.3f));

            nodes.Add(nodes["drone"].CreateChildSceneNode("orbit0"));
            nodes.Add(nodes["orbit0"].CreateChildSceneNode("orbit"));
            nodes["orbit"].Position = Location().toMogre;
            nodes["orbit"].AttachObject(OgreWindow.Instance.mCamera);
            nodes["drone"].SetFixedYawAxis(true);

            #endregion

            //#region baseball
            //entities.Add(OgreWindow.Instance.mSceneMgr.CreateEntity("baseball", "\\baseball.mesh"));
            //entities["baseball"].SetMaterialName("baseball");
            ////nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("baseball"));
            //nodes.Add(nodes["drone"].CreateChildSceneNode("baseball"));
            //nodes["baseball"].AttachObject(entities["baseball"]);
            //nodes["baseball"].SetScale(.5f, .5f, .5f);
            //nodes["baseball"].SetPosition(-3f, 7f, 3f);
            //// nodes["baseball"].SetScale(5f, 5f, 5f);
            //#endregion

            #region player physics
            bcd = new BoxControllerDesc();
            control = OgreWindow.Instance.physics.ControllerManager.CreateController(OgreWindow.Instance.scene, bcd); //System.NullReferenceException
            #endregion

            nodes.Add(OgreWindow.Instance.mSceneMgr.RootSceneNode.CreateChildSceneNode("suspensionY"));

            OgreWindow.g_m.MouseMoved += new MouseListener.MouseMovedHandler(mouseMoved);
            middlemousetimer.reset();
            middlemousetimer.start();

            this.btnLimiter_F.reset();
            this.btnLimiter_F.start();

            ready = true;
            new Thread(new ThreadStart(controlThread)).Start();
            new Thread(new ThreadStart(statusUpdaterThread)).Start();

            localY = nodes["drone"]._getDerivedOrientation() * Mogre.Vector3.UNIT_Y;
            localZ = nodes["drone"]._getDerivedOrientation() * Mogre.Vector3.UNIT_Z;
            localX = nodes["drone"]._getDerivedOrientation() * Mogre.Vector3.UNIT_X;

            OgreWindow.Instance.tbTextToSend.GotFocus += new EventHandler(tbTextToSend_GotFocus);
            OgreWindow.Instance.tbTextToSend.LostFocus += new EventHandler(tbTextToSend_LostFocus);
            OgreWindow.Instance.tbConsole.GotFocus += new EventHandler(tbConsole_GotFocus);
            OgreWindow.Instance.tbConsole.LostFocus += new EventHandler(tbConsole_LostFocus);
        }