Esempio n. 1
0
        static void Main(string[] args)
        {
            RenderForm form = new RenderForm("Underground - POO version");
            form.Size = new Size(1280, 700);

            Direct3D direct3D = new Direct3D();
            PresentParameters parameters = new PresentParameters(form.ClientSize.Width, form.ClientSize.Height);
            Device device = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, parameters);
            ResManager.Initialize(ref device, ref form);
            IngameClass ingame = new IngameClass(ref device, ref form);

            Stopwatch clock = new Stopwatch();
            clock.Start();

            RenderLoop.Run(form, () =>
            {
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                device.BeginScene();

                ingame.Draw(ref device, ref form, ref clock);

                device.EndScene();
                device.Present();
            });

            ResManager.Dispose();
            device.Dispose();
            direct3D.Dispose();
        }
Esempio n. 2
0
 public override void Dispose()
 {
     if (dx9Device != null)
     {
         dx9Device.Dispose();
     }
     if (dx9ScreenSurface != null)
     {
         dx9ScreenSurface.Dispose();
     }
     if (screenShot != null)
     {
         screenShot.Dispose();
     }
     bmpData = null;
 }
Esempio n. 3
0
        public static void Initiate()
        {
            var form = new RenderForm("SharpDX - MiniCube Direct3D9 Sample");
            // Creates the Device
            var direct3D = new Direct3D();
            var device   = new SharpDX.Direct3D9.Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

            // Prepare matrices
            var view     = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            var proj     = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f);
            var viewProj = Matrix.Multiply(view, proj);

            // Use clock
            var clock = new Stopwatch();

            clock.Start();

            string Game = "WOT";

            switch (Game)
            {
            case "WOT":
                _list.Add(new DrawTextureAndCatchIt(SharpDX.Direct3D9.Texture.FromFile(device, "Resources/error_enter.png"), SharpDX.Direct3D9.Texture.FromFile(device, "Resources/error_6473.png"), new SharpDX.Mathematics.Interop.RawRectangle(1, 1, 100, 100), new SharpDX.Vector3(100, 100, 0)));
                _list.Add(new DrawTextureAndCatchIt(SharpDX.Direct3D9.Texture.FromFile(device, "Resources/edit-addenter.png"), SharpDX.Direct3D9.Texture.FromFile(device, "Resources/edit-add.png"), new SharpDX.Mathematics.Interop.RawRectangle(1, 1, 100, 100), new SharpDX.Vector3(100, 400, 0)));
                break;
            }
            //choose game


            RenderLoop.Run(form, () =>
            {
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                device.BeginScene();
                foreach (DrawTextureAndCatchIt dr in _list)
                {
                    dr.CheckCursorPosition();
                    dr.DrawTexture(device);
                }

                device.EndScene();
                device.Present();
            });

            device.Dispose();
            direct3D.Dispose();
        }
