Beispiel #1
0
        public void Run()
        {
            while (device.Run())
            {
                if (OnUpdate != null)
                {
                    OnUpdate();
                }

                sphere.Rotation += new Vector3Df(0, 1, 0);

                device.SetWindowCaption(Driver.FPS.ToString());

                //collision

                selectionCube.Position = _cam.Intersection;


                Driver.BeginScene(true, true, new Color(110, 60, 50));

                Scene.DrawAll();
                Gui.DrawAll();

                Driver.EndScene();

                device.Yield();
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(
                DriverType.OpenGL, new Dimension2Di(640, 480), 16, false, false, false);

            device.SetWindowCaption("testing irrlicht engine lol");

            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);

            smgr.AddCameraSceneNode(null, new Vector3Df(0, 30, -40), new Vector3Df(0, 5, 0));

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

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

                driver.EndScene();
            }

            device.Drop();
        }
Beispiel #3
0
        static void Main()
        {
            device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(1280, 768));             // minimum: 1024 (which is 16x64) x 768 (which is 16x48)
            if (device == null)
            {
                return;
            }

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

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

            Texture pathfindingTexture = driver.GetTexture("../../media/pathfinding.png");
            int     cellSize           = pathfindingTexture.Size.Height;

            pathfinding = new Pathfinding(64, 48, cellSize, 0, 0);
            pathfinding.SetCell(4, 4, Pathfinding.CellType.Start);
            pathfinding.SetCell(pathfinding.Width - 5, pathfinding.Height - 5, Pathfinding.CellType.Finish);

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

                pathfinding.FindPath();
                pathfinding.Draw(driver, pathfindingTexture);

                // draw info panel

                Vector2Di v = new Vector2Di(pathfinding.Width * pathfinding.CellSize + 20, 20);
                font.Draw("FPS: " + driver.FPS, v, fontNormalColor);

                v.Y += 32;
                font.Draw("Map size: " + pathfinding.Width + " x " + pathfinding.Height, v, fontNormalColor);
                v.Y += 16;
                font.Draw("Shortest path: " + (pathfinding.PathLength == -1 ? "N/A" : pathfinding.PathLength.ToString()), v, fontNormalColor);
                v.Y += 16;
                font.Draw("Calculation time: " + pathfinding.PathCalcTimeMs + " ms", v, fontNormalColor);

                v.Y += 32;
                font.Draw(workMode ? "[LMB] Set cell impassable" : "[LMB] Set Start cell", v, fontActionColor);
                v.Y += 16;
                font.Draw(workMode ? "[RMB] Set cell passable" : "[RMB] Set Finish cell", v, fontActionColor);
                v.Y += 16;
                font.Draw("[Space] Change mode", v, fontActionColor);

                v.Y += 32;
                font.Draw("[F1] Clean up the map", v, fontActionColor);
                v.Y += 16;
                font.Draw("[F2] Add random blocks", v, fontActionColor);

                driver.EndScene();
            }

            device.Drop();
        }
Beispiel #4
0
		static void Main(string[] args)
		{
			device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(1280, 768));
			if (device == null)
				return;

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

			VideoDriver driver = device.VideoDriver;
			GUIFont font = device.GUIEnvironment.GetFont("../../media/fontlucida.png");
			Color fontNormalColor = Color.OpaqueWhite;
			Color fontActionColor = Color.OpaqueYellow;

			Texture pathfindingTexture = driver.GetTexture("../../media/pathfinding.png");
			int cellSize = pathfindingTexture.Size.Height;
			pathfinding = new Pathfinding(64, 48, cellSize, 0, 0);
			pathfinding.SetCell(4, 4, Pathfinding.CellType.Start);
			pathfinding.SetCell(pathfinding.Width - 5, pathfinding.Height - 5, Pathfinding.CellType.Finish);

			while (device.Run())
			{
				driver.BeginScene(true, false);

				pathfinding.FindPath();
				pathfinding.Draw(driver, pathfindingTexture);

				// draw info panel

				Vector2Di v = new Vector2Di(pathfinding.Width * pathfinding.CellSize + 20, 20);
				font.Draw("FPS: " + driver.FPS, v, fontNormalColor);

				v.Y += 32;
				font.Draw("Map size: " + pathfinding.Width + " x " + pathfinding.Height, v, fontNormalColor);
				v.Y += 16;
				font.Draw("Shortest path: " + (pathfinding.PathLength == -1 ? "N/A" : pathfinding.PathLength.ToString()), v, fontNormalColor);
				v.Y += 16;
				font.Draw("Calculation time: " + pathfinding.PathCalcTimeMs + " ms", v, fontNormalColor);

				v.Y += 32;
				font.Draw(workMode ? "[LMB] Set cell impassable" : "[LMB] Set Start cell", v, fontActionColor);
				v.Y += 16;
				font.Draw(workMode ? "[RMB] Set cell passable" : "[RMB] Set Finish cell", v, fontActionColor);
				v.Y += 16;
				font.Draw("[Space] Change mode", v, fontActionColor);

				v.Y += 32;
				font.Draw("[F1] Clean up the map", v, fontActionColor);
				v.Y += 16;
				font.Draw("[F2] Add random blocks", v, fontActionColor);

				driver.EndScene();
			}

			device.Drop();
		}
Beispiel #5
0
    void runIrrlichtInWindowsFormTest()
    {
        // testing irrlicht running embedded in a windows form

        System.Windows.Forms.Form f = new System.Windows.Forms.Form();
        f.Text = "Irrlicht running embedded in Windows.Form";

        device = new IrrlichtDevice(SelectedDriverType,
                                    new Dimension2D(800, 600), 16, false, false, false, true, f.Handle);

        f.Show();

        // set up a simple scene

        ICameraSceneNode cam =
            device.SceneManager.AddCameraSceneNode(null, new Vector3D(), new Vector3D(), -1);

        ISceneNodeAnimator anim = device.SceneManager.CreateFlyCircleAnimator(
            new Vector3D(0, 10, 0), 30.0f, 0.003f);

        cam.AddAnimator(anim);

        ISceneNode cube = device.SceneManager.AddCubeSceneNode(25, null, -1, new Vector3D());

        cube.SetMaterialTexture(0, device.VideoDriver.GetTexture("../../media/rockwall.bmp"));
        cube.SetMaterialFlag(Irrlicht.Video.MaterialFlag.LIGHTING, false);

        // draw everything

        device.Run();         // fix for a temporary bug where quit messages are not be removed in the queue
        while (device.Run() && f.Visible)
        {
            if (device.WindowActive)
            {
                device.VideoDriver.BeginScene(true, true, new Color(255, 0, 0, 50));

                device.SceneManager.DrawAll();
                device.GUIEnvironment.DrawAll();

                device.VideoDriver.EndScene();
            }
        }
    }
        public void render_scene()
        {
            _device.Run();

            _driver.BeginScene(true, true, Color.Gray);


            _scene.DrawAll();

            _driver.EndScene();
        }
Beispiel #7
0
        static void Main()
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(800, 600));

            device.SetWindowCaption("RGB swirl example - Irrlicht Lime");

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

            var camera = scene.AddCameraSceneNode(null, new Vector3Df(0, 0, -15), new Vector3Df());

            camera.ViewMatrixAffector = camera.ProjectionMatrix.GetInverse();

            var lightRed = scene.AddLightSceneNode(null, new Vector3Df(0, 40, 0));

            lightRed.LightData.DiffuseColor = new Colorf(1, 0, 0);
            var a = scene.CreateFlyCircleAnimator(new Vector3Df(), 40, 0.0003f, new Vector3Df(0, 0, 1), 0.000f);

            lightRed.AddAnimator(a);
            a.Drop();

            var lightGreen = scene.AddLightSceneNode(null, new Vector3Df(-30, -20, 0));

            lightGreen.LightData.DiffuseColor = new Colorf(0, 1, 0);
            a = scene.CreateFlyCircleAnimator(new Vector3Df(), 40, 0.0003f, new Vector3Df(0, 0, 1), 0.333f);
            lightGreen.AddAnimator(a);
            a.Drop();

            var lightBlue = scene.AddLightSceneNode(null, new Vector3Df(30, -20, 0));

            lightBlue.LightData.DiffuseColor = new Colorf(0, 0, 1);
            a = scene.CreateFlyCircleAnimator(new Vector3Df(), 40, 0.0003f, new Vector3Df(0, 0, 1), 0.667f);
            lightBlue.AddAnimator(a);
            a.Drop();

            var node = scene.AddSphereSceneNode(5.5f, 255);

            node.SetMaterialFlag(MaterialFlag.BackFaceCulling, false);
            node.SetMaterialFlag(MaterialFlag.PointCloud, true);
            node.GetMaterial(0).Thickness = 4;

            while (device.Run())
            {
                node.Rotation = new Vector3Df(device.Timer.Time / 1, device.Timer.Time / 2, device.Timer.Time / 3);

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

            device.Drop();
        }
Beispiel #8
0
        static void Main()
        {
            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.SolidYellow);
                font.Draw("Press [RMB] on Earth to place new path point", 10, 20, Color.SolidYellow);
                font.Draw("Press [R] to reload path data from file", 10, 30, Color.SolidYellow);
                font.Draw("Press [C] to clean up", 10, 40, Color.SolidYellow);

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

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

            path.Drop();
            device.Drop();
        }
Beispiel #9
0
        static void Main()
        {
            device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(1280, 720));
            if (device == null)
            {
                return;
            }

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

            device.SetWindowCaption("Abstract Trace - Irrlicht Engine");
            device.OnEvent += Device_OnEvent;

            GUIFont font      = device.GUIEnvironment.GetFont("../../media/fontlucida.png");
            Color   textColor = Color.SolidWhite;

            CameraSceneNode camera = scene.AddCameraSceneNode();

            camera.FarValue = 20000;
            SceneNodeAnimator a = scene.CreateFlyCircleAnimator(new Vector3Df(), (AbstractTrace.CubeSize * AbstractTrace.GridDim) / 1.25f, 0.000025f, new Vector3Df(0.1f, 1, 0));

            camera.AddAnimator(a);
            a.Drop();

            trace = new AbstractTrace(device);
            trace.Init();

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

                if (!isPaused)
                {
                    trace.Step();
                }

                trace.Draw(drawGenerator);

                font.Draw("[G]enerator: " + (drawGenerator ? "ON" : "OFF"), new Vector2Di(20, 20), textColor);
                font.Draw("[P]ause: " + (isPaused ? "ON" : "OFF"), new Vector2Di(20, 35), textColor);
                font.Draw("Cubes: " + trace.GetTotalCubeCount(), new Vector2Di(20, 50), textColor);
                font.Draw("FPS: " + driver.FPS, new Vector2Di(20, 65), textColor);

                driver.EndScene();
            }

            trace.Drop();
            device.Drop();
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            int  N = AskUserForN();
            bool B = AskUserForB();

            DriverType driverType;

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

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

            if (device == null)
            {
                return;
            }

            device.CursorControl.Visible = false;

            CameraSceneNode camera = device.SceneManager.AddCameraSceneNodeFPS();

            camera.FarValue = 20000;
            camera.Position = new Vector3Df(-200);
            camera.Target   = new Vector3Df(0);

            MeshBuffersBatch batch = new MeshBuffersBatch(device, N, B);

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

                device.SceneManager.DrawAll();

                batch.Draw();

                device.VideoDriver.EndScene();

                device.SetWindowCaption(
                    "Fast static rendering - Irrlicht Lime - " +
                    device.VideoDriver.Name + " | " +
                    device.VideoDriver.FPS + " fps | " +
                    N * N * N + " cubes  | " +
                    device.VideoDriver.PrimitiveCountDrawn + " primitives | " +
                    MemUsageText + " of physical memory used");
            }

            batch.Drop();
            device.Drop();
        }
Beispiel #11
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();
		}
Beispiel #12
0
        static void Main()
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(512, 512));

            device.SetWindowCaption("Screenshot to texture - Irrlicht Lime");

            // set up very simple scene {{

            CameraSceneNode cam = device.SceneManager.AddCameraSceneNode();

            cam.Target = new Vector3Df(0);

            SceneNodeAnimator anim = device.SceneManager.CreateFlyCircleAnimator(new Vector3Df(0, 16, 0), 30, 0.0004f);

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

            SceneNode cube = device.SceneManager.AddCubeSceneNode(20);

            cube.SetMaterialFlag(MaterialFlag.Lighting, false);

            // }}

            while (device.Run())
            {
                cube.SetMaterialTexture(0, null);
                device.VideoDriver.RemoveAllTextures();

                Texture t = getDesktopTexture(device);
                cube.SetMaterialTexture(0, t);

                device.VideoDriver.BeginScene(ClearBufferFlag.Depth);

                device.VideoDriver.Draw2DImage(t, device.VideoDriver.ViewPort, new Recti(new Vector2Di(0), t.Size));
                device.VideoDriver.Draw2DRectangle(device.VideoDriver.ViewPort, new IrrlichtLime.Video.Color(0, 0, 0, 160));

                device.SceneManager.DrawAll();

                device.GUIEnvironment.BuiltInFont.Draw(
                    device.Timer.ToString() +
                    "\nMemory: " + (System.Diagnostics.Process.GetCurrentProcess().WorkingSet64 / (1 << 20)).ToString() + " Mb" +
                    "\nFPS: " + device.VideoDriver.FPS.ToString(),
                    new Vector2Di(16),
                    new IrrlichtLime.Video.Color(255, 255, 255));

                device.VideoDriver.EndScene();
            }

            device.Drop();
        }
Beispiel #13
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();
		}
