Exemplo n.º 1
0
		static void Main(string[] args)
		{
			device = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(800, 600));
			device.SetWindowCaption("Sphere Camera - Irrlicht Engine");
			driver = device.VideoDriver;
			scene = device.SceneManager;

			sphere = scene.AddSphereSceneNode(5, 100);
			sphere.SetMaterialTexture(0, driver.GetTexture("../../media/earth.jpg"));
			sphere.TriangleSelector = scene.CreateTriangleSelector(sphere.Mesh, sphere);
			sphere.TriangleSelector.Drop();

			scene.AmbientLight = new Colorf(0.2f, 0.2f, 0.2f);
			LightSceneNode light = scene.AddLightSceneNode();
			light.Position = new Vector3Df(-10, 10, -10);

			camera = new SphereCamera(device, new Vector3Df(0), 8, 20, 10, 0, 0);
			camera.Inclination = 200;

			path = new SpherePath(5.4f);

			GUIFont font = device.GUIEnvironment.BuiltInFont;
			device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
			device.PostEvent(new Event('r', KeyCode.KeyR, true)); // pretend user pressed [R]

			while (device.Run())
			{
				driver.BeginScene();

				scene.DrawAll();

				path.Draw(driver);

				font.Draw("Press [Arrows], [LMB] and [Mouse Scroll] to change view", 10, 10, Color.OpaqueYellow);
				font.Draw("Press [RMB] on Earth to place new path point", 10, 20, Color.OpaqueYellow);
				font.Draw("Press [R] to reload path data from file", 10, 30, Color.OpaqueYellow);
				font.Draw("Press [C] to clean up", 10, 40, Color.OpaqueYellow);

				font.Draw(driver.FPS.ToString() + " fps", 10, driver.ScreenSize.Height - 40, Color.OpaqueYellow);
				font.Draw(path.PointCount.ToString() + " point(s)", 10, driver.ScreenSize.Height - 30, Color.OpaqueYellow);
				font.Draw(camera.ToString(), 10, driver.ScreenSize.Height - 20, Color.OpaqueYellow);

				driver.EndScene();
			}

			path.Drop();
			device.Drop();
		}
Exemplo n.º 2
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(640, 480));

            if (device == null)
            {
                return;
            }

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);

            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;

            scene.GUIEnvironment.AddStaticText("Press Space to hide occluder.", new Recti(10, 10, 200, 50));

            // Create the node to be occluded. We create a sphere node with high poly count.

            MeshSceneNode node = scene.AddSphereSceneNode(10, 64);

            if (node != null)
            {
                node.Position = new Vector3Df(0, 0, 60);
                node.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp"));
                node.SetMaterialFlag(MaterialFlag.Lighting, false);
            }

            // Now we create another node, the occluder. It's a simple plane.

            SceneNode plane = scene.AddMeshSceneNode(
                scene.AddHillPlaneMesh("plane", new Dimension2Df(10), new Dimension2Di(2)), // mesh
                null,                                                                       // parent
                -1,                                                                         // id
                new Vector3Df(0, 0, 20),                                                    // position
                new Vector3Df(270, 0, 0));                                                  // rotation

            if (plane != null)
            {
                plane.SetMaterialTexture(0, driver.GetTexture("../../media/t351sml.jpg"));
                plane.SetMaterialFlag(MaterialFlag.Lighting, false);
                plane.SetMaterialFlag(MaterialFlag.BackFaceCulling, true);
            }

            // Here we create the occlusion query. Because we don't have a plain mesh scene node
            // (SceneNodeType.Mesh or SceneNodeType.AnimatedMesh), we pass the base geometry as well. Instead,
            // we could also pass a simpler mesh or the bounding box. But we will use a time
            // based method, where the occlusion query renders to the frame buffer and in case
            // of success (occlusion), the mesh is not drawn for several frames.

            driver.AddOcclusionQuery(node, node.Mesh);

            // We have done everything, just a camera and draw it. We also write the
            // current frames per second and the name of the driver to the caption of the
            // window to examine the render speedup.
            // We also store the time for measuring the time since the last occlusion query ran
            // and store whether the node should be visible in the next frames.

            scene.AddCameraSceneNode();
            uint timeNow     = device.Timer.Time;
            bool nodeVisible = true;

            while (device.Run())
            {
                plane.Visible = !IsKeyDown(KeyCode.Space);

                driver.BeginScene(ClearBufferFlag.All, new Color(113, 113, 133));

                // First, we draw the scene, possibly without the occluded element. This is necessary
                // because we need the occluder to be drawn first. You can also use several scene
                // managers to collect a number of possible occluders in a separately rendered scene.

                node.Visible = nodeVisible;
                scene.DrawAll();
                scene.GUIEnvironment.DrawAll();

                // Once in a while, here every 100 ms, we check the visibility. We run the queries,
                // update the pixel value, and query the result. Since we already rendered the node
                // we render the query invisible. The update is made blocking, as we need the result
                // immediately. If you don't need the result immediately, e.g. because oyu have other
                // things to render, you can call the update non-blocking. This gives the GPU more
                // time to pass back the results without flushing the render pipeline.
                // If the update was called non-blocking, the result from getOcclusionQueryResult is
                // either the previous value, or 0xffffffff if no value has been generated at all, yet.
                // The result is taken immediately as visibility flag for the node.

                if (device.Timer.Time - timeNow > 100)
                {
                    driver.RunAllOcclusionQueries(false);
                    driver.UpdateAllOcclusionQueries();
                    nodeVisible = driver.GetOcclusionQueryResult(node) > 0;
                    timeNow     = device.Timer.Time;
                }

                driver.EndScene();

                device.SetWindowCaption(String.Format(
                                            "Occlusion Query Example - Irrlicht Engine [{0}] fps: {1} (primitives: {2})",
                                            driver.Name, driver.FPS, driver.PrimitiveCountDrawn));
            }

            device.Drop();
        }
Exemplo n.º 3
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(640, 480));

            if (device == null)
            {
                return;
            }

            VideoDriver    driver = device.VideoDriver;
            SceneManager   smgr   = device.SceneManager;
            GUIEnvironment env    = device.GUIEnvironment;

            driver.SetTextureCreationFlag(TextureCreationFlag.Always32Bit, true);

            // add irrlicht logo
            env.AddImage(driver.GetTexture("../../media/irrlichtlogoalpha2.tga"), new Vector2Di(10));

            // add camera
            CameraSceneNode camera = smgr.AddCameraSceneNodeFPS();

            camera.Position = new Vector3Df(-200, 200, -200);

            // disable mouse cursor
            device.CursorControl.Visible = false;

            driver.Fog = new Fog(new Color(138, 125, 81, 0), FogType.Linear, 250, 1000, 0.003f, true, false);

            AnimatedMesh roomMesh = smgr.GetMesh("../../media/room.3ds");
            SceneNode    room     = null;
            SceneNode    earth    = null;

            if (roomMesh != null)
            {
                // the room mesh doesn't have proper texture mapping on the floor,
                // so we can recreate them on runtime
                smgr.MeshManipulator.MakePlanarTextureMapping(roomMesh.GetMesh(0), 0.003f);

                Texture normalMap = driver.GetTexture("../../media/rockwall_height.bmp");
                if (normalMap != null)
                {
                    driver.MakeNormalMapTexture(normalMap, 9.0f);
                }

                Mesh tangentMesh = smgr.MeshManipulator.CreateMeshWithTangents(roomMesh.GetMesh(0));
                room = smgr.AddMeshSceneNode(tangentMesh);
                room.SetMaterialTexture(0, driver.GetTexture("../../media/rockwall.jpg"));
                room.SetMaterialTexture(1, normalMap);
                room.GetMaterial(0).SpecularColor = new Color(0);
                room.GetMaterial(0).Shininess     = 0.0f;
                room.SetMaterialFlag(MaterialFlag.Fog, true);
                room.SetMaterialType(MaterialType.ParallaxMapSolid);
                room.GetMaterial(0).MaterialTypeParam = 1.0f / 64.0f; // adjust height for parallax effect

                tangentMesh.Drop();                                   // drop mesh because we created it with a "create" call
            }

            // add earth sphere
            AnimatedMesh earthMesh = smgr.GetMesh("../../media/earth.x");

            if (earthMesh != null)
            {
                // perform various task with the mesh manipulator
                MeshManipulator manipulator = smgr.MeshManipulator;

                // create mesh copy with tangent informations from original earth.x mesh
                Mesh tangentSphereMesh = manipulator.CreateMeshWithTangents(earthMesh.GetMesh(0));

                // set the alpha value of all vertices to 200
                manipulator.SetVertexColorAlpha(tangentSphereMesh, 200);

                // scale the mesh by factor 50
                Matrix m = new Matrix();
                m.Scale = new Vector3Df(50);
                manipulator.Transform(tangentSphereMesh, m);

                earth          = smgr.AddMeshSceneNode(tangentSphereMesh);
                earth.Position = new Vector3Df(-70, 130, 45);

                // load heightmap, create normal map from it and set it
                Texture earthNormalMap = driver.GetTexture("../../media/earthbump.jpg");
                if (earthNormalMap != null)
                {
                    driver.MakeNormalMapTexture(earthNormalMap, 20);
                    earth.SetMaterialTexture(1, earthNormalMap);
                    earth.SetMaterialType(MaterialType.NormalMapTransparentVertexAlpha);
                }

                // adjust material settings
                earth.SetMaterialFlag(MaterialFlag.Fog, true);

                // add rotation animator
                SceneNodeAnimator anim = smgr.CreateRotationAnimator(new Vector3Df(0, 0.1f, 0));
                earth.AddAnimator(anim);
                anim.Drop();

                // drop mesh because we created it with a "create" call.
                tangentSphereMesh.Drop();
            }

            // add light 1 (more green)
            LightSceneNode light1 = smgr.AddLightSceneNode(null, new Vector3Df(), new Colorf(0.5f, 1.0f, 0.5f, 0.0f), 800);

            if (light1 != null)
            {
                light1.DebugDataVisible = DebugSceneType.BBox;

                // add fly circle animator to light
                SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(50, 300, 0), 190.0f, -0.003f);
                light1.AddAnimator(anim);
                anim.Drop();

                // attach billboard to the light
                BillboardSceneNode bill = smgr.AddBillboardSceneNode(light1, new Dimension2Df(60, 60));
                bill.SetMaterialFlag(MaterialFlag.Lighting, false);
                bill.SetMaterialFlag(MaterialFlag.ZWrite, false);
                bill.SetMaterialType(MaterialType.TransparentAddColor);
                bill.SetMaterialTexture(0, driver.GetTexture("../../media/particlegreen.jpg"));
            }

            // add light 2 (red)
            SceneNode light2 = smgr.AddLightSceneNode(null, new Vector3Df(), new Colorf(1.0f, 0.2f, 0.2f, 0.0f), 800.0f);

            if (light2 != null)
            {
                // add fly circle animator to light
                SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 150, 0), 200.0f, 0.001f, new Vector3Df(0.2f, 0.9f, 0.0f));
                light2.AddAnimator(anim);
                anim.Drop();

                // attach billboard to light
                SceneNode bill = smgr.AddBillboardSceneNode(light2, new Dimension2Df(120, 120));
                bill.SetMaterialFlag(MaterialFlag.Lighting, false);
                bill.SetMaterialFlag(MaterialFlag.ZWrite, false);
                bill.SetMaterialType(MaterialType.TransparentAddColor);
                bill.SetMaterialTexture(0, driver.GetTexture("../../media/particlered.bmp"));

                // add particle system
                ParticleSystemSceneNode ps = smgr.AddParticleSystemSceneNode(false, light2);

                // create and set emitter
                ParticleEmitter em = ps.CreateBoxEmitter(
                    new AABBox(-3, 0, -3, 3, 1, 3),
                    new Vector3Df(0.0f, 0.03f, 0.0f),
                    80, 100,
                    new Color(255, 255, 255, 10), new Color(255, 255, 255, 10),
                    400, 1100);

                em.MinStartSize = new Dimension2Df(30.0f, 40.0f);
                em.MaxStartSize = new Dimension2Df(30.0f, 40.0f);

                ps.Emitter = em;
                em.Drop();

                // create and set affector
                ParticleAffector paf = ps.CreateFadeOutParticleAffector();
                ps.AddAffector(paf);
                paf.Drop();

                // adjust some material settings
                ps.SetMaterialFlag(MaterialFlag.Lighting, false);
                ps.SetMaterialFlag(MaterialFlag.ZWrite, false);
                ps.SetMaterialTexture(0, driver.GetTexture("../../media/fireball.bmp"));
                ps.SetMaterialType(MaterialType.TransparentAddColor);
            }

            MyEventReceiver receiver = new MyEventReceiver(device, room, earth);

            int lastFPS = -1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    driver.BeginScene(ClearBufferFlag.All, new Color(0));

                    smgr.DrawAll();
                    env.DrawAll();

                    driver.EndScene();

                    int fps = driver.FPS;
                    if (lastFPS != fps)
                    {
                        device.SetWindowCaption(String.Format(
                                                    "Per pixel lighting example - Irrlicht Engine [{0}] fps: {1}",
                                                    driver.Name, fps));

                        lastFPS = fps;
                    }
                }
            }

            device.Drop();
        }
Exemplo n.º 4
0
        static void Main()
        {
            bool shadows = AskForRealtimeShadows();

            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(640, 480), 16, false, shadows);

            if (device == null)
            {
                return;
            }

            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

            AnimatedMesh mesh = smgr.GetMesh("../../media/room.3ds");

            smgr.MeshManipulator.MakePlanarTextureMapping(mesh.GetMesh(0), 0.004f);

            SceneNode node = smgr.AddAnimatedMeshSceneNode(mesh);

            node.SetMaterialTexture(0, driver.GetTexture("../../media/wall.jpg"));
            node.GetMaterial(0).SpecularColor = new Color(0);

            mesh = smgr.AddHillPlaneMesh("myHill",
                                         new Dimension2Df(20, 20),
                                         new Dimension2Di(40, 40), null, 0,
                                         new Dimension2Df(0),
                                         new Dimension2Df(10, 10));

            node          = smgr.AddWaterSurfaceSceneNode(mesh.GetMesh(0), 3.0f, 300.0f, 30.0f);
            node.Position = new Vector3Df(0, 7, 0);

            node.SetMaterialTexture(0, driver.GetTexture("../../media/stones.jpg"));
            node.SetMaterialTexture(1, driver.GetTexture("../../media/water.jpg"));

            node.SetMaterialType(MaterialType.Reflection2Layer);

            // create light

            node = smgr.AddLightSceneNode(null, new Vector3Df(0), new Colorf(1.0f, 0.6f, 0.7f, 1.0f), 800);
            SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 150, 0), 250);

            node.AddAnimator(anim);
            anim.Drop();

            // attach billboard to light

            node = smgr.AddBillboardSceneNode(node, new Dimension2Df(50, 50));
            node.SetMaterialFlag(MaterialFlag.Lighting, false);
            node.SetMaterialType(MaterialType.TransparentAddColor);
            node.SetMaterialTexture(0, driver.GetTexture("../../media/particlewhite.bmp"));

            // create a particle system

            ParticleSystemSceneNode ps = smgr.AddParticleSystemSceneNode(false);

            if (ps != null)
            {
                ParticleEmitter em = ps.CreateBoxEmitter(
                    new AABBox(-7, 0, -7, 7, 1, 7),   // emitter size
                    new Vector3Df(0.0f, 0.06f, 0.0f), // initial direction
                    80, 100,                          // emit rate
                    new Color(255, 255, 255, 0),      // darkest color
                    new Color(255, 255, 255, 0),      // brightest color
                    800, 2000, 0,                     // min and max age, angle
                    new Dimension2Df(10.0f),          // min size
                    new Dimension2Df(20.0f));         // max size

                ps.Emitter = em;                      // this grabs the emitter
                em.Drop();                            // so we can drop it here without deleting it

                ParticleAffector paf = ps.CreateFadeOutParticleAffector();

                ps.AddAffector(paf);                 // same goes for the affector
                paf.Drop();

                ps.Position = new Vector3Df(-70, 60, 40);
                ps.Scale    = new Vector3Df(2);
                ps.SetMaterialFlag(MaterialFlag.Lighting, false);
                ps.SetMaterialFlag(MaterialFlag.ZWrite, false);
                ps.SetMaterialTexture(0, driver.GetTexture("../../media/fire.bmp"));
                ps.SetMaterialType(MaterialType.TransparentAddColor);
            }

            VolumeLightSceneNode n = smgr.AddVolumeLightSceneNode(null, -1,
                                                                  32,                          // Subdivisions on U axis
                                                                  32,                          // Subdivisions on V axis
                                                                  new Color(255, 255, 255, 0), // foot color
                                                                  new Color(0, 0, 0, 0));      // tail color

            if (n != null)
            {
                n.Scale    = new Vector3Df(56);
                n.Position = new Vector3Df(-120, 50, 40);

                // load textures for animation
                List <Texture> textures = new List <Texture>();
                for (int i = 7; i > 0; i--)
                {
                    string s = string.Format("../../media/portal{0}.bmp", i);
                    textures.Add(driver.GetTexture(s));
                }

                // create texture animator
                SceneNodeAnimator glow = smgr.CreateTextureAnimator(textures, 0.150f);

                // add the animator
                n.AddAnimator(glow);

                // drop the animator because it was created with a create() function
                glow.Drop();
            }

            // add animated character

            mesh = smgr.GetMesh("../../media/dwarf.x");
            AnimatedMeshSceneNode anode = smgr.AddAnimatedMeshSceneNode(mesh);

            anode.Position       = new Vector3Df(-50, 20, -60);
            anode.AnimationSpeed = 15;

            // add shadow
            anode.AddShadowVolumeSceneNode();
            smgr.ShadowColor = new Color(0, 0, 0, 150);

            // make the model a little bit bigger and normalize its normals
            // because of the scaling, for correct lighting
            anode.Scale = new Vector3Df(2);
            anode.SetMaterialFlag(MaterialFlag.NormalizeNormals, true);

            CameraSceneNode camera = smgr.AddCameraSceneNodeFPS();

            camera.Position = new Vector3Df(-50, 50, -150);

            // disable mouse cursor
            device.CursorControl.Visible = false;

            int lastFPS = -1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    driver.BeginScene(ClearBufferFlag.All, new Color(0));
                    smgr.DrawAll();
                    driver.EndScene();

                    int fps = driver.FPS;
                    if (lastFPS != fps)
                    {
                        device.SetWindowCaption(String.Format(
                                                    "SpecialFX example - Irrlicht Engine [{0}] fps: {1}",
                                                    driver.Name, fps));

                        lastFPS = fps;
                    }
                }
            }

            device.Drop();
        }
