Showing posts with label skybox. Show all posts
Showing posts with label skybox. Show all posts

Thursday, March 23, 2023

87.) Cyclone Game Engine Character Physics Controller Part 2


     Because of limited time, the design and creation of 3D models was placed on hold to focus on getting the physics collision working with low-poly models properly. I went back and utilized the Stage 1 scene from the Robot Game Starter Kit for testing purposes. It not only provided me with rapid results and made me very happy, but gave me room to further expand and modify the scene in the future for improving the graphics. I plan to add particle effects, shaders and more models.


Cyclone Game Engine Character Controller Pics Part-2

     I used JigLibX as the physics engine which is one of the favored open-source physics engines for physics and collision detection. Using JigLibX was a one of the best decisions about this project because it allowed me to focus more on gameplay, instead of spending time on creating my own physics library. JigLibX is a physics engine written in C# using Microsoft's XNA framework. It is based off the physics engine JigLib and I am currently porting it to MonoGame and further expanding it. Having a collision system and a rigid body physics engine makes JigLibX one of the favored free open-source physics engines designed for use with XNA.



Cyclone Game Engine Character Controller Pics Part-2

     With my Ai obstacle-avoidance and steering behaviors sample working recently, I might expand this map to create an arcade style wave based survival game prototype starting out. The player will fight off hordes of various enemies and creatures to rack up a large kill count and points. I don't want to get too far ahead of myself but I think this prototype will hold a lot of potential. 


Cyclone Game Engine Character Controller Pics Part-2

     I plan on implementing Parallax Occlusion Mapping to make the textures pop out and add depth to the textures so that they don't appear too flat.  


Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2

     I might implement Deferred Rendering which will allow the game engine to render a huge number of dynamic lights very efficiently.


Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2

     I plan to add a real-time reflection shader to the car's vehicle body. 


Cyclone Game Engine Character Controller Pics Part-2

     Each game object is represented in the physics engine by a simplified mesh called a collision skin. The collision skins are often rough estimations of the geometry of the game object in order to make simulation faster. The chassis if this car object for example is actually composed of two boxes, one large for the bottom of the model and a smaller box for the top. Rigid body physics is the part of physics that deals with the motion of rigid bodies. Rigid body simulations are fast and easy to calculate relative to other methods of simulating physics. 

     This makes it very useful in game development where performance plays an important role when trying to create a realistic playing experience. Rigid body physics can simulate movement and rotation in three dimensions and allows a body to have properties like mass, friction, torque, velocity etc. In a rigid body physics simulation, all objects are non-deformable. This means that an object can never be squeezed or bent regardless of what forces are applied to them.


Cyclone Game Engine Character Controller Pics Part-2

     The grass area will be separated into its own models and I will add plants and vegetation to it. 


Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Lens Flare Updated Effect



Lens Flare Updated Effect



Lens Flare Updated Effect



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



Cyclone Game Engine Character Controller Pics Part-2



More Robot Mechs Coming!



Friday, June 3, 2016

39. Engine Update 5 Teaser


       This is a brief video teaser sneak peek of my next game engine update. Everything is still a work-in-progress. Since rigged and non-rigged models can be attached to the character now, I am working on character customization. Soon, players will be able to customize their armor. They will be able to swap out head-wear such as hats, helmets and mask. Soon they will also be able to swap between chest pieces and knee guards. This might not be fully shown in the next video update but I have this working for the most part. As players progress through the game, the upgrades to their suit will greatly improve their gameplay experience. Lately, I have been building up content for creating the models and assets that will go into the game world. I am improving artificial intelligence at the moment. This is just a teaser, so it will be a while before my next engine video update. I have been focusing on my 2D game and my independent studies to further educate myself and make far more progress. I am taking some time off and working on the gameplay! So excited. Below are some more screenshots of some fun I had with armor customization.







Wednesday, April 13, 2016