Beispiel #14
0
        static void Main(string[] args)
        {
            device = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(1024, 600));
            device.SetWindowCaption("LightningShots - Irrlicht Engine");
            VideoDriver  driver = device.VideoDriver;
            SceneManager smgr   = device.SceneManager;

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

            AnimatedMesh  mesh = smgr.GetMesh("20kdm2.bsp");
            MeshSceneNode node = smgr.AddMeshSceneNode(mesh.GetMesh(0));

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

            node.SetMaterialType(MaterialType.LightMapLightingM4);
            node.SetMaterialFlag(MaterialFlag.Lighting, true);

            node.TriangleSelector = smgr.CreateTriangleSelector(node.Mesh, node);
            node.TriangleSelector.Drop();

            smgr.AmbientLight = new Colorf(0.15f, 0.14f, 0.13f);

            CameraSceneNode camera = smgr.AddCameraSceneNodeFPS();

            lightningShot   = new LightningShot(smgr, node.TriangleSelector);
            device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
            device.CursorControl.Visible = false;

            while (device.Run())
            {
                driver.BeginScene(true, true, new Color(100, 80, 75));

                smgr.DrawAll();

                lightningShot.Draw(device.Timer.Time);

                GUIFont f = device.GUIEnvironment.BuiltInFont;
                f.Draw("Use [LMB] to shoot", 10, 10, Color.OpaqueYellow);
                f.Draw("Total lightnings: " + lightningShot.TotalLightnings, 10, 20, Color.OpaqueWhite);
                f.Draw("Total shots: " + lightningShot.TotalShots, 10, 30, Color.OpaqueWhite);
                f.Draw(driver.FPS + " fps", 10, 40, Color.OpaqueWhite);

                driver.EndScene();
            }

            lightningShot.Drop();
            device.Drop();
        }
Beispiel #15
0
		static void Main(string[] args)
		{
			device = IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(1024, 600));
			device.SetWindowCaption("LightningShots - Irrlicht Engine");
			VideoDriver driver = device.VideoDriver;
			SceneManager smgr = device.SceneManager;

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

			AnimatedMesh mesh = smgr.GetMesh("20kdm2.bsp");
			MeshSceneNode node = smgr.AddMeshSceneNode(mesh.GetMesh(0));
			node.Position = new Vector3Df(-1300, -144, -1249);
			
			node.SetMaterialType(MaterialType.LightMapLightingM4);
			node.SetMaterialFlag(MaterialFlag.Lighting, true);

			node.TriangleSelector = smgr.CreateTriangleSelector(node.Mesh, node);
			node.TriangleSelector.Drop();

			smgr.AmbientLight = new Colorf(0.15f, 0.14f, 0.13f);

			CameraSceneNode camera = smgr.AddCameraSceneNodeFPS();

			lightningShot = new LightningShot(smgr, node.TriangleSelector);
			device.OnEvent += new IrrlichtDevice.EventHandler(device_OnEvent);
			device.CursorControl.Visible = false;

			while (device.Run())
			{
				driver.BeginScene(true, true, new Color(100, 80, 75));

				smgr.DrawAll();

				lightningShot.Draw(device.Timer.Time);

				GUIFont f = device.GUIEnvironment.BuiltInFont;
				f.Draw("Use [LMB] to shoot", 10, 10, Color.OpaqueYellow);
				f.Draw("Total lightnings: " + lightningShot.TotalLightnings, 10, 20, Color.OpaqueWhite);
				f.Draw("Total shots: " + lightningShot.TotalShots, 10, 30, Color.OpaqueWhite);
				f.Draw(driver.FPS + " fps", 10, 40, Color.OpaqueWhite);

				driver.EndScene();
			}

			lightningShot.Drop();
			device.Drop();
		}
Beispiel #16
0
        static void Main(string[] args)
        {
            IrrlichtDevice device =
                IrrlichtDevice.CreateDevice(DriverType.OpenGL, new Dimension2Di(640, 480), 16, false);

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

            smgr.AddCameraSceneNode(null, new Vector3Df(0, -40, 0), new Vector3Df(0));

            CSampleSceneNode myNode = new CSampleSceneNode(smgr.RootNode, smgr, 667);

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

            if (anim != null)
            {
                myNode.AddAnimator(anim);
                anim.Drop();
                anim = null;
            }

            myNode.Drop();
            myNode = null;

            int frames = 0;

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

                if (++frames == 100)
                {
                    device.SetWindowCaption(String.Format(
                                                "Custom Scene Node - Irrlicht Engine [{0}] fps: {1}",
                                                driver.Name, driver.FPS));

                    frames = 0;
                }
            }

            device.Drop();
        }
Beispiel #17
0
        static void Main(string[] args)
        {
            device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(1280, 720));
            if (device == null)
            {
                return;
            }

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

            CameraSceneNode camera = scene.AddCameraSceneNode();

            camera.FarValue = 20000;
            SceneNodeAnimator a = scene.CreateFlyCircleAnimator(new Vector3Df(), (AbstractTrace.CubeSize * AbstractTrace.GridDim) / 1.25f, 0.000025f, new Vector3Df(0.1f, 1, 0));

            camera.AddAnimator(a);
            a.Drop();

            trace = new AbstractTrace(device);
            trace.Init();

            int lastFps = -1;

            while (device.Run())
            {
                driver.BeginScene();
                scene.DrawAll();
                trace.Step();
                trace.Draw();
                driver.EndScene();

                int fps = driver.FPS;
                if (fps != lastFps)
                {
                    device.SetWindowCaption("Abstract Trace - Irrlicht Engine [" + fps + " fps; " + trace.GetTotalCubeCount() + " cubes]");
                    lastFps = fps;
                }
            }

            trace.Drop();
            device.Drop();
        }
Beispiel #18
0
 /// <summary>
 /// Starts the Irrlicht rendering loop.
 /// </summary>
 /// <param name="c">The <see cref="Control"/> that Irrlicht is running in.</param>
 private void RunDevice(Control c)
 {
     if (model == null)
     {
         LoadModel(path + startupModelFile);
     }
     while (!paused && !quitting && device.Run() && device.VideoDriver != null)
     {
         device.VideoDriver.BeginScene(true, true, new Irrlicht.Video.Color(150, 50, 50, 50));
         device.SceneManager.DrawAll();
         device.GUIEnvironment.DrawAll();
         core.Position2D logoLocation = new core.Position2D(c.ClientRectangle.Left + 20, c.ClientRectangle.Bottom - 40);
         device.VideoDriver.Draw2DImage(irrLogo, logoLocation);
         device.VideoDriver.EndScene();
         if (!quitting && !paused)
         {
             txtFPS.Text = device.VideoDriver.FPS + " FPS";
         }
     }
 }
Beispiel #19
0
		static void Main(string[] args)
		{
			device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, new Dimension2Di(1280, 720));
			if (device == null)
				return;

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

			CameraSceneNode camera = scene.AddCameraSceneNode();
			camera.FarValue = 20000;
			SceneNodeAnimator a = scene.CreateFlyCircleAnimator(new Vector3Df(), (AbstractTrace.CubeSize * AbstractTrace.GridDim) / 1.25f, 0.000025f, new Vector3Df(0.1f, 1, 0));
			camera.AddAnimator(a);
			a.Drop();

			trace = new AbstractTrace(device);
			trace.Init();

			int lastFps = -1;
			while (device.Run())
			{
				driver.BeginScene();
				scene.DrawAll();
				trace.Step();
				trace.Draw();
				driver.EndScene();

				int fps = driver.FPS;
				if (fps != lastFps)
				{
					device.SetWindowCaption("Abstract Trace - Irrlicht Engine [" + fps + " fps; " + trace.GetTotalCubeCount() + " cubes]");
					lastFps = fps;
				}
			}

			trace.Drop();
			device.Drop();
		}
Beispiel #20
0
        private static void Main()
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(
                DriverType.OpenGL, new Dimension2Di(640, 480), 16, false, false, false);

            device.SetWindowCaption("Rockplanets BUILD 16 (DEBUG MODE)");

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

            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(20f);

            cube.SetMaterialFlag(MaterialFlag.Lighting, false);



            while (device.Run())
            {
                driver.BeginScene(ClearBufferFlag.All, new Color(235, 235, 235));

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

                driver.EndScene();
            }

            device.Drop();
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(
                DriverType.Software, new Dimension2Di(640, 480), 16, false, false, false);

            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 node = smgr.AddAnimatedMeshSceneNode(mesh);
            //
            //          if (node != null)
            //          {
            //              node.SetMaterialFlag(MaterialFlag.Lighting, false);
            //              node.SetMD2Animation(AnimationTypeMD2.Stand);
            //              node.SetMaterialTexture(0, driver.GetTexture("../../media/sydney.bmp"));
            //          }

            smgr.AddCameraSceneNode(null, new Vector3Df(0, 30, -40), new Vector3Df(0, 5, 0));

            while (device.Run())
            {
                driver.BeginScene(true, true, new Color(100, 101, 140));

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

                driver.EndScene();
            }

            device.Drop();
        }
Beispiel #22
0
        void runIrrlichtInWindowsFormTest(Control c)
        {
            device = new IrrlichtDevice(Irrlicht.Video.DriverType.DIRECT3D9,
                                        new Dimension2D(c.Width, c.Height),
                                        32, false, false, false, true, c.Handle);
            ICameraSceneNode   cam  = device.SceneManager.AddCameraSceneNode(null, new Vector3D(), new Vector3D(), -1);
            ISceneNodeAnimator anim = device.SceneManager.CreateFlyCircleAnimator(new Vector3D(0, 10, 0), 30.0f, 0.003f);

            cam.AddAnimator(anim);
            ISceneNode cube = device.SceneManager.AddTestSceneNode(25, null, -1, new Vector3D());

            cube.SetMaterialTexture(0, device.VideoDriver.GetTexture("../../../media/rockwall.bmp"));
            cube.SetMaterialFlag(MaterialFlag.LIGHTING, false);
            // draw everything
            // Note, using device.WindowActive will not work on a control, since we don't
            // really activate controls..
            while (device.Run() && c.Enabled)
            {
                device.VideoDriver.BeginScene(true, true, new Irrlicht.Video.Color(255, 0, 0, 50));
                device.SceneManager.DrawAll();
                device.GUIEnvironment.DrawAll();
                device.VideoDriver.EndScene();
            }
        }
Beispiel #23
0
        static void Main()
        {
            IrrlichtDevice device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9);

            device.SetWindowCaption("Analogue Clock - Irrlicht Lime");
            device.CursorControl.Visible = false;

            ClockNode.AddClockNode(device.SceneManager.RootNode);

            CameraSceneNode camera = device.SceneManager.AddCameraSceneNodeFPS(null, 100, 0.1f);

            camera.Position = new Vector3Df(40, -20, -100); // start up position
            camera.Target   = new Vector3Df();              // prev position change has also moved target, so we update it

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

                device.SceneManager.DrawAll();

                string s = string.Format(
                    "{0}\n{1}\n{2}\n{3} tris\n{4} fps",
                    device.Timer.RealTimeAndDate,
                    device.VideoDriver.VendorInfo,
                    device.VideoDriver.Name,
                    device.VideoDriver.PrimitiveCountDrawn,
                    device.VideoDriver.FPS);

                device.GUIEnvironment.BuiltInFont.Draw(s, 11, 11, new Color(0, 0, 0));
                device.GUIEnvironment.BuiltInFont.Draw(s, 10, 10, new Color(255, 255, 255));

                device.VideoDriver.EndScene();
            }

            device.Drop();
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            DriverType?driverType = AskForDriver();

            if (!driverType.HasValue)
            {
                return;
            }

            device = IrrlichtDevice.CreateDevice(driverType.Value, 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, 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(ClearBufferFlag.All, 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();
        }
        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(false);

                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();
        }
Beispiel #26
0
        static void Main(string[] args)
        {
            // start up the engine

            IrrlichtDevice device = new IrrlichtDevice(DriverType.OPENGL);

            device.ResizeAble = true;
            device.WindowCaption = "Irrlicht.NET C# example 01 - Hello World";

            // load some textures

            ITexture texSydney = device.VideoDriver.GetTexture(@"..\..\media\sydney.bmp");
            ITexture texWall = device.VideoDriver.GetTexture(@"..\..\media\wall.bmp");
            ITexture texLogo = device.VideoDriver.GetTexture(@"..\..\media\irrlichtlogoaligned.jpg");

            // load the animated mesh of sydney

            Irrlicht.Scene.IAnimatedMesh mesh =
                device.SceneManager.GetMesh(@"..\..\media\sydney.md2");

            if (mesh == null)
            {
                System.Windows.Forms.MessageBox.Show(
                    @"Could not load mesh ..\..\media\sydney.md2, exiting.",
                    "Problem starting program");
                return;
            }

            // add a camera, a test scene node and the animated mesh to the scene

            ICameraSceneNode cam =
                device.SceneManager.AddCameraSceneNodeFPS(null, 100, 100, -1);
            cam.Position = new Vector3D(20,0,-50);

            ISceneNode node = device.SceneManager.AddCubeSceneNode(15,
                null, -1, new Vector3D(30,-15,0));
            node.SetMaterialTexture(0, texWall);

            node = device.SceneManager.AddAnimatedMeshSceneNode(mesh, null, -1);
            node.SetMaterialTexture(0, texSydney);
            node.SetMaterialFlag(MaterialFlag.LIGHTING, false);

            // make cursor invisible
            device.CursorControl.Visible = false;

            // start drawing loop

            int fps = 0;

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

                    device.SceneManager.DrawAll();

                    // draw the logo
                    device.VideoDriver.Draw2DImage(
                        texLogo, new Position2D(10,10),
                        new Rect(0,0,88,31),
                        new Rect(new Position2D(0,0),device.VideoDriver.ScreenSize),
                        new Color(0xffffff), false);

                    device.VideoDriver.EndScene();

                    if (fps != device.VideoDriver.FPS)
                    {
                        fps = device.VideoDriver.FPS;
                        device.WindowCaption = "Irrlicht.NET C# example 01 - Hello World ["+
                            device.VideoDriver.Name + "] fps:" + fps;
                    }
                }
            } // end drawing-loop
        }