Exemplo n.º 5
0
        static void Main()
        {
            int lodItemCount = AskForLODItemCount();

            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(800, 600));
            if (device == null)
            {
                return;
            }

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            device.SetWindowCaption("Simple LOD - Irrlicht Lime");
            device.CursorControl.Visible = false;

            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;

            // generate all LODs of mesh

            List <Mesh> lodMesh          = new List <Mesh>();
            Material    meshMaterial     = null;
            List <int>  lodTriangleCount = new List <int>();

            int[] p = new int[] { 100, 50, 32, 20, 12, 6, 3 };
            for (int i = 0; i < p.Length; i++)
            {
                Mesh m = scene.GeometryCreator.CreateSphereMesh(50, p[i], p[i]);

                MeshBuffer mb = m.GetMeshBuffer(0);
                mb.Material.Type = MaterialType.Solid;
                mb.Material.SetTexture(0, driver.GetTexture("../../media/earth.jpg"));

                m.SetMaterialFlag(MaterialFlag.Lighting, false);
                lodMesh.Add(m);

                if (meshMaterial == null)
                {
                    meshMaterial = m.GetMeshBuffer(0).Material;
                }

                lodTriangleCount.Add(mb.IndexCount / 3);
            }

            // generate world,
            // we generate a lot of objects with random positions in huge virtual cube

            int virtualCubeSide = 20000;

            LODItem[] lodItems = new LODItem[lodItemCount];
            Random    r        = new Random(12345000);

            for (int i = 0; i < lodItemCount; i++)
            {
                Matrix tmat = new Matrix(
                    new Vector3Df(                     // translation
                        r.Next(virtualCubeSide) - virtualCubeSide / 2,
                        r.Next(virtualCubeSide) - virtualCubeSide / 2,
                        r.Next(virtualCubeSide) - virtualCubeSide / 2));

                Vector3Df rvect = new Vector3Df(
                    (float)r.NextDouble() / 200.0f,
                    (float)r.NextDouble() / 200.0f,
                    (float)r.NextDouble() / 200.0f);

                lodItems[i] = LODItem.Create(device, lodMesh, tmat, rvect);
            }

            // split world on virtual sectors (cubes) for faster visibility check

            int lodSectorSide = 6;             // total number of sectors will be lodSectorSide^3, so for 6 it is 216
            int lodSectorSize = virtualCubeSide / lodSectorSide;

            LODSector[,,] lodSectors = new LODSector[lodSectorSide, lodSectorSide, lodSectorSide];

            for (int i = 0; i < lodSectorSide; i++)
            {
                for (int j = 0; j < lodSectorSide; j++)
                {
                    for (int k = 0; k < lodSectorSide; k++)
                    {
                        AABBox dimension = new AABBox(
                            new Vector3Df(i * lodSectorSize, j * lodSectorSize, k * lodSectorSize),
                            new Vector3Df((i + 1) * lodSectorSize, (j + 1) * lodSectorSize, (k + 1) * lodSectorSize));

                        dimension.MinEdge -= virtualCubeSide / 2;
                        dimension.MaxEdge -= virtualCubeSide / 2;

                        LODSector s = LODSector.Create(dimension);
                        lodSectors[i, j, k] = s;
                    }
                }
            }

            for (int i = 0; i < lodItems.Length; i++)
            {
                Vector3Df pos = lodItems[i].Position;
                pos += virtualCubeSide / 2;
                pos /= lodSectorSize;

                int ix = (int)pos.X;
                int iy = (int)pos.Y;
                int iz = (int)pos.Z;

                if (ix < 0)
                {
                    ix = 0;
                }
                if (ix > lodSectorSide - 1)
                {
                    ix = lodSectorSide - 1;
                }

                if (iy < 0)
                {
                    ix = 0;
                }
                if (iy > lodSectorSide - 1)
                {
                    iy = lodSectorSide - 1;
                }

                if (iz < 0)
                {
                    iz = 0;
                }
                if (iz > lodSectorSide - 1)
                {
                    iz = lodSectorSide - 1;
                }

                lodSectors[ix, iy, iz].AddLODItem(lodItems[i]);
            }

            // camera

            CameraSceneNode camera = scene.AddCameraSceneNodeFPS();

            camera.FarValue = 30000;

            // font, which we are going to use to show any text we need

            IrrlichtLime.GUI.GUIFont font = device.GUIEnvironment.GetFont("../../media/fontlucida.png");

            // render loop

            while (device.Run())
            {
                driver.BeginScene();
                scene.DrawAll();

                if (isLabelMode)
                {
                    LODItem.LabelPositions = new List <Vector2Di>();
                    LODItem.LabelTexts     = new List <string>();
                }
                else
                {
                    LODItem.LabelPositions = null;
                    LODItem.LabelTexts     = null;
                }

                meshMaterial.Wireframe = isWireframeMode;
                device.VideoDriver.SetMaterial(meshMaterial);

                uint      timer          = device.Timer.Time;
                Vector3Df cameraPosition = camera.AbsolutePosition;
                AABBox    cameraViewBox  = camera.ViewFrustum.BoundingBox;

                for (int i = 0; i < lodSectorSide; i++)
                {
                    for (int j = 0; j < lodSectorSide; j++)
                    {
                        for (int k = 0; k < lodSectorSide; k++)
                        {
                            lodSectors[i, j, k].Draw(timer, cameraPosition, cameraViewBox);
                        }
                    }
                }

                if (isLabelMode)
                {
                    for (int i = 0; i < LODItem.LabelPositions.Count; i++)
                    {
                        driver.Draw2DLine(
                            LODItem.LabelPositions[i] - new Vector2Di(10, 0),
                            LODItem.LabelPositions[i] + new Vector2Di(50, 0),
                            Color.SolidGreen);

                        driver.Draw2DLine(
                            LODItem.LabelPositions[i] - new Vector2Di(0, 10),
                            LODItem.LabelPositions[i] + new Vector2Di(0, 50),
                            Color.SolidGreen);

                        font.Draw(LODItem.LabelTexts[i], LODItem.LabelPositions[i], Color.SolidGreen);
                    }
                }

                if (isStatsMode)
                {
                    // show LOD stats

                    int[] lodCount = new int[7] {
                        0, 0, 0, 0, 0, 0, 0
                    };
                    for (int i = 0; i < lodItems.Length; i++)
                    {
                        lodCount[lodItems[i].CurrentLOD]++;
                    }

                    string f = "";
                    for (int i = 0; i < lodCount.Length; i++)
                    {
                        int n = lodCount[i];
                        f += "LOD" + i.ToString() + ": " + n.ToString() + " [" + ((n * 100) / lodItemCount).ToString() + "%] objects\n";
                    }

                    string l = "------------------------";

                    font.Draw(
                        string.Format("Stats\n{0}\n{1}{2}\nTotal: {3} [100%] objects", l, f, l, lodItemCount),
                        new Vector2Di(10, 140),
                        Color.SolidMagenta);
                }

                // show general stats

                font.Draw(string.Format(
                              "Camera position: {0}\nTotal LOD 0 triangles: {1}\nTriangles currently drawn: {2}\nDriver: {3}\nFPS: {4}",
                              camera.AbsolutePosition,
                              lodTriangleCount[0] * lodItemCount,
                              driver.PrimitiveCountDrawn,
                              driver.Name,
                              driver.FPS),
                          10, 10, Color.SolidYellow);

                // show active keys

                font.Draw(
                    "[S] Toggle stats\n[W] Toggle wireframe\n[L] Toggle labels (only for LODs from 0 to 4)\n[Esc] Exit application",
                    10, driver.ScreenSize.Height - 80, Color.SolidCyan);

                driver.EndScene();
            }

            // drop

            device.Drop();
        }
Exemplo n.º 6
0
        /// <summary>
        /// The irrlicht thread for rendering.
        /// </summary>
        private void StartIrr()
        {
            try
            {
                IrrlichtCreationParameters irrparam = new IrrlichtCreationParameters();
                if (irrlichtPanel.IsDisposed)
                {
                    throw new Exception("Form closed!");
                }
                if (irrlichtPanel.InvokeRequired)
                {
                    irrlichtPanel.Invoke(new MethodInvoker(delegate { irrparam.WindowID = irrlichtPanel.Handle; }));
                }
                irrparam.DriverType   = DriverType.Direct3D9;
                irrparam.BitsPerPixel = 16;

                device = IrrlichtDevice.CreateDevice(irrparam);

                if (device == null)
                {
                    throw new NullReferenceException("Could not create device for engine!");
                }

                driver = device.VideoDriver;
                smgr   = device.SceneManager;
                gui    = device.GUIEnvironment;

                var animText = "";
                if (Animations.AnimationNames.Count > 0)
                {
                    animText = "Animation: " + Animations.AnimationNames[selectedAnimIdx].Key;
                }
                var mAnimText     = gui.AddStaticText(animText, new Recti(0, this.ClientSize.Height - 80, 100, this.ClientSize.Height - 70));
                var mPositionText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 70, 100, this.ClientSize.Height - 60));
                var mRotationText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 60, 100, this.ClientSize.Height - 50));
                var fpsText       = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 50, 100, this.ClientSize.Height - 40));
                var infoText      = gui.AddStaticText("[Space] - Reset\n[LMouse] - Rotate\n[MMouse] - Move\n[Wheel] - Zoom", new Recti(0, this.ClientSize.Height - 40, 100, this.ClientSize.Height));
                mAnimText.OverrideColor   = mPositionText.OverrideColor = mRotationText.OverrideColor = fpsText.OverrideColor = infoText.OverrideColor = new Color(255, 255, 255);
                mAnimText.BackgroundColor = mPositionText.BackgroundColor = mRotationText.BackgroundColor = fpsText.BackgroundColor = infoText.BackgroundColor = new Color(0, 0, 0);

                SkinnedMesh skinnedMesh = smgr.CreateSkinnedMesh();
                foreach (var meshBuffer in cdata.staticMesh.MeshBuffers)
                {
                    skinnedMesh.AddMeshBuffer(meshBuffer);
                }
                smgr.MeshManipulator.RecalculateNormals(skinnedMesh);
                if (RigFile != null)
                {
                    rig.Apply(skinnedMesh);
                    if (AnimFile != null)
                    {
                        anims.Apply(skinnedMesh);
                    }
                }
                skinnedMesh.SetDirty(HardwareBufferType.VertexAndIndex);
                skinnedMesh.FinalizeMeshPopulation();
                AnimatedMeshSceneNode node = smgr.AddAnimatedMeshSceneNode(skinnedMesh);

                if (node == null)
                {
                    throw new Exception("Could not load file!");
                }

                node.Scale = new Vector3Df(3.0f);
                node.SetMaterialFlag(MaterialFlag.Lighting, false);
                SetMaterials(driver, node);

                CameraSceneNode camera = smgr.AddCameraSceneNode(null, new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0), new Vector3Df(0, node.BoundingBox.Radius, 0));
                camera.NearValue = 0.001f;
                camera.FOV       = 45 * CommonData.PI_OVER_180;
                scaleMul         = node.BoundingBox.Radius / 4;

                var viewPort = driver.ViewPort;
                var lineMat  = new Material();
                lineMat.Lighting = false;

                while (device.Run())
                {
                    driver.ViewPort = viewPort;
                    driver.BeginScene(ClearBufferFlag.All, new Color(100, 101, 140));

                    node.Position         = modelPosition;
                    node.Rotation         = modelAngle;
                    node.DebugDataVisible = DebugSceneType.Skeleton | DebugSceneType.BBox;
                    mPositionText.Text    = $"X: {modelPosition.X.ToString("F2")} Y: {modelPosition.Y.ToString("F2")} Z: {modelPosition.Z.ToString("F2")}";
                    mRotationText.Text    = $"Yaw: {modelAngle.Y.ToString("F2")} Roll: {modelAngle.Z.ToString("F2")}";
                    fpsText.Text          = $"FPS: {driver.FPS}";

                    smgr.DrawAll();
                    gui.DrawAll();

                    driver.ViewPort = new Recti(this.ClientSize.Width - 100, this.ClientSize.Height - 80, this.ClientSize.Width, this.ClientSize.Height);
                    //driver.ClearBuffers(ClearBufferFlag.None);

                    driver.SetMaterial(lineMat);
                    var matrix = new Matrix(new Vector3Df(0, 0, 0), modelAngle);
                    driver.SetTransform(TransformationState.World, matrix);
                    matrix = matrix.BuildProjectionMatrixOrthoLH(100, 80, camera.NearValue, camera.FarValue);
                    driver.SetTransform(TransformationState.Projection, matrix);
                    matrix = matrix.BuildCameraLookAtMatrixLH(new Vector3Df(50, 0, 0), new Vector3Df(0, 0, 0), new Vector3Df(0, 1f, 0));
                    driver.SetTransform(TransformationState.View, matrix);
                    driver.Draw3DLine(0, 0, 0, 30f, 0, 0, Color.OpaqueGreen);
                    driver.Draw3DLine(0, 0, 0, 0, 30f, 0, Color.OpaqueBlue);
                    driver.Draw3DLine(0, 0, 0, 0, 0, 30f, Color.OpaqueRed);

                    driver.EndScene();
                }

                device.Drop();
            }
            catch (ThreadAbortException) { }
            catch (NullReferenceException) { }
            catch (Exception ex)
            {
                if (!this.IsDisposed)
                {
                    MessageBox.Show(ex.Message);
                    //this.Invoke(new MethodInvoker(delegate { this.Close(); }));
                }
            }
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            DriverType driverType;

            if (!AskUserForDriver(out driverType))
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType, new Dimension2Di(640, 480));

            if (device == null)
            {
                return;
            }

            VideoDriver    driver = device.VideoDriver;
            SceneManager   smgr   = device.SceneManager;
            GUIEnvironment env    = device.GUIEnvironment;

            // load and display animated fairy mesh
            AnimatedMeshSceneNode fairy = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/faerie.md2"));

            if (fairy != null)
            {
                fairy.SetMaterialTexture(0, driver.GetTexture("../../media/faerie2.bmp")); // set diffuse texture
                fairy.SetMaterialFlag(MaterialFlag.Lighting, true);                        // enable dynamic lighting
                fairy.GetMaterial(0).Shininess = 20.0f;                                    // set size of specular highlights
                fairy.Position = new Vector3Df(-10, 0, -100);
                fairy.SetMD2Animation(AnimationTypeMD2.Stand);
            }

            // add white light
            smgr.AddLightSceneNode(null, new Vector3Df(-15, 5, -105), new Colorf(1, 1, 1));

            // set ambient light
            smgr.AmbientLight = new Colorf(0.25f, 0.25f, 0.25f);

            // add fps camera
            CameraSceneNode fpsCamera = smgr.AddCameraSceneNodeFPS();

            fpsCamera.Position = new Vector3Df(-50, 50, -150);

            // disable mouse cursor
            device.CursorControl.Visible = false;

            // create test cube
            SceneNode test = smgr.AddCubeSceneNode(60);

            // let the cube rotate and set some light settings
            SceneNodeAnimator anim = smgr.CreateRotationAnimator(new Vector3Df(0.3f, 0.3f, 0));

            test.Position = new Vector3Df(-100, 0, -100);
            test.SetMaterialFlag(MaterialFlag.Lighting, false);             // disable dynamic lighting
            test.AddAnimator(anim);
            anim.Drop();

            // create render target
            Texture         rt       = null;
            CameraSceneNode fixedCam = null;

            if (driver.QueryFeature(VideoDriverFeature.RenderToTarget))
            {
                rt = driver.AddRenderTargetTexture(new Dimension2Di(256), "RTT1");
                test.SetMaterialTexture(0, rt);                 // set material of cube to render target

                // add fixed camera
                fixedCam = smgr.AddCameraSceneNode(null, new Vector3Df(10, 10, -80), new Vector3Df(-10, 10, -100));
            }
            else
            {
                // create problem text
                GUIFont font = env.GetFont("../../media/fonthaettenschweiler.bmp");
                if (font != null)
                {
                    env.Skin.SetFont(font);
                }

                GUIStaticText text = env.AddStaticText(
                    "Your hardware or this renderer is not able to use the " +
                    "render to texture feature. RTT Disabled.",
                    new Recti(150, 20, 470, 60));

                text.OverrideColor = new Color(255, 255, 255, 100);
            }

            int lastFPS = -1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    driver.BeginScene(true, true, new Color(0));

                    if (rt != null)
                    {
                        // draw scene into render target

                        // set render target texture
                        driver.SetRenderTarget(rt, true, true, new Color(0, 0, 255));

                        // make cube invisible and set fixed camera as active camera
                        test.Visible      = false;
                        smgr.ActiveCamera = fixedCam;

                        // draw whole scene into render buffer
                        smgr.DrawAll();

                        // set back old render target
                        // The buffer might have been distorted, so clear it
                        driver.SetRenderTarget(null, true, true, new Color(0));

                        // make the cube visible and set the user controlled camera as active one
                        test.Visible      = true;
                        smgr.ActiveCamera = fpsCamera;
                    }

                    // draw scene normally
                    smgr.DrawAll();
                    env.DrawAll();

                    driver.EndScene();

                    // display frames per second in window title
                    int fps = driver.FPS;
                    if (lastFPS != fps)
                    {
                        device.SetWindowCaption(String.Format(
                                                    "Render to Texture and Specular Highlights example - Irrlicht Engine [{0}] fps: {1}",
                                                    driver.Name, fps));

                        lastFPS = fps;
                    }
                }
            }

            device.Drop();
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            checkBulletSharpDllPresence();

            // setup Irrlicht

            device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(1024, 768));
            if (device == null)
            {
                return;
            }

            device.SetWindowCaption("BulletSharp Test - Irrlicht Engine");
            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);

            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;
            GUIFont      font   = device.GUIEnvironment.GetFont("../../media/fontlucida.png");

            CameraSceneNode camera = scene.AddCameraSceneNodeFPS();

            camera.Position         = new Vector3Df(100, 800, -1000);
            camera.Target           = new Vector3Df(0, 100, 0);
            camera.FarValue         = 30000;
            camera.AutomaticCulling = CullingType.FrustumBox;

            device.CursorControl.Visible = false;

            // setup physics

            physics = new Physics();
            physics.Setup(new Vector3Df(0, -worldGravity, 0));

            // setup particles

            particles = new Particles(device);

            // load quake level

            device.FileSystem.AddFileArchive("../../media/map-20kdm2.pk3");

            Mesh      mesh       = scene.GetMesh("20kdm2.bsp").GetMesh(0);
            SceneNode quakeLevel = scene.AddOctreeSceneNode(mesh, null, -1, 1024);

            quakeLevel.Position = new Vector3Df(-1300, -144, -1249);

            physics.AddShape(Physics.Shape.Mesh, quakeLevel);

            // generate dynamic objects

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 30; j++)
                {
                    for (int k = 0; k < 3; k++)
                    {
                        MeshSceneNode n = scene.AddCubeSceneNode(cubeSize);
                        n.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp"));
                        n.SetMaterialFlag(MaterialFlag.Lighting, false);
                        n.Position = new Vector3Df(70 + i * cubeSize, 520 + j * cubeSize, -650 + k * cubeSize);

                        physics.AddShape(Physics.Shape.Box, n, cubeMass);
                    }
                }
            }

            // main loop

            uint curTime       = 0;
            uint lastTime      = 0;
            int  simFps        = 0;
            int  simFrames     = 0;
            uint simFramesTime = 0;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    // simulate physics

                    lastTime = curTime;
                    curTime  = device.Timer.Time;
                    if (!simPaused)
                    {
                        float deltaTime = (curTime - lastTime) / 1000.0f;
                        bool  b         = physics.StepSimulation(deltaTime);
                        if (b)
                        {
                            simFrames++;
                        }
                    }

                    if (curTime - simFramesTime > 1000)
                    {
                        simFramesTime = curTime;
                        simFps        = simFrames;
                        simFrames     = 0;
                    }

                    // winnow particles

                    particles.Winnow(curTime, simPaused);

                    // render scene

                    driver.BeginScene(true, true, new Color(40, 80, 160));
                    scene.DrawAll();

                    Material material = new Material();
                    material.Lighting = false;
                    device.VideoDriver.SetMaterial(material);

                    // display stats

                    driver.Draw2DRectangle(new Recti(10, 10, 140, 180), new Color(0x7f000000));

                    Vector2Di v = new Vector2Di(20, 20);
                    font.Draw("Rendering", v, Color.OpaqueYellow);
                    v.Y += 16;
                    font.Draw(scene.Attributes.GetValue("calls") + " nodes", v, Color.OpaqueWhite);
                    v.Y += 16;
                    font.Draw(driver.FPS + " fps", v, Color.OpaqueWhite);
                    v.Y += 16;
                    font.Draw("[T]rails " + (useTrails ? "ON" : "OFF"), v, Color.OpaqueGreen);
                    v.Y += 32;
                    font.Draw("Physics" + (simPaused ? " (paused)" : ""), v, Color.OpaqueYellow);
                    v.Y += 16;
                    font.Draw(physics.NumCollisionObjects + " shapes", v, Color.OpaqueWhite);
                    v.Y += 16;
                    font.Draw(simFps + " fps", v, Color.OpaqueWhite);
                    v.Y += 16;
                    font.Draw("[Space] to pause", v, Color.OpaqueGreen);

                    driver.EndScene();
                }

                device.Yield();
            }

            // drop

            physics.Drop();
            device.Drop();
        }
Exemplo n.º 9
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(800, 600));

            if (device == null)
            {
                return;
            }

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            device.SetWindowCaption("Mesh handling - Irrlicht Engine - press [1], [2], [3] to regenerate mesh");
            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;

            // Generate starting height map and mesh

            HeightMap map = new HeightMap(255, 255);

            map.Generate(HeightMap.HeightFunc.EggBox);

            HeightMesh mesh = new HeightMesh();

            mesh.Init(driver, map, 50.0f, HeightMesh.ColorFunc.GreyscaleBasedOnTheHeight);

            // Add the mesh to the scene graph

            MeshSceneNode meshnode = scene.AddMeshSceneNode(mesh.Mesh);

            meshnode.SetMaterialFlag(MaterialFlag.BackFaceCulling, false);

            // Add light (just for nice effects)

            LightSceneNode    lightnode = scene.AddLightSceneNode(null, new Vector3Df(0, 100, 0), new Colorf(1, 1, 1), 500.0f);
            SceneNodeAnimator anim      = scene.CreateFlyCircleAnimator(new Vector3Df(0, 150, 0), 250.0f);

            lightnode.AddAnimator(anim);
            anim.Drop();

            // Add camera

            CameraSceneNode camera = scene.AddCameraSceneNodeFPS();

            camera.Position = new Vector3Df(-20.0f, 100.0f, -20.0f);
            camera.Target   = new Vector3Df(200.0f, -100.0f, 200.0f);
            camera.FarValue = 20000.0f;

            // Main loop

            while (device.Run())
            {
                if (!device.WindowActive)
                {
                    device.Sleep(100);
                    continue;
                }

                if (IsKeyDown(KeyCode.KeyW))
                {
                    meshnode.SetMaterialFlag(MaterialFlag.Wireframe, !meshnode.GetMaterial(0).Wireframe);
                }
                else if (IsKeyDown(KeyCode.Key1))
                {
                    map.Generate(HeightMap.HeightFunc.EggBox);
                    mesh.Init(driver, map, 50.0f, HeightMesh.ColorFunc.GreyscaleBasedOnTheHeight);
                }
                else if (IsKeyDown(KeyCode.Key2))
                {
                    map.Generate(HeightMap.HeightFunc.MoreSine);
                    mesh.Init(driver, map, 50.0f, HeightMesh.ColorFunc.CoordinateInterpolation);
                }
                else if (IsKeyDown(KeyCode.Key3))
                {
                    map.Generate(HeightMap.HeightFunc.JustExp);
                    mesh.Init(driver, map, 50.0f, HeightMesh.ColorFunc.CoordinateInterpolation);
                }

                driver.BeginScene();
                scene.DrawAll();
                driver.EndScene();
            }

            // Clean up

            mesh.Drop();
            device.Drop();
        }
