public void RenderLoopCallback() { if (_firstRun) { RenderFormResizedCallback(this, EventArgs.Empty); _firstRun = false; } _timeHelper.Update(); _renderForm.Text = "FPS: " + _timeHelper.FPS.ToString(); _inputController.UpdateKeyboardState(); _inputController.UpdateMouseState(); Transition.UpdateTransitions(_timeHelper.DeltaT); _scene.Update(_timeHelper.DeltaT); if (_inputController.KeyboardUpdate) { if (_inputController.KeyEsc) { _renderForm.Close(); } if (_inputController.KeyF2) { _directX3DGraphics.IsFullScreen = !_directX3DGraphics.IsFullScreen; } } //if (_inputController.MouseUpdate) //{ // float deltaAngle = _camera.FOVY / _renderForm.ClientSize.Height; // _camera.RotateZ(deltaAngle * _inputController.MouseRelativePositionX); // _camera.RotateY(deltaAngle * _inputController.MouseRelativePositionY); //} _renderer.UpdatePerFrameConstantBuffers(_timeHelper.Time); _illumination.eyePosition = (Vector4)_camera.Position; _renderer.UpdateIllumination(_illumination); _renderer.BeginRender(); _scene.RenderGameObjects(_camera, _renderer); _renderer.RenderUserInterface(_ui); _renderer.EndRender(); if (_nextScene != null) { _nextScene.PreviousScene = _scene; _scene = _nextScene; _nextScene = null; InitializeScene(); RenderFormResizedCallback(this, EventArgs.Empty); } }
private void UpdateKeyBoard() { inputController.UpdateKeyboardState(); if (inputController.Esc) { renderForm.Close(); } // Switch solid and wireframe modes by F2, F3. if (inputController.Func[1]) { directX3DGraphics.RenderMode = DirectX3DGraphics.RenderModes.Solid; } if (inputController.Func[2]) { directX3DGraphics.RenderMode = DirectX3DGraphics.RenderModes.Wireframe; } // Toggle fullscreen mode by F4, F5. if (inputController.Func[3]) { directX3DGraphics.IsFullScreen = false; } if (inputController.Func[4]) { directX3DGraphics.IsFullScreen = true; } //mainCharacterService.Update(); levelService.Update(); cameraService.Update(); }
public void Run() { timer.Reset(); Load(); RenderLoop.Run(RenderForm, () => { CalculateFrameRate(); if (isResize) { graphicsDevice.Resize(RenderForm.ClientSize.Width, RenderForm.ClientSize.Height); isResize = false; } Update(timer); Render(timer); graphicsDevice.Present(IsVSyncEnable); if (!IsRunning) { renderForm.Close(); } }); Unload(); }
protected virtual void KeyboardHandler(object sender, KeyEventArgs args) { // Do interesting stuff with the keyboard if (args.KeyCode == Keys.Escape) { mRenderForm.Close(); } }
public void keyDown(object sender, KeyEventArgs args) { key = args.KeyCode; if (args.KeyCode == Keys.Escape) { _form.Close(); } }
public override void OnDisable() { if (_renderForm != null) { OverlayManager.OnDrawing -= OnDrawing; _renderForm.Close(); } }
// [STAThread] private static void Main() { var form = new RenderForm("Material editor"); form.ClientSize = new System.Drawing.Size(1800, 900); form.MaximizeBox = false; Graphics.Renderer Ren = new Graphics.Renderer(); Ren.Initialize(form); form.UserResized += (sender, args) => { Ren.OnResize(form); }; bool Rotate = false; form.KeyUp += (sender, args) => { if (args.KeyCode == Keys.F5) { Rotate = false; } else if (args.KeyCode == Keys.F4) { Rotate = true; } else if (args.KeyCode == Keys.Escape) { form.Close(); } }; if (!Ren.Textures.LoadTexture(Ren.RawDevice, @"..\..\Textures\brick.jpg", "Brick")) { Console.WriteLine("ERROR in loading brick.jpg"); } Graphics.TextureInfo Info; if (!Ren.Textures.GetTexture("Brick", out Info)) { Console.WriteLine("ERROR in getting brick"); } Sprite TestSprite = new Sprite(Info); RenderLoop.Run(form, () => { Ren.OnDraw(TestSprite); if (Rotate) { TestSprite.GetTransform.Rotate(0.01f); } }); }
private void HandleKeyDown(object sender, KeyEventArgs e) { // Hardcoded escape key! if (e.KeyCode == Keys.Escape) { renderForm.Close(); } keyboard.SetDown(e.KeyCode, true); }
protected virtual void OnKeyUp(object sender, KeyEventArgs args) { switch (args.KeyCode) { case Keys.Escape: args.Handled = true; Form.Close(); break; } }
public virtual void UpdateScene(float deltaTime) { _input.Update(); if (_input.IsKeyPressed(Key.Return) && (_input.IsKeyPressed(Key.LeftAlt) || _input.IsKeyPressed(Key.RightAlt))) { ToggleFullscreen(); } else if (_input.IsKeyPressed(Key.Escape)) { _form.Close(); } }
static void Main(string[] args) { System.Console.WriteLine("Victorem for by_Owl 17.07.2016"); System.Console.WriteLine("Загрузка ресурсов ..."); double start = System.Environment.TickCount; if (!SharpDX.Direct3D11.Device.IsSupportedFeatureLevel(SharpDX.Direct3D.FeatureLevel.Level_11_0)) { MessageBox.Show("Для запуска этой игры нужен DirectX 11 ОБЯЗАТЕЛЬНО!"); return; } #if DEBUG SharpDX.Configuration.EnableObjectTracking = true; #endif using (var _renderForm = new RenderForm("SharpDX game by Winbringer") { AllowUserResizing = false, IsFullscreen = false, StartPosition = FormStartPosition.CenterScreen, ClientSize = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height), FormBorderStyle = FormBorderStyle.None, Icon = new Icon("LogoVW.ico") }) { _renderForm.Shown += (sender, e) => { _renderForm.Activate(); }; _renderForm.KeyDown += (sender, e) => { if (e.KeyCode == Keys.Escape) { _renderForm.Close(); } }; using (Game game = new Game(_renderForm)) { System.Console.WriteLine("Для начала игры нажмите \"Enter\""); System.Console.WriteLine("Для выхода из игры нажмите \"Esc\""); System.Console.WriteLine("Для паузы нажмите латинскую \"P\""); System.Console.WriteLine("\"U\" - Возврат снаряда "); System.Console.WriteLine("\" W A S D \" - Движение камеры "); System.Console.WriteLine("\"<- | -> \" - Стрелки на клавиатуре, поворот камеры "); System.Console.WriteLine("\"Z X\" - Изменение высоты камеры "); System.Console.WriteLine("\" 1 2 3 4 5 6\" - Цифры на клавиатуре, управление направлением, углом стрельбы и скоростью полета планеты"); System.Console.WriteLine("\"Пробел\" - Клавиша пробела запускает снаряд в цель"); System.Console.ReadLine(); game.Run(); } } double end = (System.Environment.TickCount - start) / 1000; System.Console.WriteLine("Всего проведено в игре секунд : " + end.ToString()); System.Console.WriteLine("Для завершения нажмите ввод"); System.Console.ReadLine(); }
public void Run() { this.Initialize(); form.DesktopLocation = new Point(10, 600); MessagePump.Run(form, () => { this.RunGameLoop(); if (shutdown) { form.Close(); } }); this.Dispose(); }
public static void Show(Wallpaper wallpaper) { IntPtr handler = IntPtr.Zero; Execute.OnUIThread(() => { if (RenderWindow == null) { RenderWindow = new RenderForm { Wallpaper = wallpaper }; RenderWindow.SetAspect(VideoAspect); RenderWindow.Show(); } else { try { RenderWindow.Wallpaper = wallpaper; RenderWindow.SetAspect(VideoAspect); //RenderWindow .Visibility = System.Windows.Visibility.Visible; RenderWindow.Visible = true; } catch (Exception) { RenderWindow?.Close(); RenderWindow = null; //explorer 崩溃后会触发这个问题 RenderWindow = new RenderForm { Wallpaper = wallpaper }; RenderWindow.Show(); } } //handler = new WindowInteropHelper(RenderWindow).Handle; handler = RenderWindow.Handle; }); //HandlerWallpaper.Show(handler); _LWECore.SendToBackground(handler); }
/// <summary> /// Initializes Geisha Engine for specified <paramref name="game" /> and starts the game loop. /// </summary> /// <param name="game"><see cref="IGame" /> instance providing custom game functionality.</param> public static void Run(IGame game) { AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; LogFactory.ConfigureFileTarget("GeishaEngine.log"); var log = LogFactory.Create(typeof(GeishaEngineForWindows)); log.Info("Starting engine."); log.Info("Loading configuration from file."); var configuration = Configuration.LoadFromFile(EngineConfigFile); Application.SetHighDpiMode(HighDpiMode.SystemAware); using (var form = new RenderForm(game.WindowTitle) { ClientSize = new Size(configuration.Rendering.ScreenWidth, configuration.Rendering.ScreenHeight), AllowUserResizing = false }) { using var engine = new Engine( configuration, new CSCoreAudioBackend(), new WindowsInputBackend(form), new DirectXRenderingBackend(form, DriverType.Hardware), game ); log.Info("Engine started successfully."); RenderLoop.Run(form, () => { // ReSharper disable AccessToDisposedClosure engine.Update(); if (engine.IsScheduledForShutdown) { form.Close(); } // ReSharper restore AccessToDisposedClosure }); } log.Info("Engine shutdown completed."); }
public static void Render() { InitializeDirectX(); _dvdImage = LoadImage("dvd.png"); Timer.Start(); Timer.Update(); RenderLoop.Run(renderForm, () => { if (renderForm.WindowState == System.Windows.Forms.FormWindowState.Minimized) { return; } try { while (Timer.VerifyLag()) { Timer.Update(); Update(); } renderTarget.BeginDraw(); renderTarget.Transform = Matrix3x2.Identity; renderTarget.Clear(Color.White); Draw(renderTarget); renderTarget.Flush(); renderTarget.EndDraw(); swapChain.Present(0, PresentFlags.None); } catch (Exception ex) { renderForm.Close(); } //swapChain.IsFullScreen = false; //textFormat.Dispose(); //renderTarget.Dispose(); //swapChain.Dispose(); //device.Dispose(); }); }
/// <summary> /// Run the game by allowing SlimDx to run the message pump and call /// anything that registers for a per frame update. Not ideal but /// apparently best practice. /// </summary> /// <param name="updateFunctions"></param> public void Run(Core.UpdateFunctions updateFunctions) { //updateFunctions.AddUpdateFunction(Render, new TimeSpan(0)); updateFunctions.AddUpdateFunction(RenderBlobArray, new TimeSpan(0)); MessagePump.Run(form_, () => { DateTime currentTime = DateTime.Now; TimeSpan timeSinceLastUpdate = currentTime - lastTime_; lastTime_ = currentTime; bool shouldQuit = updateFunctions.CallUpdateFunction(timeSinceLastUpdate); if (shouldQuit) { form_.Close(); } }); }
private void exitToolStripMenuItem_Click(object sender, EventArgs e) { if (mediaEngine != null) { mediaEngine.Shutdown(); } if (Program.swapChain != null) { Program.swapChain.Dispose(); } if (Program.device != null) { Program.device.Dispose(); } if (renderForm != null) { renderForm.Close(); } Application.Exit(); }
public static void Dispose() { try { if (RenderWindow == null) { return; } MonitorMaxiemized(false); Close(); _LWECore.RestoreParent(); _LWECore.Dispose(); RenderWindow.Close(); RenderWindow = null; } catch (Exception) { } }
protected override void Show() { RenderLoop.Run(renderForm, () => { int mouseX; int mouseY; input.Frame(); input.GetMouseLocation(out mouseX, out mouseY); if (!graphics.Frame(mouseX, mouseY)) { throw new InvalidOperationException(); } if (!graphics.Render()) { throw new InvalidOperationException(); } if (input.IsPressed(Key.Escape)) { renderForm.Close(); } }); }
private void _renderForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { switch (e.KeyCode) { //元素 P-点 L-线 T-三角形 case System.Windows.Forms.Keys.P: _d3DDeviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.PointList; break; case System.Windows.Forms.Keys.L: _d3DDeviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.LineList; break; case System.Windows.Forms.Keys.T: _d3DDeviceContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleList; break; //全屏 case System.Windows.Forms.Keys.F5: _swapChain.SetFullscreenState(true, null); _resized = true; break; case System.Windows.Forms.Keys.F6: _swapChain.SetFullscreenState(false, null); _resized = true; break; //移动摄像机: case System.Windows.Forms.Keys.W: camPos += camLook * 1f; break; case System.Windows.Forms.Keys.S: camPos -= camLook * 1f; break; case System.Windows.Forms.Keys.A: camPos -= camRight * 1f; break; case System.Windows.Forms.Keys.D: camPos += camRight * 1f; break; case System.Windows.Forms.Keys.Space: camPos.Y += 1f; break; case System.Windows.Forms.Keys.Z: camPos.Y -= 1f; break; case System.Windows.Forms.Keys.Escape: _renderForm.Close(); break; // 切换pass case System.Windows.Forms.Keys.F1: mfxPass = mfxPassW; break; case System.Windows.Forms.Keys.F2: mfxPass = mfxPassS; break; default: break; } }
public void Exit() { form.Close(); }
private void RenderFrame() { Input.XInputInput.Update(); if ((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.Back) == SharpDX.XInput.GamepadButtonFlags.Back) { renderForm.Close(); } if (((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.Start) == SharpDX.XInput.GamepadButtonFlags.Start) && ((Input.XInputInput.PrevState[0].Buttons & SharpDX.XInput.GamepadButtonFlags.Start) != SharpDX.XInput.GamepadButtonFlags.Start)) { swapChain.GetFullscreenState(out SharpDX.Mathematics.Interop.RawBool fs, out Output o); o?.Dispose(); swapChain.SetFullscreenState(!fs, null); } fishManager.Update(); fishRenderer.Update(); foodManager.Update(); //theta = 0.0f; if (((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.X) == SharpDX.XInput.GamepadButtonFlags.X) && ((Input.XInputInput.PrevState[0].Buttons & SharpDX.XInput.GamepadButtonFlags.X) != SharpDX.XInput.GamepadButtonFlags.X)) { camState = !camState; } if (((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadUp) == SharpDX.XInput.GamepadButtonFlags.DPadUp) && ((Input.XInputInput.PrevState[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadUp) != SharpDX.XInput.GamepadButtonFlags.DPadUp)) { Wireframe = !Wireframe; } if (((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadLeft) == SharpDX.XInput.GamepadButtonFlags.DPadLeft) && ((Input.XInputInput.PrevState[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadLeft) != SharpDX.XInput.GamepadButtonFlags.DPadLeft)) { frameSkip = frameSkip > 1 ? frameSkip - 1 : 1; } if (((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadRight) == SharpDX.XInput.GamepadButtonFlags.DPadRight) && ((Input.XInputInput.PrevState[0].Buttons & SharpDX.XInput.GamepadButtonFlags.DPadRight) != SharpDX.XInput.GamepadButtonFlags.DPadRight)) { frameSkip++; } if (!camState) { SetCamera(Matrix.LookAtLH(new Vector3((float)Math.Sin(Math.Sin(theta) * 0.1f), 0, (float)Math.Cos(Math.Sin(theta) * 0.1f)) * -1.3333f, Vector3.Zero, Vector3.Up), //Matrix.LookAtLH(Vector3.BackwardLH * 5, Vector3.Zero, Vector3.Up), //Matrix.OrthoLH(16.0f / 9.0f * 2.0f, 2.0f, 0, 10.0f)); Matrix.PerspectiveFovLH(MathUtil.DegreesToRadians(75.0f), RenderWidth / (float)RenderHeight, 0.1f, 20.0f)); } else { SetCamera(Matrix.LookAtLH(new Vector3(fishManager.FishList[0].Position * 0.75f, -1.33333f), new Vector3(fishManager.FishList[0].Position * 0.75f, 0.0f), Vector3.Up), Matrix.PerspectiveFovLH(MathUtil.DegreesToRadians(45.0f), RenderWidth / (float)RenderHeight, 0.1f, 20.0f)); } theta += (float)Math.PI / 30.0f / 60.0f * (Input.XInputInput.State[0].LeftThumbY / (float)short.MaxValue + 0.25f) * 4.0f; if (frameNumber % (ulong)frameSkip == 0 && (Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.LeftShoulder) != SharpDX.XInput.GamepadButtonFlags.LeftShoulder) { DeviceContext.Rasterizer.State = Wireframe ? RasterizerStates.Wire : RasterizerStates.Back; //DeviceContext.OutputMerger.SetRenderTargets(renderTargetView); DeviceContext.PixelShader.SetShaderResource(0, null); DeviceContext.OutputMerger.SetRenderTargets(colorTarget.DSV, colorTarget.RTV); DeviceContext.OutputMerger.DepthStencilState = DepthStencilStates.Enabled; DeviceContext.ClearRenderTargetView(renderTargetView, new Color(0.0f, 0.0f, 0.0f)); colorTarget.Clear(Color4.Lerp(new Color4(0, 0, 0.04f, 0.0f), new Color4(0.08f, 0.08f, 0.2f, 0.0f), Math.Max(0, -(float)Math.Cos(theta)))); //RenderDebugTri(); var intensity = Math.Max(0, -(float)Math.Cos(theta)); var sunDir = new Vector3((float)Math.Sin(theta), (float)Math.Cos(theta), 1.0f); Sun.Set(sunDir, new Vector3(1.0f, 1.0f, 1.0f), intensity); fishGlow.Intensity = Math.Max(0, ((float)Math.Cos(intensity * MathUtil.Pi) + 0.2f) / 1.2f); raysRenderer.Intensity = 0.02f * (1 - fishGlow.Intensity); fishGlow.Intensity *= 0.75f; decorRenderer.Render(); fishRenderer.Render(); DeviceContext.OutputMerger.SetRenderTargets(colorTarget.DSV, renderTargetView); //var pos = new Vector3(fishManager.FishList[0].Position, 0); //var np = Vector3.Transform(pos, Projection * View); var np = Vector3.Transform(sunDir * new Vector3(1, 1, 0) * -10, Projection * View); DeviceContext.OutputMerger.DepthStencilState = DepthStencilStates.Disabled; DeviceContext.Rasterizer.State = RasterizerStates.Back; raysRenderer.CentrePoint = new Vector2(-sunDir.X * RenderWidth * 10.0f, sunDir.Y * RenderHeight * 10.0f);//new Vector2((np.X / np.W / 2.0f + 0.5f) * RenderWidth, (-np.Y / np.W / 2.0f + 0.5f) * RenderHeight); raysRenderer.Render(colorTarget.SRV, 1.0f / 60.0f); fishGlow.Render(); DeviceContext.Rasterizer.State = Wireframe ? RasterizerStates.Wire : RasterizerStates.Back; DeviceContext.OutputMerger.DepthStencilState = DepthStencilStates.Enabled; foodRenderer.Render(); decorRenderer.Render2(); try { if ((Input.XInputInput.State[0].Buttons & SharpDX.XInput.GamepadButtonFlags.RightShoulder) != SharpDX.XInput.GamepadButtonFlags.RightShoulder) { swapChain.Present(1, PresentFlags.None); } else { swapChain.Present(0, PresentFlags.None); } } catch (Exception e) { Console.WriteLine(Device.DeviceRemovedReason.ToString()); Console.ReadLine(); renderForm.Close(); } } frameNumber++; }
public void Init() { form = new RenderForm("Raytracer"); form.FormClosing += (sender, args) => { running = false; }; var prevMousePos = Vector2.Zero; form.KeyUp += (sender, args) => { if (args.KeyCode == Keys.Escape) { form.Close(); } if (args.Control || args.Alt || args.Shift) { Inputs.SetModifierKeyDown(false, args.KeyCode); } if (args.KeyCode == Keys.W) { pressed[0] = false; } if (args.KeyCode == Keys.A) { pressed[1] = false; } if (args.KeyCode == Keys.S) { pressed[2] = false; } if (args.KeyCode == Keys.D) { pressed[3] = false; } if (args.KeyCode == Keys.Q) { pressed[4] = false; } if (args.KeyCode == Keys.E) { pressed[5] = false; } }; // handle mouse drag form.MouseDown += (sender, args) => { Inputs.SetMouseDown(true, args.Button); prevMousePos = new Vector2(args.X, args.Y); }; form.MouseUp += (sender, args) => { Inputs.SetMouseDown(false, args.Button); }; form.MouseMove += (sender, args) => { Inputs.MousePosition = new Vector2(args.X, args.Y); }; form.KeyDown += (sender, args) => { if (args.Control || args.Alt || args.Shift) { Inputs.SetModifierKeyDown(true, args.KeyCode); } if (args.KeyCode == Keys.W) { pressed[0] = true; } if (args.KeyCode == Keys.A) { pressed[1] = true; } if (args.KeyCode == Keys.S) { pressed[2] = true; } if (args.KeyCode == Keys.D) { pressed[3] = true; } if (args.KeyCode == Keys.Q) { pressed[4] = true; } if (args.KeyCode == Keys.E) { pressed[5] = true; } if (args.KeyCode == Keys.R) { cameraPos = new Vector3(0, 1, 0); } }; InitRenderer(); form.Show(); Loop(); }
private void onGameStateChanged(GameState newState) { switch (newState) { case GameState.StartUp: mainMenuControl.Hide(); highscoreControl.Hide(); creditsControl.Hide(); pauseControl.Hide(); victoryControl.Hide(); gameOverControl.Hide(); hud.Hide(); audioPlayer.PlayEvent("audio/music/menu"); break; case GameState.Menu: mainMenuControl.Show(); highscoreControl.Hide(); creditsControl.Hide(); pauseControl.Hide(); victoryControl.Hide(); gameOverControl.Hide(); hud.Hide(); audioPlayer.PauseCategory("ingame"); audioPlayer.UnpauseCategory("menu"); break; case GameState.Highscore: mainMenuControl.Hide(); highscoreControl.Show(); creditsControl.Hide(); pauseControl.Hide(); victoryControl.Hide(); gameOverControl.Hide(); hud.Hide(); audioPlayer.PauseCategory("ingame"); audioPlayer.UnpauseCategory("menu"); break; case GameState.Credits: mainMenuControl.Hide(); highscoreControl.Hide(); creditsControl.Show(); pauseControl.Hide(); victoryControl.Hide(); gameOverControl.Hide(); hud.Hide(); creditsControl.Start(); audioPlayer.PauseCategory("ingame"); audioPlayer.UnpauseCategory("menu"); break; case GameState.Loading: mainMenuControl.Hide(); highscoreControl.Hide(); creditsControl.Hide(); pauseControl.Hide(); victoryControl.Hide(); gameOverControl.Hide();; hud.Hide(); audioPlayer.PlayEvent("audio/music/ingame"); OnDetach(); break; case GameState.Running: mainMenuControl.Hide(); highscoreControl.Hide(); creditsControl.Hide(); pauseControl.Hide(); victoryControl.Hide(); gameOverControl.Hide(); hud.Show(); audioPlayer.PauseCategory("menu"); audioPlayer.UnpauseCategory("ingame"); break; case GameState.Paused: pauseControl.Show(); victoryControl.Hide(); gameOverControl.Hide(); hud.Hide(); audioPlayer.PauseCategory("ingame"); audioPlayer.PauseCategory("menu"); break; case GameState.Victory: int remainingLifes = 0; if (playerEntity != null) // Happens on a draw { remainingLifes = playerEntity[HealthBehavior.Key_Lifes]; } int totalScore = 100 * remainingLifes + playerEntity[CollectsPointsBehavior.Key_PointsCollected]; victoryControl.CurrentScore = totalScore; mainMenuControl.Hide(); highscoreControl.Hide(); creditsControl.Hide(); pauseControl.Hide(); victoryControl.Show(); gameOverControl.Hide(); hud.Hide(); audioPlayer.StopCategory("ingame"); audioPlayer.PlayEvent("audio/game/win"); break; case GameState.GameOver: mainMenuControl.Hide(); highscoreControl.Hide(); creditsControl.Hide(); pauseControl.Hide(); victoryControl.Hide(); gameOverControl.Show(); hud.Hide(); audioPlayer.StopCategory("ingame"); audioPlayer.PlayEvent("audio/game/lose"); break; case GameState.Quit: audioPlayer.StopCategory("menu"); RenderForm.Close(); break; } }
public void Close() { window.Close(); }
public void Run() { form = new RenderForm("ComposIt"); form.ClientSize = new Size(1920, 1080); //TODO sound = new Sound(form.Handle); form.KeyDown += (target, arg) => { if (arg.KeyCode == System.Windows.Forms.Keys.Escape) { exit = true; } if (arg.KeyCode == System.Windows.Forms.Keys.Enter) { ClearScreen(); } }; form.MouseMove += (target, arg) => { mouseState.X = arg.X / (float)form.ClientSize.Width; mouseState.Y = arg.Y / (float)form.ClientSize.Height; }; form.MouseDown += (target, arg) => { mouseState.left |= arg.Button == MouseButtons.Left; mouseState.right |= arg.Button == MouseButtons.Right; mouseState.middle |= arg.Button == MouseButtons.Middle; }; form.MouseUp += (target, arg) => { mouseState.left ^= arg.Button == MouseButtons.Left; mouseState.right ^= arg.Button == MouseButtons.Right; mouseState.middle ^= arg.Button == MouseButtons.Middle; }; var desc = new SwapChainDescription() { BufferCount = 2, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(8, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; //Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); //int quality = device.CheckMultisampleQualityLevels(Format.R8G8B8A8_UNorm, 8); //Console.WriteLine(quality); //desc.SampleDescription.Quality = quality > 0 ? quality - 1 : 0; //device.Dispose(); //swapChain.Dispose(); //Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); //device = ToDispose(device); graphicsDevice = ToDispose(GraphicsDevice.New(DriverType.Hardware)); Cursor.Hide();//Hides cursor PresentationParameters pp = new PresentationParameters(desc.ModeDescription.Width, desc.ModeDescription.Height, desc.OutputHandle, desc.ModeDescription.Format); pp.MultiSampleCount = MSAALevel.X4; pp.IsFullScreen = true; graphicsDevice.Presenter = new SwapChainGraphicsPresenter(graphicsDevice, pp); //Factory factory = ToDispose(swapChain.GetParent<Factory>()); //factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); //backBuffer = ToDispose(SharpDX.Direct3D11.Texture2D.FromSwapChain<SharpDX.Direct3D11.Texture2D>(swapChain, 0)); //renderView = ToDispose(new RenderTargetView(device, backBuffer)); LoadContent(); Stopwatch totalTime = new Stopwatch(); totalTime.Start(); Stopwatch elapsedTime = new Stopwatch(); RenderLoop.Run(form, () => { if (exit) { form.Close(); Dispose(); Application.Exit(); } Update(new GameTime(totalTime.Elapsed, elapsedTime.Elapsed)); TimeSpan old = elapsedTime.Elapsed; elapsedTime.Restart(); Draw(new GameTime(totalTime.Elapsed, old)); graphicsDevice.Present(); }); Dispose(); //kinect.Initialize(); }
static public void Close() { form.Close(); }
private static void Main() { var form = new RenderForm("SharpDX - MiniCube Direct3D11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Used for debugging dispose object references // Configuration.EnableObjectTracking = true; // Disable throws on shader compilation errors //Configuration.ThrowOnShaderCompileError = false; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCube.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); var signature = ShaderSignature.GetInputSignature(vertexShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("COLOR", 0, Format.R32G32B32A32_Float, 12, 0) }); var floatsPerVertex = 7; // Instantiate Vertex buffer from vertex data var axesVertices = Buffer.Create(device, BindFlags.VertexBuffer, new float[] { +0.0f, +0.0f, +0.0f, 1, 0, 0, 1, +1.0f, +0.0f, +0.0f, 1, 0, 0, 1, +0.0f, +0.0f, +0.0f, 0, 1, 0, 1, +0.0f, +1.0f, +0.0f, 0, 1, 0, 1, +0.0f, +0.0f, +0.0f, 0, 0, 1, 1, +0.0f, +0.0f, +1.0f, 0, 0, 1, 1, }); var axesVertexCount = 9; var axesVertexBufferBinding = new VertexBufferBinding(axesVertices, Utilities.SizeOf <float>() * floatsPerVertex, 0); // Create Constant Buffer var contantBuffer = new Buffer(device, Utilities.SizeOf <Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.LineList; context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.PixelShader.Set(pixelShader); // Prepare matrices // Use clock var clock = new Stopwatch(); clock.Start(); // Declare texture for rendering bool userResized = true; Texture2D backBuffer = null; RenderTargetView renderView = null; Texture2D depthBuffer = null; DepthStencilView depthView = null; // Setup handler on resize form form.UserResized += (sender, args) => userResized = true; // Setup full screen mode change F5 (Full) F4 (Window) form.KeyDown += (sender, args) => { if (args.KeyCode == Keys.F5) { swapChain.SetFullscreenState(true, null); } else if (args.KeyCode == Keys.F4) { swapChain.SetFullscreenState(false, null); } else if (args.KeyCode == Keys.Escape) { form.Close(); } }; // Main loop RenderLoop.Run(form, () => { // If Form resized if (userResized) { // Dispose all previous allocated resources ComObject.Dispose(ref backBuffer); ComObject.Dispose(ref renderView); ComObject.Dispose(ref depthBuffer); ComObject.Dispose(ref depthView); // Resize the backbuffer swapChain.ResizeBuffers(desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None); // Get the backbuffer from the swapchain backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); // Renderview on the backbuffer renderView = new RenderTargetView(device, backBuffer); // Create the depth buffer depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); // Create the depth buffer view depthView = new DepthStencilView(device, depthBuffer); // Setup targets and viewport for rendering context.Rasterizer.SetViewports(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(depthView, renderView); // Setup new projection matrix with correct aspect ratio //proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); // We are done resizing userResized = false; } float time = clock.ElapsedMilliseconds / 1000.0f; //var viewProj = Matrix.Multiply(view, proj); // Clear views context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Colors.Black); // Update WorldViewProj Matrix //var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj; var basisX = new Vector4(1, 0, 0, 1); var basisY = new Vector4(0, 1, 0, 1); var basisZ = new Vector4(0, 0, 1, 1); // Rotate around X. basisY = Vector4.Transform(basisY, Matrix.RotationX((float)(Math.PI / 4))); basisZ = Vector4.Transform(basisZ, Matrix.RotationX((float)(Math.PI / 4))); // Rotate around basisY basisX = Vector4.Transform(basisX, Matrix.RotationAxis((Vector3)basisY, time)); basisZ = Vector4.Transform(basisZ, Matrix.RotationAxis((Vector3)basisY, time)); var worldViewProj = Matrix.Identity; worldViewProj.Row1 = basisX; worldViewProj.Row2 = basisY; worldViewProj.Row3 = basisZ; worldViewProj *= Matrix.Translation(0, 0, 0.5f); // View worldViewProj *= Matrix.LookAtLH(new Vector3(0, 0, -1), new Vector3(0, 0, 0), Vector3.UnitY); // Proj worldViewProj *= Matrix.PerspectiveFovLH((float)(Math.PI / 2f), form.ClientSize.Width / (float)form.ClientSize.Height, 0.00001f, 2000); worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, contantBuffer); // Draw the cube context.InputAssembler.SetVertexBuffers(0, axesVertexBufferBinding); context.Draw(axesVertexCount, 0); // Present! swapChain.Present(0, PresentFlags.None); }); // Release all resources signature.Dispose(); vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); axesVertices.Dispose(); layout.Dispose(); contantBuffer.Dispose(); depthBuffer.Dispose(); depthView.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); }
static void D2d() { var plugfire = new Plugfire(); InitializeXAudio2(); //var fileStream = new NativeFileStream(@"D:\plug17.mp3", NativeFileMode.Open, NativeFileAccess.Read); var embeddedStream = Assembly.GetEntryAssembly().GetManifestResourceStream(typeof(Program), "music.mp3"); var audioPlayer = new AudioPlayer(xaudio2, embeddedStream); audioPlayer.Play(); var form = new RenderForm("SharpDX - MiniCube Direct3D11 Sample"); form.Width = Plugfire.WIDTH * 4; form.Height = Plugfire.HEIGHT * 4; Device device; SwapChain swapChain; var d2dFactory = new SharpDX.Direct2D1.Factory(); var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = false, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.BgraSupport, new SharpDX.Direct3D.FeatureLevel[] { SharpDX.Direct3D.FeatureLevel.Level_10_0 }, desc, out device, out swapChain); // Ignore all windows events Factory factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); form.KeyUp += (sender, args) => { if (args.KeyCode == Keys.F5) { swapChain.SetFullscreenState(true, null); } else if (args.KeyCode == Keys.F4) { swapChain.SetFullscreenState(false, null); } else if (args.KeyCode == Keys.Escape) { form.Close(); } }; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Texture2D backBuffer = null; Bitmap bitmap = null; RenderTarget render = null; RenderTargetView renderView = null; backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); //var textBuffer = new Texture2D(device, new Texture2DDescription {Height = 100, Width = 100, Format = Format.R8G8B8A8_UNorm}); renderView = new RenderTargetView(device, backBuffer); //var textView = new RenderTargetView(device, textBuffer); Surface surface = backBuffer.QueryInterface <Surface>(); //Surface textSurface = textBuffer.QueryInterface<Surface>(); render = new RenderTarget(d2dFactory, surface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))); //var textRender = new RenderTarget(d2dFactory, textSurface, new RenderTargetProperties(new PixelFormat(Format.Unknown, AlphaMode.Premultiplied))); bitmap = new Bitmap(render, new Size2(Plugfire.WIDTH, Plugfire.HEIGHT), new BitmapProperties(new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Ignore))); SharpDX.DirectWrite.Factory FactoryDWrite = new SharpDX.DirectWrite.Factory(); var whiteTextBrush = new SolidColorBrush(render, new RawColor4(1, 1, 1, 1)); var debugTextFormat = new TextFormat(FactoryDWrite, "Arial", 10); var titleTextBrush = new SolidColorBrush(render, new RawColor4(1, 1, 0.3f, 1)); var foamTextFormat = new TextFormat(FactoryDWrite, "Arial", FontWeight.Bold, FontStyle.Normal, 100); var presentsTextFormat = new TextFormat(FactoryDWrite, "Arial", FontWeight.Bold, FontStyle.Normal, 60); var titleTextFormat = new TextFormat(FactoryDWrite, "Arial", FontWeight.Bold, FontStyle.Normal, 80); // Main loop RenderLoop.Run(form, () => { plugfire.Frame(stopwatch.ElapsedMilliseconds, audioPlayer.Position.TotalMilliseconds); bitmap.CopyFromMemory(plugfire.GetRgbImage(), Plugfire.WIDTH * 4); render.BeginDraw(); //render.Clear(Color.Wheat); //solidColorBrush.Color = new Color4(1, 1, 1, (float)Math.Abs(Math.Cos(stopwatch.ElapsedMilliseconds * .001))); //d2dRenderTarget.FillGeometry(rectangleGeometry, solidColorBrush, null); render.DrawBitmap(bitmap, new RawRectangleF(0, 0, render.Size.Width, render.Size.Height), 1.0f, BitmapInterpolationMode.Linear); //render.DrawText(audioPlayer.Position.ToString(), debugTextFormat, new RawRectangleF(10,10,100,100), whiteTextBrush); //if (plugfire.Mode == 0) //{ // var fade = (float)Math.Min((stopwatch.Elapsed.TotalMilliseconds - 500) / 2000, 1); // titleTextBrush.Color = new RawColor4(fade, fade, fade * 0.3f, 1); // render.DrawText("FOAM", foamTextFormat, new RawRectangleF(500, 100, 2000, 2000), titleTextBrush); // render.DrawText("presents", presentsTextFormat, new RawRectangleF(520, 200, 2000, 2000), titleTextBrush); // render.DrawText("Plugfire Regurgitated", titleTextFormat, new RawRectangleF(250, 400, 2000, 2000), titleTextBrush); //} render.EndDraw(); swapChain.Present(0, PresentFlags.None); }); // Release all resources renderView.Dispose(); backBuffer.Dispose(); device.ImmediateContext.ClearState(); device.ImmediateContext.Flush(); device.Dispose(); device.Dispose(); swapChain.Dispose(); factory.Dispose(); }
// [STAThread] private static void Main() { var form = new RenderForm("Sharp XFile Parser Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Used for debugging dispose object references // Configuration.EnableObjectTracking = true; // Disable throws on shader compilation errors //Configuration.ThrowOnShaderCompileError = false; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.None, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent <Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); var mesh = new XFileMesh(device); mesh.Load("../../../ゲキド街v3.0/ゲキド街v3.0.x"); var camera = new GlobeCamera(form); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); Matrix proj = Matrix.Identity; // Use clock var clock = new Stopwatch(); clock.Start(); // Declare texture for rendering bool userResized = true; Texture2D backBuffer = null; RenderTargetView renderView = null; Texture2D depthBuffer = null; DepthStencilView depthView = null; // Setup handler on resize form form.UserResized += (sender, args) => userResized = true; // Setup full screen mode change F5 (Full) F4 (Window) form.KeyUp += (sender, args) => { if (args.KeyCode == Keys.F5) { swapChain.SetFullscreenState(true, null); } else if (args.KeyCode == Keys.F4) { swapChain.SetFullscreenState(false, null); } else if (args.KeyCode == Keys.Escape) { form.Close(); } }; // Main loop RenderLoop.Run(form, () => { // If Form resized if (userResized) { // Dispose all previous allocated resources Utilities.Dispose(ref backBuffer); Utilities.Dispose(ref renderView); Utilities.Dispose(ref depthBuffer); Utilities.Dispose(ref depthView); // Resize the backbuffer swapChain.ResizeBuffers(desc.BufferCount, form.ClientSize.Width, form.ClientSize.Height, Format.Unknown, SwapChainFlags.None); // Get the backbuffer from the swapchain backBuffer = Texture2D.FromSwapChain <Texture2D>(swapChain, 0); // Renderview on the backbuffer renderView = new RenderTargetView(device, backBuffer); // Create the depth buffer depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); // Create the depth buffer view depthView = new DepthStencilView(device, depthBuffer); // Setup targets and viewport for rendering context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.OutputMerger.SetTargets(depthView, renderView); // Setup new projection matrix with correct aspect ratio proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); // We are done resizing userResized = false; } var time = clock.ElapsedMilliseconds / 1000.0f; var viewProj = Matrix.Multiply(view, proj); // Clear views context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); // context.ClearRenderTargetView(renderView, Color.Black); context.ClearRenderTargetView(renderView, new Color(100, 149, 237, 255)); // Draw the cube camera.OnUpdate(time); mesh.World = Matrix.Scaling(0.1f); mesh.Projection = camera.ProjectionMat; mesh.View = camera.ViewMat; mesh.Draw(context); // Present! swapChain.Present(1, PresentFlags.None); }); // Release all resources mesh.Dispose(); depthBuffer.Dispose(); depthView.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); }