Beispiel #27
0
 public void run()
 {
     // ask user for driver
     DriverType driverType;
     // Ask user to select driver:
     StringBuilder sb = new StringBuilder();
     sb.Append("Please select the driver you want for this example:\n");
     sb.Append("\n(a) Direct3D 9.0c\n(b) Direct3D 8.1\n(c) OpenGL 1.5");
     sb.Append("\n(d) Software Renderer\n(e) Apfelbaum Software Renderer");
     sb.Append("\n(f) Null Device\n(otherKey) exit\n\n");
     // Get the user's input:
     TextReader tIn = Console.In;
     TextWriter tOut = Console.Out;
     tOut.Write(sb.ToString());
     string input = tIn.ReadLine();
     // Select device based on user's input:
     switch (input)
     {
         case "a":
             driverType = DriverType.DIRECT3D9;
             break;
         case "b":
             driverType = DriverType.DIRECT3D8;
             break;
         case "c":
             driverType = DriverType.OPENGL;
             break;
         case "d":
             driverType = DriverType.SOFTWARE;
             break;
         case "e":
             driverType = DriverType.SOFTWARE2;
             break;
         case "f":
             driverType = DriverType.NULL_DRIVER;
             break;
         default:
             return;
     }
     // Create device and exit if creation fails:
     device = new IrrlichtDevice(driverType, new Dimension2D(1024, 768), 32, false, true, true);
     if (device == null)
     {
         tOut.Write("Device creation failed.");
         return;
     }
     /* set this as event receiver*/
     device.EventReceiver = this;
     /*
     Get a pointer to the video driver and the SceneManager so that
     we do not always have to write device.VideoDriver and
     device.SceneManager and device.GUIEnvironment.
     */
     ISceneManager smgr = device.SceneManager;
     IVideoDriver driver = device.VideoDriver;
     IGUIEnvironment env = device.GUIEnvironment;
     /*We add three buttons. The first one closes the engine. The second creates
       a window and the third opens a file open dialog. The third parameter is
       the id of the button, with which we can easily identify the button in the
       event receiver.*/
     env.AddButton(new Rect(10, 210, 100, 240), null, 101, "Quit");
     env.AddButton(new Rect(10, 250, 100, 290), null, 102, "New Window");
     env.AddButton(new Rect(10, 300, 100, 340), null, 103, "File Open");
     /*Now, we add a static text and a scrollbar, which modifies the transparency
       of all gui elements. We set the maximum value of the scrollbar to 255,
       because that's the maximal value for a color value. Then we create an other
       static text and a list box.*/
     env.AddStaticText("Transparent Control:", new Rect(150, 20, 350, 40), true, false, null, 0);
     IGUIElement scrollbar = env.AddScrollBar(true, new Rect(150, 45, 350, 60), null, 104);
     //nopt implemented yet
     //scrollbar.Max=255;
     env.AddStaticText("Logging Listbox:", new Rect(50, 80, 250, 100), true, false, null, 0);
     listbox = env.AddListBox(new Rect(50, 110, 250, 180), null, 0, true);
     /*To make the font a little bit nicer, we load an external font and set it as
       new font in the skin. An at last, we create a nice Irrlicht Engine logo in the
       top left corner. */
     IGUISkin skin = env.Skin;
     IGUIFont font = env.GetFont(path + "fonthaettenschweiler.bmp");
     if (font != null)
     {
         skin.Font = font;
     }
     IGUIElement img = env.AddImage(driver.GetTexture(path + "irrlichtlogoalpha.tga"),
         new Position2D(10, 10),
         false,   //UseAlphaChannel
         null,   //Parent
         0,      //ID
         "");   //Text
     /*
     We have done everything, so lets draw it.
     */
     while (device.Run())
     {
         if (device.WindowActive)
         {
             device.VideoDriver.BeginScene(true, true, new Color(0, 122, 65, 171));
             device.SceneManager.DrawAll();
             device.GUIEnvironment.DrawAll();
             device.VideoDriver.EndScene();
         }
     }
     /*
     In the end, delete the Irrlicht device.
     */
     // Instead of device->drop, we'll use:
     GC.Collect();
 }
Beispiel #28
0
		static void Main(string[] args)
		{
			int lodItemCount = AskUserForLODItemCount();

			DriverType driverType;
			if (!AskUserForDriver(out driverType))
				return;

			device = IrrlichtDevice.CreateDevice(driverType, 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.OpaqueGreen);

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

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

				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.OpaqueMagenta);
				}

				// 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.OpaqueYellow);

				// 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.OpaqueCyan);

				driver.EndScene();
			}

			// drop

			device.Drop();
		}
Beispiel #29
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();
		}
Beispiel #30
0
 public void run()
 {
     /* At first, we let the user select the driver type,
        then start up the engine, set a caption, and get a
        pointer to the video driver.
     */
     // ask user for driver
     DriverType driverType;
     // Ask user to select driver:
     StringBuilder sb = new StringBuilder();
     sb.Append("Please select the driver you want for this example:\n");
     sb.Append("\n(a) Direct3D 9.0c\n(b) Direct3D 8.1\n(c) OpenGL 1.5");
     sb.Append("\n(d) Software Renderer\n(e) Apfelbaum Software Renderer");
     sb.Append("\n(f) Null Device\n(otherKey) exit\n\n");
     // Get the user's input:
     TextReader tIn = Console.In;
     TextWriter tOut = Console.Out;
     tOut.Write(sb.ToString());
     string input = tIn.ReadLine();
     // Select device based on user's input:
     switch (input)
     {
         case "a":
             driverType = DriverType.DIRECT3D9;
             break;
         case "b":
             driverType = DriverType.DIRECT3D8;
             break;
         case "c":
             driverType = DriverType.OPENGL;
             break;
         case "d":
             driverType = DriverType.SOFTWARE;
             break;
         case "e":
             driverType = DriverType.SOFTWARE2;
             break;
         case "f":
             driverType = DriverType.NULL_DRIVER;
             break;
         default:
             return;
     }
     // Create device and exit if creation fails:
     device = new IrrlichtDevice(driverType, new Dimension2D(1024, 768), 32, false, true, true);
     if (device == null)
     {
         tOut.Write("Device creation failed.");
         return;
     }
     /*
     Get a pointer to the video driver and the SceneManager so that
     we do not always have to write device.VideoDriver()
     */
     IVideoDriver driver = device.VideoDriver;
     /*All 2d graphics in this example are put together into one texture,
       2ddemo.bmp. Because we want to draw colorkey based sprites, we need
       to load this texture and tell the engine, which part of it should be
       transparent based on a colorkey. In this example, we don't tell it
       the color directly, we just say "Hey Irrlicht Engine, you'll find the
       color I want at position (0,0) on the texture.". Instead, it would be
       also possible to call driver.MakeColorKeyTexture(images, Color)
       to make e.g. all black pixels transparent. Please note, that
       makeColorKeyTexture just creates an alpha channel based on the color.*/
     ITexture images = driver.GetTexture(path + "2ddemo.bmp");
     driver.MakeColorKeyTexture(images, new Position2D(0, 0));
     /*
      To be able to draw some text with two different fonts,
      we load them. Ok, we load just one, as first font we just
      use the default font which is built into the engine.
      Also, we define two rectangles, which specify the position
      of the images of the red imps (little flying creatures) in
      the texture.
      */
     IGUIFont font = device.GUIEnvironment.BuiltInFont;
     IGUIFont font2 = device.GUIEnvironment.GetFont(path + "fonthaettenschweiler.bmp");
     Rect imp1 = new Rect(349, 15, 385, 78);
     Rect imp2 = new Rect(387, 15, 423, 78);
     /*
      Everything is prepared, now we can draw everything in the draw loop,
      between the begin scene and end scene calls. In this example, we are just
      doing 2d graphics, but it would be no problem to mix them with 3d graphics.
      Just try it out, and draw some 3d vertices or set up a scene with the scene
      manager and draw it.
      */
     while (device.Run() && driver != null)
     {
         if (device.WindowActive)
         {
             uint time = device.Timer.Time;
             driver.BeginScene(true, true, new Color(0, 120, 102, 136));
             /*
              First, we draw 3 sprites, using the alpha channel we created with
              makeColorKeyTexture. The last parameter specifiys that the drawing
              method should use thiw alpha channel. The parameter before the last
              one specifies a color, with which the sprite should be colored.
              (255,255,255,255) is full white, so the sprite will look like the
              original. The third sprite is drawed colored based on the time.*/
             // draw fire & dragons background world
             driver.Draw2DImage(images, new Position2D(50, 50),
                 new Rect(0, 0, 342, 224),
                 new Color(255, 255, 255, 255), true);
             // draw flying imp
             driver.Draw2DImage(images, new Position2D(164, 125),
                 (time / 500 % 2) == 0 ? imp1 : imp2,
                 new Color(255, 255, 255, 255), true);
             // draw second flying imp with colorcylce
             driver.Draw2DImage(images, new Position2D(270, 105),
                 (time / 500 % 2) == 0 ? imp1 : imp2,
                 new Color(255, ((int)(time) % 255), 255, 255), true);
             // Drawing text is really simple. The code should be self explanatory.
             if (font != null)
             {
                 font.Draw("This is some text",
                     new Rect(130, 10, 300, 50),
                     new Color(255, 255, 255, 255), false, false);
             }
             if (font2 != null)
             {
                 font2.Draw("This is some text",
                     new Rect(130, 20, 300, 60),
                     new Color(255, (int)time % 255, (int)time % 255, 255),
                     false, false);
             }
             /*At last, we draw the Irrlicht Engine logo (without using
               a color or an alpha channel) and a transparent 2d Rectangle
               at the position of the mouse cursor.*/
             // draw logo
             driver.Draw2DImage(images, new Position2D(10, 10),
                 new Rect(354, 87, 442, 118), new Color(255, 255, 255, 255), false);
             // draw transparent rect under cursor
             Position2D m = device.CursorControl.Position;
             driver.Draw2DRectangle(new Color(100, 255, 255, 255),
                 new Rect(m.X - 20, m.Y - 20, m.X + 20, m.Y + 20));
             driver.EndScene();
         }
     }
     /*
     In the end, delete the Irrlicht device.
     */
     // Instead of device->drop, we'll use:
     GC.Collect();
 }
Beispiel #31
0
        public Jeu()
        {
            Device = IrrlichtDevice.CreateDevice(
                DriverType.Direct3D9,
                new Dimension2Di(800, 600),
                32, false, false, true);

            Device.SetWindowCaption("Canardstein 3D");
            Device.OnEvent += Evenement;
            SceneNode cube = Device.SceneManager.AddCubeSceneNode(1, null, 0, new Vector3Df(2, 0, 0), new Vector3Df(0, 45, 0));

            cube.SetMaterialFlag(MaterialFlag.Lighting, false);
            CameraSceneNode camera = Device.SceneManager.AddCameraSceneNode(null, new Vector3Df(0, 0, 0), new Vector3Df(2, 0, 0));

            Device.CursorControl.Position = new Vector2Di(400, 300);
            Device.CursorControl.Visible  = false;

            while (Device.Run())
            {
                float tempsEcoule = (Device.Timer.Time - DerniereFrame) / 1000f;
                DerniereFrame = Device.Timer.Time;

                if (Device.CursorControl.Position.X != 400)
                {
                    Rotation += (Device.CursorControl.Position.X - 400) * 0.0025;
                    Device.CursorControl.Position = new Vector2Di(400, 300);
                    VecteurAvant = new Vector3Df(
                        x: (float)Math.Cos(Rotation),
                        y: 0,
                        z: -(float)Math.Sin(Rotation));
                    VecteurDroite = VecteurAvant;
                    VecteurDroite.RotateXZby(-90);
                }
                Vector3Df vitesse = new Vector3Df();
                if (K_Avant)
                {
                    vitesse += VecteurAvant;
                }
                else if (K_Arriere)
                {
                    vitesse -= VecteurAvant;
                }
                if (K_Gauche)
                {
                    vitesse -= VecteurDroite;
                }
                else if (K_Droite)
                {
                    vitesse += VecteurDroite;
                }

                vitesse = vitesse.Normalize() * tempsEcoule * 2;

                camera.Position += vitesse;
                camera.Target    = camera.Position + VecteurAvant;

                Device.VideoDriver.BeginScene(ClearBufferFlag.Color | ClearBufferFlag.Depth, Color.OpaqueMagenta);
                Device.SceneManager.DrawAll();
                Device.VideoDriver.EndScene();
            }
        }
Beispiel #32
0
 void runIrrlichtInWindowsFormTest(Control c)
 {
     device = new IrrlichtDevice(Irrlicht.Video.DriverType.DIRECT3D9,
                        new Dimension2D(c.Width, c.Height),
                        32, false, false, false, true, c.Handle);
                    ICameraSceneNode cam = device.SceneManager.AddCameraSceneNode(null, new Vector3D(), new Vector3D(), -1);
                    ISceneNodeAnimator anim = device.SceneManager.CreateFlyCircleAnimator(new Vector3D(0, 10, 0), 30.0f, 0.003f);
                    cam.AddAnimator(anim);
                    ISceneNode cube = device.SceneManager.AddTestSceneNode(25, null, -1, new Vector3D());
                    cube.SetMaterialTexture(0, device.VideoDriver.GetTexture("../../../media/rockwall.bmp"));
                    cube.SetMaterialFlag(MaterialFlag.LIGHTING, false);
                    // draw everything
                    // Note, using device.WindowActive will not work on a control, since we don't
                    // really activate controls..
                    while (device.Run() && c.Enabled)
                    {
                        device.VideoDriver.BeginScene(true, true, new Irrlicht.Video.Color(255, 0, 0, 50));
                        device.SceneManager.DrawAll();
                        device.GUIEnvironment.DrawAll();
                        device.VideoDriver.EndScene();
                    }
 }