Exemplo n.º 10
0
        static void Main(string[] args)
        {
            DriverType driverType;

            if (!AskUserForDriver(out driverType))
            {
                return;
            }

            device = IrrlichtDevice.CreateDevice(driverType, new Dimension2Di(640, 480));
            if (device == null)
            {
                return;
            }

            device.SetWindowCaption("Irrlicht Engine - User Interface Demo");
            device.SetWindowResizable(true);

            VideoDriver    driver = device.VideoDriver;
            GUIEnvironment env    = device.GUIEnvironment;

            GUISkin skin = env.Skin;
            GUIFont font = env.GetFont("../../media/fonthaettenschweiler.bmp");

            if (font != null)
            {
                skin.SetFont(font);
            }

            skin.SetFont(env.BuiltInFont, GUIDefaultFont.Tooltip);

            env.AddButton(new Recti(10, 240, 110, 240 + 32), null, GUI_ID_ButtonQuit, "Quit", "Exits Program");
            env.AddButton(new Recti(10, 280, 110, 280 + 32), null, GUI_ID_ButtonWindowNew, "New Window", "Launches a new Window");
            env.AddButton(new Recti(10, 320, 110, 320 + 32), null, GUI_ID_ButtonFileOpen, "File Open", "Opens a file");

            env.AddStaticText("Transparent Control:", new Recti(150, 20, 350, 40), true);
            GUIScrollBar scrollbar = env.AddScrollBar(true, new Recti(150, 45, 350, 60), null, GUI_ID_ScrollbarTransparency);

            scrollbar.MaxValue = 255;
            scrollbar.Position = (int)env.Skin.GetColor(GUIDefaultColor.WindowBackground).Alpha;

            GUIStaticText trq = env.AddStaticText("Logging ListBox:", new Recti(50, 110, 250, 130), true);

            listbox = env.AddListBox(new Recti(50, 140, 250, 210));
            env.AddEditBox("Editable Text", new Recti(350, 80, 550, 100));

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);

            env.AddImage(driver.GetTexture("../../media/irrlichtlogoalpha2.tga"), new Vector2Di(10, 10));

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    driver.BeginScene(true, true, new Color(200, 200, 200));
                    env.DrawAll();
                    driver.EndScene();
                }
            }

            device.Drop();
        }
Exemplo n.º 11
0
        static void Main()
        {
            // setup Irrlicht

            device = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(1024, 768), 32, false, true);
            if (device == null)
            {
                return;
            }

            device.SetWindowCaption("Stencil Shadows - Irrlicht Engine");
            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);

            VideoDriver  driver = device.VideoDriver;
            SceneManager scene  = device.SceneManager;

            GUIFont statsFont = device.GUIEnvironment.GetFont("../../media/fontlucida.png");

            cameraNode          = scene.AddCameraSceneNodeFPS();
            cameraNode.FarValue = 20000;

            device.CursorControl.Visible = false;

            // setup shadows

            shadows = new Shadows(new Color(0xa0000000), 4000);

            // load quake level

            device.FileSystem.AddFileArchive("../../media/map-20kdm2.pk3");

            Mesh          m = scene.GetMesh("20kdm2.bsp").GetMesh(0);
            MeshSceneNode n = scene.AddOctreeSceneNode(m, null, -1, 1024);

            n.Position     = new Vector3Df(-1300, -144, -1249);
            quakeLevelNode = n;

            // add faerie

            faerieNode = scene.AddAnimatedMeshSceneNode(
                scene.GetMesh("../../media/faerie.md2"),
                null, -1,
                new Vector3Df(100, -40, 80),
                new Vector3Df(0, 30, 0),
                new Vector3Df(1.6f));

            faerieNode.SetMD2Animation(AnimationTypeMD2.Wave);
            faerieNode.AnimationSpeed = 20;
            faerieNode.GetMaterial(0).SetTexture(0, driver.GetTexture("../../media/faerie2.bmp"));
            faerieNode.GetMaterial(0).Lighting         = false;
            faerieNode.GetMaterial(0).NormalizeNormals = true;

            shadows.AddObject(faerieNode);

            // add light

            lightMovementHelperNode = scene.AddEmptySceneNode();

            n = scene.AddSphereSceneNode(2, 6, lightMovementHelperNode, -1, new Vector3Df(15, -10, 15));
            n.SetMaterialFlag(MaterialFlag.Lighting, false);

            lightNode = n;
            shadows.AddLight(lightNode);

            // add flashlight

            m = scene.GetMesh("../../media/flashlight.obj");
            n = scene.AddMeshSceneNode(m, lightNode, -1, new Vector3Df(0), new Vector3Df(0), new Vector3Df(5));
            n.SetMaterialFlag(MaterialFlag.Lighting, false);

            flashlightNode         = n;
            flashlightNode.Visible = false;

            // render

            uint shdFrameTime = 0;
            uint shdFrames    = 0;
            uint shdFps       = 0;

            while (device.Run())
            {
                if (useShadowsRebuilding &&
                    shadows.BuildShadowVolume())
                {
                    shdFrames++;
                }

                uint t = device.Timer.Time;
                if (t - shdFrameTime > 1000)
                {
                    shdFrameTime = t;
                    shdFps       = shdFrames;
                    shdFrames    = 0;
                }

                if (useLightBinding)
                {
                    lightMovementHelperNode.Position = cameraNode.AbsolutePosition.GetInterpolated(lightMovementHelperNode.Position, 0.1);
                    lightMovementHelperNode.Rotation = cameraNode.AbsoluteTransformation.Rotation;
                }

                driver.BeginScene(ClearBufferFlag.All, new Color(0xff112244));

                scene.DrawAll();

                if (useShadowsRendering)
                {
                    shadows.DrawShadowVolume(driver);
                }

                // display stats

                driver.Draw2DRectangle(new Recti(10, 10, 150, 220), new Color(0x7f000000));

                Vector2Di v = new Vector2Di(20, 20);
                statsFont.Draw("Rendering", v, Color.SolidYellow);
                v.Y += 16;
                statsFont.Draw(driver.FPS + " fps", v, Color.SolidWhite);
                v.Y += 16;
                statsFont.Draw("[S]hadows " + (useShadowsRendering ? "ON" : "OFF"), v, Color.SolidGreen);
                v.Y += 16;
                statsFont.Draw("[L]ight binding " + (useLightBinding ? "ON" : "OFF"), v, Color.SolidGreen);
                v.Y += 16;
                statsFont.Draw("[F]lashlight " + (useFlashlight ? "ON" : "OFF"), v, Color.SolidGreen);
                v.Y += 32;
                statsFont.Draw("Shadows", v, Color.SolidYellow);
                v.Y += 16;
                statsFont.Draw(shdFps + " fps", v, Color.SolidWhite);
                v.Y += 16;
                statsFont.Draw(shadows.VerticesBuilt + " vertices", v, Color.SolidWhite);
                v.Y += 16;
                statsFont.Draw("[R]ebuilding " + (useShadowsRebuilding ? "ON" : "OFF"), v, Color.SolidGreen);
                v.Y += 16;
                statsFont.Draw("[Q]uake level " + (useShadowsQuakeLevel ? "ON" : "OFF"), v, Color.SolidGreen);

                driver.EndScene();
            }

            shadows.Drop();
            device.Drop();
        }
Exemplo n.º 12
0
        /// <summary>
        /// The irrlicht thread for rendering.
        /// </summary>
        private void StartIrr()
        {
            try
            {
                //Setup
                IrrlichtCreationParameters irrparam = new IrrlichtCreationParameters();
                if (irrlichtPanel.IsDisposed)
                {
                    throw new Exception("Form closed!");
                }
                if (irrlichtPanel.InvokeRequired)
                {
                    irrlichtPanel.Invoke(new MethodInvoker(delegate { irrparam.WindowID = irrlichtPanel.Handle; }));
                }
                irrparam.DriverType   = DriverType.Direct3D9;
                irrparam.DriverType   = DriverType.OpenGL;
                irrparam.BitsPerPixel = 16;

                device = IrrlichtDevice.CreateDevice(irrparam);

                if (device == null)
                {
                    throw new NullReferenceException("Could not create device for engine!");
                }

                driver = device.VideoDriver;
                smgr   = device.SceneManager;
                gui    = device.GUIEnvironment;

                var cam = smgr.AddCameraSceneNode(null);
                cam.TargetAndRotationBinding = true;
                cam.Position = new Vector3Df(-100.0f, 500.0f, 100.0f);
                cam.Target   = new Vector3Df(0.0f);
                cam.FarValue = 42000.0f;

                device.CursorControl.Visible = false;

                //Terrain
                heightmap = driver.CreateImage("Terrain\\basemap.bmp");

                terrain = smgr.AddTerrainSceneNode(
                    "Terrain\\basemap.bmp",
                    null,
                    -1,
                    new Vector3Df(0.0f)
                    );
                terrain.Scale = new Vector3Df(32, 5, 32);
                terrain.SetMaterialFlag(MaterialFlag.Lighting, false);

                terrain.SetMaterialTexture(0, driver.GetTexture("Terrain\\rockwall.jpg"));
                selector = smgr.CreateTerrainTriangleSelector(terrain, 0);

                var arrow = smgr.AddAnimatedMeshSceneNode(smgr.AddArrowMesh("arrow", new IrrlichtLime.Video.Color(255, 255, 0, 0), new IrrlichtLime.Video.Color(255, 0, 255, 0)), null);
                arrow.SetMaterialFlag(MaterialFlag.Lighting, false);
                arrow.Scale    = new Vector3Df(100.0f);
                arrow.Rotation = new Vector3Df(0.0f, 0.0f, 180.0f);

                //Skybox and skydome
                driver.SetTextureCreationFlag(TextureCreationFlag.CreateMipMaps, false);

                /*var box = smgr.AddSkyBoxSceneNode(
                 *  ("Terrain\\irrlicht2_up.jpg"),
                 *  ("Terrain\\irrlicht2_dn.jpg"),
                 *  ("Terrain\\irrlicht2_lf.jpg"),
                 *  ("Terrain\\irrlicht2_rt.jpg"),
                 *  ("Terrain\\irrlicht2_ft.jpg"),
                 *  ("Terrain\\irrlicht2_bk.jpg"));
                 * box.Visible = true;*/

                var dome = smgr.AddSkyDomeSceneNode(driver.GetTexture("Terrain\\skydome.jpg"), 16, 8, 0.95f, 2.0f);
                dome.Visible = true;
                driver.SetTextureCreationFlag(TextureCreationFlag.CreateMipMaps, true);

                var helpq = gui.AddStaticText("Press Q to disable focus!",
                                              new Recti(0, this.ClientSize.Height - 40, 100, this.ClientSize.Height), true, true, null, 1, true);
                var helpesc = gui.AddStaticText("Press ESC to quit",
                                                new Recti(0, this.ClientSize.Height - 20, 100, this.ClientSize.Height), true, true, null, 1, true);
                middletext = gui.AddStaticText("Click to enable mouselook and move with WASD",
                                               new Recti(ClientSize.Width / 2 - 100, this.ClientSize.Height / 2, ClientSize.Width / 2 + 100, this.ClientSize.Height / 2 + 30), true, true, null, 1, true);
                middletext.OverrideColor   = IrrlichtLime.Video.Color.SolidWhite;
                middletext.BackgroundColor = IrrlichtLime.Video.Color.SolidBlack;
                var irrTimer = device.Timer;
                var then     = 0;
                var then30   = 0;

                device.CursorControl.Visible = false;

                Vector2Df lastcurr = new Vector2Df(0f);
                uint      dt       = 0;
                while (device.Run())
                {
                    driver.BeginScene(ClearBufferFlag.All);

                    if (catchmouse)
                    {
                        // move the arrow to the nearest vertex ...
                        IrrlichtLime.Core.Vector2Di center = new IrrlichtLime.Core.Vector2Di(irrlichtPanel.Width / 2, irrlichtPanel.Height / 2);
                        Line3Df     ray = smgr.SceneCollisionManager.GetRayFromScreenCoordinates(center, cam);
                        Vector3Df   pos;
                        Triangle3Df Tri;
                        var         curr = device.CursorControl.RelativePosition;

                        // Threshold and periodical check so we don't spin around due to float conversions
                        if (device.Timer.Time > dt && curr.GetDistanceFrom(lastcurr) > 0.01f)
                        {
                            Line3Df cursor_ray = smgr.SceneCollisionManager
                                                 .GetRayFromScreenCoordinates(new Vector2Di((int)(curr.X * irrlichtPanel.Width), (int)(curr.Y * irrlichtPanel.Height)), cam);

                            smgr.ActiveCamera.Target = cursor_ray.Middle;
                            dt       = device.Timer.Time + 30;
                            lastcurr = curr;
                            device.CursorControl.Position = center;
                        }

                        if (smgr.SceneCollisionManager.GetCollisionPoint(ray, selector, out pos, out Tri, out outnode))
                        {
                            var scale = 32;  // terrain is scaled 32X
                            var size  = 512; // heightmap is 512x512 pixels
                            var x     = (pos.X / scale);
                            var z     = (pos.Z / scale);
                            var index = x * size + z;

                            x *= scale;
                            z *= scale;

                            arrow.Position = new Vector3Df(x, terrain.GetHeight(x, z) + 100, z);
                        }
                    }

                    smgr.DrawAll();
                    gui.DrawAll();

                    driver.EndScene();

                    //device.CursorControl.Position = new Vector2Di(irrlichtPanel.
                }

                device.Drop();
            }
            catch (ThreadAbortException) { }
            catch (NullReferenceException) { }
            catch (Exception ex)
            {
                if (!this.IsDisposed)
                {
                    MessageBox.Show(ex.Message);
                    //this.Invoke(new MethodInvoker(delegate { this.Close(); }));
                }
            }
        }
Exemplo n.º 13
0
        private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker   = sender as BackgroundWorker;
            DeviceSettings   settings = e.Argument as DeviceSettings;

            // create irrlicht device using provided settings

            IrrlichtDevice dev = IrrlichtDevice.CreateDevice(settings);

            if (dev == null)
            {
                throw new Exception("Failed to create Irrlicht device.");
            }

            dev.Logger.LogLevel = LogLevel.Warning;
            VideoDriver  drv  = dev.VideoDriver;
            SceneManager smgr = dev.SceneManager;

            smgr.FileSystem.AddFileArchive("E:/WitcherMods/modTest/Test/files/Mod/Bundle");
            smgr.FileSystem.AddFileArchive("E:/WitcherMods/modTest/Test/files/Raw/Mod/TextureCache");

            smgr.Attributes.AddValue("TW_TW3_LOAD_SKEL", true);
            smgr.Attributes.AddValue("TW_TW3_LOAD_BEST_LOD_ONLY", true);

            // setup a simple 3d scene

            //CameraSceneNode cam = smgr.AddCameraSceneNode();
            //cam.Target = new Vector3Df(0);

            // added by vl
            AnimatedMesh mesh = smgr.GetMesh("E:/WitcherMods/modTest/Test/files/Mod/Bundle/characters/models/animals/cat/model/t_01__cat.w2mesh");

            if (mesh == null)
            {
                throw new Exception("Failed to load mesh.");
            }

            smgr.MeshManipulator.RecalculateNormals(mesh);

            List <String> animList = null;

            float scaleMul               = 1.0f;
            AnimatedMeshSceneNode node   = smgr.AddAnimatedMeshSceneNode(mesh);
            MeshLoaderHelper      helper = smgr.GetMeshLoader(smgr.MeshLoaderCount - 1).getMeshLoaderHelper();

            if (node != null)
            {
                scaleMul   = node.BoundingBox.Radius / 4;
                node.Scale = new Vector3Df(3.0f);
                node.SetMaterialFlag(MaterialFlag.Lighting, false);

                SkinnedMesh sm = helper.loadRig("E:/WitcherMods/modTest/Test/files/Mod/Bundle/characters/base_entities/cat_base/cat_base.w2rig", mesh);
                if (sm == null)
                {
                    throw new Exception("Failed to load rig.");
                }

                animList = helper.loadAnimation("E:/WitcherMods/modTest/Test/files/Mod/Bundle/animations/animals/cat/cat_animation.w2anims", sm);
                if (animList.Count > 0)
                {
                    AnimatedMesh am = helper.applyAnimation(animList[0], sm);
                    node.Mesh = am;
                }
                //scaleSkeleton(sm, 3.0f);
                //sm.SkinMesh();

                mesh.Drop();
                sm.Drop();
                setMaterialsSettings(node);

                /*
                 * animList = helper.loadAnimation("E:/WitcherMods/modTest/Test/files/Mod/Bundle/animations/animals/cat/cat_animation.w2anims", node);
                 * if (animList.Count > 0)
                 * {
                 *      helper.applyAnimation(animList[0]);
                 * }
                 */
            }

            var camera = smgr.AddCameraSceneNode(null,
                                                 new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0),
                                                 new Vector3Df(0, node.BoundingBox.Radius, 0)
                                                 );

            camera.NearValue = 0.001f;
            camera.FOV       = 45.0f * 3.14f / 180.0f;

            node.DebugDataVisible ^= DebugSceneType.BBox | DebugSceneType.Skeleton;

            node.Position = new Vector3Df(0.0f);

            /*
             * SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f);
             * cam.AddAnimator(anim);
             * anim.Drop();
             *
             * SceneNode cube = smgr.AddCubeSceneNode(20);
             * cube.SetMaterialTexture(0, drv.GetTexture("../../media/wall.bmp"));
             * cube.SetMaterialTexture(1, drv.GetTexture("../../media/water.jpg"));
             * cube.SetMaterialFlag(MaterialFlag.Lighting, false);
             * cube.SetMaterialType(MaterialType.Reflection2Layer);
             */

            if (settings.BackColor == null)
            {
                smgr.AddSkyBoxSceneNode(
                    "../../media/irrlicht2_up.jpg",
                    "../../media/irrlicht2_dn.jpg",
                    "../../media/irrlicht2_lf.jpg",
                    "../../media/irrlicht2_rt.jpg",
                    "../../media/irrlicht2_ft.jpg",
                    "../../media/irrlicht2_bk.jpg");
            }

            dev.GUIEnvironment.AddImage(
                drv.GetTexture("../../media/lime_logo_alpha.png"),
                new Vector2Di(30, 0));

            // draw all

            int lastFPS = -1;

            while (dev.Run())
            {
                if (settings.BackColor == null)
                {
                    // indeed, we do not need to spend time on cleaning color buffer if we use skybox
                    drv.BeginScene(ClearBufferFlag.Depth);
                }
                else
                {
                    drv.BeginScene(ClearBufferFlag.Depth | ClearBufferFlag.Color, settings.BackColor);
                }

                smgr.DrawAll();
                dev.GUIEnvironment.DrawAll();
                drv.EndScene();

                int fps = drv.FPS;
                if (lastFPS != fps)
                {
                    // report progress using common BackgroundWorker' method
                    // note: we cannot do just labelRenderingStatus.Text = "...",
                    // because we are running another thread
                    worker.ReportProgress(fps, drv.Name);
                    lastFPS = fps;
                }

                // if we requested to stop, we close the device
                if (worker.CancellationPending)
                {
                    dev.Close();
                }
            }

            // drop device
            dev.Drop();
        }
Exemplo n.º 14
0
        private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker   = sender as BackgroundWorker;
            DeviceSettings   settings = e.Argument as DeviceSettings;

            // create irrlicht device using provided settings

            IrrlichtDevice dev = IrrlichtDevice.CreateDevice(settings);

            if (dev == null)
            {
                throw new Exception("Failed to create Irrlicht device.");
            }

            VideoDriver  drv  = dev.VideoDriver;
            SceneManager smgr = dev.SceneManager;

            // setup a simple 3d scene

            CameraSceneNode cam = smgr.AddCameraSceneNode();

            cam.Target = new Vector3Df(0);

            SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f);

            cam.AddAnimator(anim);
            anim.Drop();

            SceneNode cube = smgr.AddCubeSceneNode(20);

            cube.SetMaterialTexture(0, drv.GetTexture("../../media/wall.bmp"));
            cube.SetMaterialTexture(1, drv.GetTexture("../../media/water.jpg"));
            cube.SetMaterialFlag(MaterialFlag.Lighting, false);
            cube.SetMaterialType(MaterialType.Reflection2Layer);

            if (settings.BackColor == null)
            {
                smgr.AddSkyBoxSceneNode(
                    "../../media/irrlicht2_up.jpg",
                    "../../media/irrlicht2_dn.jpg",
                    "../../media/irrlicht2_lf.jpg",
                    "../../media/irrlicht2_rt.jpg",
                    "../../media/irrlicht2_ft.jpg",
                    "../../media/irrlicht2_bk.jpg");
            }

            dev.GUIEnvironment.AddImage(
                drv.GetTexture("../../media/lime_logo_alpha.png"),
                new Vector2Di(30, 0));

            // draw all

            int lastFPS = -1;

            while (dev.Run())
            {
                if (settings.BackColor == null)
                {
                    // indeed, we do not need to spend time on cleaning color buffer if we use skybox
                    drv.BeginScene(ClearBufferFlag.Depth);
                }
                else
                {
                    drv.BeginScene(ClearBufferFlag.Depth | ClearBufferFlag.Color, settings.BackColor);
                }

                smgr.DrawAll();
                dev.GUIEnvironment.DrawAll();
                drv.EndScene();

                int fps = drv.FPS;
                if (lastFPS != fps)
                {
                    // report progress using common BackgroundWorker' method
                    // note: we cannot do just labelRenderingStatus.Text = "...",
                    // because we are running another thread
                    worker.ReportProgress(fps, drv.Name);
                    lastFPS = fps;
                }

                // if we requested to stop, we close the device
                if (worker.CancellationPending)
                {
                    dev.Close();
                }
            }

            // drop device
            dev.Drop();
        }