Esempio n. 4
0
        public static void Main()
        {
            var form = new RenderForm("SimpleD3D9 by C#")
            {
                ClientSize = new Size(1024, 768)
            };

            var device = new D3D9Device(
                new Direct3D(),
                CUDADevice.Default.ID,
                DeviceType.Hardware,
                form.Handle,
                CreateFlags.HardwareVertexProcessing,
                new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

            var vertices = new VertexBuffer(device, Utilities.SizeOf <Vector4>() * Total, Usage.WriteOnly,
                                            VertexFormat.None, Pool.Default);

            var vertexElems = new []
            {
                new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
                new VertexElement(0, 12, DeclarationType.Ubyte4, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                VertexElement.VertexDeclarationEnd
            };

            var vertexDecl = new VertexDeclaration(device, vertexElems);

            var worker  = Worker.CreateByFunc(() => Generate(device));
            var updater = new SimpleD3D9(GPUModuleTarget.Worker(worker));

            var view = Matrix.LookAtLH(
                new Vector3(0.0f, 3.0f, -2.0f), // the camera position
                new Vector3(0.0f, 0.0f, 0.0f),  // the look-at position
                new Vector3(0.0f, 1.0f, 0.0f)); // the up direction

            var proj = Matrix.PerspectiveFovLH(
                (float)(Math.PI / 4.0), // the horizontal field of view
                1.0f,
                1.0f,
                100.0f);

            device.SetTransform(TransformState.View, view);
            device.SetTransform(TransformState.Projection, proj);
            device.SetRenderState(RenderState.Lighting, false);

            var vbres = RegisterVerticesResource(vertices);
            var clock = System.Diagnostics.Stopwatch.StartNew();

            RenderLoop.Run(form, () =>
            {
                var time = (float)(clock.Elapsed.TotalMilliseconds) / 300.0f;
                updater.Update(vbres, time);

                // Now normal D3D9 rendering procedure.
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, new ColorBGRA(0, 40, 100, 0), 1.0f, 0);
                device.BeginScene();

                device.VertexDeclaration = vertexDecl;
                device.SetStreamSource(0, vertices, 0, Utilities.SizeOf <Vector4>());
                // we use PointList as the graphics primitives
                device.DrawPrimitives(SharpDX.Direct3D9.PrimitiveType.PointList, 0, Total);

                device.EndScene();
                device.Present();
            });

            UnregisterVerticesResource(vbres);

            updater.Dispose();
            worker.Dispose();
            vertexDecl.Dispose();
            vertices.Dispose();
            device.Dispose();
            form.Dispose();
        }
        static void Main()
        {
            var worldSize = new Size2(1024, 768);
            var renderSize = new Size2(1920, 1080);
            const bool windowed = true;

            const int numParticles = 1000000;
            const int numEmitters = 5;
            const int budget = numParticles / numEmitters;

            var form = new RenderForm("Mercury Particle Engine - SharpDX.Direct3D9 Sample")
            {
                Size = new System.Drawing.Size(renderSize.Width, renderSize.Height)
            };

            var direct3d = new Direct3D();
            var device = new Device(direct3d, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(renderSize.Width, renderSize.Height) { PresentationInterval = PresentInterval.Immediate, Windowed = windowed });

            var view = new Matrix(
                1.0f, 0.0f, 0.0f, 0.0f,
                0.0f, -1.0f, 0.0f, 0.0f,
                0.0f, 0.0f, -1.0f, 0.0f,
                0.0f, 0.0f, 0.0f, 1.0f);
            var proj = Matrix.OrthoOffCenterLH(worldSize.Width * -0.5f, worldSize.Width * 0.5f, worldSize.Height * 0.5f, worldSize.Height * -0.5f, 0f, 1f);
            var wvp = Matrix.Identity * view * proj;

            var emitters = new Emitter[numEmitters];

            for (int i = 0; i < numEmitters; i++)
            {
                emitters[i] = new Emitter(budget, TimeSpan.FromSeconds(600), Profile.BoxFill(worldSize.Width, worldSize.Height))
                {
                    Parameters = new ReleaseParameters
                    {
                        Colour = new Colour(220f, 0.7f, 0.1f),
                        Opacity = 1f,
                        Quantity = budget,
                        Speed = 0f,
                        Scale = 1f,
                        Rotation = 0f,
                        Mass = new RangeF(8f, 12f)
                    },
                    BlendMode = BlendMode.Add,
                    ReclaimInterval = 600f
                };

                emitters[i].Modifiers.Add(new DragModifier
                {
                    DragCoefficient = .47f,
                    Density         = .15f
                }, 15f);
                emitters[i].Modifiers.Add(new VortexModifier
                {
                    Position = Coordinate.Origin,
                    Mass = 200f,
                    MaxSpeed = 1000f
                }, 30f);
                emitters[i].Modifiers.Add(new VelocityHueModifier
                {
                    StationaryHue = 220f,
                    VelocityHue = 300f,
                    VelocityThreshold = 800f
                }, 15f);
                emitters[i].Modifiers.Add(new ContainerModifier
                        {
                            RestitutionCoefficient = 0.75f,
                            Position = Coordinate.Origin,
                            Width    = worldSize.Width,
                            Height   = worldSize.Height
                        }, 30f);
                emitters[i].Modifiers.Add(new MoveModifier(), 60f);
            };

            var renderer = new PointSpriteRenderer(device, budget)
            {
            //                EnableFastFade = true
            };

            var texture = Texture.FromFile(device, "Pixel.dds");

            var fontDescription = new FontDescription
            {
                Height         = 16,
                FaceName       = "Consolas",
                PitchAndFamily = FontPitchAndFamily.Mono,
                Quality        = FontQuality.Draft
            };

            var font = new Font(device, fontDescription);

            var totalTimer = Stopwatch.StartNew();
            var updateTimer = new Stopwatch();
            var renderTimer = new Stopwatch();

            var totalTime = 0f;

            foreach (var emitter in emitters)
            {
                emitter.Trigger(Coordinate.Origin);
            }

            float updateTime = 0f;

            RenderLoop.Run(form, () =>
                {
                    // ReSharper disable AccessToDisposedClosure
                    var frameTime = ((float)totalTimer.Elapsed.TotalSeconds) - totalTime;
                    totalTime = (float)totalTimer.Elapsed.TotalSeconds;

                    var mousePosition = form.PointToClient(RenderForm.MousePosition);

                    Task.WaitAll(
                        Task.Factory.StartNew(() =>
                        {
                            var mouseVector = new Vector3(mousePosition.X, mousePosition.Y, 0f);
                            var unprojected = Vector3.Unproject(mouseVector, 0, 0, renderSize.Width, renderSize.Height, 0f, 1f, wvp);

                            Parallel.ForEach(emitters, emitter => ((VortexModifier)emitter.Modifiers.ElementAt(1)).Position = new Coordinate(unprojected.X, unprojected.Y));

                            updateTimer.Restart();
                            Parallel.ForEach(emitters, emitter => emitter.Update(frameTime));
                            updateTimer.Stop();
                            updateTime = (float)updateTimer.Elapsed.TotalSeconds;
                            _updateTimes.Add(updateTime);
                        }),
                        Task.Factory.StartNew(() =>
                        {
                            device.Clear(ClearFlags.Target, Color.Black, 1f, 0);
                            device.BeginScene();

                            renderTimer.Restart();
                            for (int i = 0; i < numEmitters; i++)
                            {
                                renderer.Render(emitters[i], wvp, texture);
                            }
                            renderTimer.Stop();
                            var renderTime = (float)renderTimer.Elapsed.TotalSeconds;

                            var totalUpdateTime = 0f;
            //	                        foreach (var time in _updateTimes)
            //	                        {
            //		                        totalUpdateTime += time;
            //	                        }
            //	                        totalUpdateTime /= _updateTimes.Count;
            //
            //							if(_updateTimes.Count > 100)
            //								_updateTimes.RemoveAt(0);

                            font.DrawText(null, String.Format("Time:        {0}", totalTimer.Elapsed), 0, 0, Color.White);
                            font.DrawText(null, String.Format("Particles:   {0:n0}", emitters[0].ActiveParticles * numEmitters), 0, 16, Color.White);
                            font.DrawText(null, String.Format("Update:      {0:n4} ({1,8:P2})", updateTime, updateTime / 0.01666666f), 0, 32, Color.White);
                            font.DrawText(null, String.Format("Render:      {0:n4} ({1,8:P2})", renderTime, renderTime / 0.01666666f), 0, 48, Color.White);

                            device.EndScene();
                            device.Present();
                        })
                    );

                    if (Keyboard.IsKeyDown(Key.Escape))
                        Environment.Exit(0);
            // ReSharper restore AccessToDisposedClosure
                });

            form.Dispose();
            font.Dispose();
            device.Dispose();
            direct3d.Dispose();
        }
Esempio n. 6
0
        private static void Main()
        {
            var form = new RenderForm("SharpDX - MiniCube Direct3D9 Sample");

            // Creates the Device
            var direct3D = new Direct3D();
            var device = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

            // Creates the VertexBuffer
            var vertices = new VertexBuffer(device, Utilities.SizeOf<Vector4>() * 2 * 36, Usage.WriteOnly, VertexFormat.None, Pool.Managed);
            vertices.Lock(0, 0, LockFlags.None).WriteRange(new[]
                                  {
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), // Front
                                      new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f), // BACK
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f), // Top
                                      new Vector4(-1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f,  1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, 1.0f, -1.0f,  1.0f), new Vector4(0.0f, 0.0f, 1.0f, 1.0f),

                                      new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f), // Bottom
                                      new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4(-1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,-1.0f, -1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),
                                      new Vector4( 1.0f,-1.0f,  1.0f,  1.0f), new Vector4(1.0f, 1.0f, 0.0f, 1.0f),

                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f), // Left
                                      new Vector4(-1.0f, -1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f, -1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f,  1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),
                                      new Vector4(-1.0f,  1.0f, -1.0f, 1.0f), new Vector4(1.0f, 0.0f, 1.0f, 1.0f),

                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f), // Right
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f, -1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f, -1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                                      new Vector4( 1.0f,  1.0f,  1.0f, 1.0f), new Vector4(0.0f, 1.0f, 1.0f, 1.0f),
                            });
            vertices.Unlock();

            // Compiles the effect
            var effect = Effect.FromFile(device, "MiniCube.fx", ShaderFlags.None);

            // Allocate Vertex Elements
            var vertexElems = new[] {
        		new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Position, 0),
        		new VertexElement(0, 16, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Color, 0),
				VertexElement.VertexDeclarationEnd
        	};

            // Creates and sets the Vertex Declaration
            var vertexDecl = new VertexDeclaration(device, vertexElems);
            device.SetStreamSource(0, vertices, 0, Utilities.SizeOf<Vector4>() * 2);
            device.VertexDeclaration = vertexDecl;

            // Get the technique
            var technique = effect.GetTechnique(0);
            var pass = effect.GetPass(technique, 0);

            // Prepare matrices
            var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY);
            var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f);
            var viewProj = Matrix.Multiply(view, proj);

            // Use clock
            var clock = new Stopwatch();
            clock.Start();

            RenderLoop.Run(form, () =>
            {
                var time = clock.ElapsedMilliseconds / 1000.0f;

                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0);
                device.BeginScene();

                effect.Technique = technique;
                effect.Begin();
                effect.BeginPass(0);

                var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj;
                effect.SetValue("worldViewProj", worldViewProj);

                device.DrawPrimitives(PrimitiveType.TriangleList, 0, 12);

                effect.EndPass();
                effect.End();

                device.EndScene();
                device.Present();
            });

            effect.Dispose();
            vertices.Dispose();
            device.Dispose();
            direct3D.Dispose();
        }