Beispiel #33
0
		static void Main(string[] args)
		{
			DriverType driverType;
			if (!AskUserForDriver(out driverType))
				return;

			useHighLevelShaders = AskUserForHighLevelShaders(driverType);

			if (useHighLevelShaders)
				useCgShaders = AskUserForCgShaders(driverType);

			device = IrrlichtDevice.CreateDevice(driverType, 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.Direct3D8:
					psFileName = "../../media/d3d8.psh";
					vsFileName = "../../media/d3d8.vsh";
					break;

				case DriverType.Direct3D9:
					if (useHighLevelShaders)
					{
						// Cg can also handle this syntax
						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)
					{
						if (useCgShaders)
						{
							// Use HLSL syntax for Cg
							psFileName = "../../media/d3d9.hlsl";
							vsFileName = psFileName; // both shaders are in the same file
						}
						else
						{
							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.");

			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.");

			// create materials
			
			GPUProgrammingServices gpu = driver.GPUProgrammingServices;
			MaterialType newMaterialType1 = MaterialType.Solid;
			MaterialType newMaterialType2 = MaterialType.TransparentAddColor;

			if (gpu != null)
			{
				gpu.OnSetConstants += new GPUProgrammingServices.SetConstantsHandler(gpu_OnSetConstants);

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

				if (useHighLevelShaders)
				{
					GPUShadingLanguage shadingLanguage = useCgShaders
						? GPUShadingLanguage.Cg
						: GPUShadingLanguage.Default;

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

					newMaterialType2 = gpu.AddHighLevelShaderMaterialFromFiles(
						vsFileName, "vertexMain", VertexShaderType.VS_1_1,
						psFileName, "pixelMain", PixelShaderType.PS_1_1,
						MaterialType.TransparentAddColor, 0, shadingLanguage);
				}
				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)
				newMaterialType2 = 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);

			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");

			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(true, true, 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();
		}
Beispiel #34
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();
		}
Beispiel #35
0
        static void Main(string[] args)
        {
            // Initialize device.

            DriverType driverType;

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

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType, 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 Lime - " + 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;
                    if (plane.GetIntersectionWithLine(ray.Start, ray.Vector, out mousePosition))
                    {
                        // 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(true, true, new Color(113, 113, 133));
                smgr.DrawAll();
                driver.EndScene();
            }

            // Drop the device.

            device.Drop();
        }
Beispiel #36
0
        static void Main(string[] args)
        {
            DriverType driverType;

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

            useHighLevelShaders = AskUserForHighLevelShaders(driverType);

            if (useHighLevelShaders)
            {
                useCgShaders = AskUserForCgShaders(driverType);
            }

            device = IrrlichtDevice.CreateDevice(driverType, 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.Direct3D8:
                psFileName = "../../media/d3d8.psh";
                vsFileName = "../../media/d3d8.vsh";
                break;

            case DriverType.Direct3D9:
                if (useHighLevelShaders)
                {
                    // Cg can also handle this syntax
                    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)
                {
                    if (useCgShaders)
                    {
                        // Use HLSL syntax for Cg
                        psFileName = "../../media/d3d9.hlsl";
                        vsFileName = psFileName;                                 // both shaders are in the same file
                    }
                    else
                    {
                        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.");
            }

            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.");
            }

            // create materials

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

            if (gpu != null)
            {
                gpu.OnSetConstants += new GPUProgrammingServices.SetConstantsHandler(gpu_OnSetConstants);

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

                if (useHighLevelShaders)
                {
                    GPUShadingLanguage shadingLanguage = useCgShaders
                                                ? GPUShadingLanguage.Cg
                                                : GPUShadingLanguage.Default;

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

                    newMaterialType2 = gpu.AddHighLevelShaderMaterialFromFiles(
                        vsFileName, "vertexMain", VertexShaderType.VS_1_1,
                        psFileName, "pixelMain", PixelShaderType.PS_1_1,
                        MaterialType.TransparentAddColor, 0, shadingLanguage);
                }
                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)
            {
                newMaterialType2 = 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);

            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");

            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(true, true, 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();
        }
Beispiel #37
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;

            // 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(ClearBufferFlag.All, new Color(0));

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

                        // set render target texture
                        driver.SetRenderTarget(rt, ClearBufferFlag.All, 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, ClearBufferFlag.All, 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();
        }
Beispiel #38
0
		ParticleRotationAffector affRotation; // its pointer back later :(

		void irrThreadMain(object args)
		{
			irrDevice = IrrlichtDevice.CreateDevice(args as IrrlichtCreationParameters);

			// Camera

			CameraSceneNode camera = irrDevice.SceneManager.AddCameraSceneNode(null, new Vector3Df(0), new Vector3Df(0, 80, 0), (int)SceneNodeID.Camera);
			SceneNodeAnimator anim = irrDevice.SceneManager.CreateFlyCircleAnimator(new Vector3Df(0, 100, 0), 200.0f, 0.0002f);
			camera.AddAnimator(anim);
			anim.Drop();

			// Skydome

			irrDevice.SceneManager.AddSkyDomeSceneNode(irrDevice.VideoDriver.GetTexture("../../media/skydome.jpg"), 16, 8, 0.95f, 2.0f);

			// Plane

			var m = irrDevice.SceneManager.AddHillPlaneMesh("plane", new Dimension2Df(1000), new Dimension2Di(1), null, 0, new Dimension2Df(0), new Dimension2Df(8));
			var n = irrDevice.SceneManager.AddAnimatedMeshSceneNode(m, null, (int)SceneNodeID.Plane);
			n.SetMaterialFlag(MaterialFlag.Lighting, false);
			n.SetMaterialTexture(0, irrDevice.VideoDriver.GetTexture("../../media/rockwall.jpg"));

			// Axes

			m = irrDevice.SceneManager.AddArrowMesh("axisX");
			n = irrDevice.SceneManager.AddAnimatedMeshSceneNode(m, null, (int)SceneNodeID.AxisX, new Vector3Df(), new Vector3Df(0, 0, -90), new Vector3Df(50, 120, 50));
			n.GetMaterial(0).EmissiveColor = new Color(250, 250, 250);
			n.GetMaterial(1).EmissiveColor = new Color(250, 0, 0);

			m = irrDevice.SceneManager.AddArrowMesh("axisY");
			n = irrDevice.SceneManager.AddAnimatedMeshSceneNode(m, null, (int)SceneNodeID.AxisY, new Vector3Df(), new Vector3Df(0, 0, 0), new Vector3Df(50, 120, 50));
			n.GetMaterial(0).EmissiveColor = new Color(250, 250, 250);
			n.GetMaterial(1).EmissiveColor = new Color(0, 250, 0);

			m = irrDevice.SceneManager.AddArrowMesh("axisZ");
			n = irrDevice.SceneManager.AddAnimatedMeshSceneNode(m, null, (int)SceneNodeID.AxisZ, new Vector3Df(), new Vector3Df(90, 0, 0), new Vector3Df(50, 120, 50));
			n.GetMaterial(0).EmissiveColor = new Color(250, 250, 250);
			n.GetMaterial(1).EmissiveColor = new Color(0, 0, 250);

			irrThreadShowAxes(false);

			// Particle system

			var ps = irrDevice.SceneManager.AddParticleSystemSceneNode(false, null, (int)SceneNodeID.ParticleSystem);

			ps.SetMaterialFlag(MaterialFlag.Lighting, false);
			ps.SetMaterialFlag(MaterialFlag.ZWrite, false);
			ps.SetMaterialTexture(0, irrDevice.VideoDriver.GetTexture("../../media/particle.bmp"));
			ps.SetMaterialType(MaterialType.TransparentAddColor);

			ParticleEmitter em = ps.CreateSphereEmitter(
				new Vector3Df(), 20,				// position and radius
				new Vector3Df(0.0f, 0.1f, 0.0f),	// initial direction
				150, 300,							// emit rate
				new Color(255, 255, 255, 0),		// darkest color
				new Color(255, 255, 255, 0),		// brightest color
				750, 1500, 0,						// min and max age, angle
				new Dimension2Df(20.0f),			// min size
				new Dimension2Df(40.0f));			// max size

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

			// Particle affectors

			affFadeOut = ps.CreateFadeOutParticleAffector();
			ps.AddAffector(affFadeOut);
			affFadeOut.Drop();

			affGravity = ps.CreateGravityAffector(new Vector3Df(0, -1, 0), 3000);
			affGravity.Enabled = false;
			ps.AddAffector(affGravity);
			affGravity.Drop();

			affRotation = ps.CreateRotationAffector(new Vector3Df(-90, 240, -120), new Vector3Df(0, 100, 0));
			ps.AddAffector(affRotation);
			affRotation.Drop();

			// Rendering loop

			uint rs = 0, re = 0; // render frame time
			while (irrDevice.Run())
			{
				if (irrDevice.VideoDriver.ScreenSize.Area != 0)
				{
					irrDevice.VideoDriver.BeginScene();
					irrDevice.SceneManager.DrawAll();
					re = irrDevice.Timer.Time;

					irrThreadDrawText(new Vector2Di(8, 8),
						"Frame time: " + (irrDevice.VideoDriver.FPS > 1000 ? "< 1" : (re - rs).ToString()) + " ms");

					irrDevice.VideoDriver.EndScene();
				}
				else
				{
					Thread.Sleep(50);
				}

				irrThreadProcessCommandQueue();
				rs = irrDevice.Timer.Time;
			}

			irrDevice.Drop();
		}
Beispiel #39
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(false);
                }
                else
                {
                    drv.BeginScene(true, true, 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();
        }
Beispiel #40
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();
		}
Beispiel #41
0
		static void Main(string[] args)
		{
			device = IrrlichtDevice.CreateDevice(DriverType.Direct3D8, 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.OpaqueWhite;
			Color fontActionColor = Color.OpaqueYellow;

			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(false);

				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();
		}
Beispiel #42
0
        static void Main(string[] args)
        {
            DriverType driverType;

            Console.Write("Please select the driver you want for this example:\n" +
                          " (a) OpenGL\n (b) Direct3D 9.0c\n (c) Direct3D 8.1\n" +
                          " (d) Burning's Software Renderer\n (e) Software Renderer\n" +
                          " (f) NullDevice\n (otherKey) exit\n\n");

            ConsoleKeyInfo i = Console.ReadKey();

            switch (i.Key)
            {
            case ConsoleKey.A: driverType = DriverType.OpenGL; break;

            case ConsoleKey.B: driverType = DriverType.Direct3D9; break;

            case ConsoleKey.C: driverType = DriverType.Direct3D8; break;

            case ConsoleKey.D: driverType = DriverType.BurningsVideo; break;

            case ConsoleKey.E: driverType = DriverType.Software; break;

            case ConsoleKey.F: driverType = DriverType.Null; break;

            default:
                return;
            }

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType, 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(true, true, 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();
        }
Beispiel #43
0
        public void run()
        {
            /* At first, we let the user select the driver type,
               then start up the engine, set a caption, and get a
               pointer to the video driver.
            */

            // ask user for driver
            DriverType driverType;

            // Ask user to select driver:
            StringBuilder sb = new StringBuilder();
            sb.Append("Please select the driver you want for this example:\n");
            sb.Append("\n(a) Direct3D 9.0c\n(b) Direct3D 8.1\n(c) OpenGL 1.5");
            sb.Append("\n(d) Software Renderer\n(e) Apfelbaum Software Renderer");
            sb.Append("\n(f) Null Device\n(otherKey) exit\n\n");

            // Get the user's input:
            TextReader tIn = Console.In;
            TextWriter tOut = Console.Out;
            string input = string.Empty;
            bool shadows = false;
            tOut.Write("Do you want to use realtime shadows? (y/n)");
            input = tIn.ReadLine();
            if (input == "y") shadows = true;
            tOut.Write(sb.ToString());
            input = tIn.ReadLine();

            // Select device based on user's input:
            switch (input)
            {
                case "a":
                    driverType = DriverType.DIRECT3D9;
                    break;
                case "b":
                    driverType = DriverType.DIRECT3D8;
                    break;
                case "c":
                    driverType = DriverType.OPENGL;
                    break;
                case "d":
                    driverType = DriverType.SOFTWARE;
                    break;
                case "e":
                    driverType = DriverType.SOFTWARE2;
                    break;
                case "f":
                    driverType = DriverType.NULL_DRIVER;
                    break;
                default:
                    return;
            }

            /* We start like in some tutorials before. Please note that this time, the
               'shadows' flag in createDevice() is set to true, for we want to have a
               dynamic shadow casted from an animated character. If your this example
               runs to slow, set it to false. The Irrlicht Engine checks if your hardware
               doesn't support the stencil buffer, and disables shadows by itself, but
               just in case the demo runs slow on your hardware.*/
            /*
             * From the unmanaged API documentation:
             * stencilbuffer:
             * Specifies if the stencil buffer should be enabled.
             * Set this to true, if you want the engine be able to draw stencil buffer shadows.
             * Note that not all devices are able to use the stencil buffer.
             * If they don't no shadows will be drawn.
             */
            device = new IrrlichtDevice(driverType, new Dimension2D(1024, 768), 32, false, shadows, true);
            if (device == null)
            {
                tOut.Write("Device creation failed.");
                return;
            }

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

            /* For our environment, we load a .3ds file. It is a small room I modelled with
               Anim8or and exported it into the 3ds format because the Irrlicht Engine did
               not support the .an8 format when I wrote this tutorial. I am a very bad 3d
               graphic artist, and so the texture mapping is not very nice in this model.
               Luckily I am a better programmer than artist, and so the Irrlicht Engine is
               able to create a cool texture mapping for me: Just use the mesh manipulator
               and create a planar texture mapping for the mesh. If you want to see the
               mapping I made with Anim8or, uncomment this line. I also did not figure out
               how to set the material right in Anim8or, it has an emissive light color
               which I don't really like. I'll switch it off too with this code.*/
            IAnimatedMesh mesh= smgr.GetMesh(
                path+"room.3ds");

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

            ISceneNode node = smgr.AddAnimatedMeshSceneNode(mesh, null, 0);
            node.SetMaterialTexture(
                0,driver.GetTexture(path+"wall.jpg"));
            node.GetMaterial(0).EmissiveColor.Set(0,0,0,0);

            //       Add a shadow to the room if it is not dark enough
            /* The result is interesting but not exactly what I was expecting!
               Try for yourself... I think this could be a little problem in the
               Irrlicht.NET wrapper but I promise I will investigate further to see
               if I can make it work as intended
               Forum Article (http://irrlicht.sourceforge.net/phpBB2/viewtopic.php?t=10584)
            */
            //          IAnimatedMeshSceneNode xnode = (IAnimatedMeshSceneNode)node;
            //          xnode.AddShadowVolumeSceneNode();
            //
            /*Now, for the first special effect: Animated water. It works like this: The
              WaterSurfaceSceneNode takes a mesh as input and makes it wave like a water
              surface. And if we let this scene node use a nice material like the
              MT_REFLECTION_2_LAYER, it looks really cool. We are doing this with the
              next few lines of code. As input mesh, we create a hill plane mesh, without
              hills. But any other mesh could be used for this, you could even use the
              room.3ds (which would look really strange) if you wanted to.*/
            mesh = smgr.AddHillPlaneMesh("myHill",
                new Dimension2Df(20,20),
                new Dimension2D(40,40),new Material(),0,
                new Dimension2Df(0,0),
                new Dimension2Df(10,10));

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

            node.SetMaterialTexture(0, driver.GetTexture(path+"water.jpg"));
            node.SetMaterialTexture(1, driver.GetTexture(path+"stones.jpg"));

            node.SetMaterialType(MaterialType.REFLECTION_2_LAYER);

            /*The second special effect is very basic, I bet you saw it already in some
              Irrlicht Engine demos: A transparent billboard combined with a dynamic light.
              We simply create a light scene node, let it fly around, an to make it look
              more cool, we attach a billboard scene node to it.*/
            // create light

            node = smgr.AddLightSceneNode(null, new Vector3D(0,0,0),
                new Colorf(1.0f, 0.6f, 0.7f, 1.0f), 600.0f,0);
            ISceneNodeAnimator anim = smgr.CreateFlyCircleAnimator(new Vector3D(0,150,0),250.0f,0.0005f);
            node.AddAnimator(anim);

            // attach billboard to light
            node = smgr.AddBillboardSceneNode(node, new Dimension2Df(50, 50),new Vector3D(),0);
            node.SetMaterialFlag(MaterialFlag.LIGHTING, false);
            node.SetMaterialType(MaterialType.TRANSPARENT_ADD_COLOR);
            node.SetMaterialTexture(0,
                driver.GetTexture(path+"particlewhite.bmp"));

            /* The next special effect is a lot more interesting: A particle system. The
               particle system in the Irrlicht Engine is quit modular and extensible and
               yet easy to use. There is a particle system scene node into which you can
               put particle emitters, which make particles come out of nothing. These
               emitters are quite flexible and usually have lots of parameters like
               direction, amount and color of the particles they should create.
               There are different emitters, for example a point emitter which lets
               particles pop out at a fixed point. If the particle emitters available
               in the engine are not enough for you, you can easily create your own ones,
               you'll simply have to create a class derived from the IParticleEmitter
               interface and attach it to the particle system using setEmitter().
               In this example we create a box particle emitter, which creates particles
               randomly inside a box. The parameters define the box, direction of the
               articles, minimal and maximal new particles per second, color and minimal
               and maximal livetime of the particles. Because only with emitters particle
               system would be a little bit boring, there are particle affectors, which
               modify particles during they fly around. They can be added to the particle
               system, simulating additional effects like gravity or wind. The particle
               affector we use in this example is an affector, which modifies the color
               of the particles: It lets them fade out. Like the particle emitters,
               additional particle affectors can also be implemented by you, simply derive
               a class from IParticleAffector and add it with addAffector(). After we set
               a nice material to the particle system, we have a cool looking camp fire.
               By adjusting material, texture, particle emitter and affector parameters,
               it is also easily possible to create smoke, rain, explosions, snow, and
               so on.*/
            IParticleSystemSceneNode ps = smgr.AddParticleSystemSceneNode(
                false,null,0,new Vector3D(-70,60,40),new Vector3D(),new Vector3D(2,2,2));

            ps.ParticleSize= new Dimension2Df(20,10);

            IParticleEmitter em = ps.CreateBoxEmitter(
                new Box3D(-7,0,-7,7,1,7),new Vector3D(0.0f,0.03f,0.0f),
                80,100,
                new Color(0,255,255,255),new Color(0,255,255,255),
                800,2000,0);

            ps.SetEmitter(em);

            IParticleAffector paf=
                ps.CreateFadeOutParticleAffector(new Color(),1500);

            ps.AddAffector(paf);

            ps.SetMaterialFlag(MaterialFlag.LIGHTING, false);
            ps.SetMaterialTexture(0,
                driver.GetTexture(path+"particle.bmp"));
            ps.SetMaterialType(MaterialType.TRANSPARENT_VERTEX_ALPHA);

            /*As our last special effect, we want a dynamic shadow be casted from an animated
              character. For this we load a quake 2 .md2 model and place it into our world.
              For creating the shadow, we simply need to call addShadowVolumeSceneNode(). The
              color of shadows is only adjustable globally for all shadows, by calling
              ISceneManager::setShadowColor(). Voila, here is our dynamic shadow. Because
              the character is a little bit too small for this scene, we make it bigger
              using setScale(). And because the character is lighted by a dynamic light,
              we need to normalize the normals to make the lighting on it correct. This
              is always necessary if the scale of a dynamic lighted model is not (1,1,1).
              Otherwise it would get too dark or too bright because the normals will be
              scaled too.*/
            mesh = smgr.GetMesh(path+"faerie.md2");
            IAnimatedMeshSceneNode anode = smgr.AddAnimatedMeshSceneNode(mesh,null,0);
            anode.Position = new Vector3D(-50,45,-60);
            anode.SetMD2Animation(MD2AnimationType.STAND);
            anode.SetMaterialTexture(0,
                driver.GetTexture(path+"Faerie5.BMP"));

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

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

            /*Finally we simply have to draw everything, that's all.*/
            ICameraSceneNode camera = smgr.AddCameraSceneNodeFPS();
            camera.Position=new Vector3D(-50,50,-150);
            // Remove the mouse cursor:
            device.CursorControl.Visible = false;
            int lastFPS=-1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    device.VideoDriver.BeginScene(true, true, new Color(0, 200, 200, 200));
                    device.SceneManager.DrawAll();
                    device.VideoDriver.EndScene();

                    int fps = device.VideoDriver.FPS;
                    if (lastFPS != fps)
                    {
                        device.WindowCaption = "Irrlicht Engine - SpecialFX tutorial [" +
                            device.VideoDriver.Name + "] FPS:" + fps.ToString();
                        lastFPS = fps;
                    }
                }
            }
            /*
            In the end, delete the Irrlicht device.
            */
            // Instead of device->drop, we'll use:
            GC.Collect();
        }
Beispiel #44
0
		static void Main(string[] args)
		{
			// setup Irrlicht

			device = IrrlichtDevice.CreateDevice(DriverType.Direct3D9, 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");
			Material statsMaterial = Material.IdentityNoLighting;

			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(true, true, new Color(0xff112244));

				scene.DrawAll();

				if (useShadowsRendering)
					shadows.DrawShadowVolume(driver);

				// display stats

				device.VideoDriver.SetMaterial(statsMaterial);

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

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

				driver.EndScene();
			}

			shadows.Drop();
			device.Drop();
		}
Beispiel #45
0
        static void Main(string[] args)
        {
            DriverType driverType;

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

            IrrlichtDevice device = IrrlichtDevice.CreateDevice(driverType, new Dimension2Di(512, 384));

            if (device == null)
            {
                return;
            }

            device.SetWindowCaption("Irrlicht Engine - 2D Graphics Demo");

            VideoDriver driver = device.VideoDriver;

            Texture images = driver.GetTexture("../../media/2ddemo.png");

            driver.MakeColorKeyTexture(images, new Vector2Di(0, 0));

            GUIFont font  = device.GUIEnvironment.BuiltInFont;
            GUIFont font2 = device.GUIEnvironment.GetFont("../../media/fonthaettenschweiler.bmp");

            Recti imp1 = new Recti(349, 15, 385, 78);
            Recti imp2 = new Recti(387, 15, 423, 78);

            driver.Material2D.Layer[0].BilinearFilter = true;
            driver.Material2D.AntiAliasing            = AntiAliasingMode.FullBasic;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    int time = (int)device.Timer.Time;

                    driver.BeginScene(true, true, new Color(120, 102, 136));

                    // draw fire & dragons background world
                    driver.Draw2DImage(images, new Vector2Di(50, 50),
                                       new Recti(0, 0, 342, 224), null,
                                       new Color(255, 255, 255), true);

                    // draw flying imp
                    driver.Draw2DImage(images, new Vector2Di(164, 125),
                                       (time / 500 % 2) == 1 ? imp1 : imp2, null,
                                       new Color(255, 255, 255), true);

                    // draw second flying imp with colorcylce
                    driver.Draw2DImage(images, new Vector2Di(270, 105),
                                       (time / 500 % 2) == 1 ? imp1 : imp2, null,
                                       new Color(time % 255, 255, 255), true);

                    // draw some text
                    if (font != null)
                    {
                        font.Draw("This demo shows that Irrlicht is also capable of drawing 2D graphics.",
                                  130, 10, new Color(255, 255, 255));
                    }

                    // draw some other text
                    if (font2 != null)
                    {
                        font2.Draw("Also mixing with 3d graphics is possible.",
                                   130, 20, new Color(time % 255, time % 255, 255));
                    }

                    driver.EnableMaterial2D();
                    driver.Draw2DImage(images, new Recti(10, 10, 108, 48), new Recti(354, 87, 442, 118));
                    driver.EnableMaterial2D(false);

                    Vector2Di m = device.CursorControl.Position;
                    driver.Draw2DRectangle(new Recti(m.X - 20, m.Y - 20, m.X + 20, m.Y + 20), new Color(255, 255, 255, 100));

                    driver.EndScene();
                }
            }

            device.Drop();
        }
Beispiel #46
0
        public void run()
        {
            /* The next few lines start up the engine. Just like in most other tutorials
               before. But in addition, we ask the user if he wants this example to use
               high level shaders if he selected a driver which is capable of doing so.
            */

            // ask user for driver
            DriverType driverType;

            // Ask user to select driver:
            StringBuilder sb = new StringBuilder();
            sb.Append("Please select the driver you want for this example:\n");
            sb.Append("\n(a) Direct3D 9.0c\n(b) Direct3D 8.1\n(c) OpenGL 1.5");
            sb.Append("\n(d) Software Renderer\n(e) Apfelbaum Software Renderer");
            sb.Append("\n(f) Null Device\n(otherKey) exit\n\n");

            // Get the user's input:
            TextReader tIn = Console.In;
            TextWriter tOut = Console.Out;
            tOut.Write(sb.ToString());
            string input = tIn.ReadLine();

            // Select device based on user's input:
            switch (input)
            {
                case "a":
                    driverType = DriverType.DIRECT3D9;
                    break;
                case "b":
                    driverType = DriverType.DIRECT3D8;
                    break;
                case "c":
                    driverType = DriverType.OPENGL;
                    break;
                case "d":
                    driverType = DriverType.SOFTWARE;
                    break;
                case "e":
                    driverType = DriverType.SOFTWARE2;
                    break;
                case "f":
                    driverType = DriverType.NULL_DRIVER;
                    break;
                default:
                    return;
            }
            // ask the user if we should use high level shaders for this example
            if (driverType == DriverType.DIRECT3D9 ||
                driverType == DriverType.OPENGL)
            {
                tOut.Write("Please press 'y' if you want to use high level shaders.\n");
                input=tIn.ReadLine();
                if (input.ToLower()=="y")
                    UseHighLevelShaders=true;
            }

            // create device
            device = new IrrlichtDevice(driverType, new Dimension2D(1024, 768), 32, false, true, true);
            if (device == null)
            {
                tOut.Write("Device creation failed.");
                return;
            }

            ISceneManager smgr=device.SceneManager;
            IVideoDriver driver=device.VideoDriver;
            IGUIEnvironment gui = device.GUIEnvironment;

            /*Now for the more interesting parts. If we are using Direct3D, we want to
              load vertex and pixel shader programs, if we have OpenGL, we want to use ARB
              fragment and vertex programs. I wrote the corresponding programs down into the
              files d3d8.ps, d3d8.vs, d3d9.ps, d3d9.vs, opengl.ps and opengl.vs. We only
              need the right filenames now. This is done in the following switch. Note,
              that it is not necessary to write the shaders into text files, like in this
              example. You can even write the shaders directly as strings into the cpp source
              file, and use later addShaderMaterial() instead of addShaderMaterialFromFiles().*/
            string vsFileName="" ;
            string psFileName="" ;

            switch (driverType)
            {
                case DriverType.DIRECT3D8:
                    psFileName = path+"d3d8.psh";
                    vsFileName = path+"d3d8.vsh";
                    break;
                case DriverType.DIRECT3D9:
                    if (UseHighLevelShaders)
                    {
                        psFileName = path+"d3d9.hlsl";
                        vsFileName = psFileName; // both shaders are in the same file
                    }
                    else
                    {
                        psFileName = path+"d3d9.psh";
                        vsFileName = path+"d3d9.vsh";
                    }
                    break;
                case DriverType.OPENGL:
                    if (UseHighLevelShaders)
                    {
                        psFileName = path+"opengl.frag";
                        vsFileName = path+"opengl.vert";
                    }
                    else
                    {
                        psFileName = path+"opengl.psh";
                        vsFileName = path+"opengl.vsh";
                    }
                    break;
            }

            /*In addition, we check if the hardware and the selected renderer is capable
              of executing the shaders we want. If not, we simply set the filename string
              to 0. This is not necessary, but useful in this example: For example, if the
              hardware is able to execute vertex shaders but not pixel shaders, we create a
              new material which only uses the vertex shader, and no pixel shader. Otherwise,
              if we would tell the engine to create this material and the engine sees that
              the hardware wouldn't be able to fullfill the request completely, it would not
              create any new material at all. So in this example you would see at least the
              vertex shader in action, without the pixel shader.*/
            if(!driver.QueryFeature(VideoDriverFeature.PIXEL_SHADER_1_1)&&
                !driver.QueryFeature(VideoDriverFeature.ARB_FRAGMENT_PROGRAM_1))
            {
                // still unimplemented
                //device.Logger.log("WARNING: Pixel shaders disabled \n"+
                //   "because of missing driver/hardware support.");
                psFileName = null;
            }
            if(!driver.QueryFeature(VideoDriverFeature.VERTEX_SHADER_1_1)&&
                !driver.QueryFeature(VideoDriverFeature.ARB_FRAGMENT_PROGRAM_1))
            {
                // still unimplemented
                //device.Logger.log("WARNING: Vertex shaders disabled \n"+
                //   "because of missing driver/hardware support.");
                vsFileName = null;
            }

            /*Now lets create the new materials. As you maybe know from previous examples,
              a material type in the Irrlicht engine is set by simply changing the
              MaterialType value in the SMaterial struct. And this value is just a simple
              32 bit value, like video::EMT_SOLID. So we only need the engine to create a
              new value for us which we can set there. To do this, we get a pointer to the
              IGPUProgrammingServices and call addShaderMaterialFromFiles(), which returns
              such a new 32 bit value. That's all. The parameters to this method are the
              following: First, the names of the files containing the code of the vertex
              and the pixel shader. If you would use addShaderMaterial() instead, you would
              not need file names, then you could write the code of the shader directly as
              string. The following parameter is a pointer to the IShaderConstantSetCallBack
              class we wrote at the beginning of this tutorial. If you don't want to set
              constants, set this to 0. The last paramter tells the engine which material
              it should use as base material. To demonstrate this, we create two materials
              with a different base material, one with EMT_SOLID and one with
              EMT_TRANSPARENT_ADD_COLOR.*/
            // create materials

            IGPUProgrammingServices gpu = driver.GPUProgrammingServices;

            int newMaterialType1 = 0;
            int newMaterialType2 = 0;

            if(gpu!=null)
            {
                IShaderConstantSetCallBack callBack = this;
                // create the shaders depending on if the user wanted high level
                // or low level shaders:
                if(UseHighLevelShaders)
                {
                    // create material from high level shaders (hlsl or glsl)
                    newMaterialType1=gpu.AddHighLevelShaderMaterialFromFiles(
                        vsFileName,"vertexMain",VertexShaderType.VST_VS_1_1,
                        psFileName,"pixelMain",PixelShaderType.PST_PS_1_1,
                        callBack,MaterialType.SOLID);
                    newMaterialType2=gpu.AddHighLevelShaderMaterialFromFiles(
                        vsFileName,"vertexMain",VertexShaderType.VST_VS_1_1,
                        psFileName,"pixelMain",PixelShaderType.PST_PS_1_1,
                        callBack,MaterialType.TRANSPARENT_ADD_COLOR);
                }
                else
                {
                    newMaterialType1=gpu.AddShaderMaterialFromFiles(vsFileName,
                        psFileName,callBack,MaterialType.SOLID);
                    newMaterialType2=gpu.AddShaderMaterialFromFiles(vsFileName,
                        psFileName,callBack,MaterialType.TRANSPARENT_ADD_COLOR);
                }
            }

            /*Now its time for testing out the materials. We create a test cube and set the
              material we created. In addition, we add a text scene node to the cube and a
              rotatation animator, to make it look more interesting and important.*/

            // create test scene node 1, with the new created material type 1
            ISceneNode node = smgr.AddTestSceneNode(50,null,0,new Vector3D(0,0,0));
            node.SetMaterialTexture(0,driver.GetTexture(path+"wall.bmp"));
            node.SetMaterialType((MaterialType)newMaterialType1);

            smgr.AddTextSceneNode(gui.BuiltInFont,"PS & VS & EMT_SOLID",
                new Color(255,255,255,255),node,new Vector3D(),0);

            ISceneNodeAnimator anim= smgr.CreateRotationAnimator(
                new Vector3D(0,0.3f,0));
            node.AddAnimator(anim);

            //Same for the second cube, but with the second material we created.
            node = smgr.AddTestSceneNode(50,null,0,new Vector3D(0,-10,50));
            node.SetMaterialTexture(0,driver.GetTexture(path+"wall.bmp"));
            node.SetMaterialType((MaterialType)newMaterialType2);

            smgr.AddTextSceneNode(gui.BuiltInFont,"PS & VS & EMT_TRANSPARENT",
                new Color(255,255,255,255),node,new Vector3D(),0);

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

            // Then we add a third cube without a shader on it, to be able to compare the cubes.
            node = smgr.AddTestSceneNode(50,null,0,new Vector3D(0,50,25));
            node.SetMaterialTexture(0,driver.GetTexture(path+"wall.bmp"));
            smgr.AddTextSceneNode(gui.BuiltInFont,"NO SHADER",
                new Color(255,255,255,255),node,new Vector3D(),0);

            //And last, we add a skybox and a user controlled camera to the scene. For the
            //skybox textures, we disable mipmap generation, because we don't need mipmaps on it.

            // add a nice skybox
            driver.SetTextureCreationFlag(TextureCreationFlag.CREATE_MIP_MAPS,false);
            smgr.AddSkyBoxSceneNode(
                driver.GetTexture(path+"irrlicht2_up.jpg"),
                driver.GetTexture(path+"irrlicht2_dn.jpg"),
                driver.GetTexture(path+"irrlicht2_lf.jpg"),
                driver.GetTexture(path+"irrlicht2_rt.jpg"),
                driver.GetTexture(path+"irrlicht2_ft.jpg"),
                driver.GetTexture(path+"irrlicht2_bk.jpg"),
                null,0);
            driver.SetTextureCreationFlag(TextureCreationFlag.CREATE_MIP_MAPS,true);

            // add a camera and disable the mouse cursor
            ICameraSceneNode cam = smgr.AddCameraSceneNodeFPS(null,100,100,0);
            cam.Position=new Vector3D(-100,50,100);
            cam.Target=new Vector3D();
            device.CursorControl.Visible=false;

            /*Finally we simply have to draw everything, that's all.*/
            int lastFPS=-1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    device.VideoDriver.BeginScene(true, true, new Color(0, 200, 200, 200));
                    device.SceneManager.DrawAll();
                    device.VideoDriver.EndScene();

                    int fps = device.VideoDriver.FPS;
                    if (lastFPS != fps)
                    {
                        device.WindowCaption = "Irrlicht Engine - Quake 3 Map example [" +
                            device.VideoDriver.Name + "] FPS:" + fps.ToString();
                        lastFPS = fps;
                    }
                }
            }
            /*
            In the end, delete the Irrlicht device.
            */
            // Instead of device->drop, we'll use:
            GC.Collect();
        }
        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();
        }