Exemplo n.º 15
0
        static void Main()
        {
            // Initialize device.

            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(640, 480));

            if (device == null)
            {
                return;
            }

            // Add event handling.

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);

            // Save important pointers.

            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;
            Logger       logger = device.Logger;

            // Initialize joysticks and print info about them.

            List <JoystickInfo> joystickList = device.ActivateJoysticks();

            if (joystickList != null)
            {
                logger.Log("Joystick support is enabled and " + joystickList.Count.ToString() + " joystick(s) are present.");

                foreach (JoystickInfo j in joystickList)
                {
                    logger.Log("Joystick " + j.Joystick.ToString() + ":");
                    logger.Log("\tName: \"" + j.Name + "\"");
                    logger.Log("\tAxisCount: " + j.AxisCount.ToString());
                    logger.Log("\tButtonCount: " + j.ButtonCount.ToString());
                    logger.Log("\tPovHat: " + j.PovHat.ToString());
                }
            }
            else
            {
                logger.Log("Joystick support is not enabled.");
            }

            device.SetWindowCaption("Mouse and joystick - Irrlicht Engine - " + joystickList.Count.ToString() + " joystick(s)");

            // Create an arrow mesh and move it around either with the joystick axis/hat,
            // or make it follow the mouse pointer (when no joystick movement).

            SceneNode node = smgr.AddMeshSceneNode(
                smgr.AddArrowMesh(
                    "Arrow",
                    new Color(255, 0, 0),
                    new Color(0, 255, 0),
                    16, 16,
                    2.0f, 1.3f,
                    0.1f, 0.6f
                    )
                );

            node.SetMaterialFlag(MaterialFlag.Lighting, false);

            CameraSceneNode camera = smgr.AddCameraSceneNode();

            camera.Position = new Vector3Df(0, 0, -10);

            // As in example #4, we'll use framerate independent movement.
            uint        then          = device.Timer.Time;
            const float MovementSpeed = 5.0f;

            // Run main cycle.

            while (device.Run())
            {
                // Work out a frame delta time.
                uint  now            = device.Timer.Time;
                float frameDeltaTime = (float)(now - then) / 1000.0f;                 // in seconds
                then = now;

                bool      movedWithJoystick = false;
                Vector3Df nodePosition      = node.Position;

                if (joystickList.Count > 0)
                {
                    float moveHorizontal = 0.0f;                   // range is -1.0 for full left to +1.0 for full right
                    float moveVertical   = 0.0f;                   // range is -1.0 for full down to +1.0 for full up

                    // We receive the full analog range of the axes, and so have to implement our own dead zone.
                    // This is an empirical value, since some joysticks have more jitter or creep around the center
                    // point than others. We'll use 5% of the range as the dead zone, but generally you would want
                    // to give the user the option to change this.
                    float DeadZone = 0.05f;

                    moveHorizontal = joystickState.Axis[0] / 32767.0f;                     // "0" for X axis
                    if (Math.Abs(moveHorizontal) < DeadZone)
                    {
                        moveHorizontal = 0.0f;
                    }

                    moveVertical = joystickState.Axis[1] / -32767.0f;                     // "1" for Y axis
                    if (Math.Abs(moveVertical) < DeadZone)
                    {
                        moveVertical = 0.0f;
                    }

                    // POV will contain 65535 if POV hat info no0t supported, so we can check its range.
                    ushort povDegrees = (ushort)(joystickState.POV / 100);
                    if (povDegrees < 360)
                    {
                        if (povDegrees > 0 && povDegrees < 180)
                        {
                            moveHorizontal = +1.0f;
                        }
                        else if (povDegrees > 180)
                        {
                            moveHorizontal = -1.0f;
                        }

                        if (povDegrees > 90 && povDegrees < 270)
                        {
                            moveVertical = -1.0f;
                        }
                        else if (povDegrees > 270 || povDegrees < 90)
                        {
                            moveVertical = +1.0f;
                        }
                    }

                    // If we have any movement, apply it.
                    if (Math.Abs(moveHorizontal) > 0.0001f || Math.Abs(moveVertical) > 0.0001f)
                    {
                        float m = frameDeltaTime * MovementSpeed;
                        nodePosition      = new Vector3Df(moveHorizontal * m, moveVertical * m, nodePosition.Z);
                        movedWithJoystick = true;
                    }
                }

                // If the arrow node isn't being moved with the joystick, then have it follow the mouse cursor.
                if (!movedWithJoystick)
                {
                    // Create a ray through the mouse cursor.
                    Line3Df ray = smgr.SceneCollisionManager.GetRayFromScreenCoordinates(mouseState.Position, camera);

                    // And intersect the ray with a plane around the node facing towards the camera.
                    Plane3Df  plane         = new Plane3Df(nodePosition, new Vector3Df(0, 0, -1));
                    Vector3Df mousePosition = plane.GetIntersectionWithLine(ray.Start, ray.Vector);
                    if (mousePosition != null)
                    {
                        // We now have a mouse position in 3d space; move towards it.
                        Vector3Df toMousePosition   = mousePosition - nodePosition;
                        float     availableMovement = frameDeltaTime * MovementSpeed;

                        if (toMousePosition.Length <= availableMovement)
                        {
                            nodePosition = mousePosition;                             // jump to the final position
                        }
                        else
                        {
                            nodePosition += toMousePosition.Normalize() * availableMovement;                             // move towards it
                        }
                    }
                }

                node.Position = nodePosition;

                // Turn lighting on and off depending on whether the left mouse button is down.
                node.SetMaterialFlag(MaterialFlag.Lighting, mouseState.IsLeftButtonDown);

                // Draw all.
                driver.BeginScene(ClearBufferFlag.All, new Color(113, 113, 133));
                smgr.DrawAll();
                driver.EndScene();
            }

            // Drop the device.

            device.Drop();
        }
Exemplo n.º 16
0
        public void Initialize3D()
        {
            device = new IrrlichtDevice(DriverType.Direct3D9, /* TODO: for Linux/OSX it should be OpenGL */
                                        new Dimension2D(800, 600), 32, false, true, true, true, GetHandle());
            device.FileSystem.WorkingDirectory = "3d";
            device.Resizeable = true;

            // setup a simple 3d scene
            SceneManager sceneManager = device.SceneManager;

            VideoDriver driver = device.VideoDriver;

            camera          = sceneManager.AddCameraSceneNodeFPS(null, 100.0f, 50000.0f, false);
            camera.Position = new Vector3D(1900 * 2, 255 * 2, 3700 * 2);
            camera.Target   = new Vector3D(2397 * 2, 343 * 2, 2700 * 2);
            camera.FarValue = 12000.0f;

            camera.InputReceiverEnabled = false;

            /*
             * Here comes the terrain renderer scene node: We add it just like any
             * other scene node to the scene using ISceneManager::addTerrainSceneNode().
             * The only parameter we use is a file name to the heightmap we use. A heightmap
             * is simply a gray scale texture. The terrain renderer loads it and creates
             * the 3D terrain from it.
             * To make the terrain look more big, we change the scale factor of it to (40, 4.4, 40).
             * Because we don't have any dynamic lights in the scene, we switch off the lighting,
             * and we set the file terrain-texture.jpg as texture for the terrain and
             * detailmap3.jpg as second texture, called detail map. At last, we set
             * the scale values for the texture: The first texture will be repeated only one time over
             * the whole terrain, and the second one (detail map) 20 times.
             */

            terrain = sceneManager.AddTerrainSceneNode("terrain-heightmap.bmp",
                                                       null,                          // parent node
                                                       -1,                            // node id
                                                       new Vector3D(0f, 0f, 0f),      // position
                                                       new Vector3D(0f, 0f, 0f),      // rotation
                                                       new Vector3D(40f, 4.4f, 40f),  // scale
                                                       new Color(255, 255, 255, 255), // vertexColor,
                                                       5,                             // maxLOD
                                                       TerrainPatchSize.TPS17         // patchSize
                                                       );

            terrain.SetMaterialFlag(MaterialFlag.Lighting, false);
            terrain.SetMaterialTexture(0, driver.GetTexture("terrain-texture.jpg"));
            terrain.SetMaterialTexture(1, driver.GetTexture("detailmap3.jpg"));
            terrain.SetMaterialType(MaterialType.DetailMap);
            terrain.ScaleTexture(1.0f, 20.0f);
            //terrain->setDebugDataVisible ( true );

            /*
             * To be able to do collision with the terrain, we create a triangle selector.
             * If you want to know what triangle selectors do, just take a look into the
             * collision tutorial. The terrain triangle selector works together with the
             * terrain. To demonstrate this, we create a collision response animator
             * and attach it to the camera, so that the camera will not be able to fly
             * through the terrain.
             */

            // create triangle selector for the terrain
            TriangleSelector selector = sceneManager.CreateTerrainTriangleSelector(terrain, 0);

            terrain.TriangleSelector = selector;

            // create collision response animator and attach it to the camera
            Animator animator = sceneManager.CreateCollisionResponseAnimator(selector, camera, new Vector3D(60, 100, 60), new Vector3D(0, 0, 0), new Vector3D(0, 50, 0), 0);

            selector.Dispose();
            camera.AddAnimator(animator);
            animator.Dispose();;

            /*
             * To make the user be able to switch between normal and wireframe mode, we create
             * an instance of the event reciever from above and let Irrlicht know about it. In
             * addition, we add the skybox which we already used in lots of Irrlicht examples.
             */

            // create skybox
            driver.SetTextureFlag(TextureCreationFlag.CreateMipMaps, false);

            sceneManager.AddSkyBoxSceneNode(null, new Texture[] {
                driver.GetTexture("irrlicht2_up.jpg"),
                driver.GetTexture("irrlicht2_dn.jpg"),
                driver.GetTexture("irrlicht2_lf.jpg"),
                driver.GetTexture("irrlicht2_rt.jpg"),
                driver.GetTexture("irrlicht2_ft.jpg"),
                driver.GetTexture("irrlicht2_bk.jpg")
            }, -1);

            while (device.Run())
            {
                driver.BeginScene(true, true, new Color());
                sceneManager.DrawAll();
                driver.EndScene();
            }

            device.Dispose();

            return;
        }
Exemplo n.º 17
0
        static void Main()
        {
            device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(1024, 768));
            if (device == null)
            {
                return;
            }

            device.SetWindowCaption("Fractal Generator - Irrlicht Engine");
            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);

            VideoDriver driver = device.VideoDriver;
            GUIFont     font   = device.GUIEnvironment.GetFont("../../media/fontlucida.png");
            Color       fontBackgroundColor = new Color(0x7f000000);
            Color       fontNormalColor     = Color.SolidWhite;
            Color       fontActionColor     = Color.SolidYellow;

            fGen = new FractalGenerator(device);
            fGen.Generate(new Rectd(
                              -driver.ScreenSize.Width / 250.0,
                              -driver.ScreenSize.Height / 250.0,
                              driver.ScreenSize.Width / 250.0,
                              driver.ScreenSize.Height / 250.0));

            while (device.Run())
            {
                driver.BeginScene(ClearBufferFlag.None);

                Vector2Di o = null;
                if (mouseMoveStart != null)
                {
                    o = device.CursorControl.Position - mouseMoveStart;
                }

                float w = fGen.DrawAll(o);

                // draw stats

                driver.Draw2DRectangle(new Recti(10, 10, 160, 56 + (w < 1 ? 16 : 0)), fontBackgroundColor);

                Vector2Di v = new Vector2Di(20, 16);
                font.Draw("Max iterations: " + fGen.GetMaxIterations(), v, fontNormalColor);
                v.Y += 16;
                font.Draw("Zoom: " + (long)fGen.GetZoomFactor().X + "x", v, fontNormalColor);
                if (w < 1)
                {
                    v.Y += 16;
                    font.Draw("Computing: " + (int)(w * 100) + "%...", v, fontActionColor);
                }

                // draw help

                int h = driver.ScreenSize.Height;
                driver.Draw2DRectangle(new Recti(10, showHelp ? h - 130 : h - 40, showHelp ? 220 : 160, h - 10), fontBackgroundColor);

                v.Y = h - 34;
                font.Draw("[F1] " + (showHelp ? "Hide" : "Show") + " help", v, fontNormalColor);

                if (showHelp)
                {
                    v.Y = h - 124;
                    font.Draw("[Mouse Left Button] Navigate", v, fontNormalColor);
                    v.Y += 16;
                    font.Draw("[Mouse Wheel] Zoom in/out", v, fontNormalColor);
                    v.Y += 16;
                    font.Draw("[+][-][*][/] Max iterations", v, fontNormalColor);
                    v.Y += 16;
                    font.Draw("[PrintScreen] Save screenshot", v, fontNormalColor);
                    v.Y += 16;
                    font.Draw("[Esc] Exit application", v, fontNormalColor);
                }

                driver.EndScene();
                device.Yield();
            }

            fGen.Drop();
            device.Drop();
        }
Exemplo n.º 18
0
        public Application()
        {
            _01.HelloWorld.Kinect kinect = new _01.HelloWorld.Kinect();
            mfX = mouseX = 840; mfY = mouseY = 525; mouseL = false; mouseR = false;
            //device = IrrlichtDevice.CreateDevice(
            //    DriverType.Direct3D9, new Dimension2Di(800, 600), 16, false, true, false);
            //                                                           |
            device = IrrlichtDevice.CreateDevice(                    // \|/ Fullscreen
                DriverType.Direct3D9, new Dimension2Di(1680, 1050), 32, false, true, false);

            device.SetWindowCaption("BENder3D");

            VideoDriver    driver = device.VideoDriver;
            SceneManager   smgr   = device.SceneManager;
            GUIEnvironment gui    = device.GUIEnvironment;

            device.OnEvent   += new IrrlichtDevice.EventHandler(device_OnEvent);
            smgr.AmbientLight = new Colorf(128, 128, 128, 128);
            //smgr.AddLightSceneNode(null, new Vector3Df(0, 70, 0), new Colorf(122,0,122,0), (float)10);
            MeshSceneNode box = smgr.AddCubeSceneNode(100, null, 9001, new Vector3Df(0.0f, -ballRadius * 3 / 2, 0.0f));

            box.Scale = new Vector3Df(100.0f, 0.1f, 100.0f);
            //Mesh cyl = smgr.GeometryCreator.CreateCylinderMesh(ballRadius, 50, 256);
            //Mesh sphere = smgr.GeometryCreator.CreateSphereMesh(ballRadius, 16,16);
            //MeshSceneNode t = smgr.AddSphereSceneNode(ballRadius, 32);
            //MeshSceneNode t = smgr.AddOctreeSceneNode(sphere);
            MeshSceneNode t = smgr.AddMeshSceneNode(smgr.GetMesh("pill.obj"));
            //MeshSceneNode t = smgr.AddMeshSceneNode(cyl);
            TriangleSelector triselect = smgr.CreateTriangleSelector(t.Mesh, t);

            t.TriangleSelector = triselect;
            triselect.Drop();
            //t = smgr.AddMeshSceneNode(smgr.GetMesh("../../media/sphere.x"));
            //smgr
            t.SetMaterialTexture(0, driver.GetTexture("rockwall.jpg"));
            //t.SetMaterialFlag(MaterialFlag.Lighting, true);
            t.GetMaterial(0).SpecularColor.Set(0, 0, 0);
            //t.GetMaterial(0).Lighting = true;
            t.GetMaterial(0).NormalizeNormals = false;

            /*Texture citrus = driver.AddTexture(new Dimension2Di(200, 200), "citrus.png");
             * gui.AddImage(citrus, new Vector2Di(824, 0), true);*/
            gui.AddStaticText("Hey, Listen! Press C to switch the mesh to a cylinder!\n Press S to change to a sphere, and enter to send yourself the obj file!", new Recti(0, 0, 400, 60));
            //t.AddShadowVolumeSceneNode();
            //           driver.GPUProgrammingServices.OnSetConstants += new GPUProgrammingServices.SetConstantsHandler(gpu_OnSetConstants);

            /*
             * MaterialType shaderMat = MaterialType.Solid;
             * shaderMat = driver.GPUProgrammingServices.AddHighLevelShaderMaterialFromFiles("C:/IrrlichtLime-1.4/examples/01.HelloWorld/bumpmap.hlsl", "VertexShaderFunction", VertexShaderType.VS_3_0,
             * "C:/IrrlichtLime-1.4/examples/01.HelloWorld/bumpmap.hlsl", "PixelShaderFunction", PixelShaderType.PS_3_0, MaterialType.Solid);
             *
             * t.SetMaterialType(shaderMat);
             * t.SetMaterialTexture(1, driver.GetTexture("../../media/rockwall_height.bmp"));*/

            GPUProgrammingServices gpu = driver.GPUProgrammingServices;
            MaterialType           newMaterialType1 = MaterialType.Solid;
            MaterialType           newMaterialType2 = MaterialType.TransparentAddColor;

            gpu.OnSetConstants += new GPUProgrammingServices.SetConstantsHandler(gpu_OnSetConstants);

            // create the shaders depending on if the user wanted high level or low level shaders

            newMaterialType1 = gpu.AddHighLevelShaderMaterialFromFiles(
                "d3d9.hlsl", "vertexMain", VertexShaderType.VS_1_1,
                "d3d9.hlsl", "pixelMain", PixelShaderType.PS_1_1,
                MaterialType.Solid, 0, GPUShadingLanguage.Default);
            t.SetMaterialType(newMaterialType1);
            //t.GetMaterial(0).Wireframe = true;
            //t.DebugDataVisible = DebugSceneType.Full;
            //t.AddShadowVolumeSceneNode(null, -1, false, 1000.0f);
            smgr.AddLightSceneNode(null, new Vector3Df(40, 150, -50), new Colorf(255, 255, 255, 255), 250.0f);
            //CSampleSceneNode sceneNode = new CSampleSceneNode(smgr.RootNode, smgr, 667);
            camera = smgr.AddCameraSceneNode(null, new Vector3Df(0, 50, -140), new Vector3Df(0, 5, 0));

            //camera.Target = new Vector3Df(-70, 30, -60);
            //smgr.AddCameraSceneNodeFPS(null, (float)50.0);
            Material m = new Material();

            m.Lighting = false;
            double PI        = 3.1415926f;
            float  distance  = 200.0f;
            double angle     = 180.0f;
            double angleY    = 20.0f;
            int    oldMouseX = mouseX;
            int    oldMouseY = mouseY;



            uint then          = device.Timer.Time;
            uint currentAutism = device.Timer.Time;
            bool autism        = false;

            while (device.Run())
            {
                uint  now            = device.Timer.Time;
                float frameDeltaTime = (float)(now - then) / 1000.0f;
                then = now;
                if (kinect.isTranslating && (kinect.translation.X < 30 && kinect.translation.X > -30))
                {
                    mfX -= (int)(kinect.translation.X);
                    mfY -= (int)(kinect.translation.Y);

                    Console.WriteLine(mouseX + ", " + mouseY + " ----------------- " + (int)(kinect.translation.X) + ", " + (int)(kinect.translation.Y));
                }

                kinect.resetTranslation();

                /*
                 * if (getDistance((int)mfX, (int)mfY, 512, 384) > 150)
                 * {
                 *  mfX = 512; mfY= 384;
                 * }*/


                mouseX = Math.Abs((int)mfX) % 1024;
                mouseY = Math.Abs((int)mfY) % 768;
                //mouseX = kinect.position.X;

                device.CursorControl.Position = new Vector2Di(mouseX, mouseY);

                if (!potterWheelDown && IsKeyDown(KeyCode.Up))
                {
                    potterWheelDown     = true;
                    deltaAngle          = 1.0d;
                    potterWheelActivate = !potterWheelActivate;
                }
                else if (!IsKeyDown(KeyCode.Up))
                {
                    potterWheelDown = false;
                }
                if (!leftKeyPressed && IsKeyDown(KeyCode.Left))
                {
                    leftKeyPressed = true;
                    deltaAngle    /= 2;
                }
                else if (!IsKeyDown(KeyCode.Left))
                {
                    leftKeyPressed = false;
                }
                if (!rightKeyPressed && IsKeyDown(KeyCode.Right))
                {
                    rightKeyPressed = true;
                    deltaAngle     *= 2;
                }
                else if (!IsKeyDown(KeyCode.Right))
                {
                    rightKeyPressed = false;
                }
                if (potterWheelActivate)
                {
                    angle -= 700.0f * deltaAngle * frameDeltaTime;
                }

                if (angle > 360)
                {
                    angle -= 360;
                }
                else if (angle < 0)
                {
                    angle += 360;
                }

                if (angleY > 360)
                {
                    angle -= 360;
                }
                else if (angleY < 0)
                {
                    angleY += 360;
                }
                driver.BeginScene(true, true, new Color(100, 101, 140));
                camera.Target = new Vector3Df(0, 0, 0);
                double temp = Math.Cos(angleY * PI / 180.0) * distance;
                double X    = Math.Sin(angle * PI / 180.0) * temp;
                double Y    = Math.Sin(angleY * PI / 180.0) * distance;
                double Z    = Math.Cos(angle * PI / 180.0) * temp;
                camera.Position = new Vector3Df((float)X, (float)Y, (float)Z);
                smgr.DrawAll();

                gui.DrawAll();
                driver.SetMaterial(m);
                Triangle3Df triangle = interpolateFrom2D(new Vector2Di(mouseX, mouseY));
                if (kinect.isMorphing && kinect.morphDist > 0)
                //if (IsKeyDown(KeyCode.KeyW))
                {
                    //Console.WriteLine("PRESSED KEY");
                    triangle.A *= new Vector3Df(0.5f);
                    triangle.B *= new Vector3Df(0.5f);
                    triangle.C *= new Vector3Df(0.5f);
                    if (isCyl)
                    {
                        deformCyl(t, triangle.A, new Vector3Df(.5f / (potterWheelActivate ? (float)(1 / deltaAngle) : 60f)), triangle);
                    }
                    else
                    {
                        deformMesh(t, triangle.A, new Vector3Df(.5f / (potterWheelActivate ? (float)(1 / deltaAngle) : 60f)), triangle);
                    }
                }
                else if (kinect.isMorphing && kinect.morphDist < 0)
                {
                    //Console.WriteLine("PRESSED KEY");
                    triangle.A *= new Vector3Df(1.5f);
                    triangle.B *= new Vector3Df(1.5f);
                    triangle.C *= new Vector3Df(1.5f);
                    if (isCyl)
                    {
                        deformCyl(t, triangle.A, new Vector3Df(-.5f / (potterWheelActivate ? (float)(1 / deltaAngle) : 60f)), triangle);
                    }
                    else
                    {
                        deformMesh(t, triangle.A, new Vector3Df(-.5f / (potterWheelActivate ? (float)(1 / deltaAngle) : 60f)), triangle);
                    }
                }
                if (kinect.isZoom && kinect.zoomDist < 0)
                {
                    if (distance < 300.0f)
                    {
                        distance += .0625f;
                    }
                }
                if (kinect.isZoom && kinect.zoomDist > 0)
                {
                    if (distance > 150)
                    {
                        distance -= .0625f;
                    }
                }
                if (kinect.isRotating && kinect.rotation > 0)
                {
                    angle += 200 * frameDeltaTime;
                }
                if (kinect.isRotating && kinect.rotation < 0)
                {
                    angle -= 200 * frameDeltaTime;
                }

                //Change shape

                if (IsKeyDown(KeyCode.KeyA))
                {
                    IrrlichtLime.IO.WriteFile file = device.FileSystem.CreateWriteFile("./Saved.obj");
                    writeMesh(file, t.Mesh, 1);

                    mail();
                }
                if (IsKeyDown(KeyCode.KeyC))
                {
                    isCyl = true;
                    t.Remove();
                    t = smgr.AddMeshSceneNode(smgr.GetMesh("pill.obj"));
                    //MeshSceneNode t = smgr.AddMeshSceneNode(cyl);
                    triselect          = smgr.CreateTriangleSelector(t.Mesh, t);
                    t.TriangleSelector = triselect;
                    triselect.Drop();
                    //t = smgr.AddMeshSceneNode(smgr.GetMesh("../../media/sphere.x"));
                    //smgr
                    t.SetMaterialTexture(0, driver.GetTexture("rockwall.jpg"));
                    //t.SetMaterialFlag(MaterialFlag.Lighting, true);
                    t.GetMaterial(0).SpecularColor.Set(0, 0, 0);
                    //t.GetMaterial(0).Lighting = true;
                    t.GetMaterial(0).NormalizeNormals = false;
                    t.SetMaterialType(newMaterialType1);
                }
                else if (IsKeyDown(KeyCode.KeyS))
                {
                    isCyl = false;
                    t.Remove();
                    t                  = smgr.AddSphereSceneNode(ballRadius, 32);
                    triselect          = smgr.CreateTriangleSelector(t.Mesh, t);
                    t.TriangleSelector = triselect;
                    triselect.Drop();
                    //t = smgr.AddMeshSceneNode(smgr.GetMesh("../../media/sphere.x"));
                    //smgr
                    t.SetMaterialTexture(0, driver.GetTexture("rockwall.jpg"));
                    //t.SetMaterialFlag(MaterialFlag.Lighting, true);
                    t.GetMaterial(0).SpecularColor.Set(0, 0, 0);
                    //t.GetMaterial(0).Lighting = true;
                    t.GetMaterial(0).NormalizeNormals = false;
                    t.SetMaterialType(newMaterialType1);
                }
                driver.EndScene();
            }

            device.Drop();
        }