Esempio n. 7
0
        public static void Main()
        {
            var form = new RenderForm("SimpleD3D9 by C#") { ClientSize = new Size(1024, 768) };

            var device = new D3D9Device(
                new Direct3D(),
                CUDADevice.Default.ID,
                DeviceType.Hardware,
                form.Handle,
                CreateFlags.HardwareVertexProcessing,
                new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

            var vertices = new VertexBuffer(device, Utilities.SizeOf<Vector4>()*Total, Usage.WriteOnly,
                VertexFormat.None, Pool.Default);

            var vertexElems = new []
            {
                new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0),
                new VertexElement(0, 12, DeclarationType.Ubyte4, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                VertexElement.VertexDeclarationEnd
            };

            var vertexDecl = new VertexDeclaration(device, vertexElems);

            var worker = Worker.CreateByFunc(() => Generate(device));
            var updater = new SimpleD3D9(GPUModuleTarget.Worker(worker));

            var view = Matrix.LookAtLH(
                new Vector3(0.0f, 3.0f, -2.0f), // the camera position
                new Vector3(0.0f, 0.0f, 0.0f),  // the look-at position
                new Vector3(0.0f, 1.0f, 0.0f)); // the up direction

            var proj = Matrix.PerspectiveFovLH(
                (float) (Math.PI/4.0), // the horizontal field of view
                1.0f,
                1.0f,
                100.0f);

            device.SetTransform(TransformState.View, view);
            device.SetTransform(TransformState.Projection, proj);
            device.SetRenderState(RenderState.Lighting, false);

            var vbres = RegisterVerticesResource(vertices);
            var clock = System.Diagnostics.Stopwatch.StartNew();

            RenderLoop.Run(form, () =>
            {
                var time = (float) (clock.Elapsed.TotalMilliseconds)/300.0f;
                updater.Update(vbres, time);

                // Now normal D3D9 rendering procedure.
                device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, new ColorBGRA(0, 40, 100, 0), 1.0f, 0);
                device.BeginScene();

                device.VertexDeclaration = vertexDecl;
                device.SetStreamSource(0, vertices, 0, Utilities.SizeOf<Vector4>());
                // we use PointList as the graphics primitives
                device.DrawPrimitives(SharpDX.Direct3D9.PrimitiveType.PointList, 0, Total);

                device.EndScene();
                device.Present();
            });

            UnregisterVerticesResource(vbres);

            updater.Dispose();
            worker.Dispose();
            vertexDecl.Dispose();
            vertices.Dispose();
            device.Dispose();
            form.Dispose();
        }
        private void DumpCubeTexture(NovaTexture texture, BabylonTexture babylonTexture, BabylonScene babylonScene)
        {
            var textureFilename = Path.Combine(texture.LoadedTexture.Directory, texture.LoadedTexture.Filename);
            var baseName = Path.GetFileNameWithoutExtension(texture.LoadedTexture.Filename);

            babylonTexture.isCube = true;
            babylonTexture.name = baseName;

            baseName = Path.Combine(babylonScene.OutputPath, baseName);

            if (!File.Exists(textureFilename))
            {
                texture.LoadedTexture.SaveToDDS(false, textureFilename);
            }

            if (!alreadyExportedTextures.Contains(textureFilename))
            {
                alreadyExportedTextures.Add(textureFilename);

                // Use SharpDX to extract face images
                var form = new Form { ClientSize = new Size(64, 64) };
                var device = new Device(new Direct3D(), 0, DeviceType.Hardware, form.Handle,
                                        CreateFlags.HardwareVertexProcessing,
                                        new PresentParameters(form.ClientSize.Width, form.ClientSize.Height));

                var cubeTexture = CubeTexture.FromFile(device, textureFilename);

                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.PositiveX, 0))
                {
                    Surface.ToFile(surface, baseName + "_px.jpg", ImageFileFormat.Jpg);
                }
                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.PositiveY, 0))
                {
                    Surface.ToFile(surface, baseName + "_py.jpg", ImageFileFormat.Jpg);
                }
                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.PositiveZ, 0))
                {
                    Surface.ToFile(surface, baseName + "_pz.jpg", ImageFileFormat.Jpg);
                }
                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.NegativeX, 0))
                {
                    Surface.ToFile(surface, baseName + "_nx.jpg", ImageFileFormat.Jpg);
                }
                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.NegativeY, 0))
                {
                    Surface.ToFile(surface, baseName + "_ny.jpg", ImageFileFormat.Jpg);
                }
                using (var surface = cubeTexture.GetCubeMapSurface(CubeMapFace.NegativeZ, 0))
                {
                    Surface.ToFile(surface, baseName + "_nz.jpg", ImageFileFormat.Jpg);
                }

                cubeTexture.Dispose();
                device.Dispose();
                form.Dispose();
            }
        }