Beispiel #48
0
    public void runIndoorTest()
    {
        device = new IrrlichtDevice(SelectedDriverType,
            new Dimension2D(800,600), 16, false, true, false);

        device.EventReceiver = this;
        device.ResizeAble = true;
        device.WindowCaption = "Irrlicht.NET indoor test";

        // load some textures and meshes

        ITexture texSydney = device.VideoDriver.GetTexture(@"..\..\media\sydney.bmp");
        ITexture texWall = device.VideoDriver.GetTexture(@"..\..\media\wall.jpg");
        ITexture texLogo = device.VideoDriver.GetTexture(@"..\..\media\irrlichtlogoaligned.jpg");
        Irrlicht.Scene.IAnimatedMesh mesh =
            device.SceneManager.GetMesh(@"..\..\media\sydney.md2");

        if (mesh == null)
        {
            System.Windows.Forms.MessageBox.Show(
                @"Could not load mesh ..\..\media\sydney.md2, exiting.",
                "Problem starting program");
            return;
        }

        // add a cube to the scene

        ISceneNode node = device.SceneManager.AddCubeSceneNode(15,
            null, -1, new Vector3D(30,-15,0));
        node.SetMaterialTexture(0, texWall);
        node.SetMaterialFlag(Irrlicht.Video.MaterialFlag.LIGHTING, false);

        // add an animator to the cube to make it rotate

        ISceneNodeAnimator anim = device.SceneManager.CreateRotationAnimator(new Vector3D(0.2f, 0.2f, 0));
        node.AddAnimator(anim);

        // add animated mesh

        IAnimatedMeshSceneNode anode = device.SceneManager.AddAnimatedMeshSceneNode(mesh, null, -1);
        anode.SetMaterialTexture(0, texSydney);
        anode.SetMaterialFlag(MaterialFlag.LIGHTING, false);

        anode.Scale = new Vector3D(2,2,2);
        anode.Position = new Vector3D(0, -20, 0);

        // add a shadow

        Shadow = anode.AddShadowVolumeSceneNode();
        if (Shadow != null)
            Shadow.Visible = false;

        // where no light there no shadow
        device.SceneManager.AddLightSceneNode(null, new Vector3D(20,100,-50),
            new Colorf(255,0,0), 200, -1);

        // add quake 3 level

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

        IAnimatedMesh q3levelmesh = device.SceneManager.GetMesh("20kdm2.bsp");
        ISceneNode q3node = device.SceneManager.AddOctTreeSceneNode(q3levelmesh, null, -1);
        q3node.Position = new Vector3D(-1370,-130,-1400);

        // create octtree triangle selector for q3 mesh

        ITriangleSelector selector = device.SceneManager.CreateOctTreeTriangleSelector(
            q3levelmesh.GetMesh(0), q3node, 128);

        // add billboard

        IBillboardSceneNode bill = device.SceneManager.AddBillboardSceneNode(null,
            new Dimension2Df(20,20), new Vector3D(0,0,0), -1);

        bill.SetMaterialType(MaterialType.TRANSPARENT_ADD_COLOR);
        bill.SetMaterialTexture(0, device.VideoDriver.GetTexture("../../media/particle.bmp"));
        bill.SetMaterialFlag(MaterialFlag.LIGHTING, false);
        bill.SetMaterialFlag(MaterialFlag.ZBUFFER, false);

        // create camera

        ICameraSceneNode cam =
            device.SceneManager.AddCameraSceneNodeFPS(null, 100, 300, -1);
        cam.Position = new Vector3D(20,300,-50);

        // make cursor invisible
        device.CursorControl.Visible = false;

        // create collision animator and add it to the camera

        ISceneNodeAnimator collAnim = device.SceneManager.CreateCollisionResponseAnimator(
            selector, cam,
            new Vector3D(30,50,30),  // size of ellipsoid around camera
            new Vector3D(0, -3, 0),  // gravity
            new Vector3D(0, 50, 0),  // translation
            0.0005f);                // sliding value

        cam.AddAnimator(collAnim);

        // load some font and set it into the skin

        IGUIFont font = device.GUIEnvironment.GetFont("../../media/fonthaettenschweiler.bmp");
        device.GUIEnvironment.Skin.Font = font;

        // add some gui stuff

        device.GUIEnvironment.AddMessageBox("Hello World",
            "I'm a Irrlicht.NET MessageBox. Please press SPACE to close me.", true,
            MessageBoxFlag.OK | MessageBoxFlag.CANCEL, null, -1);

        // start drawing loop

        int fps = 0;

        device.Run(); // fix for a temporary bug where quit messages are not be removed in the queue
        while(device.Run())
            if (device.WindowActive)
            {
                device.VideoDriver.BeginScene(true, true, new Color(255,0,0,50));

                // draw scene

                device.SceneManager.DrawAll();
                device.GUIEnvironment.DrawAll();

                // do some collision testing

                Line3D line = new Line3D();
                line.start = cam.Position;
                line.end = ((cam.Target - line.start).Normalize() * 1000.0f ) + line.start;

                Vector3D intersection = new Vector3D();
                Triangle3D tri = new Triangle3D();

                if (device.SceneManager.SceneCollisionManager.GetCollisionPoint(
                    line, selector, out intersection, out tri))
                {
                    bill.Position = intersection;

                    Material mat = new Material();
                    mat.Lighting = false;

                    device.VideoDriver.SetTransform(TransformationState.WORLD, new Matrix4());
                    device.VideoDriver.SetMaterial(mat);
                    device.VideoDriver.Draw3DTriangle(tri, new Color(0,255,0,0));
                }

                // draw 2d logo

                device.VideoDriver.Draw2DImage(
                    texLogo, new Position2D(10,10),
                    new Rect(0,0,88,31),
                    new Rect(new Position2D(0,0),device.VideoDriver.ScreenSize),
                    new Color(0xffffff), false);

                // draw some text
                font.Draw("Press 'S' to toggle the visibility of the realtime shadow.",
                    new Position2D(120,20), new Color(100,150,200,200));

                device.VideoDriver.EndScene();

                if (fps != device.VideoDriver.FPS)
                {
                    fps = device.VideoDriver.FPS;
                    device.WindowCaption = "Irrlicht.NET test (primitives:" +
                        device.VideoDriver.PrimitiveCountDrawn + ") fps:" + fps;
                }
            }
    }