Exemplo n.º 19
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(640, 480));

            if (device == null)
            {
                return;
            }

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);

            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

            SceneNode node = smgr.AddSphereSceneNode();

            if (node != null)
            {
                node.Position = new Vector3Df(0, 0, 30);
                node.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp"));
                node.SetMaterialFlag(MaterialFlag.Lighting, false);
            }

            SceneNode n = smgr.AddCubeSceneNode();

            if (n != null)
            {
                n.SetMaterialTexture(0, driver.GetTexture("../../media/t351sml.jpg"));
                n.SetMaterialFlag(MaterialFlag.Lighting, false);

                SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 0, 30), 20.0f);
                if (anim != null)
                {
                    n.AddAnimator(anim);
                    anim.Drop();
                }
            }

            AnimatedMeshSceneNode anms = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/ninja.b3d"));

            if (anms != null)
            {
                SceneNodeAnimator anim = smgr.CreateFlyStraightAnimator(
                    new Vector3Df(100, 0, 60), new Vector3Df(-100, 0, 60), 3.5f, true);
                if (anim != null)
                {
                    anms.AddAnimator(anim);
                    anim.Drop();
                }

                anms.SetMaterialFlag(MaterialFlag.Lighting, false);

                anms.SetFrameLoop(0, 13);
                anms.AnimationSpeed = 15;

                anms.Scale    = new Vector3Df(2);
                anms.Rotation = new Vector3Df(0, -90, 0);
            }

            smgr.AddCameraSceneNodeFPS();
            device.CursorControl.Visible = false;

            device.GUIEnvironment.AddImage(
                driver.GetTexture("../../media/irrlichtlogoalpha2.tga"),
                new Vector2Di(10, 20));

            int lastFPS = -1;

            uint then = device.Timer.Time;

            const float MOVEMENT_SPEED = 5.0f;

            while (device.Run())
            {
                uint  now            = device.Timer.Time;
                float frameDeltaTime = (float)(now - then) / 1000.0f;
                then = now;

                Vector3Df nodePosition = node.Position;

                if (IsKeyDown(KeyCode.KeyW))
                {
                    nodePosition.Y += MOVEMENT_SPEED * frameDeltaTime;
                }
                else if (IsKeyDown(KeyCode.KeyS))
                {
                    nodePosition.Y -= MOVEMENT_SPEED * frameDeltaTime;
                }

                if (IsKeyDown(KeyCode.KeyA))
                {
                    nodePosition.X -= MOVEMENT_SPEED * frameDeltaTime;
                }
                else if (IsKeyDown(KeyCode.KeyD))
                {
                    nodePosition.X += MOVEMENT_SPEED * frameDeltaTime;
                }

                node.Position = nodePosition;

                driver.BeginScene(ClearBufferFlag.All, new Color(113, 113, 113));
                smgr.DrawAll();
                device.GUIEnvironment.DrawAll();
                driver.EndScene();

                int fps = driver.FPS;
                if (lastFPS != fps)
                {
                    device.SetWindowCaption(String.Format(
                                                "Movement example - Irrlicht Engine [{0}] fps: {1}",
                                                driver.Name, fps));

                    lastFPS = fps;
                }
            }

            device.Drop();
        }
Exemplo n.º 20
0
        static void Main(string[] args)
        {
            device          = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(1024, 768), 32, false, true);
            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            device.SetWindowCaption("Minesweeper - Irrlicht Engine");

            VideoDriver    driver = device.VideoDriver;
            SceneManager   scene  = device.SceneManager;
            GUIEnvironment gui    = device.GUIEnvironment;

            device.FileSystem.AddFileArchive("../../media/minesweeper.media.files");
            game = new Game(device);

            // set up camera

            camera = scene.AddCameraSceneNode();             // Maya(null, -500, 50, 200);
            setupCameraPositionAndTarget();

            // set up background

            Mesh m = scene.GetMesh("back.obj");

            scene.MeshManipulator.Scale(m, new Vector3Df(80));
            scene.MeshManipulator.FlipSurfaces(m);
            scene.MeshManipulator.RecalculateNormals(m);
            scene.MeshManipulator.SetVertexColors(m, new Color(80, 80, 80));

            Material t = new Material();

            t.Type     = MaterialType.Reflection2Layer;
            t.Lighting = false;
            t.SetTexture(0, device.VideoDriver.GetTexture("TEXTURE-ref.jpg"));
            t.SetTexture(1, device.VideoDriver.GetTexture("TEXTURE-ref.jpg"));

            MeshSceneNode n = scene.AddMeshSceneNode(m, null, 7777);

            n.SetMaterial(0, t);
            n.Position = game.CenterOfTheBoard;

            SceneNodeAnimator a = scene.CreateRotationAnimator(new Vector3Df(0.07f, 0.01f, 0.05f));

            n.AddAnimator(a);
            a.Drop();

            // set up light

            light = scene.AddLightSceneNode(null, game.CenterOfTheBoard, new Colorf(1, 1, 1), 200);

            m = scene.AddVolumeLightMesh("lvol1", 32, 32, new Color(5, 5, 5));
            scene.MeshManipulator.Scale(m, new Vector3Df(15, 30, 15));
            n          = scene.AddMeshSceneNode(m, light);
            n.Position = new Vector3Df(0, -10, 0);
            n.Rotation = new Vector3Df(180, 0, 0);
            n.SetMaterialType(MaterialType.TransparentAddColor);

            m = scene.AddVolumeLightMesh("lvol2", 32, 32, new Color(5, 5, 5));
            scene.MeshManipulator.Scale(m, new Vector3Df(15, 30, 15));
            n          = scene.AddMeshSceneNode(m, light);
            n.Position = new Vector3Df(0, -10, 0);
            n.SetMaterialType(MaterialType.TransparentAddColor);

            // add gui hint

            text = gui.AddStaticText(TextStart, new Recti(10, 10, 200, 40));
            text.OverrideColor = Color.OpaqueYellow;

            // main loop

            while (device.Run())
            {
                driver.BeginScene();
                scene.DrawAll();
                gui.DrawAll();

                if (optionFPS)
                {
                    gui.BuiltInFont.Draw(driver.FPS + " FPS", driver.ScreenSize.Width - 50, 10, Color.OpaqueWhite);
                }

                driver.EndScene();
            }

            device.Drop();
        }
Exemplo n.º 21
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(640, 480));

            if (device == null)
            {
                return;
            }

            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

            device.FileSystem.AddFileArchive("../../media/map-20kdm2.pk3");

            AnimatedMesh mesh = smgr.GetMesh("20kdm2.bsp");
            SceneNode    node = null;

            if (mesh != null)
            {
                node = smgr.AddOctreeSceneNode(mesh.GetMesh(0), null, -1, 1024);
            }

            if (node != null)
            {
                node.Position = new Vector3Df(-1300, -144, -1249);
            }

            smgr.AddCameraSceneNodeFPS();

            device.CursorControl.Visible = false;

            int lastFPS = -1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    driver.BeginScene(ClearBufferFlag.All, new Color(200, 200, 200));
                    smgr.DrawAll();
                    driver.EndScene();

                    int fps = driver.FPS;
                    if (lastFPS != fps)
                    {
                        device.SetWindowCaption(String.Format(
                                                    "Quake 3 Map Example - Irrlicht Engine [{0}] fps: {1}",
                                                    driver.Name, fps));

                        lastFPS = fps;
                    }
                }
            }

            device.Drop();
        }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            DriverType driverType;

            if (!AskUserForDriver(out driverType))
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType, new Dimension2Di(ResX, ResY), 32, fullScreen);

            if (device == null)
            {
                return;
            }

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

            // load model
            AnimatedMesh model = smgr.GetMesh("../../media/sydney.md2");

            if (model == null)
            {
                return;
            }

            AnimatedMeshSceneNode model_node = smgr.AddAnimatedMeshSceneNode(model);

            // load texture
            if (model_node != null)
            {
                Texture texture = driver.GetTexture("../../media/sydney.bmp");
                model_node.SetMaterialTexture(0, texture);
                model_node.SetMD2Animation(AnimationTypeMD2.Run);
                model_node.SetMaterialFlag(MaterialFlag.Lighting, false);
            }

            // load map
            device.FileSystem.AddFileArchive("../../media/map-20kdm2.pk3");
            AnimatedMesh map = smgr.GetMesh("20kdm2.bsp");

            if (map != null)
            {
                SceneNode map_node = smgr.AddOctreeSceneNode(map.GetMesh(0));
                map_node.Position = new Vector3Df(-850, -220, -850);
            }

            // create 3 fixed and one user-controlled cameras
            camera[0]          = smgr.AddCameraSceneNode(null, new Vector3Df(50, 0, 0), new Vector3Df(0)); // font
            camera[1]          = smgr.AddCameraSceneNode(null, new Vector3Df(0, 50, 0), new Vector3Df(0)); // top
            camera[2]          = smgr.AddCameraSceneNode(null, new Vector3Df(0, 0, 50), new Vector3Df(0)); // left
            camera[3]          = smgr.AddCameraSceneNodeFPS();                                             // user-controlled
            camera[3].Position = new Vector3Df(-50, 0, -50);

            device.CursorControl.Visible = false;

            int lastFPS = -1;

            while (device.Run())
            {
                // set the viewpoint to the whole screen and begin scene
                driver.ViewPort = new Recti(0, 0, ResX, ResY);
                driver.BeginScene(true, true, new Color(100, 100, 100));

                if (splitScreen)
                {
                    smgr.ActiveCamera = camera[0];
                    driver.ViewPort   = new Recti(0, 0, ResX / 2, ResY / 2);                   // top left
                    smgr.DrawAll();

                    smgr.ActiveCamera = camera[1];
                    driver.ViewPort   = new Recti(ResX / 2, 0, ResX, ResY / 2);                   // top right
                    smgr.DrawAll();

                    smgr.ActiveCamera = camera[2];
                    driver.ViewPort   = new Recti(0, ResY / 2, ResX / 2, ResY);                   // bottom left
                    smgr.DrawAll();

                    driver.ViewPort = new Recti(ResX / 2, ResY / 2, ResX, ResY);                     // bottom right
                }

                smgr.ActiveCamera = camera[3];
                smgr.DrawAll();

                driver.EndScene();

                int fps = driver.FPS;
                if (lastFPS != fps)
                {
                    device.SetWindowCaption(String.Format(
                                                "Split Screen example - Irrlicht Engine [{0}] fps: {1}",
                                                driver.Name, fps));

                    lastFPS = fps;
                }
            }

            device.Drop();
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            DriverType driverType;

            if (!AskUserForDriver(out driverType))
            {
                return;
            }

            device = IrrlichtDevice.CreateDevice(driverType, new Dimension2Di(800, 600), 16);
            if (device == null)
            {
                return;
            }

            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            device.SetWindowResizable(true);
            device.SetWindowCaption("Irrlicht Engine - Loading...");

            VideoDriver    driver = device.VideoDriver;
            GUIEnvironment env    = device.GUIEnvironment;
            SceneManager   smgr   = device.SceneManager;

            smgr.Attributes.SetValue(SceneParameters.COLLADA_CreateSceneInstances, true);

            driver.SetTextureCreationFlag(TextureCreationFlag.Always32Bit, true);

            smgr.AddLightSceneNode(null, new Vector3Df(200), new Colorf(1.0f, 1.0f, 1.0f), 2000);
            smgr.AmbientLight = new Colorf(0.3f, 0.3f, 0.3f);

            // add our media directory as "search path"
            device.FileSystem.AddFileArchive("../../media/");

            // read configuration from xml file
            // (we use .NET way to do this, since Lime doesn't support native Irrlicht' xml reader)
            XmlDocument xml = new XmlDocument();

            xml.Load("../../media/config.xml");
            startUpModelFile = xml.DocumentElement["startUpModel"].Attributes["file"].Value;
            caption          = xml.DocumentElement["messageText"].Attributes["caption"].Value;
            messageText      = xml.DocumentElement["messageText"].InnerText;

            if (args.Length > 0)
            {
                startUpModelFile = args[0];
            }

            // set a nicer font
            GUIFont font = env.GetFont("fonthaettenschweiler.bmp");

            if (font != null)
            {
                env.Skin.SetFont(font);
            }

            // load the irrlicht engine logo
            GUIImage img = env.AddImage(
                driver.GetTexture("irrlichtlogoalpha2.tga"),
                new Vector2Di(10, (int)driver.ScreenSize.Height - 128));

            img.ID = (int)guiID.Logo;

            // lock the logo's edges to the bottom left corner of the screen
            img.SetAlignment(GUIAlignment.UpperLeft, GUIAlignment.UpperLeft, GUIAlignment.LowerRight, GUIAlignment.LowerRight);

            // create menu
            GUIContextMenu menu = env.AddMenu();

            menu.AddItem("File", -1, true, true);
            menu.AddItem("View", -1, true, true);
            menu.AddItem("Camera", -1, true, true);
            menu.AddItem("Help", -1, true, true);

            GUIContextMenu submenu;

            submenu = menu.GetSubMenu(0);
            submenu.AddItem("Open Model File & Texture...", (int)guiID.OpenModel);
            submenu.AddItem("Set Model Archive...", (int)guiID.SetModelArchive);
            submenu.AddItem("Load as Octree", (int)guiID.LoadAsOctree);
            submenu.AddSeparator();
            submenu.AddItem("Quit", (int)guiID.Quit);

            submenu = menu.GetSubMenu(1);
            submenu.AddItem("sky box visible", (int)guiID.SkyBoxVisible, true, false, true);
            submenu.AddItem("toggle model debug information", (int)guiID.ToggleDebugInfo, true, true);
            submenu.AddItem("model material", -1, true, true);

            submenu = submenu.GetSubMenu(1);
            submenu.AddItem("Off", (int)guiID.DebugOff);
            submenu.AddItem("Bounding Box", (int)guiID.DebugBoundingBox);
            submenu.AddItem("Normals", (int)guiID.DebugNormals);
            submenu.AddItem("Skeleton", (int)guiID.DebugSkeleton);
            submenu.AddItem("Wire overlay", (int)guiID.DebugWireOverlay);
            submenu.AddItem("Half-Transparent", (int)guiID.DebugHalfTransparent);
            submenu.AddItem("Buffers bounding boxes", (int)guiID.DebugBuffersBoundingBoxes);
            submenu.AddItem("All", (int)guiID.DebugAll);

            submenu = menu.GetSubMenu(1).GetSubMenu(2);
            submenu.AddItem("Solid", (int)guiID.ModelMaterialSolid);
            submenu.AddItem("Transparent", (int)guiID.ModelMaterialTransparent);
            submenu.AddItem("Reflection", (int)guiID.ModelMaterialReflection);

            submenu = menu.GetSubMenu(2);
            submenu.AddItem("Maya Style", (int)guiID.CameraMaya);
            submenu.AddItem("First Person", (int)guiID.CameraFirstPerson);

            submenu = menu.GetSubMenu(3);
            submenu.AddItem("About", (int)guiID.About);

            // create toolbar

            GUIToolBar bar = env.AddToolBar();

            Texture image = driver.GetTexture("open.png");

            bar.AddButton((int)guiID.ButtonOpenModel, null, "Open a model", image, null, false, true);

            image = driver.GetTexture("tools.png");
            bar.AddButton((int)guiID.ButtonShowToolbox, null, "Open Toolset", image, null, false, true);

            image = driver.GetTexture("zip.png");
            bar.AddButton((int)guiID.ButtonSelectArchive, null, "Set Model Archive", image, null, false, true);

            image = driver.GetTexture("help.png");
            bar.AddButton((int)guiID.ButtonShowAbout, null, "Open Help", image, null, false, true);

            // create a combobox with some senseless texts

            GUIComboBox box = env.AddComboBox(new Recti(250, 4, 350, 23), bar, (int)guiID.TextureFilter);

            box.AddItem("No filtering");
            box.AddItem("Bilinear");
            box.AddItem("Trilinear");
            box.AddItem("Anisotropic");
            box.AddItem("Isotropic");

            // disable alpha
            setSkinTransparency(255, env.Skin);

            // add a tabcontrol
            createToolBox();

            // create fps text
            GUIStaticText fpstext = env.AddStaticText("", new Recti(400, 4, 570, 23), true, false, bar);
            GUIStaticText postext = env.AddStaticText("", new Recti(10, 50, 470, 80), false, false, null, (int)guiID.PositionText);

            postext.Visible = false;

            // show about message box and load default model
            if (args.Length == 0)
            {
                showAboutText();
            }

            loadModel(startUpModelFile);

            // add skybox

            skybox = smgr.AddSkyBoxSceneNode(
                "irrlicht2_up.jpg", "irrlicht2_dn.jpg",
                "irrlicht2_lf.jpg", "irrlicht2_rt.jpg",
                "irrlicht2_ft.jpg", "irrlicht2_bk.jpg");

            // add a camera scene node

            camera[0]          = smgr.AddCameraSceneNodeMaya();
            camera[0].FarValue = 20000;
            // Maya cameras reposition themselves relative to their target,
            // so target the location where the mesh scene node is placed.
            camera[0].Target = new Vector3Df(0, 30, 0);

            camera[1]          = smgr.AddCameraSceneNodeFPS();
            camera[1].FarValue = 20000;
            camera[1].Position = new Vector3Df(0, 0, -70);
            camera[1].Target   = new Vector3Df(0, 30, 0);

            setActiveCamera(camera[0]);

            // set window caption
            caption = string.Format("{0} - [{1}]", caption, driver.Name);
            device.SetWindowCaption(caption);

            // remember state so we notice when the window does lose the focus
            bool hasFocus = device.WindowFocused;

            // draw everything
            while (device.Run() && driver != null)
            {
                // Catch focus changes (workaround until Irrlicht has events for this)
                bool focused = device.WindowFocused;
                if (hasFocus && !focused)
                {
                    onKillFocus();
                }

                hasFocus = focused;

                if (device.WindowActive)
                {
                    driver.BeginScene(true, true, new Color(50, 50, 50));
                    smgr.DrawAll();
                    env.DrawAll();
                    driver.EndScene();

                    string str = string.Format("FPS: {0} Tris: {1}", driver.FPS, driver.PrimitiveCountDrawn);
                    fpstext.Text = str;

                    CameraSceneNode cam = device.SceneManager.ActiveCamera;
                    str          = string.Format("Pos: {0} Tgt: {1}", cam.Position, cam.Target);
                    postext.Text = str;
                }
                else
                {
                    device.Yield();
                }
            }

            device.Drop();
        }