33. Basic Car Drifting Physics


       After some trial and error, I was able to get some drifting mechanics working for my vehicle physics. I am continuing to modify and improve the JigLibX Physics Library that I ported over to XNA 4.0 and MonoGame. Inside my Wheel.cs (wheel class), the key was a variable named "smallVel". This variable applies a force between the drive force and the side force. Initially, it was set to three and I decided to change it to 20 for this vehicle. At the moment, it feels like I am driving on ice but it is controllable which makes it a lot of fun to drift. 

Make the following changes so that the car doesn't slide around too much when stopped: 

            float smallVel;
            if (angVel == 0 & !locked)
            {
                smallVel = 1;
            }
            else smallVel = 20;



To give it more of an authentic feel, you can decrease smallVel to tweleve. I also greatly improved the handling. I will most likely create a starter kit based off of this sample program. So if you are using XNA 4.0 or MonoGame and need some on-road, off-road or arcade style car physics, this will help.




Triangle Mesh Collision Problem
       Many developers using JigLibX in XNA had many problems with the Triangle Mesh Object, especially when using it as a ground model but not with the Height Map Object. I sometimes run into these issues. When a physics object hits a vertex or seam between triangles in the mesh, strange things can occur. 




Solution 
       I separated the garage model into multiple meshes; just two for the most part. Using Autodesk Maya, I then selected them all, grouped them and finally exported the selection. You might have to separate models that have a lot of triangles and faces into separate models. JigLibX uses models that support 16-bit indices in size and not 32-bit. When using the TriangleMeshObject, I found that JigLibX handles collision detection better with models whose polygon faces contain quads rather than triangles. So my next step was to convert my models containing lots of triangles to quads. Converting polygon faces to quads is a good was to clean up polygons or reduce the number of faces. To convert polygon faces to quads in Autodesk Maya, simply select the Mesh option at the top and then Quadrangulate. Below is the changes made to my JigLibX TriangeMeshObject.cs code that lets you extract the vertices and indices from a loaded model.


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using JigLibX.Geometry;
using JigLibX.Physics;
using JigLibX.Collision;


namespace JigLibXGame
{
    class TriangleMeshObject : PhysicObject
    {
        TriangleMesh triangleMesh;
        Matrix xform;
        public TriangleMeshObject(Game game, Model model, Matrix orientation, Vector3 position)
            : base(game, model)
        {
            body = new Body();
            collision = new CollisionSkin(null);
            triangleMesh = new TriangleMesh();
            List<Vector3> vertexList = new List<Vector3>();
            List<TriangleVertexIndices> indexList = new List<TriangleVertexIndices>();
            ExtractData(vertexList, indexList, model);
            triangleMesh.CreateMesh(vertexList, indexList, 4, 1.0f);
            collision.AddPrimitive(triangleMesh, new MaterialProperties(0.8f, 0.7f, 0.6f));
            PhysicsSystem.CurrentPhysicsSystem.CollisionSystem.AddCollisionSkin(collision);
            // Transform
            collision.ApplyLocalTransform(new JigLibX.Math.Transform(position, orientation));
            // we also need to move this dummy, so the object is *rendered* at the correct 
               position
            // body.MoveTo(position, orientation);
            this.body.CollisionSkin = this.collision;
          
        }

    
        // Helper Method to get the vertex and index List from the model.
        public void ExtractData(List<Vector3> vertices, List<TriangleVertexIndices> indices, Model model)
        {
            Matrix[] bones_ = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(bones_);
            foreach (ModelMesh mm in model.Meshes)
            {
                Game.GraphicsDevice.RasterizerState = RasterizerState.CullNone;
              
                xform = bones_[mm.ParentBone.Index];
                foreach (ModelMeshPart mmp in mm.MeshParts)
                {
                    int offset = vertices.Count;
                    Vector3[] a = new Vector3[mmp.NumVertices];
                    int vertexStride = mmp.VertexBuffer.VertexDeclaration.VertexStride;
                    mmp.VertexBuffer.GetData<Vector3>(mmp.VertexOffset * vertexStride, a, 0, mmp.NumVertices, vertexStride);
                   
                    for (int i = 0; i != a.Length; ++i)
                        Vector3.Transform(ref a[i], ref xform, out a[i]);
                    vertices.AddRange(a);

                    // new
                    for (int i = 0; i < a.Length; i++) vertices.Add(new Vector3(a[i].X, a[i].Y, a[i].Z));

                    if (mmp.IndexBuffer.IndexElementSize != IndexElementSize.SixteenBits)
                        throw new Exception(
                            String.Format("Model uses 32-bit indices, which are not supported."));
                    short[] s = new short[mmp.PrimitiveCount * 3];
                    
                    mmp.IndexBuffer.GetData<short>(mmp.StartIndex * 2, s, 0, mmp.PrimitiveCount * 3);
                    JigLibX.Geometry.TriangleVertexIndices[] tvi = new JigLibX.Geometry.TriangleVertexIndices[mmp.PrimitiveCount];
                    for (int i = 0; i != tvi.Length; ++i)
                    {
                        tvi[i].I0 = s[i * 3 + 2] + offset;
                        tvi[i].I1 = s[i * 3 + 1] + offset;
                        tvi[i].I2 = s[i * 3 + 0] + offset;
                    }
                    indices.AddRange(tvi);
                }
            }
        }
  