Beispiel #49
0
        public void run()
        {
            /* At first, we let the user select the driver type,
               then start up the engine, set a caption, and get a
               pointer to the video driver.
            */

            // ask user for driver
            DriverType driverType;

            // Ask user to select driver:
            StringBuilder sb = new StringBuilder();
            sb.Append("Please select the driver you want for this example:\n");
            sb.Append("\n(a) Direct3D 9.0c\n(b) Direct3D 8.1\n(c) OpenGL 1.5");
            sb.Append("\n(d) Software Renderer\n(e) Apfelbaum Software Renderer");
            sb.Append("\n(f) Null Device\n(otherKey) exit\n\n");

            // Get the user's input:
            TextReader tIn = Console.In;
            TextWriter tOut = Console.Out;
            tOut.Write(sb.ToString());
            string input = tIn.ReadLine();

            // Select device based on user's input:
            switch (input)
            {
                case "a":
                    driverType = DriverType.DIRECT3D9;
                    break;
                case "b":
                    driverType = DriverType.DIRECT3D8;
                    break;
                case "c":
                    driverType = DriverType.OPENGL;
                    break;
                case "d":
                    driverType = DriverType.SOFTWARE;
                    break;
                case "e":
                    driverType = DriverType.SOFTWARE2;
                    break;
                case "f":
                    driverType = DriverType.NULL_DRIVER;
                    break;
                default:
                    return;
            }

            // Create device and exit if creation fails:
            device = new IrrlichtDevice(driverType, new Dimension2D(1024, 768), 32, false, true, true);

            if (device == null)
            {
                tOut.Write("Device creation failed.");
                return;
            }

            /*
            Get a pointer to the video driver and the SceneManager so that
            we do not always have to write device->getVideoDriver() and
            device->getSceneManager().
            */

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

            device.FileSystem.AddZipFileArchive(path+"map-20kdm2.pk3");

            IAnimatedMesh q3levelmesh = smgr.GetMesh("20kdm2.bsp");
            ISceneNode q3node = null;
            if (q3levelmesh!=null)
                q3node=smgr.AddOctTreeSceneNode(q3levelmesh.GetMesh(0),null,0);

            /*So far so good, we've loaded the quake 3 level like in tutorial 2.
             Now, here comes something different: We create a triangle selector. A
             triangle selector is a class which can fetch the triangles from scene
             nodes for doing different things with them, for example collision
             detection. There are different triangle selectors, and all can be
             created with the ISceneManager. In this example, we create an
             OctTreeTriangleSelector, which optimizes the triangle output a little
             bit by reducing it like an octree. This is very useful for huge meshes
             like quake 3 levels.
             After we created the triangle selector, we attach it to the q3node.
             This is not necessary, but in this way, we do not need to care for the
             selector, for example dropping it after we do not need it anymore.*/

            ITriangleSelector selector = null;
            if (q3node!=null)
            {
                q3node.Position= new Vector3D(-1370,-130,-1400);
                selector=smgr.CreateOctTreeTriangleSelector(
                    q3levelmesh.GetMesh(0),q3node,128);
                // not implemented but not necessary
                //q3node.TriangleSelector=selector;
            }

            /*We add a first person shooter camera to the scene for being able to move in
              the quake 3 level like in tutorial 2. But this, time, we add a special
              animator to the camera: A Collision Response animator. This thing modifies
              the scene node to which it is attached to in that way, that it may no
              more move through walls and is affected by gravity. The only thing we have
              to tell the animator is how the world looks like, how big the scene node is,
              how gravity and so on. After the collision response animator is attached to
              the camera, we do not have to do anything more for collision detection,
              anything is done automaticly, all other collision detection code below is
              for picking. And please note another cool feature: The collsion response
              animator can be attached also to all other scene nodes, not only to cameras.
              And it can be mixed with other scene node animators. In this way, collision
              detection and response in the Irrlicht engine is really, really easy.
              Now we'll take a closer look on the parameters of
              createCollisionResponseAnimator(). The first parameter is the TriangleSelector,
              which specifies how the world, against collision detection is done looks like.
              The second parameter is the scene node, which is the object, which is affected
              by collision detection, in our case it is the camera. The third defines how big
              the object is, it is the radius of an ellipsoid. Try it out and change the radius
              to smaller values, the camera will be able to move closer to walls after this.
              The next parameter is the direction and speed of gravity. You could set it to
              (0,0,0) to disable gravity. And the last value is just a translation: Without
              this, the ellipsoid with which collision detection is done would be around
              the camera, and the camera would be in the middle of the ellipsoid. But as
              human beings, we are used to have our eyes on top of the body, with which
              we collide with our world, not in the middle of it. So we place the scene
              node 50 units over the center of the ellipsoid with this parameter. And
              that's it, collision detection works now.
             */
            ICameraSceneNode camera = smgr.AddCameraSceneNodeFPS(null,100,300,0);
            camera.Position=new Vector3D(-100,50,-150);
            ISceneNodeAnimator anim = smgr.CreateCollisionResponseAnimator(
                selector,camera,new Vector3D(30,50,30),
                new Vector3D(0,-3,0),new Vector3D(0,50,0),0);
            camera.AddAnimator(anim);

            /*Because collision detection is no big deal in irrlicht, I'll describe how
              to do two different types of picking in the next section. But before this,
              I'll prepare the scene a little. I need three animated characters which we
              could pick later, a dynamic light for lighting them, a billboard for drawing
              where we found an intersection, and, yes, I need to get rid of this mouse
              cursor. :)*/
            //disable mouse cursor
            device.CursorControl.Visible=false;

            // add billboard
            IBillboardSceneNode bill = smgr.AddBillboardSceneNode(
                null,new Dimension2Df(20,20),new Vector3D(),0);
            bill.SetMaterialType(MaterialType.TRANSPARENT_ADD_COLOR);
            bill.SetMaterialTexture(0,driver.GetTexture(
                path+"particle.bmp"));
            bill.SetMaterialFlag(MaterialFlag.LIGHTING,false);
            bill.SetMaterialFlag(MaterialFlag.ZBUFFER,false);
            Material material = new Material();
            material.Texture1= driver.GetTexture(
                path+"faerie2.bmp");
            material.Lighting=true;

            IAnimatedMeshSceneNode node = null;
            IAnimatedMesh faerie = smgr.GetMesh(
                path+"faerie.md2");
            if (faerie!=null)
            {
                node=smgr.AddAnimatedMeshSceneNode(faerie,null,0);
                node.Position=new Vector3D(-70,0,-90);
                node.SetMD2Animation(MD2AnimationType.RUN);
                node.SetMaterial(0,material);

                node=smgr.AddAnimatedMeshSceneNode(faerie,null,0);
                node.Position=new Vector3D(-70,0,-30);
                node.SetMD2Animation(MD2AnimationType.SALUTE);
                node.SetMaterial(0,material);

                node=smgr.AddAnimatedMeshSceneNode(faerie,null,0);
                node.Position=new Vector3D(-70,0,-60);
                node.SetMD2Animation(MD2AnimationType.JUMP);
                node.SetMaterial(0,material);
            }

            material.Texture1=null;
            material.Lighting=false;

            //Add a light
            smgr.AddLightSceneNode(null,new Vector3D(-60,100,400),
                new Colorf(1.0f,1.0f,1.0f,1.0f),600,0);

            /*For not making it too complicated, I'm doing picking inside the drawing
              loop. We take two pointers for storing the current and the last selected
              scene node and start the loop.*/
            ISceneNode selectedSceneNode =null;
            ISceneNode lastSelectedSceneNode =null;

            int lastFPS=-1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    device.VideoDriver.BeginScene(true, true, new Color(0, 200, 200, 200));
                    device.SceneManager.DrawAll();
                    /*After we've drawn the whole scene whit smgr->drawAll(), we'll do the
                      first picking: We want to know which triangle of the world we are
                      looking at. In addition, we want the exact point of the quake 3
                      level we are looking at. For this, we create a 3d line starting at
                      the position of the camera and going through the lookAt-target of it.
                      Then we ask the collision manager if this line collides with a
                      triangle of the world stored in the triangle selector. If yes, we draw
                      the 3d triangle and set the position of the billboard to the intersection
                      point.*/
                    Line3D line = new Line3D();
                    line.start=camera.Position;
                    line.end=line.start+
                        (camera.Target - line.start).Normalize() * 1000;
                    Vector3D intersection;
                    Triangle3D tri;
                    if (smgr.SceneCollisionManager.GetCollisionPoint(
                        line,selector,out intersection, out tri))
                    {
                        bill.Position=intersection;

                        driver.SetTransform(TransformationState.WORLD, new Matrix4());
                        driver.SetMaterial(material);
                        driver.Draw3DTriangle(tri,new Color(0,255,0,0));
                    }
                    /*Another type of picking supported by the Irrlicht Engine is scene node
                      picking based on bouding boxes. Every scene node has got a bounding box,
                      and because of that, it's very fast for example to get the scene node
                      which the camera looks at. Again, we ask the collision manager for this,
                      and if we've got a scene node, we highlight it by disabling Lighting in
                      its material, if it is not the billboard or the quake 3 level.*/
                    selectedSceneNode=smgr.SceneCollisionManager.
                        GetSceneNodeFromCameraBB(camera,0);

                    if (lastSelectedSceneNode!=null)
                        lastSelectedSceneNode.SetMaterialFlag(
                            MaterialFlag.LIGHTING, true);

                    if (selectedSceneNode==q3node||
                        selectedSceneNode==bill)
                        selectedSceneNode=null;

                    if(selectedSceneNode!=null)
                        selectedSceneNode.SetMaterialFlag(
                            MaterialFlag.LIGHTING,false);
                    lastSelectedSceneNode=selectedSceneNode;

                    /*That's it, we just have to finish drawing.*/

                    driver.EndScene();

                    int fps = device.VideoDriver.FPS;
                    if (lastFPS != fps)
                    {
                        device.WindowCaption = "Irrlicht Engine - Quake 3 Map example [" +
                            device.VideoDriver.Name + "] FPS:" + fps.ToString();
                        lastFPS = fps;
                    }
                }
            }
            /*
            In the end, delete the Irrlicht device.
            */
            // Instead of device->drop, we'll use:
            GC.Collect();
        }