Exemplo n.º 24
0
        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker           worker = sender as BackgroundWorker;
            IrrlichtCreationParameters p      = new IrrlichtCreationParameters();

            p.DriverType = DriverType.Direct3D9;
            p.WindowID   = (IntPtr)e.Argument;

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(p);

            if (device == null)
            {
                // if device cannot be created by any reason - we just leave this thread,
                // after all IsRedering will report false, so it is all OK.
                return;
            }

            VideoDriver    driver = device.VideoDriver;
            SceneManager   smgr   = device.SceneManager;
            GUIEnvironment gui    = device.GUIEnvironment;

            // setup a simple 3d scene

            CameraSceneNode cam = smgr.AddCameraSceneNode();

            cam.Target = new Vector3Df(0);

            SceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3Df(0, 15, 0), 30.0f);

            cam.AddAnimator(anim);
            anim.Drop();

            SceneNode cube = smgr.AddCubeSceneNode(20);

            cube.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp"));
            cube.SetMaterialTexture(1, driver.GetTexture("../../media/water.jpg"));
            cube.SetMaterialFlag(MaterialFlag.Lighting, false);
            cube.SetMaterialType(MaterialType.Reflection2Layer);

            smgr.AddSkyBoxSceneNode(
                "../../media/irrlicht2_up.jpg",
                "../../media/irrlicht2_dn.jpg",
                "../../media/irrlicht2_lf.jpg",
                "../../media/irrlicht2_rt.jpg",
                "../../media/irrlicht2_ft.jpg",
                "../../media/irrlicht2_bk.jpg");

            gui.AddImage(
                driver.GetTexture("../../media/lime_logo_alpha.png"),
                new Vector2Di(30, 0));

            // draw all

            while (device.Run())
            {
                driver.BeginScene(ClearBufferFlag.Depth);

                smgr.DrawAll();
                gui.DrawAll();

                // draw stats

                int x = 20;
                int y = driver.ScreenSize.Height - 50;

                driver.Draw2DRectangle(
                    new Recti(x, y, x + driver.ScreenSize.Width - 2 * x, y + 30),
                    new IrrlichtLime.Video.Color(0, 0, 0, 128));

                device.GUIEnvironment.BuiltInFont.Draw(
                    "Driver: " + driver.Name,
                    new Vector2Di(x + 5, y + 5),
                    new IrrlichtLime.Video.Color(255, 255, 255));

                device.GUIEnvironment.BuiltInFont.Draw(
                    "FPS: " + driver.FPS.ToString(),
                    new Vector2Di(x + 5, y + 15),
                    new IrrlichtLime.Video.Color(255, 255, 255));

                driver.EndScene();

                // check for cancellation

                if (worker.CancellationPending)
                {
                    device.Close();
                }

                // check for new command

                lock (backgroundCommand)
                {
                    switch (backgroundCommand.Type)
                    {
                    case Command.Kind.Resized:
                        driver.ResizeNotify(backgroundCommand.Value as Dimension2Di);
                        backgroundCommand.Clear();
                        break;
                    }
                }
            }

            // drop the device

            device.Drop();
        }
Exemplo n.º 25
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(640, 480));

            if (device == null)
            {
                return;
            }

            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

            device.FileSystem.AddFileArchive("../../media/map-20kdm2.pk3");

            AnimatedMesh  q3levelmesh = smgr.GetMesh("20kdm2.bsp");
            MeshSceneNode q3node      = null;

            // The Quake mesh is pickable, but doesn't get highlighted.
            if (q3levelmesh != null)
            {
                q3node = smgr.AddOctreeSceneNode(q3levelmesh.GetMesh(0), null, IDFlag_IsPickable);
            }

            TriangleSelector selector = null;

            if (q3node != null)
            {
                q3node.Position         = new Vector3Df(-1350, -130, -1400);
                selector                = smgr.CreateOctreeTriangleSelector(q3node.Mesh, q3node, 128);
                q3node.TriangleSelector = selector;
                // We're not done with this selector yet, so don't drop it.
            }

            // Set a jump speed of 3 units per second, which gives a fairly realistic jump
            // when used with the gravity of (0, -1000, 0) in the collision response animator.
            CameraSceneNode camera = smgr.AddCameraSceneNodeFPS(null, 100.0f, 0.3f, ID_IsNotPickable, null, true, 3.0f);

            camera.Position = new Vector3Df(50, 50, -60);
            camera.Target   = new Vector3Df(-70, 30, -60);

            if (selector != null)
            {
                SceneNodeAnimator anim = smgr.CreateCollisionResponseAnimator(
                    selector,
                    camera,
                    new Vector3Df(30, 50, 30),
                    new Vector3Df(0, -1000, 0),
                    new Vector3Df(0, 30, 0));

                selector.Drop();             // As soon as we're done with the selector, drop it.
                camera.AddAnimator(anim);
                anim.Drop();                 // And likewise, drop the animator when we're done referring to it.
            }

            // Now I create three animated characters which we can pick, a dynamic light for
            // lighting them, and a billboard for drawing where we found an intersection.

            // First, let's get rid of the mouse cursor. We'll use a billboard to show what we're looking at.
            device.CursorControl.Visible = false;

            // Add the billboard.
            BillboardSceneNode bill = smgr.AddBillboardSceneNode();

            bill.SetMaterialType(MaterialType.TransparentAddColor);
            bill.SetMaterialTexture(0, driver.GetTexture("../../media/particle.bmp"));
            bill.SetMaterialFlag(MaterialFlag.Lighting, false);
            bill.SetMaterialFlag(MaterialFlag.ZBuffer, false);
            bill.SetSize(20, 20, 20);
            bill.ID = ID_IsNotPickable;             // This ensures that we don't accidentally ray-pick it

            AnimatedMeshSceneNode node = null;

            // Add an MD2 node, which uses vertex-based animation.
            node          = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/faerie.md2"), null, IDFlag_IsPickable | IDFlag_IsHighlightable);
            node.Position = new Vector3Df(-90, -15, -140); // Put its feet on the floor.
            node.Scale    = new Vector3Df(1.6f);           // Make it appear realistically scaled
            node.SetMD2Animation(AnimationTypeMD2.Point);
            node.AnimationSpeed = 20.0f;
            node.GetMaterial(0).SetTexture(0, driver.GetTexture("../../media/faerie2.bmp"));
            node.GetMaterial(0).Lighting         = true;
            node.GetMaterial(0).NormalizeNormals = true;

            // Now create a triangle selector for it.  The selector will know that it
            // is associated with an animated node, and will update itself as necessary.
            selector = smgr.CreateTriangleSelector(node);
            node.TriangleSelector = selector;
            selector.Drop();             // We're done with this selector, so drop it now.

            // And this B3D file uses skinned skeletal animation.
            node                = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/ninja.b3d"), null, IDFlag_IsPickable | IDFlag_IsHighlightable);
            node.Scale          = new Vector3Df(10);
            node.Position       = new Vector3Df(-75, -66, -80);
            node.Rotation       = new Vector3Df(0, 90, 0);
            node.AnimationSpeed = 8.0f;
            node.GetMaterial(0).NormalizeNormals = true;
            // Just do the same as we did above.
            selector = smgr.CreateTriangleSelector(node);
            node.TriangleSelector = selector;
            selector.Drop();

            // This X files uses skeletal animation, but without skinning.
            node                  = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/dwarf.x"), null, IDFlag_IsPickable | IDFlag_IsHighlightable);
            node.Position         = new Vector3Df(-70, -66, -30); // Put its feet on the floor.
            node.Rotation         = new Vector3Df(0, -90, 0);     // And turn it towards the camera.
            node.AnimationSpeed   = 20.0f;
            selector              = smgr.CreateTriangleSelector(node);
            node.TriangleSelector = selector;
            selector.Drop();

            // And this mdl file uses skinned skeletal animation.
            node          = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("../../media/yodan.mdl"), null, IDFlag_IsPickable | IDFlag_IsHighlightable);
            node.Position = new Vector3Df(-90, -25, 20);
            node.Scale    = new Vector3Df(0.8f);
            node.GetMaterial(0).Lighting = true;
            node.AnimationSpeed          = 20.0f;

            // Just do the same as we did above.
            selector = smgr.CreateTriangleSelector(node);
            node.TriangleSelector = selector;
            selector.Drop();

            // Add a light, so that the unselected nodes aren't completely dark.
            LightSceneNode light = smgr.AddLightSceneNode(null, new Vector3Df(-60, 100, 400), new Colorf(1.0f, 1.0f, 1.0f), 600.0f);

            light.ID = ID_IsNotPickable;             // Make it an invalid target for selection.

            // Remember which scene node is highlighted
            SceneNode             highlightedSceneNode = null;
            SceneCollisionManager collMan = smgr.SceneCollisionManager;
            int lastFPS = -1;

            // draw the selection triangle only as wireframe
            Material material = new Material();

            material.Lighting  = false;
            material.Wireframe = true;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    driver.BeginScene(ClearBufferFlag.All, new Color(0));
                    smgr.DrawAll();

                    // Unlight any currently highlighted scene node
                    if (highlightedSceneNode != null)
                    {
                        highlightedSceneNode.SetMaterialFlag(MaterialFlag.Lighting, true);
                        highlightedSceneNode = null;
                    }

                    // All intersections in this example are done with a ray cast out from the camera to
                    // a distance of 1000.  You can easily modify this to check (e.g.) a bullet
                    // trajectory or a sword's position, or create a ray from a mouse click position using
                    // collMan.GetRayFromScreenCoordinates()
                    Line3Df ray = new Line3Df();
                    ray.Start = camera.Position;
                    ray.End   = ray.Start + (camera.Target - ray.Start).Normalize() * 1000.0f;

                    // This call is all you need to perform ray/triangle collision on every scene node
                    // that has a triangle selector, including the Quake level mesh.  It finds the nearest
                    // collision point/triangle, and returns the scene node containing that point.
                    // Irrlicht provides other types of selection, including ray/triangle selector,
                    // ray/box and ellipse/triangle selector, plus associated helpers.
                    // See the methods of ISceneCollisionManager
                    SceneNode selectedSceneNode =
                        collMan.GetSceneNodeAndCollisionPointFromRay(
                            ray,
                            out Vector3Df intersection,             // This will be the position of the collision
                            out Triangle3Df hitTriangle,            // This will be the triangle hit in the collision
                            IDFlag_IsPickable);                     // This ensures that only nodes that we have set up to be pickable are considered

                    // If the ray hit anything, move the billboard to the collision position
                    // and draw the triangle that was hit.
                    if (selectedSceneNode != null)
                    {
                        bill.Position = intersection;

                        // We need to reset the transform before doing our own rendering.
                        driver.SetTransform(TransformationState.World, Matrix.Identity);
                        driver.SetMaterial(material);
                        driver.Draw3DTriangle(hitTriangle, new Color(255, 0, 0));

                        // We can check the flags for the scene node that was hit to see if it should be
                        // highlighted. The animated nodes can be highlighted, but not the Quake level mesh
                        if ((selectedSceneNode.ID & IDFlag_IsHighlightable) == IDFlag_IsHighlightable)
                        {
                            highlightedSceneNode = selectedSceneNode;

                            // Highlighting in this case means turning lighting OFF for this node,
                            // which means that it will be drawn with full brightness.
                            highlightedSceneNode.SetMaterialFlag(MaterialFlag.Lighting, false);
                        }
                    }

                    // We're all done drawing, so end the scene.
                    driver.EndScene();

                    int fps = driver.FPS;
                    if (lastFPS != fps)
                    {
                        device.SetWindowCaption(String.Format(
                                                    "Collision detection example - Irrlicht Engine [{0}] fps: {1}",
                                                    driver.Name, fps));

                        lastFPS = fps;
                    }
                }
            }

            device.Drop();
        }
Exemplo n.º 26
0
        /// <summary>
        /// The irrlicht thread for rendering.
        /// </summary>
        private void StartIrr()
        {
#if DEBUG
            try
#endif
            {
                float DEGREES_TO_RADIANS = (float)(Math.PI / 180.0);

                //Setup
                IrrlichtCreationParameters irrparam = new IrrlichtCreationParameters();
                if (irrlichtPanel.IsDisposed)
                {
                    throw new Exception("Form closed!");
                }
                if (irrlichtPanel.InvokeRequired)
                {
                    irrlichtPanel.Invoke(new MethodInvoker(delegate { irrparam.WindowID = irrlichtPanel.Handle; }));
                }
                irrparam.DriverType   = DriverType.Direct3D9;
                irrparam.BitsPerPixel = 32;
                irrparam.AntiAliasing = 1;

                device = IrrlichtDevice.CreateDevice(irrparam);

                if (device == null)
                {
                    throw new NullReferenceException("Could not create device for engine!");
                }

                driver = device.VideoDriver;
                smgr   = SceneManagerWolvenKit.Create(device);
                gui    = device.GUIEnvironment;

                smgr.Attributes.SetValue("TW_TW3_TEX_PATH", depot);
                driver.SetTextureCreationFlag(TextureCreationFlag.Always32Bit, true);

                lightNode         = smgr.AddLightSceneNode(null, new Vector3Df(0, 0, 0), new Colorf(1.0f, 1.0f, 1.0f), 200000.0f);
                smgr.AmbientLight = new Colorf(1.0f, 1.0f, 1.0f);
                worldNode         = smgr.AddEmptySceneNode();
                //NOTE: Witcher assets use Z up but Irrlicht uses Y up so rotate the model
                worldNode.Rotation = new Vector3Df(-90, 0, 0);
                //NOTE: We also need to flip the x-coordinate with this rotation
                worldNode.Scale   = new Vector3Df(-1.0f, 1.0f, 1.0f);
                worldNode.Visible = true;

                var dome = smgr.AddSkyDomeSceneNode(driver.GetTexture("Terrain\\skydome.jpg"), 16, 8, 0.95f, 2.0f);
                dome.Visible = true;

                fpsText = gui.AddStaticText("FPS: 0",
                                            new Recti(2, 10, 200, 30), false, false, null, 1, false);
                fpsText.OverrideColor = IrrlichtLime.Video.Color.SolidRed;
                fpsText.OverrideFont  = gui.GetFont("#DefaultWKFont");

                vertexCountText = gui.AddStaticText("Vertices: " + totalVertexCount.ToString(),
                                                    new Recti(2, 32, 300, 52), false, false, null, 1, false);
                vertexCountText.OverrideColor = IrrlichtLime.Video.Color.SolidRed;
                vertexCountText.OverrideFont  = gui.GetFont("#DefaultWKFont");

                meshCountText = gui.AddStaticText("Meshes: " + totalMeshCount.ToString(),
                                                  new Recti(2, 54, 300, 74), false, false, null, 1, false);
                meshCountText.OverrideColor = IrrlichtLime.Video.Color.SolidRed;
                meshCountText.OverrideFont  = gui.GetFont("#DefaultWKFont");

                var camera = smgr.AddCameraSceneNodeWolvenKit();
                camera.FarValue = 10000.0f;

                //distanceBar.Invoke((MethodInvoker)delegate
                //{
                //    camera.FarValue = (float)Math.Pow(10.0, (double)distanceBar.Value);
                //});

                viewPort = driver.ViewPort;
                var lineMat = new IrrlichtLime.Video.Material
                {
                    Lighting = false
                };

                var WMatrix = new Matrix(new Vector3Df(0, 0, 0), smgr.ActiveCamera.ModelRotation);

                var PMatrix = new Matrix();
                PMatrix = PMatrix.BuildProjectionMatrixOrthoLH(100, 80, 0.001f, 10000.0f);

                var VMatrix = new Matrix();
                VMatrix = VMatrix.BuildCameraLookAtMatrixLH(new Vector3Df(50, 0, 0), new Vector3Df(0, 0, 0), new Vector3Df(0, 1f, 0));

                int gizmoX        = (int)(irrlichtPanel.Width * 0.92f);
                int gizmoY        = (int)(irrlichtPanel.Height * 0.92f);
                var gizmoViewPort = new Recti(gizmoX, gizmoY, irrlichtPanel.Width, irrlichtPanel.Height);

                while (device.Run())
                {
                    if (this.Visible)
                    {
                        ProcessCommand();

                        driver.BeginScene(ClearBufferFlag.All);
                        int val = driver.FPS;
                        fpsText.Text = "FPS: " + val.ToString();

                        smgr.DrawAll();
                        gui.DrawAll();

                        // draw xyz axis right bottom
                        driver.ViewPort = gizmoViewPort;

                        driver.SetMaterial(lineMat);

                        WMatrix.SetRotationRadians(smgr.ActiveCamera.ModelRotation * DEGREES_TO_RADIANS);
                        driver.SetTransform(TransformationState.World, WMatrix);
                        driver.SetTransform(TransformationState.Projection, PMatrix);
                        driver.SetTransform(TransformationState.View, VMatrix);

                        driver.Draw3DLine(0, 0, 0, 30f, 0, 0, IrrlichtLime.Video.Color.SolidGreen);
                        driver.Draw3DLine(0, 0, 0, 0, 30f, 0, IrrlichtLime.Video.Color.SolidBlue);
                        driver.Draw3DLine(0, 0, 0, 0, 0, 30f, IrrlichtLime.Video.Color.SolidRed);

                        driver.ViewPort = viewPort;

                        driver.EndScene();
                    }
                    else
                    {
                        device.Yield();
                    }
                }
            }
#if DEBUG
            catch (ThreadAbortException) { }
            catch (NullReferenceException) { }
            catch (Exception ex)
            {
                if (!this.IsDisposed)
                {
                    MessageBox.Show(ex.Message);
                    //this.Invoke(new MethodInvoker(delegate { this.Close(); }));
                }
            }
#endif
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            DriverType driverType;

            if (!AskUserForDriver(out driverType))
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType, new Dimension2Di(640, 480));

            if (device == null)
            {
                return;
            }

            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

            // load the scene
            if (args.Length > 0)
            {
                smgr.LoadScene(args[0]);
            }
            else
            {
                smgr.LoadScene("../../media/example.irr");
            }

            CameraSceneNode camera = smgr.AddCameraSceneNodeFPS(null, 50, 0.1f);

            // create a meta triangle selector to hold several triangle selectors
            MetaTriangleSelector meta = smgr.CreateMetaTriangleSelector();

            List <SceneNode> nodes = smgr.GetSceneNodesFromType(SceneNodeType.Any);            // find all nodes

            foreach (SceneNode n in nodes)
            {
                TriangleSelector selector = null;

                switch (n.Type)
                {
                case SceneNodeType.Cube:
                case SceneNodeType.AnimatedMesh:
                    // because the selector won't animate with the mesh,
                    // and is only being used for camera collision, we'll just use an approximate
                    // bounding box instead of "(node as AnimatedMeshSceneNode).GetMesh(0)"
                    selector = smgr.CreateTriangleSelectorFromBoundingBox(n);
                    break;

                case SceneNodeType.Mesh:
                case SceneNodeType.Sphere:
                    // derived from MeshSceneNode
                    selector = smgr.CreateTriangleSelector((n as MeshSceneNode).Mesh, n);
                    break;

                case SceneNodeType.Terrain:
                    selector = smgr.CreateTerrainTriangleSelector(n as TerrainSceneNode);
                    break;

                case SceneNodeType.Octree:
                    selector = smgr.CreateOctreeTriangleSelector((n as MeshSceneNode).Mesh, n);
                    break;
                }

                if (selector != null)
                {
                    // add it to the meta selector, which will take a reference to it
                    meta.AddTriangleSelector(selector);
                    // and drop my reference to it, so that the meta selector owns it
                    selector.Drop();
                }
            }

            SceneNodeAnimator anim = smgr.CreateCollisionResponseAnimator(meta, camera, new Vector3Df(5), new Vector3Df(0));

            meta.Drop();             // i'm done with the meta selector now

            camera.AddAnimator(anim);
            anim.Drop();             // i'm done with the animator now

            // and set the camera position so that it doesn't start off stuck in the geometry
            camera.Position = new Vector3Df(0, 20, 0);

            // point the camera at the cube node, by finding the first node of type SceneNodeType.Cube
            SceneNode cube = smgr.GetSceneNodeFromType(SceneNodeType.Cube);

            if (cube != null)
            {
                camera.Target = cube.AbsolutePosition;
            }

            int lastFPS = -1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    driver.BeginScene(true, true, new Color(200, 200, 200));
                    smgr.DrawAll();
                    driver.EndScene();

                    int fps = driver.FPS;
                    if (lastFPS != fps)
                    {
                        device.SetWindowCaption(String.Format(
                                                    "Load Irrlicht File example - Irrlicht Engine [{0}] fps: {1}",
                                                    driver.Name, fps));

                        lastFPS = fps;
                    }
                }
            }

            device.Drop();
        }