        public override void ApplyEffects(BasicEffect effect)
        {
            //effect.DiffuseColor = Vector3.One * 0.8f;
            
        }
    }
}


How to Convert a Triangulated Mesh into Quads in 3DS Max 
       So now I have encountered a situation where I need quad based meshes and I have many 3D models with triangulated ones. Initially I would manually convert the model to quads by selecting groups of triangles. If the model is very complex, this can be extremely time consuming which can pose a problem. Luckily, there is an easier way in this tutorial below by Chandan Kumar who introduces an amazing free script to save time converting triangulated meshes to quads. You can download it here.



       Next I will be making a way where the player can switch to cockpit-view and drive in first-person perspective while in-game. Thanks for reading and I look forward to posting more updates. If you have found this blog post helpful or would like to share any improvements, please comment below.





Friday, March 4, 2016

30. XNA Vehicle Physics Test 4


       In this update, I am continuing to modify and expand the JigLibX (Jiggle Library X) Physics Engine. Recently I added an exhaust particle effect to the vehicle. You can download the XNA 4.0  version of JigLibX below.



       This particle effect streams behind the vehicle when the player presses the gas so often. I will change the color of the smoke to grey. The standard vehicle class in my game engine has a hand brake that locks the rear wheels, thereby creating some drag and slowing the car down. That part is realistic. What isn't realistic is the rear wheels still have full traction. If you've ever pulled a hand brake in a car while moving you've notice that the rear end loses traction and wants to swing around causing a spin. It can be useful for making tight 180 degree turns, orienting your car coming into a turn and for good 'ol fashioned fun. This is why I kept this feature. 


Adding the smoke particle

Vector3 OffsetAmount = new Vector3(0, 0, -3);

Vector3 OffsetPosition = Car.carObject.Car.Chassis.Body.Position +
    (Car.carObject.Car.Chassis.Body.Orientation.Right * OffsetAmount.Z) +
    (Car.carObject.Car.Chassis.Body.Orientation.Up * OffsetAmount.Y) -
    (Car.carObject.Car.Chassis.Body.Orientation.Forward * OffsetAmount.X);


ParticleComponent.smokeParticles.AddParticle(OffsetPosition, Vector3.Zero);


       OffsetAmount is a Vector3 that is the relative offset you want, in this case 3 units behind the center of the car. OffsetPosition is the final, global, relative position, that you can then pass into your particle system or something. It took some trial and error to get all of these working correctly, but I've tested it in several positions and it seems to work OK. And the last line tells my ParticleComponent to add a particle at the specified position and initial velocity - replace it with your own particle code to get a nice stream of particles behind your car. I plan on adding a similar particle effect to the actual engine when the vehicle takes damage. For example, if the engine is emitting grey smoke, the damage to the vehicle is rather light. But if the smoke is black, the vehicle is heavily damaged and requires repair. The next particle effect I will be working on is adding a dust trail streaming behind the tires.