Beispiel #50
0
    public void runShaderTest()
    {
        // testing irrlicht with shaders

        device = new IrrlichtDevice(SelectedDriverType,
            new Dimension2D(800,600), 16, false, true, false);

        device.EventReceiver = this;
        device.ResizeAble = true;
        device.WindowCaption = "Irrlicht.NET shader test";

        String vsFileName = "";
        String psFileName = "";
        UseHighLevelShaders = false;

        switch(SelectedDriverType)
        {
            case DriverType.DIRECT3D8:
                psFileName = "../../media/d3d8.psh";
                vsFileName = "../../media/d3d8.vsh";
                break;
            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;
        }

        // create materials
        int newMaterialType1 = 0;
        int newMaterialType2 = 0;

        if ( device.VideoDriver.GPUProgrammingServices != null )
        {
            IShaderConstantSetCallBack callBack = this;

            if (UseHighLevelShaders)
            {
                newMaterialType1 = device.VideoDriver.GPUProgrammingServices.AddHighLevelShaderMaterialFromFiles(
                    vsFileName, "vertexMain", VertexShaderType.VST_VS_1_1,
                    psFileName, "pixelMain", PixelShaderType.PST_PS_1_1,
                    callBack, MaterialType.SOLID);

                newMaterialType2 = device.VideoDriver.GPUProgrammingServices.AddHighLevelShaderMaterialFromFiles(
                    vsFileName, "vertexMain", VertexShaderType.VST_VS_1_1,
                    psFileName, "pixelMain", PixelShaderType.PST_PS_1_1,
                    callBack, MaterialType.TRANSPARENT_ADD_COLOR);
            }
            else
            {
                newMaterialType1 = device.VideoDriver.GPUProgrammingServices.AddShaderMaterialFromFiles(
                    vsFileName, psFileName, callBack, MaterialType.SOLID );

                newMaterialType2 = device.VideoDriver.GPUProgrammingServices.AddShaderMaterialFromFiles(
                    vsFileName, psFileName, callBack, MaterialType.TRANSPARENT_ADD_COLOR );
            }
        }

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

        ISceneNode node = device.SceneManager.AddCubeSceneNode(50, null, -1, new Vector3D(0,0,0));
        node.SetMaterialTexture(0, device.VideoDriver.GetTexture("../../media/wall.bmp"));
        node.SetMaterialType((MaterialType)newMaterialType1);
        node.SetMaterialFlag(Irrlicht.Video.MaterialFlag.LIGHTING, false);

        //device.SceneManager.AddTextSceneNode( device.GUIEnvironment.BuiltInFont,
        //	"PS & VS & EMT_SOLID", new Color(255,255,255,255), node, new Vector3D(0,0,0), -1);

        ISceneNodeAnimator anim = device.SceneManager.CreateRotationAnimator(
            new Vector3D(0,0.3f,0) );
        node.AddAnimator(anim);

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

        node = device.SceneManager.AddCubeSceneNode(50, null, -1, new Vector3D(0,-10,50));
        node.SetMaterialTexture(0, device.VideoDriver.GetTexture("../../media/wall.bmp"));
        node.SetMaterialType((MaterialType)newMaterialType2);
        node.SetMaterialFlag(Irrlicht.Video.MaterialFlag.LIGHTING, false);

        //device.SceneManager.AddTextSceneNode( device.GUIEnvironment.BuiltInFont,
        //	"PS & VS & EMT_TRANSPARENT", new Color(255,255,255,255), node, new Vector3D(0,0,0), -1);

        anim = device.SceneManager.CreateRotationAnimator(
            new Vector3D(0,0.3f,0) );
        node.AddAnimator(anim);

        //Then we add a third cube without a shader on it, to be able to compare the
        //cubes.

        node = device.SceneManager.AddCubeSceneNode(50, null, -1, new Vector3D(0,50,25));
        node.SetMaterialTexture(0, device.VideoDriver.GetTexture("../../media/wall.bmp"));
        node.SetMaterialFlag(Irrlicht.Video.MaterialFlag.LIGHTING, false);

        //device.SceneManager.AddTextSceneNode( device.GUIEnvironment.BuiltInFont,
        //	"NO SHADER", new Color(255,255,255,255), node, new Vector3D(0,0,0), -1);

        // And last, we add a skybox and a user controlled camera to the scene.

        device.SceneManager.AddSkyBoxSceneNode(
            device.VideoDriver.GetTexture("../../media/irrlicht2_up.jpg"),
            device.VideoDriver.GetTexture("../../media/irrlicht2_dn.jpg"),
            device.VideoDriver.GetTexture("../../media/irrlicht2_lf.jpg"),
            device.VideoDriver.GetTexture("../../media/irrlicht2_rt.jpg"),
            device.VideoDriver.GetTexture("../../media/irrlicht2_ft.jpg"),
            device.VideoDriver.GetTexture("../../media/irrlicht2_bk.jpg"), null, -1 );

        ICameraSceneNode cam = device.SceneManager.AddCameraSceneNodeFPS();
        cam.Target = new Vector3D(0,0,0);
        cam.Position = new Vector3D(-100,50,100);

        device.CursorControl.Visible = false;

        device.Run(); // fix for a temporary bug where quit messages are not be removed in the queue
        while(device.Run())
            if (device.WindowActive)
            {
                device.VideoDriver.BeginScene(true, true, new Color(255,0,0,50));

                device.SceneManager.DrawAll();
                device.GUIEnvironment.DrawAll();

                device.VideoDriver.EndScene();
            }
    }