Exemplo n.º 28
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(640, 480));

            if (device == null)
            {
                return;
            }

            VideoDriver    driver = device.VideoDriver;
            SceneManager   smgr   = device.SceneManager;
            GUIEnvironment env    = device.GUIEnvironment;

            driver.SetTextureCreationFlag(TextureCreationFlag.Always32Bit, true);

            // add irrlicht logo
            env.AddImage(driver.GetTexture("../../media/irrlichtlogoalpha2.tga"), new Vector2Di(10));

            // set gui font
            env.Skin.SetFont(env.GetFont("../../media/fontlucida.png"));

            // add some help text
            env.AddStaticText(
                "Press 'W' to change wireframe mode\nPress 'D' to toggle detail map\nPress 'S' to toggle skybox/skydome",
                new Recti(10, 421, 250, 475), true, true, null, -1, true);

            // add camera
            CameraSceneNode camera = smgr.AddCameraSceneNodeFPS(null, 100.0f, 1.2f);

            camera.Position = new Vector3Df(2700 * 2, 255 * 2, 2600 * 2);
            camera.Target   = new Vector3Df(2397 * 2, 343 * 2, 2700 * 2);
            camera.FarValue = 42000.0f;

            // disable mouse cursor
            device.CursorControl.Visible = false;

            // add terrain scene node
            TerrainSceneNode terrain = smgr.AddTerrainSceneNode(
                "../../media/terrain-heightmap.bmp",                    // heightmap
                null,                                                   // parent node
                -1,                                                     // node id
                new Vector3Df(),                                        // position
                new Vector3Df(),                                        // rotation
                new Vector3Df(40, 4.4f, 40),                            // scale
                new Color(255, 255, 255),                               // vertex color
                5,                                                      // max LOD
                TerrainPatchSize._17,                                   // patch size
                4);                                                     // smooth factor

            terrain.SetMaterialFlag(MaterialFlag.Lighting, false);
            terrain.SetMaterialTexture(0, driver.GetTexture("../../media/terrain-texture.jpg"));
            terrain.SetMaterialTexture(1, driver.GetTexture("../../media/detailmap3.jpg"));
            terrain.SetMaterialType(MaterialType.DetailMap);

            terrain.ScaleTexture(1, 20);

            // create triangle selector for the terrain
            TriangleSelector selector = smgr.CreateTerrainTriangleSelector(terrain, 0);

            terrain.TriangleSelector = selector;

            // create collision response animator and attach it to the camera
            SceneNodeAnimator anim = smgr.CreateCollisionResponseAnimator(
                selector, camera,
                new Vector3Df(60, 100, 60),
                new Vector3Df(0, 0, 0),
                new Vector3Df(0, 50, 0));

            selector.Drop();
            camera.AddAnimator(anim);
            anim.Drop();

            // create skybox and skydome
            driver.SetTextureCreationFlag(TextureCreationFlag.CreateMipMaps, false);

            SceneNode skybox = smgr.AddSkyBoxSceneNode(
                "../../media/irrlicht2_up.jpg",
                "../../media/irrlicht2_dn.jpg",
                "../../media/irrlicht2_lf.jpg",
                "../../media/irrlicht2_rt.jpg",
                "../../media/irrlicht2_ft.jpg",
                "../../media/irrlicht2_bk.jpg");

            SceneNode skydome = smgr.AddSkyDomeSceneNode(driver.GetTexture("../../media/skydome.jpg"), 16, 8, 0.95f, 2);

            driver.SetTextureCreationFlag(TextureCreationFlag.CreateMipMaps, true);

            // create event receiver
            new MyEventReceiver(device, terrain, skybox, skydome);

            int lastFPS = -1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    driver.BeginScene(ClearBufferFlag.All, new Color(0));

                    smgr.DrawAll();
                    env.DrawAll();

                    driver.EndScene();

                    // display frames per second in window title
                    int fps = driver.FPS;
                    if (lastFPS != fps)
                    {
                        // also print terrain height of current camera position
                        // we can use camera position because terrain is located at coordinate origin

                        device.SetWindowCaption(String.Format(
                                                    "Terrain rendering example - Irrlicht Engine [{0}] fps: {1} Height: {2}",
                                                    driver.Name, fps, terrain.GetHeight(camera.AbsolutePosition.X, camera.AbsolutePosition.Z)));

                        lastFPS = fps;
                    }
                }
            }

            device.Drop();
        }
Exemplo n.º 29
0
        private static float _playerVerticalSpeed = 0.0f; // used to calculate vertical speed for gravity and jump
        static void Main(string[] args)
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(ResolutionX, ResolutionY), 24, false, false, false);

            device.OnEvent += Device_OnEvent;
            device.SetWindowCaption("Hello World! - Irrlicht Engine Demo");

            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

            GUIEnvironment gui = device.GUIEnvironment;

            gui.AddStaticText("Hello World! This is the Irrlicht Software renderer!",
                              new Recti(10, 10, 260, 22), true);

            AnimatedMesh          mesh       = smgr.GetMesh("../../media/sydney.md2");
            AnimatedMeshSceneNode sydneyNode = smgr.AddAnimatedMeshSceneNode(mesh);

            var cubeSceneNode = smgr.AddCubeSceneNode(2.0f);

            cubeSceneNode.Scale    = new Vector3Df(6.0f, 2.0f, 100.0f);
            cubeSceneNode.Position = new Vector3Df(cubeSceneNode.Position.X, GroundAltitude + 0.5f, cubeSceneNode.Position.Z);

            if (sydneyNode != null)
            {
                sydneyNode.SetMaterialFlag(MaterialFlag.Lighting, true);
                sydneyNode.SetMD2Animation(AnimationTypeMD2.Stand);
                sydneyNode.SetMaterialTexture(0, driver.GetTexture("../../media/sydney.bmp"));
            }

            var lightSceneNode = smgr.AddLightSceneNode();
            var light          = lightSceneNode.LightData;

            light.DiffuseColor = new Colorf(0.8f, 1.0f, 1.0f);
            light.Type         = LightType.Directional;
            light.Position     = new Vector3Df(0.0f, 5.0f, 5.0f);


            var cam = smgr.AddCameraSceneNode(null, new Vector3Df(20, 30, -40), new Vector3Df(20, 5, 0));

            device.Timer.Start();

            uint then = device.Timer.RealTime;

            while (device.Run())
            {
                // As the game is simple we will handle our simple physics ourselves
                uint  now            = device.Timer.RealTime;
                uint  elapsed        = now - then;
                float elapsedTimeSec = (float)elapsed / 1000.0f;
                then = now;

                // we target 58.8 FPS
                if (elapsed < 17)
                {
                    device.Sleep(17 - (int)elapsed);
                }
                else
                {
                    // uh-oh, it took more than .125 sec to do render loop!
                    // what do we do now?
                }

                _playerVerticalSpeed += elapsedTimeSec * -(VerticalGravity * 10.0f);

                var calculatedNewPos = sydneyNode.Position - new Vector3Df(0.0f, _playerVerticalSpeed * elapsedTimeSec, 0.0f);

                float offsetSydney = sydneyNode.BoundingBox.Extent.Y / 2.0f;
                _isGrounded = calculatedNewPos.Y <= (GroundAltitude + offsetSydney);
                if (_isGrounded)
                {
                    _playerVerticalSpeed = 0.0f;
                    calculatedNewPos.Y   = GroundAltitude + offsetSydney;
                }
                else
                {
                    calculatedNewPos.Y = calculatedNewPos.Y;
                }

                sydneyNode.Position = calculatedNewPos;

                driver.BeginScene(true, true, new Color(100, 101, 140));
                smgr.DrawAll();
                gui.DrawAll();

                driver.EndScene();
            }

            device.Drop();
        }
Exemplo n.º 30
0
        private void backgroundRendering_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            //DeviceSettings settings = e.Argument as DeviceSettings;

            // create irrlicht device using provided settings
            if (panelRenderWindow.IsDisposed)
            {
                throw new Exception("Form closed!");
            }

            DeviceSettings s = new DeviceSettings(
                IntPtr.Zero,
                DriverType.Direct3D9,
                0,                  //antialias
                new Color(100, 101, 140),
                false);

            if (panelRenderWindow.InvokeRequired)
            {
                panelRenderWindow.Invoke(new MethodInvoker(delegate { s.WindowID = panelRenderWindow.Handle; }));
            }

            dev = IrrlichtDevice.CreateDevice(s);
            if (dev == null)
            {
                throw new NullReferenceException("Could not create device for engine!");
            }
            dev.OnEvent        += new IrrlichtDevice.EventHandler(this.device_OnEvent);
            dev.Logger.LogLevel = LogLevel.Warning;

            drv  = dev.VideoDriver;
            smgr = dev.SceneManager;
            gui  = dev.GUIEnvironment;

            _ = smgr.FileSystem.AddFileArchive(activeMod.FileDirectory);

            smgr.Attributes.AddValue("TW_TW3_LOAD_SKEL", true);
            smgr.Attributes.AddValue("TW_TW3_LOAD_BEST_LOD_ONLY", true);


            // added by vl
            if (meshFile != null && meshFile.Length > 0)
            {
                mesh = smgr.GetMesh(meshFile);
            }

            if (mesh == null)
            {
                throw new Exception("Failed to load mesh.");
            }

            mesh.Grab();
            smgr.MeshManipulator.RecalculateNormals(mesh);
            meshLoaded = true;

            float scaleMul = 1.0f;

            node   = smgr.AddAnimatedMeshSceneNode(mesh);
            helper = smgr.GetMeshLoader(smgr.MeshLoaderCount - 1).getMeshLoaderHelper();             // hacked to gat witcher3 loader
            if (node != null && meshLoaded)
            {
                node.Scale = new Vector3Df(3.0f);
                node.SetMaterialFlag(MaterialFlag.Lighting, false);

                scaleMul = node.BoundingBox.Radius / 4;

                if (!string.IsNullOrEmpty(rigFile))
                {
                    meshToAnimate = helper.loadRig(rigFile, mesh);
                    if (meshToAnimate == null)
                    {
                        throw new Exception("Failed to load rig.");
                    }
                    else
                    {
                        meshToAnimate.Grab();
                        rigLoaded = true;
                        Logger.LogString("Rig loaded!", Logtype.Success);
                        node.Mesh = meshToAnimate;
                    }
                }

                if (!string.IsNullOrEmpty(animFile) && rigLoaded)
                {
                    animList = helper.loadAnimation(animFile, meshToAnimate);
                    if (animList.Count > 0)
                    {
                        animLoaded = true;
                        Logger.LogString($"{animList.Count} animations loaded! Select animation to play", Logtype.Success);
                    }
                    else
                    {
                        Logger.LogString("No animations loaded!", Logtype.Important);
                    }
                }

                setMaterialsSettings(node);
            }

            var camera = smgr.AddCameraSceneNode(null,
                                                 new Vector3Df(node.BoundingBox.Radius * 8, node.BoundingBox.Radius, 0),
                                                 new Vector3Df(0, node.BoundingBox.Radius, 0));

            camera.NearValue = 0.001f;
            camera.FOV       = 45.0f * 3.14f / 180.0f;


            var animText = activeAnim;

            var mAnimText     = gui.AddStaticText(animText, new Recti(0, this.ClientSize.Height - 80, 100, this.ClientSize.Height - 70));
            var mPositionText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 70, 100, this.ClientSize.Height - 60));
            var mRotationText = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 60, 100, this.ClientSize.Height - 50));
            var fpsText       = gui.AddStaticText("", new Recti(0, this.ClientSize.Height - 50, 100, this.ClientSize.Height - 40));
            var infoText      = gui.AddStaticText("[Space] - Reset\n[LMouse] - Rotate\n[MMouse] - Move\n[Wheel] - Zoom", new Recti(0, this.ClientSize.Height - 40, 100, this.ClientSize.Height));

            mAnimText.OverrideColor   = mPositionText.OverrideColor = mRotationText.OverrideColor = fpsText.OverrideColor = infoText.OverrideColor = new Color(255, 255, 255);
            mAnimText.BackgroundColor = mPositionText.BackgroundColor = mRotationText.BackgroundColor = fpsText.BackgroundColor = infoText.BackgroundColor = new Color(0, 0, 0);

            viewPort = drv.ViewPort;
            var lineMat = new Material
            {
                Lighting = false
            };

            while (dev.Run())
            {
                drv.ViewPort = viewPort;

                drv.BeginScene(ClearBufferFlag.Depth | ClearBufferFlag.Color, s.BackColor);

                node.Position = modelPosition;
                node.Rotation = modelAngle;

                //update info box
                mPositionText.Text = $"X: {modelPosition.X.ToString("F2")} Y: {modelPosition.Y.ToString("F2")} Z: {modelPosition.Z.ToString("F2")}";
                mRotationText.Text = $"Yaw: {modelAngle.Y.ToString("F2")} Roll: {modelAngle.Z.ToString("F2")}";
                fpsText.Text       = $"FPS: {drv.FPS}";

                smgr.DrawAll();
                gui.DrawAll();

                // draw xyz axis right bottom

                drv.ViewPort = new Recti(this.ClientSize.Width - 100, this.ClientSize.Height - 80, this.ClientSize.Width, this.ClientSize.Height);

                drv.SetMaterial(lineMat);
                var matrix = new Matrix(new Vector3Df(0, 0, 0), modelAngle);
                drv.SetTransform(TransformationState.World, matrix);
                matrix = matrix.BuildProjectionMatrixOrthoLH(100, 80, camera.NearValue, camera.FarValue);
                drv.SetTransform(TransformationState.Projection, matrix);
                matrix = matrix.BuildCameraLookAtMatrixLH(new Vector3Df(50, 0, 0), new Vector3Df(0, 0, 0), new Vector3Df(0, 1f, 0));
                drv.SetTransform(TransformationState.View, matrix);
                drv.Draw3DLine(0, 0, 0, 30f, 0, 0, Color.SolidGreen);
                drv.Draw3DLine(0, 0, 0, 0, 30f, 0, Color.SolidBlue);
                drv.Draw3DLine(0, 0, 0, 0, 0, 30f, Color.SolidRed);

                drv.EndScene();

                // if we requested to stop, we close the device
                if (worker.CancellationPending)
                {
                    dev.Close();
                }
            }
            // drop device
            dev.Drop();
        }