Change the Gravity 
       One thing I forgot to mention in my previous vehicle physics post was how I changed the gravity. Inside the Physics System Class (PhysicsSystem.cs), scroll down and change the gravity variable from -10 to -30. 

        public PhysicsSystem()  
        {  
            CurrentPhysicsSystem = this;  
            Gravity = -30.0f * Vector3.Up;  
        } 

This will make the car and the physics in general less like the "moon's gravity" and more like the Earth's gravity.


Add Rotational Friction to the Wheels
       Now open up the Wheels.cs file. Before, if you were on level ground, you could coast forever after letting off the throttle.

     if (driveTorque == 0)
    {
        angVel *= .97f;
    }  

Put this in Update() in the Wheels.cs right above angVel += driveTorque * dt / inertia:

                 if (driveTorque == 0)
                {
                    float axleFriction = 5; // higher number = more rotational friction
                    if (angVel > axleFriction)
                    {
                        if (angVel > 0) angVel -= axleFriction;
                        else angVel += axleFriction;
                    }
                    else angVel = 0;
                }

If you want to add more friction, multiply by a smaller number. For less friction, use a bigger number that's less than 1. Also, to help counteract any bumps on the track, I decreased the wheel's damping fraction.


Improve JigLibX's Performance 
       I have highly modified the Jiggle Physics Library to run on XNA 4.0 and MonoGame. I am extending and improving it in many ways. Many indie game developers chose BEPU rather than JigLibX when developing their games for Xbox 360. One of the major reasons why was the fact that JigLibX's performance on Xbox 360 was extremely slow which decreased the game's frame rate. To help with JigLibX's physics performance on Xbox 360 as well as other less advanced hardware, I am changing its foreach statements to for and I will be adding separate loading threads to help improve the low frame-rate issues. JigLibX also makes extensive use of the "float" object. I mention this because the Xbox 360 has some issues processing floating points. So I am changing out all the floats to avoid major physics performance issues.


How to Get Rid of of the Infamous Wobble at High Speed
       One of the major issues people encountered using JigLibX was once the vehicle got to a certain speed, it started to rock side to side, with no obvious way to stop it. Nikescar came up with a solution to fix this issue. If you would like to see this problem for yourself, adjust the wheelFriction to 5.0f and wheelDampingFrac to 0.3f. The car should start wobbling at max speed.

       Each Update( ) is called at a different time for each wheel. One wheel gets slowed down and the other wheels stay at the current speed. Next, the update from one of the three wheels from the last frame gets slowed down and the remaining wheels go at the same speed. If you do this sixty times a second, you will get quick declaration corners of the car causing the wobbling. After a lot of trial and error, here is how you can fix this.

This problem occurs when the andVel reaches maxAngVel in the Update( ) method of the Wheel.cs:

angVel = MathHelper.Clamp(angVel, -maxAngVel, maxAngVel);

Either delete or comment out this line and it will take care of the problem. However, this creates another problem because now you won't be able to set a limit for the top speed.

In the Wheel.cs, add this with the rest of them:

public float AngVel
        {
            get { return angVel; }

        }


Then just after this under PostPhysics( ) in the Car.cs:

for (int i = 0; i < wheels.Count; i++)
                wheels[i].Update(dt);


add this:

for (int i = 0; i < wheels.Count; i++)
            {
                if (wheels[i].AngVel >= topSpeed)
                    destAccelerate = 0;
            }


This should fix it. Now you can freely setup your car without having to worry about the limitations of the infamous wobble. Lastly, to see how I implemented the skybox, check out my blog post here. Thanks for reading and if anyone has found this blog post helpful, please comment below.