Beispiel #51
0
    public void displayMainMenu()
    {
        device = new IrrlichtDevice(DriverType.SOFTWARE,
            new Dimension2D(512, 384), 16, false, false, false);

        // set event receiver
        device.EventReceiver = this;

        // set text

        device.WindowCaption = "Irrlicht .NET test demos - main menu";

        // load font

        IGUIFont font = device.GUIEnvironment.GetFont("../../media/fonthaettenschweiler.bmp");
        if (font != null)
            device.GUIEnvironment.Skin.Font = font;

        // add images

        device.GUIEnvironment.AddImage( device.VideoDriver.GetTexture("../../media/dotnetback.jpg"),
            new Position2D(0,0), false, null, -1, "");

        // add list box

        Rect pos = new Rect(150,60,350,135);

        IGUIListBox box =
            device.GUIEnvironment.AddListBox( pos, null, -1, true );

        box.AddItem("Irrlicht Software Renderer 1.0");
        box.AddItem("Apfelbaum Software Renderer 1.0");
        box.AddItem("Direct3D 8.1");
        box.AddItem("Direct3D 9.0c");
        box.AddItem("OpenGL 1.5");
        box.Selected = ((int)SelectedDriverType)-1;

        // add terrain button

        pos.LowerRightCorner.Y += 50;
        pos.UpperLeftCorner.Y += 100;
        device.GUIEnvironment.AddButton( pos, null,
            (int)TestScenarios.TERRAIN_TEST, "Start Terrain Test" );

        // add indoor button

        pos.LowerRightCorner.Y += 30;
        pos.UpperLeftCorner.Y += 30;
        device.GUIEnvironment.AddButton( pos, null,
            (int)TestScenarios.INDOOR_TEST, "Start Indoor Test" );

        // add windows forms button

        pos.LowerRightCorner.Y += 30;
        pos.UpperLeftCorner.Y += 30;
        device.GUIEnvironment.AddButton( pos, null,
            (int)TestScenarios.WINDOWS_FORMS_TEST, "Start Windows.Forms Test" );

        // add shader test button

        pos.LowerRightCorner.Y += 30;
        pos.UpperLeftCorner.Y += 30;
        device.GUIEnvironment.AddButton( pos, null,
            (int)TestScenarios.SHADER_TEST, "Start Shader Test" );

        // add copyright stuff

        IGUIStaticText text = device.GUIEnvironment.AddStaticText(
            "Background 3D scene created by Alvaro F. Celis, rendered using Irrlicht",
            new Rect(2,368,500,384), false, false, null, -1);

        text.OverrideColor = new Color(100,150,150,150);

        // draw everything

        while(device.Run() && ClickedButton == TestScenarios.NONE)
            if (device.WindowActive)
            {
                device.VideoDriver.BeginScene(true, true, new Color(255,0,0,50));

                device.SceneManager.DrawAll();
                device.GUIEnvironment.DrawAll();

                device.VideoDriver.EndScene();
            }

        device.CloseDevice();
        return;
    }
Beispiel #52
0
    public void runTerrainTest()
    {
        device = new IrrlichtDevice(SelectedDriverType,
            new Dimension2D(800,600), 16, false, false, false);

        device.EventReceiver = this;
        device.ResizeAble = true;
        device.WindowCaption = "Irrlicht.NET terrain test";

        // create a camera

        ICameraSceneNode cam =
            device.SceneManager.AddCameraSceneNodeFPS(null, 100, 1200, -1);

        cam.Position = new Vector3D(1900*2, 255*2, 3700*2);
        cam.Target = new Vector3D(2397*2, 343*2, 2700*2);
        cam.FarValue = 12000.0f;

        // create the terrain

        ITerrainSceneNode terrain = device.SceneManager.AddTerrainSceneNode(
            "../../media/terrain-heightmap.bmp",
            null, -1, new Vector3D(), new Vector3D(40, 4.4f, 40), new Color(255,255,255,255));

        terrain.SetMaterialFlag(MaterialFlag.LIGHTING, false);
        terrain.SetMaterialType(MaterialType.DETAIL_MAP);
        terrain.SetMaterialTexture(0, device.VideoDriver.GetTexture("../../media/terrain-texture.jpg"));
        terrain.SetMaterialTexture(1, device.VideoDriver.GetTexture("../../media/detailmap3.jpg"));

        terrain.ScaleTexture( 1.0f, 20.0f );

        // create terrain triangle selector for collision

        ITriangleSelector selector = device.SceneManager.CreateTerrainTriangleSelector( terrain, 0 );

        // create collision animator and add it to the camera

        ISceneNodeAnimator collAnim = device.SceneManager.CreateCollisionResponseAnimator(
            selector, cam,
            new Vector3D(30,50,30),  // size of ellipsoid around camera
            new Vector3D(0, 0, 0),  // gravity
            new Vector3D(0, 50, 0),  // translation
            0.0005f);                // sliding value

        cam.AddAnimator(collAnim);

        // add sky box

        device.SceneManager.AddSkyBoxSceneNode(
            device.VideoDriver.GetTexture("../../media/irrlicht2_up.jpg"),
            device.VideoDriver.GetTexture("../../media/irrlicht2_dn.jpg"),
            device.VideoDriver.GetTexture("../../media/irrlicht2_lf.jpg"),
            device.VideoDriver.GetTexture("../../media/irrlicht2_rt.jpg"),
            device.VideoDriver.GetTexture("../../media/irrlicht2_ft.jpg"),
            device.VideoDriver.GetTexture("../../media/irrlicht2_bk.jpg"),
            null, -1);

        // make cursor invisible
        device.CursorControl.Visible = false;

        // draw everything

        device.Run(); // fix for a temporary bug where quit messages are not be removed in the queue
        while(device.Run())
        {
            if (device.WindowActive)
            {
                device.VideoDriver.BeginScene(true, true, new Color(255,0,0,50));

                device.SceneManager.DrawAll();
                device.GUIEnvironment.DrawAll();

                device.VideoDriver.EndScene();
            }
        }
    }
Beispiel #53
0
        static void Main()
        {
            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.SolidYellow;

            // 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.SolidWhite);
                }

                driver.EndScene();
            }

            device.Drop();
        }
Beispiel #54
0
    void runIrrlichtInWindowsFormTest()
    {
        // testing irrlicht running embedded in a windows form

        System.Windows.Forms.Form f = new System.Windows.Forms.Form();
        f.Text = "Irrlicht running embedded in Windows.Form";

        device = new IrrlichtDevice(SelectedDriverType,
            new Dimension2D(800,600), 16, false, false, false, true, f.Handle);

        f.Show();

        // set up a simple scene

        ICameraSceneNode cam =
            device.SceneManager.AddCameraSceneNode( null, new Vector3D(), new Vector3D(), -1);

        ISceneNodeAnimator anim = device.SceneManager.CreateFlyCircleAnimator(
            new Vector3D(0,10,0), 30.0f, 0.003f);
        cam.AddAnimator(anim);

        ISceneNode cube = device.SceneManager.AddCubeSceneNode(25, null, -1, new Vector3D());
        cube.SetMaterialTexture(0, device.VideoDriver.GetTexture("../../media/rockwall.bmp"));
        cube.SetMaterialFlag(Irrlicht.Video.MaterialFlag.LIGHTING, false);

        // draw everything

        device.Run(); // fix for a temporary bug where quit messages are not be removed in the queue
        while(device.Run() && f.Visible)
            if (device.WindowActive)
            {
                device.VideoDriver.BeginScene(true, true, new Color(255,0,0,50));

                device.SceneManager.DrawAll();
                device.GUIEnvironment.DrawAll();

                device.VideoDriver.EndScene();
            }
    }
Beispiel #55
0
        static void Main(string[] args)
        {
            device = IrrlichtDevice.CreateDevice(DriverType.Direct3D8, 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.OpaqueWhite;
            Color       fontActionColor     = Color.OpaqueYellow;

            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(false);

                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();
        }
Beispiel #56
0
        static void Main(string[] args)
        {
            /*
               Like in the HelloWorld example, we create an IrrlichtDevice with
               createDevice(). The difference now is that we ask the user to select
               which hardware accelerated driver to use. The Software device would be
               too slow to draw a huge Quake 3 map, but just for the fun of it, we make
               this decision possible too.
               */

            // ask user for driver
            DriverType driverType;

            // Ask user to select driver:
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Please select the driver you want for this example:");
            sb.AppendLine("(a) Direct3D 9.0c\n(b) Direct3D 8.1\n(c) OpenGL 1.5");
            sb.AppendLine("(d) Software Renderer\nApfelbaum Software Renderer");
            sb.AppendLine("(f) Null Device\n(otherKey) exit\n\n");

            // Get the user's input:
            TextReader tIn = Console.In;
            TextWriter tOut = Console.Out;
            tOut.Write(sb.ToString());
            string input = tIn.ReadLine();

            // Select device based on user's input:
            switch (input)
            {
                case "a":
                    driverType = DriverType.DIRECT3D9;
                    break;
                case "b":
                    driverType = DriverType.DIRECT3D8;
                    break;
                case "c":
                    driverType = DriverType.OPENGL;
                    break;
                case "d":
                    driverType = DriverType.SOFTWARE;
                    break;
                case "e":
                    driverType = DriverType.SOFTWARE2;
                    break;
                case "f":
                    driverType = DriverType.NULL_DRIVER;
                    break;
                default:
                    return;
            }

            // Create device and exit if creation fails:
            IrrlichtDevice device = new IrrlichtDevice(driverType, new Dimension2D(1024, 768), 32, true, true, true);

            if (device == null)
            {
                tOut.Write("Device creation failed.");
                return;
            }

            /*
            Get a pointer to the video driver and the SceneManager so that
            we do not always have to write device->getVideoDriver() and
            device->getSceneManager().
            */
            // I just left these lines here for example purposes:
            //irrv.IVideoDriver driver = device.VideoDriver;
            //irrs.ISceneManager smgr = device.SceneManager;

            /*
            To display the Quake 3 map, we first need to load it. Quake 3 maps
            are packed into .pk3 files wich are nothing other than .zip files.
            So we add the .pk3 file to our FileSystem. After it was added,
            we are able to read from the files in that archive as they would
            directly be stored on disk.
            */
            // I changed this to make it more obvious where to put the media files.
            device.FileSystem.AddZipFileArchive(Application.StartupPath + "\\map-20kdm2.pk3");

            /*
            Now we can load the mesh by calling getMesh(). We get a pointer returned
            to a IAnimatedMesh. As you know, Quake 3 maps are not really animated,
            they are only a huge chunk of static geometry with some materials
            attached. Hence the IAnimated mesh consists of only one frame,
            so we get the "first frame" of the "animation", which is our quake level
            and create an OctTree scene node with it, using addOctTreeSceneNode().
            The OctTree optimizes the scene a little bit, trying to draw only geometry
            which is currently visible. An alternative to the OctTree would be a
            AnimatedMeshSceneNode, which would draw always the complete geometry of
            the mesh, without optimization. Try it out: Write addAnimatedMeshSceneNode
            instead of addOctTreeSceneNode and compare the primitives drawed by the
            video driver. (There is a getPrimitiveCountDrawed() method in the
            IVideoDriver class). Note that this optimization with the Octree is only
            useful when drawing huge meshes consiting of lots of geometry.
            */
            // I changed this to make it more obvious where to put the media files.
            IAnimatedMesh mesh = device.SceneManager.GetMesh("20kdm2.bsp");
            ISceneNode node = null;

            if (mesh != null)
                node = device.SceneManager.AddOctTreeSceneNode(mesh, null, 0);

            /*
            Because the level was modelled not around the origin (0,0,0), we translate
            the whole level a little bit.
            */
            if (node != null)
                node.Position = (new Vector3D(-1300, -144, -1249));

            /*
            Now we only need a Camera to look at the Quake 3 map.
            And we want to create a user controlled camera. There are some
            different cameras available in the Irrlicht engine. For example the
            Maya Camera which can be controlled compareable to the camera in Maya:
            Rotate with left mouse button pressed, Zoom with both buttons pressed,
            translate with right mouse button pressed. This could be created with
            addCameraSceneNodeMaya(). But for this example, we want to create a
            camera which behaves like the ones in first person shooter games (FPS).
            */
            device.SceneManager.AddCameraSceneNodeFPS();

            /*
            The mouse cursor needs not to be visible, so we make it invisible.
            */
            device.CursorControl.Visible = false;

            /*
            We have done everything, so lets draw it. We also write the current
            frames per second and the drawn primitives to the caption of the
            window. The 'if (device->isWindowActive())' line is optional, but
            prevents the engine render to set the position of the mouse cursor
            after task switching when other program are active.
            */
            int lastFPS = -1;

            while (device.Run())
            {
                if (device.WindowActive)
                {
                    device.VideoDriver.BeginScene(true, true, new Color(0, 200, 200, 200));
                    device.SceneManager.DrawAll();
                    device.VideoDriver.EndScene();

                    int fps = device.VideoDriver.FPS;
                    if (lastFPS != fps)
                    {
                        device.WindowCaption = "Irrlicht Engine - Quake 3 Map example [" +
                            device.VideoDriver.Name + "] FPS:" + fps.ToString();
                        lastFPS = fps;
                    }
                }
            }

            /*
            In the end, delete the Irrlicht device.
            */
            // Instead of device->drop, we'll use:
            GC.Collect();
        }