Esempio n. 9
0
        private static void Main(string[] args)
        {
            #region Variables
            if (args.Length == 3 && args[0] == "-r" && int.TryParse(args[1], out resolution[0]) &&
                int.TryParse(args[2], out resolution[1])) { }
            int menu_running = 1;
            // 0 -> jeu en cours
            // 1 -> menu de demarrage
            // 2 -> menu de jeu
            #endregion

            #region Fenêtre
            form = new RenderForm("Underground - Horror game");
            form.Width = resolution[0];
            form.Height = resolution[1];

            // Intro
            panel1 = new Panel();
            panel1.Name = "panel1";
            panel1.Size = new System.Drawing.Size(resolution[0], resolution[1]);
            panel1.TabIndex = 1;
            form.Controls.Add(panel1);

            m_play = new DxPlay(panel1, @"Ressources\Video\UndergroundPS.avi");
            //m_play = new DxPlay(panel1, @"Ressources\Video\UndergrounFinal_Introduction_vidonly.avi");

            // Fonction à éxécuter après
            m_play.StopPlay += new DxPlay.DxPlayEvent(MediaPlayer.Fin_intro);

            Direct3D direct3D = new Direct3D();
            PresentParameters Parametres = new PresentParameters(
                form.Width,
                form.Height,
                Format.X8R8G8B8,
                1,
                MultisampleType.None,
                0,
                SwapEffect.Discard,
                IntPtr.Zero,
                true,
                true,
                Format.D24X8,
                PresentFlags.None,
                0,
                PresentInterval.Immediate);
            input = new Input(form);
            device = new Device(direct3D, 0, DeviceType.Hardware, form.Handle, CreateFlags.HardwareVertexProcessing, Parametres);
            vertexElems3D = new[] {
                new VertexElement(0, // POSITION
                    0,
                    DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Position, 0),
                new VertexElement(0, // TEXCOORD0
                    Convert.ToInt16(Utilities.SizeOf<Vector4>()),
                    DeclarationType.Float2, DeclarationMethod.Default,DeclarationUsage.TextureCoordinate,0),
                new VertexElement(0, // COLOR0
                    Convert.ToInt16(Utilities.SizeOf<Vector4>()+Utilities.SizeOf<Vector2>()),
                    DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Color, 0),
                new VertexElement(0, // NORMAL0
                    Convert.ToInt16(Utilities.SizeOf<Vector4>()+Utilities.SizeOf<Vector2>()+Utilities.SizeOf<Vector4>()),
                    DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Normal, 0),
                new VertexElement(0, // TANGENT
                    Convert.ToInt16(Utilities.SizeOf<Vector4>()+Utilities.SizeOf<Vector2>()+Utilities.SizeOf<Vector4>()+Utilities.SizeOf<Vector4>()),
                    DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Tangent, 0),
                VertexElement.VertexDeclarationEnd,
                new VertexElement(0, // booléen de bump mapping
                    Convert.ToInt16(Utilities.SizeOf<Vector4>()+Utilities.SizeOf<Vector2>()+Utilities.SizeOf<Vector4>()+Utilities.SizeOf<Vector4>()+Utilities.SizeOf<Vector4>()),
                    DeclarationType.Float1, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0),
                VertexElement.VertexDeclarationEnd,
            };
            vertexElems2D = new[] {
                new VertexElement(0,0,DeclarationType.Float4,DeclarationMethod.Default,DeclarationUsage.PositionTransformed,0),
                new VertexElement(0,16,DeclarationType.Float2,DeclarationMethod.Default,DeclarationUsage.TextureCoordinate,0),
                VertexElement.VertexDeclarationEnd
            };

            VertexDeclaration3D = new VertexDeclaration(Program.device, Program.vertexElems3D);
            VertexDeclaration2D = new VertexDeclaration(Program.device, Program.vertexElems2D);
            VertexBufferZero = new VertexBuffer(IntPtr.Zero);

            device.VertexDeclaration = VertexDeclaration3D;

            Program.device.SetRenderState(RenderState.AlphaBlendEnable, true); // graphics.GraphicsDevice.RenderState.AlphaBlendEnable = true;
            Program.device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha); // graphics.GraphicsDevice.RenderState.DestinationBlend = Blend.One;
            Program.device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha); // graphics.GraphicsDevice.RenderState.SourceBlend = Blend.One;
            Program.device.SetRenderState(RenderState.AlphaFunc, BlendOperation.Maximum); // graphics.GraphicsDevice.RenderState.BlendFunction = BlendFunction.Add;
            Program.device.SetRenderState(RenderState.AlphaTestEnable, true);
            Program.device.SetRenderState(RenderState.MinTessellationLevel, 8);
            #endregion

            Liste_textures = new List<structTexture>();
            Liste_binaires = new List<structBinary>();
            Liste_OBJ = new List<structOBJ>();
            Liste_Lights = new Light[2];
            Liste_Lights[0].Type = LightType.Point;
            Liste_Lights[0].Position = new Vector3(0, 0, 0);
            Liste_Lights[0].Ambient = new Color4(0.5f, 0.5f, 0.5f, 1);
            Liste_Lights[0].Range = 30f * 70;
            Liste_Lights[1].Type = LightType.Point;
            Liste_Lights[1].Position = new Vector3(-100, -100, -100);
            Liste_Lights[1].Ambient = new Color4(0.5f,0,0,1);
            Liste_Lights[1].Range = 5f * 70;
            Liste_textures.Add(new structTexture("null.bmp", Texture.FromFile(device, "null.bmp")));
            //Ingame.Slender.doit_etre_recharge = true;

            // Creation du fichier effect de référence
            Macro macro = new Macro("nblights", 2.ToString());
            BaseEffect = Effect.FromFile(Program.device, "Underground.fx", new Macro[] { macro }, null, "", ShaderFlags.OptimizationLevel3);
            BaseEffect.Technique = BaseEffect.GetTechnique(0);
            BaseEffect.SetValue("AmbientLightColor", new Vector4(0f, 0f, 0f, 0f));
            Matrix proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, Program.form.ClientSize.Width / (float)Program.form.ClientSize.Height, 0.1f, 7000.0f);
            BaseEffect.SetValue("Projection", proj);
            BaseEffect.SetValue("LightDiffuseColor[0]", Liste_Lights[0].Ambient);
            BaseEffect.SetValue("LightDiffuseColor[1]", Liste_Lights[1].Ambient);
            BaseEffect.SetValue("LightDistanceSquared[1]", Liste_Lights[1].Range);

            Thread ThSound = new Thread(Sound.main);
            Thread ThEvents = new Thread(Ingame.fevents);
            ThSound.Start();
            ThEvents.Start();

            Menu.Initialize_Menu();
            ObjLoader.Initialize();
            newmaze = new Maze(10, 10);
            newmaze.Initecelles();
            newmaze.Generate(newmaze.maze[0, 0]);
            newmaze.impefectGenerate();
            newmaze.Setaffichage();

            Ingame.ingame();

            Menu.Dispose();
            ThSound.Abort();
            ThEvents.Abort();
            VertexBufferZero.Dispose();
            VertexDeclaration3D.Dispose();
            VertexDeclaration2D.Dispose();
            device.Dispose();
            direct3D.Dispose();
        }
        // Testing function call - creates DX9 device & present test:
        public bool TestDX(Direct3D d3dh, ref MyAdapterInfo[] infos)
        {
#if !XB1
            bool isAnyGraphicsSupported = false;
            MyLog.Default.WriteLine("MyGraphicTest.TestDX() - START");
            MyLog.Default.IncreaseIndent();

            LogInfoFromWMI();

            bool isAnyGoodGCinWMI = IsAnyGoodGCinList(m_WMIGraphicsCards);
            MyLog.Default.WriteLine("Good graphics in WMI detected: " + isAnyGoodGCinWMI);

            //Check debug runtime
            MyLog.Default.WriteLine("Debug runtime enabled: " + IsDebugRuntimeEnabled);

            PresentParameters newPresentParameters;

            try
            {
                MyLog.Default.WriteLine("Adapter count: " + d3dh.AdapterCount);
                for (int i = 0; i < d3dh.AdapterCount; i++)
                {
                    var info = d3dh.GetAdapterIdentifier(i);
                    MyLog.Default.WriteLine(String.Format("Found adapter: {0} ({1})", info.Description, info.DeviceName));
                }
                MyLog.Default.WriteLine("Adapter count: " + d3dh.AdapterCount);

                // DX:
                newPresentParameters = new PresentParameters();
                newPresentParameters.InitDefaults();
                newPresentParameters.Windowed = true;
                newPresentParameters.AutoDepthStencilFormat = Format.D24S8;
                newPresentParameters.EnableAutoDepthStencil = true;
                newPresentParameters.SwapEffect = SwapEffect.Discard;
                newPresentParameters.PresentFlags = PresentFlags.DiscardDepthStencil;

                m_DXGraphicsCards.Clear();

                // Write adapter information to the LOG file:
                MyLog.Default.WriteLine("Adapters count: " + d3dh.AdapterCount);
                MyLog.Default.WriteLine("Adapter array count: " + d3dh.Adapters.Count);

                for (int adapter = 0; adapter < d3dh.AdapterCount; adapter++)
                {
                    bool adapterSupported = false;

                    var adapterIdentifier = d3dh.GetAdapterIdentifier(adapter);
                    MyLog.Default.WriteLine("Adapter " + adapterIdentifier.Description + ": " + adapterIdentifier.DeviceName);

                    Device d3d = null;
                    Form testForm = null;

                    try
                    {
                        //Create window, because other this fails on some ATIs..
                        testForm = new Form();
                        testForm.ClientSize = new System.Drawing.Size(64, 64);
                        testForm.StartPosition = FormStartPosition.CenterScreen;
                        testForm.FormBorderStyle = FormBorderStyle.None;
                        testForm.BackColor = System.Drawing.Color.Black;
                        testForm.Show();

                        newPresentParameters.DeviceWindowHandle = testForm.Handle;
                        d3d = new Device(d3dh, adapter, DeviceType.Hardware, testForm.Handle, CreateFlags.HardwareVertexProcessing | CreateFlags.FpuPreserve, newPresentParameters);

                        if (d3d == null)
                        {
                            throw new Exception("Cannot create Direct3D Device");
                        }
                        else
                            MyLog.Default.WriteLine("d3d handle ok ");
                    }
                    catch (Exception e)
                    {
                        if (testForm != null)
                            testForm.Close();

                        MyLog.Default.WriteLine("Direct3D Device create fail");
                        MyLog.Default.WriteLine(e.ToString());

                        Write(newPresentParameters, MyLog.Default.WriteLine);
                        continue;
                    }

                    adapterSupported |= !TestCapabilities(d3d, d3dh, adapter);

                    infos[adapter].MaxTextureSize = d3d.Capabilities.MaxTextureWidth;

                    bool Rgba1010102Supported = d3dh.CheckDeviceFormat(adapter, DeviceType.Hardware, Format.X8R8G8B8, Usage.RenderTarget, ResourceType.Surface, Format.A2R10G10B10);
                    MyLog.Default.WriteLine("Rgba1010102Supported: " + Rgba1010102Supported);

                    bool MipmapNonPow2Supported = !d3d.Capabilities.TextureCaps.HasFlag(TextureCaps.Pow2) &&
                        !d3d.Capabilities.TextureCaps.HasFlag(TextureCaps.NonPow2Conditional) &&
                        d3d.Capabilities.TextureCaps.HasFlag(TextureCaps.MipMap);
                    MyLog.Default.WriteLine("MipmapNonPow2Supported: " + MipmapNonPow2Supported);

                    infos[adapter].HDRSupported = Rgba1010102Supported && MipmapNonPow2Supported;
                    MyLog.Default.WriteLine("HDRSupported: " + infos[adapter].HDRSupported);

                    bool QueriesSupported = false;
                    try
                    {
                        MyLog.Default.WriteLine("Create query");
                        Query query = new Query(d3d, QueryType.Event);
                        MyLog.Default.WriteLine("Dispose query");
                        query.Dispose();
                        QueriesSupported = true;
                    }
                    catch
                    {
                        QueriesSupported = false;
                    }

                    //Test sufficient video memory (512MB)
                    bool Has512AvailableVRAM = TestAvailable512VRAM(d3d);

                    //We require queries
                    adapterSupported &= QueriesSupported;

                    infos[adapter].IsDx9Supported = adapterSupported;
                    infos[adapter].Has512MBRam = Has512AvailableVRAM;

                    isAnyGraphicsSupported |= adapterSupported;

                    MyLog.Default.WriteLine("Queries supported: " + QueriesSupported.ToString());

                    m_DXGraphicsCards.Add(adapterIdentifier.VendorId);

                    if (d3d != null)
                    {
                        d3d.Dispose();
                        d3d = null;
                    }

                    if (testForm != null)
                        testForm.Close();
                }
            }
            catch (Exception ex)
            {
                MyLog.Default.WriteLine("Exception throwed by DX test. Source: " + ex.Source);
                MyLog.Default.WriteLine("Message: " + ex.Message);
                MyLog.Default.WriteLine("Inner exception: " + ex.InnerException);
                MyLog.Default.WriteLine("Exception details" + ex.ToString());
            }

            bool isAnyGoodGCinDX = IsAnyGoodGCinList(m_DXGraphicsCards);
            MyLog.Default.WriteLine("Good graphics in DX detected: " + isAnyGoodGCinDX);

            IsBetterGCAvailable = isAnyGoodGCinWMI && !isAnyGoodGCinDX;
            MyLog.Default.WriteLine("Is better graphics available: " + IsBetterGCAvailable);

            MyLog.Default.DecreaseIndent();
            MyLog.Default.WriteLine("MyGraphicTest.TestDX() - END");

            return isAnyGraphicsSupported;
#else // XB1
            System.Diagnostics.Debug.Assert(false, "XB1 TOOD?");
            return false;
#endif // XB1
        }