Tuesday, December 4, 2012

7: Skybox System Updated

       

       Welcome back gamers to my next blog post. Recently, I have made significant improvements to the sky-box system in the game engine. Before the sky-box would rotate too much wherever the player looked. Now it stays in place and the visuals have improved since then. I am thinking about creating billboard clouds in the future and hopefully have a day & night cycle system functioning. The Cyclone Engine creates a box and places the textures on each of the sides of the box. So I had to determine which image to use for the top and the sides to make it appear 3D when the player moves around in the world.


How to Add a Skybox
       A skybox is merely nothing more than a mesh. To accompany the mesh, we will need to load some textures to along with it. We will create two variables: one to store the model, and an extra one to store the textures. Add these variables to the top of your code:

Texture2D[] skyboxTextures;
Model skybodModel;


We would normally use the LoadModel method to load our skybox, but we cannot do this since that method doesn't load the textures. We will fix this by overloading that method. We shall create a new version of the method, with the same name, but with different arguments.

private Model LoadModel(string assetName, out Texture2D[] textures)
        {
            Model newModel = Content.Load<Model>(assetName);
            textures = new Texture2D[newModel.Meshes.Count];
            int i = 0;

            foreach (ModelMesh mesh in newModel.Meshes)
            {
                foreach (BasicEffect currentEffect in mesh.Effects)
                {
                    textures[i++] = currentEffect.Texture;
                }
            }

            foreach (ModelMesh mesh in newModel.Meshes)
            {
                foreach (ModelMeshPart meshPart in mesh.MeshParts)
                {
                    meshPart.Effect = skyEffect.Clone();
                }
            }

            return newModel;
        }


We call this method from within the LoadContent method:

 skyboxModel = LoadModel("skybox", out skyboxTextures);


Now that we have the skybox loading, we need to draw it. The issue with my previous skybox program was that it would move relative to the player's movement when you looked up or down. The skybox should always be at a constant distance from the player. This will make the skybox appear as if it's far away. So as the player moves, the skybox will move according to the camera's position. That way, the player will always remain in the middle of the skybox.

public void DrawSkybox( )
        {
            SamplerState ss = new SamplerState();
            ss.AddressU = TextureAddressMode.Clamp;
            ss.AddressV = TextureAddressMode.Clamp;
            GraphicsDevice.SamplerStates[0] = ss;

            DepthStencilState dss = new DepthStencilState();
            dss.DepthBufferEnable = false;
            GraphicsDevice.DepthStencilState = dss;

            Matrix[] skyboxTransforms = new Matrix[skyBoxModel.Bones.Count];
            skyBoxModel.CopyAbsoluteBoneTransformsTo(skyboxTransforms);
            int i = 0;
            foreach (ModelMesh mesh in skyBoxModel.Meshes)
            {
                foreach (Effect currentEffect in mesh.Effects)
                {
                    Matrix worldMatrix = Matrix.CreateScale(50000f) * skyboxTransforms[mesh.ParentBone.Index] * Matrix.CreateTranslation(camera.Postion + new Vector3(0, 5.2f, 0));
                    currentEffect.CurrentTechnique = currentEffect.Techniques["Sky"];
                    currentEffect.Parameters["xWorld"].SetValue(skyboxTransforms[mesh.ParentBone.Index] * worldMatrix);
                    currentEffect.Parameters["xViewProjection"].SetValue(camera.View * camera.Projection);
                    currentEffect.Parameters["xTexture"].SetValue(skyBoxTextures[i++]);

                }
                mesh.Draw();
            }

        }

After clearing the screen, you need to call this method as the first line in your Draw method:

DrawSkybox( );


See how the skybox turned out in the images below.














Saturday, October 13, 2012

6: Cyclone Engine Skybox

by Jordon McClain

     As of 10/12/2012 I got the skybox working inside the Cyclone Engine.