Exemplo n.º 31
0
        /// <summary>
        /// Létrehoz egy sizex*sizey méretű ablakot, windowCaption címmel és deviceType renderelési eszközzel.
        /// </summary>
        /// <param name="windowCaption">Ablak címe</param>
        /// <param name="sizex">Ablak szélessége</param>
        /// <param name="sizey">Ablak magassága</param>
        /// <param name="deviceType">A render eszköz típusa ("DriverType.OpenGL;" (OpenGL) vagy "DriverType.Direct3D8;"/"DriverType.Direct3D9;" (DirectX))</param>
        /// <param name="mapName">Betöltendő pálya neve a kiterjesztés nélkül (pl. "devmap")</param>
        /// <param name="pak0">A pak0 fájl neve (pl. "pak0" vagy "pack1")</param>
        /// <param name="pak1">A pak1 fájl neve (pl. "pak1" vagy "pack4")</param>
        /// <param name="pak2">A pak2 fájl neve (pl. "pak2" vagy "pack2")</param>
        public static void createScreen(string windowCaption, int sizex, int sizey, DriverType deviceType, string mapName, string pak0, string pak1, string pak2, bool isFullScreen)
        {
            //Ablakot megjeleníteni
            if (isFullScreen == true)
            {
                device = IrrlichtDevice.CreateDevice(deviceType, new Dimension2Di(sizex, sizey), 32, true, false, true);
            }
            else
            {
                device = IrrlichtDevice.CreateDevice(deviceType, new Dimension2Di(sizex, sizey), 32, false, false, true);
            }
            if (device == null)
                return;

            AnimatedMesh q3levelmesh = null;
            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            device.SetWindowCaption(Property.modName + " Build " + Property.modVersion);
            driver = device.VideoDriver;
            smgr = device.SceneManager;

            GUIEnvironment gui = device.GUIEnvironment;
            //fadein
            GUIInOutFader fader = device.GUIEnvironment.AddInOutFader();
            fader.SetColor(new Color(0, 0, 0, 255));
            fader.FadeIn(2000);
            //hurtOverlay = device.GUIEnvironment.AddImage(driver.GetTexture("./Content/2D/Overlays/hurt.png"), new Vector2Di(0, 0));
            //hurtOverlay.Visible = false;
            GUIImage copyrightScreen = device.GUIEnvironment.AddImage(driver.GetTexture("./Content/2D/exit.tga"), new Vector2Di(0, 0));
            float guiScalex = sizex / 800;
            float guiScaley = sizey / 600;
            copyrightScreen.Visible = false;
            copyrightScreen.ScaleImage = true;
            copyrightScreen.SetMaxSize(new Dimension2Di(sizex, sizey));
            copyrightScreen.SetMinSize(new Dimension2Di(sizex, sizey));
            //Betölteni a mapot
            try
            {
                device.FileSystem.AddFileArchive("./Content/PK3/" + pak0 + ".edsf");
            }
            catch (Exception ex)
            {
                Logger.Log("pak0 fajl betoltese sikertelen vagy nem talalhato, a jatek nem tud betoltodni");
                string error = ex.ToString();
                    Logger.Log(error);
                Environment.Exit(0);
            }
            try
            {
                device.FileSystem.AddFileArchive("./Content/PK3/" + pak1 + ".edsf");
            }
            catch (Exception ex)
            {
                Logger.Log("pak1 fajl betoltese sikertelen vagy nem talalhato, ignoralva");
                string error = ex.ToString();
                    Logger.Log(error);
            }
            try
            {
                device.FileSystem.AddFileArchive("./Content/PK3/" + pak2 + ".edsf");
            }
            catch (Exception ex)
            {
                Logger.Log("pak2 fajl betoltese sikertelen vagy nem talalhato, ignoralva");
                string error = ex.ToString();
                    Logger.Log(error);
            }
            try
            {
                q3levelmesh = smgr.GetMesh(mapName + ".bsp");
            }
            catch (Exception ex)
            {
                Logger.Log("Palya betoltese sikertelen vagy nem talalhato, a jatek nem tud betoltodni");
                string error = ex.ToString();
                Logger.Log(error);
                Environment.Exit(0);
            }
            MeshSceneNode q3node = null;
                q3node = smgr.AddOctreeSceneNode(q3levelmesh.GetMesh(0), null, IDFlag_IsPickable);
                q3node.Position = new Vector3Df(-1350, -130, -1400);
            SceneNode node = null;
            if (mapName == "rpg")
            {
                IsRPG = true;
            }
            //LightSceneNode light = smgr.AddLightSceneNode(q3node, new Vector3Df(-1319, -118, -1410), new Color(255, 255, 255), 600.0, 10);
            //Half-Life Headcrab
            AnimatedMeshSceneNode anode3 = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("./Content/3D/headcrab.mdl"));
            if (IsRPG)
            {
                anode3.Position = new Vector3Df(-1212, -180, -1346);
                Audio.playWave("./Content/Music/rpg.mp3");
            }
            else
            {
                anode3.Position = new Vector3Df(-1372.951f, -145.9882f, -1319.71f);
            }
            anode3.Rotation = new Vector3Df(0, 0, 0);
            anode3.AnimationSpeed = 1;
            Scenes.changeAnimation(anode3, 1, 31);
            anode3.SetMaterialFlag(MaterialFlag.Lighting, true);
            anode3.GetMaterial(0).NormalizeNormals = true;
            anode3.GetMaterial(0).Lighting = false;
            //Yodan
            anode2 = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("./Content/3D/yodan.mdl"));
            anode2.Position = new Vector3Df(-1355, -200, -1410);
            anode2.AnimationSpeed = 15;
            anode2.SetMaterialFlag(MaterialFlag.Lighting, true);
            anode2.GetMaterial(0).NormalizeNormals = true;
            anode2.GetMaterial(0).Lighting = false;
            anode2.SetTransitionTime(3);
               			Scenes.changeYodanAnimation(anode2, "idle");
            //SkyBox
            SceneNode skybox = smgr.AddSkyBoxSceneNode("./Contents/2D/Skybox/mountains_up.jpg", "./Contents/2D/Skybox/mountains_dn.jpg", "./Contents/2D/Skybox/mountains_lf.jpg", "./Contents/2D/Skybox/mountains_rt.jpg", "./Contents/2D/Skybox/mountains_ft.jpg", "./Contents/2D/Skybox/mountains_bk.jpg");
            skybox.Visible = true;
            //FPS kamera hozzáadása
            camera = smgr.AddCameraSceneNodeFPS();
            camera.Position = new Vector3Df(-1625.723f, -145.9937f, -1532.087f);
            camera.Target = new Vector3Df(-1491.555f, -1434.106f, -1368.737f);
            //fegyver
            AnimatedMesh weaponmesh = smgr.GetMesh("./Content/3D/blades.mdl");
            AnimatedMeshSceneNode weapon = smgr.AddAnimatedMeshSceneNode(weaponmesh, camera, 30);
            weapon.Scale = new Vector3Df(0.5f, 0.5f, 0.5f);
            weapon.Position = new Vector3Df(0, 0, 15);
            weapon.Rotation = new Vector3Df(0, -90, 0);
            Scenes.changeAnimation(weapon, 1, 1);
            weapon.Visible = true;
            //fizika
            TriangleSelector selector;
            selector = smgr.CreateOctreeTriangleSelector(q3levelmesh.GetMesh(0), q3node, 128);
            q3node.TriangleSelector = selector;
            anim = smgr.CreateCollisionResponseAnimator(selector, camera, new Vector3Df(30, 50, 30), new Vector3Df(0, -10, 0), new Vector3Df(0, 30, 0));
            //Overlay
            GUIImage overlay = device.GUIEnvironment.AddImage(driver.GetTexture("./Content/2D/Overlays/vignette.png"), new Vector2Di(0, 0));
            overlay.ScaleImage = true;
            overlay.SetMaxSize(new Dimension2Di(sizex, sizey));
            overlay.SetMinSize(new Dimension2Di(sizex, sizey));
            selector.Drop();
            camera.AddAnimator(anim);
            anim.Drop();
            // fény
            lightMovementHelperNode = smgr.AddEmptySceneNode();

            q3node = smgr.AddSphereSceneNode(2, 6, lightMovementHelperNode, -1, new Vector3Df(15, -10, 15));
            q3node.SetMaterialFlag(MaterialFlag.Lighting, false);

            lightNode = q3node;

            //A Portré
            anode = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("./Content/3D/portrait.mdl"));
            anode.Position = new Vector3Df(-1177.601f, -137.975f, -1238.015f);
            anode.Rotation = new Vector3Df(0,0,0);
            anode.Scale = new Vector3Df(3);
            anode.AnimationSpeed = 1500;
            anode.SetMaterialFlag(MaterialFlag.Lighting, true);
            anode.GetMaterial(0).NormalizeNormals = true;
            anode.GetMaterial(0).Lighting = false;

            AnimatedMeshSceneNode anode4 = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("./Content/3D/waiter.mdl"));
            anode4.Position = new Vector3Df(-1130, -375, -1724);
            anode4.Rotation = new Vector3Df(0, -90, 0);
            anode4.Scale = new Vector3Df(2, 2, 2);
            anode4.SetMaterialFlag(MaterialFlag.Lighting, false);
            Scenes.changeAnimation(anode4, 0, 1);

            //Egér elrejtése
            device.CursorControl.Visible = false;
            GUIFont font = device.GUIEnvironment.BuiltInFont;
            SceneCollisionManager collMan = smgr.SceneCollisionManager;
            TextSceneNode headcrabName = smgr.AddTextSceneNode(font, "Yodan Lebegö Headcrab-je <Level 10>", new Color(255, 255, 0), null, anode3.Position + new Vector3Df(0, 25, 0), 0);
            TextSceneNode waiterName = smgr.AddTextSceneNode(font, "John <Level 15>", new Color(0, 255, 0), null, anode4.Position + new Vector3Df(0, 125, 0), 0);
            uint then = device.Timer.Time;
            float MOVEMENT_SPEED = 100.0f;

            //Energiagömb
            /*AnimatedMeshSceneNode anode5 = smgr.AddAnimatedMeshSceneNode(smgr.GetMesh("./Content/3D/core.mdl"));
            anode5.Position = new Vector3Df(-1355, 0, -1410);
            Scenes.changeAnimation(anode5, 0, 90);
            anode5.Scale = new Vector3Df(2.0f);
            Line3Df coreray = new Line3Df(-1355, 0, -1410, -1355, -500, -1410);
            driver.SetMaterial(anode5.GetMaterial(1));
            driver.SetTransform(TransformationState.World, Matrix.Identity);
            driver.Draw3DLine(coreray, new Color(255,0,0));*/

            GUIImage bartenderForm = device.GUIEnvironment.AddImage(driver.GetTexture("./Content/2D/bartender.png"), new Vector2Di(10, 10));
            bartenderForm.ScaleImage = true;
            bartenderForm.Visible = false;
            bartenderForm.SetMinSize(new Dimension2Di(sizex - 10, sizey - 10));
            bartenderForm.SetMaxSize(new Dimension2Di(sizex - 10, sizey - 10));
            bool BartenderFormIsOpen = false;
            GUIImage ActionBar = device.GUIEnvironment.AddImage(driver.GetTexture("./Content/2D/Hud/Actionbar.tga"), new Vector2Di(0, 600 - 128));
            //330, 110  790, 120
            Recti expbarrect = new Recti();
            ExperienceBar expbar = new ExperienceBar(gui, expbarrect,0, ActionBar);
            expbar.SetProgress(0);
            expbar.SetColors(new Color(255, 255, 0), new Color(255, 255, 255));
            expbar.AddBorder(5, new Color(0, 0, 0));
            expbar.SetMinSize(new Dimension2Di(128, 64));
            expbar.SetMaxSize(new Dimension2Di(128, 64));
            //Mi minek a része
            q3node.AddChild(anode);
            q3node.AddChild(anode2);
            q3node.AddChild(anode3);
            q3node.AddChild(anode4);
            TextSceneNode yodanName = smgr.AddTextSceneNode(font, "Yodan a Bérgyilkos <Level 90>", new Color(255, 0, 0), null, anode2.Position + new Vector3Df(0, 50, 0), 0);
            while (device.Run())
            {
                driver.BeginScene(true, true, new Color(135, 206, 235));

                smgr.DrawAll();
                gui.DrawAll();
                string printDate = dateTime.ToShortTimeString();
                uint now = device.Timer.Time;
                float frameDeltaTime = (float)(now - then) / 1000.0f;
                then = now;
                Vector3Df nodePosition = camera.Position;
                if (font != null)
                {
                    /*font.Draw("Build " + Property.modVersion, 5, 5, new Color(0, 0, 255));
                    font.Draw("pos= " + camera.Position, 5, 578 - 16, new Color(0, 0, 255));
                    font.Draw("tar= " + camera.Target, 5, 594 - 16, new Color(0, 0, 255));*/
                    font.Draw(Player.Experience(), new Vector2Di(505, 582), new Color(0,0,0));
                }
                if (camera.Position.Z >= 10000)
                {
                    font.Draw("Kiestél a Világból!", new Vector2Di(400, 300), new Color (0, 0, 0));
                    camera.Position = anode.Position;
                }

                if (Quest1Done)
                {
                    yodanName.SetTextColor(new Color(255, 255, 0));
                }

                if (IsKeyDown(KeyCode.Space))
                {
                    nodePosition.Y += MOVEMENT_SPEED * frameDeltaTime;
                }
                else if (IsKeyDown(KeyCode.LControl))
                {
                    nodePosition.Y -= MOVEMENT_SPEED * frameDeltaTime;
                }
                if (IsKeyDown(KeyCode.LShift))
                {
                    MOVEMENT_SPEED = 200.0f;
                }
                else
                {
                    MOVEMENT_SPEED = 100.0f;
                }

                if (IsKeyDown(KeyCode.Esc))
                {
                    copyrightScreen.Visible = true;
                }
                if (IsKeyDown(KeyCode.KeyM))
                {
                    //Yodan.Run(new Vector3Df(-1642, -172, -1421), new Vector3Df(-1053, -167, -1416));
                }
                if (IsKeyDown(KeyCode.KeyB))
                {
                   // Yodan.Wave();

                   Scripting.RunScript(Scripting.LoadScript());
                }
                if (IsKeyDown(KeyCode.KeyV))
                {
                    //Yodan.Speak("./Content/Sound/vo/yodan/yo_20ft.mp3");
                }
                else if (IsKeyDown(KeyCode.KeyN))
                {
                    //Yodan.Stand();
                }
                else if (IsKeyDown(KeyCode.KeyC))
                {
                    //Yodan.WaveAndGreet();
                }
                //Actionbar START

                //Auto-Attack
                if (IsKeyDown(KeyCode.Key1))
                {
                    if (!AutoAttack)
                    {
                        Delay(100);
                        AutoAttack = true;
                        if (currentWeapon == 1)
                        {
                            Scenes.changeAnimation(weapon, 11 + 24 + 25, 11 + 24 + 25 + 31 + 30);
                        }
                        else if (currentWeapon == 2)
                        {
                            Scenes.changeAnimation(weapon, 91 + 31 + 81 + 31, 91 + 31 + 81 + 31+90);
                        }
                    }
                    else if (AutoAttack)
                    {
                        Delay(100);
                        AutoAttack = false;
                        if (currentWeapon == 1)
                        {
                            Scenes.changeAnimation(weapon, 1, 1);
                        }
                        else if (currentWeapon == 2)
                        {
                            Scenes.changeAnimation(weapon, 1, 90);
                        }

                    }
                }
                //Blades
                if (IsKeyDown(KeyCode.Key2))
                 {
                     AnimatedMesh bladesmesh = smgr.GetMesh("./Content/3D/blades.mdl");
                     weapon.Mesh = bladesmesh;
                     weapon.Scale = new Vector3Df(0.5f, 0.5f, 0.5f);
                     weapon.Position = new Vector3Df(0, 0, 15);
                     weapon.Rotation = new Vector3Df(0, -90, 0);
                     Scenes.changeAnimation(weapon, 1, 1);
                     currentWeapon = 1;
                 }
                 //Crossbow
                 if (IsKeyDown(KeyCode.Key3))
                 {
                     AnimatedMesh crossbowmesh = smgr.GetMesh("./Content/3D/crossbow.mdl");
                     weapon.Mesh = crossbowmesh;
                     Scenes.changeAnimation(weapon, 1, 90);
                     weapon.Scale = new Vector3Df(3.0f, 3.0f, 3.0f);
                     currentWeapon = 2;

                 }
                 if (IsKeyDown(KeyCode.Key4))
                 {
                     if (IsEtlapPickedUp)
                     {
                         bartenderForm.Visible = true;
                         BartenderFormIsOpen = true;
                         Audio.playWave("./Content/sound/paper_pickup.mp3");
                     }

                 }

                //Actionbar END

                //elteszi/előveszi a fegyvert
                if(IsKeyDown(KeyCode.Tab))
                {
                    if(weaponHolster)
                    {
                    weapon.Visible = false;
                    Audio.playWave("./Content/sound/weapon.mp3");
                    weaponHolster = false;
                    }
                    else
                    {
                    weapon.Visible = true;
                    Audio.playWave("./Content/sound/weapon.mp3");
                    weaponHolster = true;
                    }
                }
                if (IsKeyDown(KeyCode.MouseLButton))
                {
                    AutoAttack = true;
                    if (currentWeapon == 1)
                    {
                        Scenes.changeAnimation(weapon, 11 + 24 + 25, 11 + 24 + 25 + 31 + 30);
                    }
                    else if (currentWeapon == 2)
                    {
                        Scenes.changeAnimation(weapon, 91 + 31 + 81 + 31, 91 + 31 + 81 + 31 + 90);
                    }
                }
                else if (!IsKeyDown(KeyCode.MouseLButton))
                {
                    AutoAttack = false;
                    if (currentWeapon == 1)
                    {
                        Scenes.changeAnimation(weapon, 1, 1);
                    }
                    else if (currentWeapon == 2)
                    {
                        Scenes.changeAnimation(weapon, 1, 90);
                    }
                }

                if (IsKeyDown(KeyCode.KeyX))
                {
                    Texture yodanMissing = driver.GetTexture("./Content/2D/yodanmissing.tga");
                    Dimension2Di yodanMisSiz = yodanMissing.Size;
                    yodanMisSiz = anode.GetMaterial(0).GetTexture(0).Size;
                    anode.SetMaterialTexture(0, yodanMissing);
                }
                if (IsKeyDown(KeyCode.KeyE))
                {
                    //Bartender Johh On-Use
                    Vector3Df camtarget = camera.Target;
                    if (!BartenderFormIsOpen)
                    {
                        if (new Vector3Df(727, 221, -986) <= camtarget)
                        {
                            if (new Vector3Df(763, 276, -2329) >= camtarget)
                            {
                                if (camtarget > new Vector3Df(184, -1843, -1255))
                                {
                                    if (camtarget > new Vector3Df(138, -1837, -2318))
                                    {
                                        bartenderForm.Visible = true;
                                        BartenderFormIsOpen = true;
                                        if (!IsEtlapPickedUp)
                                        {
                                            ActionBar.Image = driver.GetTexture("./Content/2D/Hud/Actionbar_etlap.tga");
                                            Audio.playWave("./Content/sound/vo/waiter_john/teatime.mp3");
                                        }
                                        IsEtlapPickedUp = true;
                                        Audio.playWave("./Content/sound/paper_pickup.mp3");
                                    }
                                }
                            }
                        }
                    }
                    else if (BartenderFormIsOpen)
                    {
                        bartenderForm.Visible = false;
                        BartenderFormIsOpen = false;
                        Audio.playWave("./Content/sound/paper_pickup.mp3");
                    }
                }

                if (IsKeyDown(KeyCode.KeyK))
                {
                    //Yodan.GoGhost();
                }
                if (IsKeyDown(KeyCode.KeyJ))
                {
                    //Yodan.GoNormal();
                }
                if (IsKeyDown(KeyCode.KeyL))
                {

                }
                if (IsKeyDown(KeyCode.F7))
                {
                    Delay(500);
                    takeScreenshot(device);
                }
                if (IsKeyDown(KeyCode.F9))
                {
                    Delay(500);
                    string campos = camera.Position.ToString();
                    Logger.Log("position:" + campos);
                    string camtar = camera.Target.ToString();
                    Logger.Log("target: " + camtar);
                }
                if (IsKeyDown(KeyCode.LShift))
                {
                    if (IsKeyDown(KeyCode.KeyY))
                    {
                        Environment.Exit(0);
                    } else if (IsKeyDown(KeyCode.KeyN))
                    {
                        copyrightScreen.Visible = false;
                    }
                }

                camera.Position = nodePosition;
                driver.EndScene();
            }
            device.Drop();
        }
Exemplo n.º 32
0
        static void Main()
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            useHighLevelShaders = AskForHighLevelShaders(driverType.Value);

            device = IrrlichtDevice.CreateDevice(driverType.Value, new Dimension2Di(640, 480));
            if (device == null)
            {
                return;
            }

            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

            string vsFileName = null;             // filename for the vertex shader
            string psFileName = null;             // filename for the pixel shader

            switch (driverType)
            {
            case DriverType.Direct3D9:
                if (useHighLevelShaders)
                {
                    psFileName = "../../media/d3d9.hlsl";
                    vsFileName = psFileName;                             // both shaders are in the same file
                }
                else
                {
                    psFileName = "../../media/d3d9.psh";
                    vsFileName = "../../media/d3d9.vsh";
                }
                break;

            case DriverType.OpenGL:
                if (useHighLevelShaders)
                {
                    psFileName = "../../media/opengl.frag";
                    vsFileName = "../../media/opengl.vert";
                }
                else
                {
                    psFileName = "../../media/opengl.psh";
                    vsFileName = "../../media/opengl.vsh";
                }
                break;
            }

            if (!driver.QueryFeature(VideoDriverFeature.PixelShader_1_1) &&
                !driver.QueryFeature(VideoDriverFeature.ARB_FragmentProgram_1))
            {
                device.Logger.Log("WARNING: Pixel shaders disabled because of missing driver/hardware support.");
                psFileName = null;
            }

            if (!driver.QueryFeature(VideoDriverFeature.VertexShader_1_1) &&
                !driver.QueryFeature(VideoDriverFeature.ARB_VertexProgram_1))
            {
                device.Logger.Log("WARNING: Vertex shaders disabled because of missing driver/hardware support.");
                vsFileName = null;
            }

            // create materials

            GPUProgrammingServices gpu = driver.GPUProgrammingServices;
            MaterialType           newMaterialType1 = MaterialType.Solid;
            MaterialType           newMaterialType2 = MaterialType.TransparentAddColor;

            if (gpu != null && vsFileName != null && psFileName != null)
            {
                gpu.OnSetConstants += gpu_OnSetConstants;

                // create the shaders depending on if the user wanted high level or low level shaders

                if (useHighLevelShaders)
                {
                    newMaterialType1 = gpu.AddHighLevelShaderMaterialFromFiles(
                        vsFileName, "vertexMain", VertexShaderType.VS_1_1,
                        psFileName, "pixelMain", PixelShaderType.PS_1_1,
                        MaterialType.Solid);

                    newMaterialType2 = gpu.AddHighLevelShaderMaterialFromFiles(
                        vsFileName, "vertexMain", VertexShaderType.VS_1_1,
                        psFileName, "pixelMain", PixelShaderType.PS_1_1,
                        MaterialType.TransparentAddColor);
                }
                else
                {
                    // create material from low level shaders (asm or arb_asm)

                    newMaterialType1 = gpu.AddShaderMaterialFromFiles(vsFileName, psFileName, MaterialType.Solid);
                    newMaterialType2 = gpu.AddShaderMaterialFromFiles(vsFileName, psFileName, MaterialType.TransparentAddColor);
                }
            }

            if ((int)newMaterialType1 == -1)
            {
                newMaterialType1 = MaterialType.Solid;
            }

            if ((int)newMaterialType2 == -1)
            {
                newMaterialType1 = MaterialType.TransparentAddColor;
            }

            // create test scene node 1, with the new created material type 1

            SceneNode node = smgr.AddCubeSceneNode(50);

            node.Position = new Vector3Df(0);
            node.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp"));
            node.SetMaterialFlag(MaterialFlag.Lighting, false);
            node.SetMaterialType(newMaterialType1);

            smgr.AddTextSceneNode(device.GUIEnvironment.BuiltInFont, "PS & VS & EMT_SOLID", new Color(255, 255, 255), node);

            SceneNodeAnimator anim = smgr.CreateRotationAnimator(new Vector3Df(0, 0.3f, 0));

            node.AddAnimator(anim);
            anim.Drop();

            // create test scene node 2, with the new created material type 2

            node          = smgr.AddCubeSceneNode(50);
            node.Position = new Vector3Df(0, -10, 50);
            node.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp"));
            node.SetMaterialFlag(MaterialFlag.Lighting, false);
            node.SetMaterialFlag(MaterialFlag.BlendOperation, true);
            node.SetMaterialType(newMaterialType2);

            smgr.AddTextSceneNode(device.GUIEnvironment.BuiltInFont, "PS & VS & EMT_TRANSPARENT", new Color(255, 255, 255), node);

            anim = smgr.CreateRotationAnimator(new Vector3Df(0, 0.3f, 0));
            node.AddAnimator(anim);
            anim.Drop();

            // create test scene node 3, with no shader

            node          = smgr.AddCubeSceneNode(50);
            node.Position = new Vector3Df(0, 50, 25);
            node.SetMaterialTexture(0, driver.GetTexture("../../media/wall.bmp"));
            node.SetMaterialFlag(MaterialFlag.Lighting, false);

            smgr.AddTextSceneNode(device.GUIEnvironment.BuiltInFont, "NO SHADER", new Color(255, 255, 255), node);

            // add a nice skybox

            driver.SetTextureCreationFlag(TextureCreationFlag.CreateMipMaps, false);

            smgr.AddSkyBoxSceneNode(
                "../../media/irrlicht2_up.jpg",
                "../../media/irrlicht2_dn.jpg",
                "../../media/irrlicht2_lf.jpg",
                "../../media/irrlicht2_rt.jpg",
                "../../media/irrlicht2_ft.jpg",
                "../../media/irrlicht2_bk.jpg");

            driver.SetTextureCreationFlag(TextureCreationFlag.CreateMipMaps, true);

            // add a camera and disable the mouse cursor

            CameraSceneNode cam = smgr.AddCameraSceneNodeFPS();

            cam.Position = new Vector3Df(-100, 50, 100);
            cam.Target   = new Vector3Df(0);

            device.CursorControl.Visible = false;

            // draw everything

            int lastFPS = -1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    driver.BeginScene(ClearBufferFlag.All, new Color(0));
                    smgr.DrawAll();
                    driver.EndScene();

                    int fps = driver.FPS;
                    if (lastFPS != fps)
                    {
                        device.SetWindowCaption(String.Format(
                                                    "Vertex and pixel shader example - Irrlicht Engine [{0}] fps: {1}",
                                                    driver.Name, fps));

                        lastFPS = fps;
                    }
                }
            }

            device.Drop();
        }