Esempio n. 11
0
        // Testing function call - creates DX9 device & present test:
        public bool TestDX()
        {
            bool isGraphicsSupported = true;
            MyMwcLog.WriteLine("MyGraphicTest.TestDX() - START");
            MyMwcLog.IncreaseIndent();

            PresentParameters newPresentParameters;
            Direct3D d3dh = null;
            Device d3d = null;

            try
            {
                MyMwcLog.WriteLine("Direct3D call");
                d3dh = new Direct3D();
                MyMwcLog.WriteLine("Direct3D call end");

                if (d3dh == null)
                {
                    throw new Exception("Cannot create Direct3D object");
                }
                else
                    MyMwcLog.WriteLine("d3dh handle ok ");

                // DX:
                newPresentParameters = new PresentParameters();
                newPresentParameters.Windowed = true;
                newPresentParameters.InitDefaults();

                d3d = new Device(d3dh, 0, DeviceType.Hardware, IntPtr.Zero, CreateFlags.HardwareVertexProcessing, newPresentParameters);

                if (d3d == null)
                {
                    throw new Exception("Cannot create Direct3D Device");
                }
                else
                    MyMwcLog.WriteLine("d3d handle ok ");

                isGraphicsSupported &= !TestCapabilities(d3d, d3dh);

                MaxTextureSize = d3d.Capabilities.MaxTextureWidth;

                Rgba1010102Supported = d3dh.CheckDeviceFormat(0, DeviceType.Hardware, Format.X8R8G8B8, Usage.RenderTarget, ResourceType.Surface, Format.A2R10G10B10);
                MipmapNonPow2Supported = !d3d.Capabilities.TextureCaps.HasFlag(TextureCaps.Pow2) &&
                    !d3d.Capabilities.TextureCaps.HasFlag(TextureCaps.NonPow2Conditional) &&
                    d3d.Capabilities.TextureCaps.HasFlag(TextureCaps.MipMap);
            }
            catch (Exception ex)
            {
                MyMwcLog.WriteLine("Exception throwed by DX test. Source: " + ex.Source);
                MyMwcLog.WriteLine("Message: " + ex.Message);
                MyMwcLog.WriteLine("Inner exception: " + ex.InnerException);
                MyMwcLog.WriteLine("Exception details" + ex.ToString());
                //consider returning error here
                //retValue = false;
            }
            finally
            {
                if (d3dh != null)
                {
                    d3dh.Dispose();
                    d3dh = null;
                }
                if (d3d != null)
                {
                    d3d.Dispose();
                    d3d = null;
                }
            }

            MyMwcLog.DecreaseIndent();
            MyMwcLog.WriteLine("MyGraphicTest.TestDX() - END");

            return isGraphicsSupported;
        }