The GameWindow class contains cross-platform methods to create and render on an OpenGL window, handle input and load resources.
GameWindow contains several events you can hook or override to add your custom logic: OnLoad: Occurs after creating the OpenGL context, but before entering the main loop. Override to load resources. OnUnload: Occurs after exiting the main loop, but before deleting the OpenGL context. Override to unload resources. OnResize: Occurs whenever GameWindow is resized. You should update the OpenGL Viewport and Projection Matrix here. OnUpdateFrame: Occurs at the specified logic update rate. Override to add your game logic. OnRenderFrame: Occurs at the specified frame render rate. Override to add your rendering code. Call the Run() method to start the application's main loop. Run(double, double) takes two parameters that specify the logic update rate, and the render update rate.
Inheritance: NativeWindow, IGameWindow, IDisposable
コード例 #1
3
ファイル: Program.cs プロジェクト: Mszauer/TileBasedGames
        public static void Main()
        {
            // Create static (global) window instance
            Window = new OpenTK.GameWindow();

            // Hook up the initialize callback
            Window.Load += new EventHandler<EventArgs>(Initialize);
            // Hook up the update callback
            Window.UpdateFrame += new EventHandler<FrameEventArgs>(Update);
            // Hook up the render callback
            Window.RenderFrame += new EventHandler<FrameEventArgs>(Render);
            // Hook up the shutdown callback
            Window.Unload += new EventHandler<EventArgs>(Shutdown);

            // Set window title and size
            Window.Title = "Game Name";
            Window.ClientSize = new Size(30*8, 30*6);
            Window.VSync = VSyncMode.On;
            // Run the game at 60 frames per second. This method will NOT return
            // until the window is closed.
            Window.Run(60.0f);

            // If we made it down here the window was closed. Call the windows
            // Dispose method to free any resources that the window might hold
            Window.Dispose();

            #if DEBUG
            Console.WriteLine("\nFinished executing, press any key to exit...");
            Console.ReadKey();
            #endif
        }
コード例 #2
0
 public GameWindowKeyboardInputSource(GameWindow window)
 {
     this.window = window;
     this.window.FocusedChanged += this.window_FocusedChanged;
     this.window.Keyboard.KeyDown += this.device_KeyDown;
     this.window.KeyPress += this.window_KeyPress;
 }
コード例 #3
0
ファイル: Program.cs プロジェクト: GROWrepo/OpenGL.Study
		static void Main ()
		{
			// OpenGL 창
			GameWindow window = new GameWindow ();
			
			// 창이 처음 생성됐을 때 
			window.Load += ( sender, e ) =>
			{
				
			};
			// 업데이트 프레임(연산처리, 입력처리 등)
			window.UpdateFrame += ( sender, e ) =>
			{
				
			};
			// 렌더링 프레임(화면 표시)
			window.RenderFrame += ( sender, e ) =>
			{
				// 화면 초기화 설정
				//> 화면 색상은 검정색(R: 0, G: 0, B: 0, A: 255)
				GL.ClearColor ( 0, 0, 0, 1 );
				//> 깊이 버퍼는 1(쓸 수 있는 깊이)
				GL.ClearDepth ( 1 );
				//> 스텐실 버퍼는 0
				GL.ClearStencil ( 0 );
				// 화면 초기화(색상 버퍼, 깊이 버퍼, 스텐실 버퍼에 처리)
				GL.Clear ( ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit );

				// OpenGL 1.0 삼각형 그리기 시작
				// OpenGL 3.2부터 Deprecated, OpenGL ES 2.0부터 Deprecated
				GL.Begin ( PrimitiveType.Triangles );

				// 삼각형의 세 꼭지점 설정
				// OpenGL 3.2부터 Deprecated, OpenGL ES 2.0부터 Deprecated
				GL.Vertex2 ( +0.0, +0.5 );
				GL.Vertex2 ( +0.5, -0.5 );
				GL.Vertex2 ( -0.5, -0.5 );

				// 삼각형 색상은 마젠타(R: 255, G: 0, B: 255)
				// OpenGL 3.2부터 Deprecated, OpenGL ES 2.0부터 Deprecated
				GL.Color3 ( 1.0f, 0, 1.0f );

				// OpenGL 1.0 삼각형 그리기 끝
				// OpenGL 3.2부터 Deprecated, OpenGL ES 2.0부터 Deprecated
				GL.End ();
				// 버퍼에 출력
				GL.Flush ();

				// 백 버퍼와 화면 버퍼 교환
				window.SwapBuffers ();
			};
			// 창이 종료될 때
			window.Closing += ( sender, e ) =>
			{
				
			};

			// 창을 띄우고 창이 종료될 때까지 메시지 펌프 및 무한 루프 처리
			window.Run ();
		}
コード例 #4
0
        public static void Main()
        {
            //create static(global) window instance
            Window = new OpenTK.GameWindow();

            //hook up the initialize callback
            Window.Load += new EventHandler<EventArgs>(Initialize);
            //hook up the update callback
            Window.UpdateFrame += new EventHandler<FrameEventArgs>(Update);
            //hook up render callback
            Window.RenderFrame += new EventHandler<FrameEventArgs>(Render);
            //hook up shutdown callback
            Window.Unload += new EventHandler<EventArgs>(Shutdown);
            Window.VSync = VSyncMode.On;

            //set window title and size
            Window.Title = "Game Name";
            Window.ClientSize = new Size(800, 600);
            //run game at 60fps. will not return until window is closed
            Window.Run(60.0f);

            Window.Dispose();
            #if DEBUG
            Console.ReadLine();
            #endif
        }
コード例 #5
0
        public byte[] Render(IEnumerable<FeatureCollection> featureCollections)
        {
            lock (_syncRoot)
            {
                // There needs to be a gamewindow even though we don't write to screen. It is created but not used explicitly in our code.
                using (var gameWindow = new GameWindow(_pixelWidth, _pixelHeight))
                {
                    if (!GL.GetString(StringName.Extensions).Contains("GL_EXT_framebuffer_object"))
                    {
                        throw new NotSupportedException(
                            "GL_EXT_framebuffer_object extension is required. Please update your drivers.");
                    }

                    FrameBufferObjectHelper.StartFrameBufferObject(_pixelWidth, _pixelHeight);

                    OpenTK.Graphics.ES20.GL.ClearColor(Color4.White);
                    OpenTK.Graphics.ES20.GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    Set2DViewport(_pixelWidth, _pixelHeight);

                    GL.PushMatrix();
                    GL.Scale(_pixelWidth/_extentWidth, _pixelHeight/_extentHeight, 1);
                    GL.Translate(-_extentMinX, -_extentMinY, 0);

                    PolygonRenderer(featureCollections);
                    var byteArray = GraphicsContextToBitmapConverter.ToBitmap(_pixelWidth, _pixelHeight);

                    GL.PopMatrix();

                    FrameBufferObjectHelper.StopFrameBufferObject();

                    return byteArray;
                }
            }
        }
コード例 #6
0
ファイル: RenderPass.cs プロジェクト: smalld/particle_system
 public override void Render(GameWindow window)
 {
     foreach (var item in m_Passes)
     {
         item.Render(window);
     }
 }
コード例 #7
0
ファイル: Camera.cs プロジェクト: olegbom/ObjectTK
 public void Enable(GameWindow window)
 {
     if (Behavior == null) throw new InvalidOperationException("Can not enable Camera while the Behavior is not set.");
     window.UpdateFrame += UpdateFrame;
     window.Mouse.Move += MouseMove;
     window.Mouse.WheelChanged += MouseWheelChanged;
 }
コード例 #8
0
        public MouseTrackBall(GameWindow gm)
        {
            gm.Mouse.WheelChanged += (s,e) =>{

                distance+=e.Delta*zSpeed;
            };

            gm.Mouse.ButtonDown += (s, e) => {
                if(e.Button != OpenTK.Input.MouseButton.Middle && e.Button != OpenTK.Input.MouseButton.Right)
                    return;
                isDown = true;
                lastX = e.X;
                lastY = e.Y;
            //	Console.WriteLine(string.Format("Mouse Left Click on ({0},{1}):",lastX,lastY));
            };

            gm.Mouse.ButtonUp += (s, e) => {
                if(e.Button != OpenTK.Input.MouseButton.Middle && e.Button != OpenTK.Input.MouseButton.Right)
                return;
                isDown = false;
            };

            gm.Mouse.Move += (s,e) => {
                if(!isDown) return;
                move(e);
            //	gm.SwapBuffers();
            };
        }
コード例 #9
0
ファイル: Input.cs プロジェクト: Foohy/OlegEngine
        /// <summary>
        /// Update input, including getting mouse deltas/etc.
        /// </summary>
        public static void Think(GameWindow window, FrameEventArgs e)
        {
            current = Mouse.GetState();

            window.CursorVisible = !LockMouse;

            if (current != previous && window.Focused)
            {
                // Mouse state has changed
                deltaX = current.X - previous.X;
                deltaY = current.Y - previous.Y;
                deltaZ = current.Wheel - previous.Wheel;

                if (LockMouse)
                {
                    Mouse.SetPosition(window.X + window.Width / 2, window.Y + window.Height / 2);
                }
            }
            else
            {
                deltaX = 0;
                deltaY = 0;
                deltaZ = 0;
            }
            previous = current;
        }
コード例 #10
0
ファイル: GameApp.cs プロジェクト: AndiAngerer/cubehack
        public void Run()
        {
            _gameWindow = new GameWindow(1280, 720);

            try
            {
                _gameWindow.Title = "CubeHack";
                _gameWindow.VSync = VSyncMode.On;

                /* This sequence seems necessary to bring the window to the front reliably. */
                _gameWindow.WindowState = WindowState.Maximized;
                _gameWindow.WindowState = WindowState.Minimized;
                _gameWindow.Visible = true;
                _gameWindow.WindowState = WindowState.Maximized;

                _gameWindow.KeyDown += OnKeyDown;
                _gameWindow.KeyPress += OnKeyPress;
                _gameWindow.KeyUp += OnKeyUp;

                _gameLoop.RenderFrame += RenderFrame;
                try
                {
                    _gameLoop.Run(_gameWindow);
                }
                finally
                {
                    _gameLoop.RenderFrame -= RenderFrame;
                }
            }
            finally
            {
                _gameWindow.Dispose();
                _gameWindow = null;
            }
        }
コード例 #11
0
        public OpenGLInputObservable(GameWindow window)
        {
            gameWindow = window;

            IObservable<IInput> downEvents =
                from evt in Observable.FromEventPattern<KeyboardKeyEventArgs>(window, "KeyDown")
                let keyInput = GLKeyInput.FromArgs(evt.EventArgs, false)
                where keyInput != null
                select keyInput;

            IObservable<IInput> upEvents =
                from evt in Observable.FromEventPattern<KeyboardKeyEventArgs>(window, "KeyUp")
                let keyInput = GLKeyInput.FromArgs(evt.EventArgs, true)
                where keyInput != null
                select keyInput;

            IObservable<IInput> mouseMoveEvents =
                from evt in Observable.FromEventPattern<MouseMoveEventArgs>(window, "MouseMove")
                from mouseInput in GLMouseInput.FromArgs(evt.EventArgs, gameWindow.Width, gameWindow.Height)
                select mouseInput;

            IObservable<IInput> mouseDownEvents =
                from evt in Observable.FromEventPattern<MouseButtonEventArgs>(window, "MouseDown")
                select GLMouseClickInput.FromArgs(evt.EventArgs, false);

            IObservable<IInput> mouseUpEvents =
                from evt in Observable.FromEventPattern<MouseButtonEventArgs>(window, "MouseUp")
                select GLMouseClickInput.FromArgs(evt.EventArgs, true);

            InputEvents = downEvents.Merge(upEvents).Merge(mouseMoveEvents).Merge(mouseDownEvents).Merge(mouseUpEvents);

            window.MouseMove += (sender, e) => Cursor.Position = new Point(window.Width / 2, window.Height / 2); // keep mouse centered (bc fps)
        }
コード例 #12
0
        public FastEngine(string windowName, int width, int height, int fps)
        {
            // disabling HiDPI support
            var options = new ToolkitOptions
            {
                EnableHighResolution = false
            };
            OpenTK.Toolkit.Init(options);
            window = new GameWindow (width, height, OpenTK.Graphics.GraphicsMode.Default, windowName);

            // call it AFTER GameWindow initialization to avoid problems with Windows.Forms
            this.Initialize (windowName, width, height, fps);

            // create a new texture
            texture = GL.GenTexture ();
            // use the texure (as a 2d one)
            GL.BindTexture (TextureTarget.Texture2D, texture);
            GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter (TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            this.textureRect = new Rectangle (0, 0, width, height);

            GL.Enable (EnableCap.Texture2D);

            window.Resize += this.Game_Resize;
            window.RenderFrame += this.Game_RenderFrame;

            // initialize OpenAL context (No ! do it lazily)
            // audioContext = new AudioContext ();
        }
コード例 #13
0
ファイル: Camera.cs プロジェクト: jonnyli1125/FirstPerson
        public Camera(GameWindow window, Vector3 position, Vector3 up)
        {
            Window = window;
            Position = position;
            Up = up;

            MouseDelta = new Point();

            Window.Resize += (sender, e) =>
            {
                Cursor.Position = ScreenCenter;
                Cursor.Hide();

                GL.Viewport(Window.ClientRectangle.X, Window.ClientRectangle.Y, Window.ClientRectangle.Width, Window.ClientRectangle.Height);

                Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Window.Width / (float)Window.Height, 1f, Fog);
                GL.MatrixMode(MatrixMode.Projection);
                GL.LoadMatrix(ref projection);
            };

            Window.UpdateFrame += (sender, e) =>
            {
                MouseDelta = new Point(Window.Mouse.X - WindowCenter.X, Window.Mouse.Y - WindowCenter.Y);
                Point p = Cursor.Position;
                p.X -= MouseDelta.X;
                p.Y -= MouseDelta.Y;
                Cursor.Position = p;
                Facing += MouseDelta.X / (1000 - (float)(HorizontalSensitivity * 100));
                Pitch -= MouseDelta.Y / (1000 - (float)(VerticalSensitivity * 100));
                if (Pitch < -1.5f) Pitch = -1.5f;
                if (Pitch > 1.5f) Pitch = 1.5f;
                Vector3 lookatPoint = new Vector3((float)Math.Cos(Facing), (float)Math.Tan(Pitch), (float)Math.Sin(Facing));
                CameraMatrix = Matrix4.LookAt(Position, Position + lookatPoint, Up);
            };
        }
コード例 #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="InputImp"/> class.
        /// </summary>
        /// <param name="renderCanvas">The render canvas.</param>
        /// <exception cref="System.ArgumentNullException">renderCanvas</exception>
        /// <exception cref="System.ArgumentException">renderCanvas must be of type RenderCanvasImp;renderCanvas</exception>
        public InputImp(IRenderCanvasImp renderCanvas)
        {
            if (renderCanvas == null)
                throw new ArgumentNullException("renderCanvas");

            if (!(renderCanvas is RenderCanvasImp))
                throw new ArgumentException("renderCanvas must be of type RenderCanvasImp", "renderCanvas");

            _gameWindow = ((RenderCanvasImp) renderCanvas)._gameWindow;
            if (_gameWindow != null)
            {
                _gameWindow.Keyboard.KeyDown += OnGameWinKeyDown;
                _gameWindow.Keyboard.KeyUp += OnGameWinKeyUp;
                _gameWindow.Mouse.ButtonDown += OnGameWinMouseDown;
                _gameWindow.Mouse.ButtonUp += OnGameWinMouseUp;
                _gameWindow.Mouse.Move += OnGameWinMouseMove;
            }
            else
            {
                // Todo

            }

            KeyMapper = new Keymapper();
        }
コード例 #15
0
ファイル: InputDriver.cs プロジェクト: prepare/HTML-Renderer
        public InputDriver(GameWindow parent)
        {
            if (parent == null)
                throw new ArgumentException("A valid window (IWindowInfo) must be specified to construct an InputDriver");
            switch (Environment.OSVersion.Platform)
            {
                case PlatformID.Win32Windows:
                case PlatformID.Win32NT:
                case PlatformID.Win32S:
                case PlatformID.WinCE:
                    if (Environment.OSVersion.Version.Major > 5 ||
                        (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 1))
                    {
                        inputDriver = new OpenTK.Platform.Windows.WinRawInput((OpenTK.Platform.Windows.WinWindowInfo)parent.WindowInfo);
                    }
                    else
                    {
                        // Legacy or unknown windows version:
                        inputDriver = new OpenTK.Platform.Windows.WMInput((OpenTK.Platform.Windows.WinWindowInfo)parent.WindowInfo);
                    }
                    break;
                case PlatformID.Unix:
                    // TODO: Input is currently handled asychronously by the driver in X11GLNative.
                    //inputDriver = new OpenTK.Platform.X11.X11Input(parent.WindowInfo);

                    break;
                default:
                    throw new PlatformNotSupportedException(
    "Input handling is not supported on the current platform. Please report the problem to http://opentk.sourceforge.net");
            }
        }
コード例 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="GameContext" /> class.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="requestedWidth">Width of the requested.</param>
        /// <param name="requestedHeight">Height of the requested.</param>
        public GameContext(OpenTK.GameWindow control, int requestedWidth = 0, int requestedHeight = 0)
        {
            var creationFlags = GraphicsContextFlags.Default;
            int versionMajor, versionMinor;

#if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
            versionMajor = 2;
            versionMinor = 0;
            OpenTK.Platform.Utilities.ForceEmbedded = true;
            creationFlags |= GraphicsContextFlags.Embedded;
#else
            versionMajor = 4;
            versionMinor = 2;
#endif

            if (requestedWidth == 0 || requestedHeight == 0)
            {
                requestedWidth  = 1280;
                requestedHeight = 720;
            }

            // force the stencil buffer to be not null.
            var defaultMode = GraphicsMode.Default;
            var graphicMode = new GraphicsMode(defaultMode.ColorFormat, defaultMode.Depth, 8, defaultMode.Samples, defaultMode.AccumulatorFormat, defaultMode.Buffers, defaultMode.Stereo);

            GraphicsContext.ShareContexts = true;
            Control         = control ?? new OpenTK.GameWindow(requestedWidth, requestedHeight, graphicMode, "Paradox Game", GameWindowFlags.Default, DisplayDevice.Default, versionMajor, versionMinor, creationFlags);
            RequestedWidth  = requestedWidth;
            RequestedHeight = requestedHeight;
            ContextType     = AppContextType.DesktopOpenTK;
        }
コード例 #17
0
        private void Initialize()
        {
            window                   = new OpenTK.GameWindow();
            window.RenderFrame      += OnRenderFrame;
            window.UpdateFrame      += OnUpdateFrame;
            window.Closing          += new EventHandler <CancelEventArgs>(OpenTkGameWindow_Closing);
            window.Resize           += OnResize;
            window.Keyboard.KeyDown += new EventHandler <OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyDown);
            window.Keyboard.KeyUp   += new EventHandler <OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyUp);

            updateClientBounds = false;
            clientBounds       = new Rectangle(window.ClientRectangle.X, window.ClientRectangle.Y,
                                               window.ClientRectangle.Width, window.ClientRectangle.Height);
            windowState = window.WindowState;

            keys = new List <Keys>();

            // mouse
            // TODO review this when opentk 1.1 is released
            Mouse.UpdateMouseInfo(window.Mouse);

            // Initialize GameTime
            _updateGameTime = new GameTime();
            _drawGameTime   = new GameTime();

            // Initialize _lastUpdate
            _lastUpdate = DateTime.Now;

            //Default no resizing
            AllowUserResizing = false;
        }
コード例 #18
0
ファイル: Plasma.cs プロジェクト: samerai/FastIntroFramework
        public override void OnRenderFrame(OpenTK.FrameEventArgs e, GameWindow window)
        {
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadIdentity();
            GL.Ortho(0, 1280, 0,720,0,1);
            GL.Disable(EnableCap.DepthTest);
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();
            GL.ClearColor(0.2f , 0.2f, 0.2f, 0);
            GL.Clear(ClearBufferMask.ColorBufferBit);

            for (int y=0;y<720;y++)
            {
                for (int x = 0; x < 1280; x++)
                {
                    var c = (int) (Math.Floor(Math.Sin(x/35d)*128 + Math.Sin(y/28d)*32f + Math.Sin((x + y)/16d)*64));
                    c = mod(c, 256);
                    var r = cols[0, c] % 256;
                    var g = cols[1, c] % 256;
                    var b = cols[2, c] % 256;
                    GL.Color3(r/256, g/256, b/256);
                    GL.Begin(BeginMode.Points);
                        GL.Vertex2(x, y);
                    GL.End();
                }

            }
            window.SwapBuffers();
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: Herbstein/BlunderBuzz
        private static void Main(string[] args)
        {
            var sprites = new List<Sprite>();

            Window = new GameWindow(800, 600, GraphicsMode.Default, "Blunder Buzz");

            Window.Load += (sender, e) => {
                Window.VSync = VSyncMode.On;

                sprites.Add(new Sprite(new Shader("Shaders/basicVertex.glsl", "Shaders/basicFragment.glsl")));
            };

            Window.UpdateFrame += (sender, e) => {
                if (Window.Keyboard[Key.Escape]) {
                    Window.Exit();
                }

                foreach (var sprite in sprites) {
                    sprite.Update();
                }
            };

            Window.RenderFrame += (sender, e) => {
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
                GL.ClearColor(Color.CornflowerBlue);

                foreach (var sprite in sprites) {
                    sprite.Render();
                }

                Window.SwapBuffers();
            };

            Window.Run(DisplayDevice.Default.RefreshRate);
        }
コード例 #20
0
        public override bool HandleInput(GameWindow window)
        {
            m_Initialized = window.Mouse[MouseButton.Left];

            var mousepos = 2 * new Vector2 (window.Mouse.X, window.Mouse.Y);
            mousepos.Y = -mousepos.Y;

            if (!m_Initialized)
            {
                m_OldMousePos = mousepos;
                return false;
            }

            var deltaPos = mousepos - m_OldMousePos;
            var deltaAngles = deltaPos / 400;

            var temp = Position;
            temp.Normalize();
            temp = Vector3.Cross(temp, Vector3.UnitZ);
            temp.Normalize();

            var rotationH = Quaternion.FromAxisAngle (temp, deltaAngles.Y);
            var rotationV = Quaternion.FromAxisAngle (Vector3.UnitZ, deltaAngles.X);
            Position = Vector3.Transform(Position, Matrix4.Rotate(rotationH) * Matrix4.Rotate(rotationV));

            RTstack.ValueStack[0] = Matrix4.LookAt (Position, Target, UpDirection);

            m_OldMousePos = mousepos;
            return true;
        }
コード例 #21
0
		public static void Add(GameWindow gameWindow)
		{
			IGraphicsContext context = gameWindow.Context;
			IWindowInfo window = gameWindow.WindowInfo;

			Contexts.Add(context, new ContextAsset(window));
		}
コード例 #22
0
ファイル: Game.cs プロジェクト: KodoRyu/gameplayground
        public Game()
        {
            state = new BootState(this);

            window = new GameWindow(960, 540);
            window.Load += Window_Load;
            window.RenderFrame += Window_RenderFrame;
            window.UpdateFrame += Window_UpdateFrame;
            window.Closing += Window_Closing;
            window.Closed += Window_Closed;
            window.Resize += Window_Resize;
            window.FocusedChanged += Window_FocusedChanged;

            Console.WriteLine("OpenGL: {0}", GL.GetString(StringName.Version));

            keyHandler = new KeyHandler(window);

            Canvas = new SceneCanvas(keyHandler);
            shaderManager = new ShaderManager();

            shader = new StaticShader();
            shaderManager.Add(shader);

            fontShader = new FontShader();

            fontManager = new FontManager(fontShader);
            fontShader.Compile();
            font = FontParser.ParseFNT(@"Fonts/Verdana.fnt");
            fontManager.Add(font);

            lastMousePosition = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
        }
コード例 #23
0
        private void Initialize()
        {
            OpenTK.Graphics.GraphicsContext.ShareContexts = true;
            GraphicsMode mode = new GraphicsMode((ColorFormat)DisplayDevice.Default.BitsPerPixel, 24, 8);

            this.window                   = new OpenTK.GameWindow(640, 480, mode);
            this.window.RenderFrame      += new EventHandler <FrameEventArgs>(this.OnRenderFrame);
            this.window.UpdateFrame      += new EventHandler <FrameEventArgs>(this.OnUpdateFrame);
            this.window.Closing          += new EventHandler <CancelEventArgs>(this.OpenTkGameWindow_Closing);
            this.window.Resize           += new EventHandler <EventArgs>(this.OnResize);
            this.window.Keyboard.KeyDown += new EventHandler <KeyboardKeyEventArgs>(this.Keyboard_KeyDown);
            this.window.Keyboard.KeyUp   += new EventHandler <KeyboardKeyEventArgs>(this.Keyboard_KeyUp);
            this.window.MouseEnter       += new EventHandler <EventArgs>(this.OnMouseEnter);
            this.window.MouseLeave       += new EventHandler <EventArgs>(this.OnMouseLeave);
            this.window.KeyPress         += new EventHandler <OpenTK.KeyPressEventArgs>(this.OnKeyPress);
            this.window.Icon              = Icon.ExtractAssociatedIcon(Assembly.GetEntryAssembly().Location);
            this.updateClientBounds       = false;
            this.clientBounds             = new Rectangle(this.window.ClientRectangle.X, this.window.ClientRectangle.Y, this.window.ClientRectangle.Width, this.window.ClientRectangle.Height);
            this.windowState              = this.window.WindowState;
            this._windowHandle            = (IntPtr)this.window.WindowInfo.GetType().GetProperty("WindowHandle").GetValue((object)this.window.WindowInfo, (object[])null);
            Threading.BackgroundContext   = (IGraphicsContext) new OpenTK.Graphics.GraphicsContext(mode, this.window.WindowInfo);
            Threading.WindowInfo          = this.window.WindowInfo;
            this.keys = new List <Microsoft.Xna.Framework.Input.Keys>();
            if (OpenTK.Graphics.GraphicsContext.CurrentContext == null || !OpenTK.Graphics.GraphicsContext.CurrentContext.IsCurrent)
            {
                this.window.MakeCurrent();
            }
            Microsoft.Xna.Framework.Input.Mouse.setWindows(this.window);
            this.AllowUserResizing = false;
        }
コード例 #24
0
ファイル: Main.cs プロジェクト: smalld/particle_system
        public static void Main(string[] args)
        {
            var win = new OpenTK.GameWindow (200, 200, GraphicsMode.Default, "", OpenTK.GameWindowFlags.Default);

            var form1 = new Form ();
            form1.Size = new Size(400, 1000);
            PropertyGrid propertyGrid1 = new PropertyGrid ();
            propertyGrid1.CommandsVisibleIfAvailable = true;
            propertyGrid1.Location = new Point (10, 20);
            propertyGrid1.TabIndex = 1;
            propertyGrid1.Text = "Property Grid";
            propertyGrid1.Dock = DockStyle.Fill;
            propertyGrid1.Font = new Font("URW Gothic L", 10.25f, GraphicsUnit.Point);
            propertyGrid1.CategoryForeColor = SystemColors.ControlLight;
            propertyGrid1.ViewForeColor = SystemColors.ControlText;
            propertyGrid1.ViewBackColor = SystemColors.Control;
            propertyGrid1.LineColor = SystemColors.ControlLight;
            form1.Controls.Add (propertyGrid1);
            form1.Show ();

            win.RenderFrame += (sender, aaa) => { Application.DoEvents (); };

            using(var system = (new System6.System6()).GetInstance (win))
            {
                //system.PropertyChanged += (sender, e) => propertyGrid1.Refresh();
                propertyGrid1.SelectedObject = system;
                win.Run ();
            }
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: danielscherzer/Framework
        private MyApplication()
        {
            //setup
            gameWindow = new GameWindow(700, 700);
            gameWindow.KeyDown += (s, arg) => gameWindow.Close();
            gameWindow.Resize += (s, arg) => GL.Viewport(0, 0, gameWindow.Width, gameWindow.Height);
            gameWindow.RenderFrame += GameWindow_RenderFrame;
            gameWindow.RenderFrame += (s, arg) => gameWindow.SwapBuffers();
            //animation using a single SpriteSheet
            explosion = new SpriteSheetAnimation(new SpriteSheet(TextureLoader.FromBitmap(Resourcen.explosion), 5), 0, 24, 1);
            //animation using a bitmap for each frame
            alienShip = new AnimationTextures(.5f);
            //art from http://millionthvector.blogspot.de/p/free-sprites.html
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10001));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10002));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10003));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10004));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10005));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10006));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10007));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10008));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10009));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10010));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10011));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10012));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10013));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10014));
            alienShip.AddFrame(TextureLoader.FromBitmap(Resourcen.alien10015));

            //for transparency in textures
            GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
            //start game time
            timeSource.Start();
        }
コード例 #26
0
ファイル: My.cs プロジェクト: siltutorials/TKPlatformer
        public static void Initialize(GameWindow gameWindow)
        {
            window = gameWindow;
            keysPressedLast = new List<Key>();
            keysPressed = new List<Key>();
            mousePressedLast = new List<MouseButton>();
            mousePressed = new List<MouseButton>();
            window.Keyboard.KeyDown += Keyboard_KeyDown;
            window.Keyboard.KeyUp += Keyboard_KeyUp;
            window.Mouse.ButtonDown += Mouse_ButtonDown;
            window.Mouse.ButtonUp += Mouse_ButtonUp;

            #region Create dot texture
            {
                int id = GL.GenTexture();
                GL.BindTexture(TextureTarget.Texture2D, id);

                Bitmap bmp = new Bitmap(1, 1);
                bmp.SetPixel(0, 0, Color.White);
                BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, 1, 1), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba,
                    1, 1, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra,
                    PixelType.UnsignedByte, bmpData.Scan0);

                dot = new Texture2D("dot", id, 1, 1);

                bmp.UnlockBits(bmpData);

                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMinFilter.Linear);
            }
            #endregion
        }
コード例 #27
0
        public static void Main()
        {
            //create static(global) window instance
            Window = new OpenTK.GameWindow();

            //hook up the initialize callback
            Window.Load += new EventHandler <EventArgs>(Initialize);
            //hook up the update callback
            Window.UpdateFrame += new EventHandler <FrameEventArgs>(Update);
            //hook up render callback
            Window.RenderFrame += new EventHandler <FrameEventArgs>(Render);
            //hook up shutdown callback
            Window.Unload += new EventHandler <EventArgs>(Shutdown);
            Window.VSync   = VSyncMode.On;

            //set window title and size
            Window.Title      = "Game Name";
            Window.ClientSize = new Size(800, 600);
            //run game at 60fps. will not return until window is closed
            Window.Run(60.0f);

            Window.Dispose();
#if DEBUG
            Console.ReadLine();
#endif
        }
コード例 #28
0
ファイル: WindowReactions.cs プロジェクト: johtela/Compose3D
        public static Reaction<Reaction<FrameEventArgs>> WhenRendered(this Reaction<FrameEventArgs> reaction, 
			GameWindow window)
        {
            return reaction.ToEvent<FrameEventArgs> (
                handler => window.RenderFrame += handler,
                handler => window.RenderFrame -= handler);
        }
コード例 #29
0
ファイル: WindowReactions.cs プロジェクト: johtela/Compose3D
        public static Reaction<Reaction<EventArgs>> WhenResized(this Reaction<EventArgs> reaction, 
			GameWindow window)
        {
            return reaction.ToEvent<EventArgs> (
                handler => window.Resize += handler,
                handler => window.Resize -= handler);
        }
コード例 #30
0
        private void Initialize()
        {
            GraphicsContext.ShareContexts = true;

            window                   = new OpenTK.GameWindow();
            window.RenderFrame      += OnRenderFrame;
            window.UpdateFrame      += OnUpdateFrame;
            window.Closing          += new EventHandler <CancelEventArgs>(OpenTkGameWindow_Closing);
            window.Resize           += OnResize;
            window.Keyboard.KeyDown += new EventHandler <OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyDown);
            window.Keyboard.KeyUp   += new EventHandler <OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyUp);
#if LINUX
            window.WindowBorder = WindowBorder.Resizable;
#endif
#if WINDOWS
            window.MouseEnter += OnMouseEnter;
            window.MouseLeave += OnMouseLeave;
#endif

            window.KeyPress += OnKeyPress;

            // Set the window icon.
            window.Icon = Icon.ExtractAssociatedIcon(Assembly.GetEntryAssembly().Location);

            updateClientBounds = false;
            clientBounds       = new Rectangle(window.ClientRectangle.X, window.ClientRectangle.Y,
                                               window.ClientRectangle.Width, window.ClientRectangle.Height);
            windowState = window.WindowState;

#if WINDOWS
            {
                var windowInfoType = window.WindowInfo.GetType();
                var propertyInfo   = windowInfoType.GetProperty("WindowHandle");
                _windowHandle = (IntPtr)propertyInfo.GetValue(window.WindowInfo, null);
            }
#endif
            // Provide the graphics context for background loading
            Threading.BackgroundContext = new GraphicsContext(GraphicsMode.Default, window.WindowInfo);
            Threading.WindowInfo        = window.WindowInfo;

            keys = new List <Keys>();

            // Make the foreground context the current context
            if (GraphicsContext.CurrentContext == null || !GraphicsContext.CurrentContext.IsCurrent)
            {
                window.MakeCurrent();
            }

            // mouse
            // TODO review this when opentk 1.1 is released
#if WINDOWS || LINUX
            Mouse.setWindows(window);
#else
            Mouse.UpdateMouseInfo(window.Mouse);
#endif

            //Default no resizing
            AllowUserResizing = false;
        }
コード例 #31
0
ファイル: Program.cs プロジェクト: GROWrepo/OpenGL.Study
		static void Main ()
		{
			// OpenGL 창
			GameWindow window = new GameWindow ();

			float [] vertices = new float []
			{
				+0.0f, +0.5f,
				+0.5f, -0.5f,
				-0.5f, -0.5f,
			};

			// 창이 처음 생성됐을 때 
			window.Load += ( sender, e ) =>
			{

			};
			// 업데이트 프레임(연산처리, 입력처리 등)
			window.UpdateFrame += ( sender, e ) =>
			{

			};
			// 렌더링 프레임(화면 표시)
			window.RenderFrame += ( sender, e ) =>
			{
				// 화면 초기화 설정
				//> 화면 색상은 검정색(R: 0, G: 0, B: 0, A: 255)
				GL.ClearColor ( 0, 0, 0, 1 );
				//> 깊이 버퍼는 1(쓸 수 있는 깊이)
				GL.ClearDepth ( 1 );
				//> 스텐실 버퍼는 0
				GL.ClearStencil ( 0 );
				// 화면 초기화(색상 버퍼, 깊이 버퍼, 스텐실 버퍼에 처리)
				GL.Clear ( ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit | ClearBufferMask.StencilBufferBit );

				// 정점 정보 입력
				// (정점 버퍼 사용하지 않음 = 속도가 느림)
				// OpenGL 3.2부터 Deprecated, OpenGL ES 2.0부터 Deprecated
				GL.VertexPointer<float> ( 2, VertexPointerType.Float, 0, vertices );
				GL.EnableClientState ( ArrayCap.VertexArray );

				// 삼각형 색상은 마젠타(R: 255, G: 0, B: 255)
				// OpenGL 3.2부터 Deprecated, OpenGL ES 2.0부터 Deprecated
				GL.Color3 ( 1.0f, 0, 1.0f );

				GL.DrawArrays ( PrimitiveType.Triangles, 0, 3 );

				// 백 버퍼와 화면 버퍼 교환
				window.SwapBuffers ();
			};
			// 창이 종료될 때
			window.Closing += ( sender, e ) =>
			{

			};

			// 창을 띄우고 창이 종료될 때까지 메시지 펌프 및 무한 루프 처리
			window.Run ();
		}
コード例 #32
0
        private void Task1Btn_Click(object sender, RoutedEventArgs e)
        {
            using (var visualWindow = new VisualWindow())
            {
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.VSync = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left  = -100,
                          right = 100,
                          down  = -50,
                          up    = 50;


                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(left, right, down, up, 0, 100);

                    GL.Begin(PrimitiveType.Lines);

                    // Axis
                    GL.Color3(Color.Black);
                    GL.Vertex2(0, -100);
                    GL.Vertex2(0, 100);
                    GL.Vertex2(-100, 0);
                    GL.Vertex2(100, 0);

                    // Graphic
                    GL.Color3(Color.DarkCyan);
                    float prevX = -100, prevY = 0;
                    for (float x = left; x <= right; x += 0.5f)
                    {
                        float y = Math.Abs(0.25f * x + 3 * (float)Math.Cos(100f * x) * (float)Math.Sin(x));
                        GL.Vertex2(prevX, prevY);
                        GL.Vertex2(x, y);
                        prevX = x; prevY = y;
                    }


                    GL.End();

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
コード例 #33
0
 static void Main()
 {
     gw = new OpenTK.GameWindow(800, 600, OpenTK.Graphics.GraphicsMode.Default, "Game", OpenTK.GameWindowFlags.FixedWindow);
     Initialize();
     gw.RenderFrame += Gw_RenderFrame;
     gw.Closed      += Gw_Closed;
     gw.Run(60);
 }
コード例 #34
0
        internal OpenTKWindowManager(IGraphicsDeviceService graphicsDeviceService, GameWindow gameWindow)
            : base(graphicsDeviceService)
        {
            if (gameWindow == null)
                throw new ArgumentNullException("gameWindow");

            _gameWindow = gameWindow;
        }
コード例 #35
0
ファイル: Input.cs プロジェクト: remy22/BlueberryEngine
        public static void Init(GameWindow window)
        {
            _window = window;

            _gamepads = new GamepadDevice[4];
            for (int i = 0; i < 4; i++)
                _gamepads[i] = new GamepadDevice((UserIndex)i);
        }
コード例 #36
0
        public override void init()
        {
            base.init();

            _window         = new TK.GameWindow();
            _window.Visible = true;

            _window.Closing += _window_Closing;
        }
コード例 #37
0
        public static void Initialize(OpenTK.GameWindow game)
        {
            keysDown        = new List <Key>();
            keysDownlast    = new List <Key>();
            buttonsDown     = new List <MouseButton>();
            buttonsDownlast = new List <MouseButton>();

            game.KeyDown   += Game_KeyDown;
            game.KeyUp     += Game_KeyUp;
            game.MouseDown += Game_MouseDown;
            game.MouseUp   += Game_MouseUp;
        }
コード例 #38
0
ファイル: Game.cs プロジェクト: simvery/BlueHouseProject
        public void Initialize(OpenTK.GameWindow window)
        {
            Window            = window;
            window.ClientSize = new Size(room1Layout[0].Length * 30, room1Layout.Length * 30);
            TextureManager.Instance.UseNearestFiltering = true;

            hero  = new PlayerCharacter(heroSheet, new Point(spawnTile.X * 30, spawnTile.Y * 30));
            room1 = new Map(room1Layout, spriteSheets, spriteSources, 0, 2); // 0 and 2 ae walkable
            room1[4][7].IsDoor = true;
            room2 = new Map(room2Layout, spriteSheets, spriteSources, 0, 2); // 0 and 2 are walkable
            room2[1][0].IsDoor = true;
            currentRoom        = room1;
        }
コード例 #39
0
        private void Task3Btn_Click(object sender, RoutedEventArgs e)
        {
            using (var visualWindow = new VisualWindow())
            {
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.Width = visualWindow.Height = 400;
                    visualWindow.VSync = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left  = -100,
                          right = 100,
                          down  = -100,
                          up    = 100;

                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(left, right, down, up, 0, 100);

                    DrawSplines(new List <Point>()
                    {
                        new Point(0, -80),
                        new Point(-70, 20),
                        new Point(-40, 85),
                        new Point(0, 35)
                    });
                    DrawSplines(new List <Point>()
                    {
                        new Point(0, -80),
                        new Point(70, 20),
                        new Point(40, 85),
                        new Point(0, 35)
                    });

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
コード例 #40
0
 //entry point of application, not overwritten
 public virtual void Main(string[] args)
 {
     Window              = new OpenTK.GameWindow();
     Window.Load        += new EventHandler <EventArgs>(OpenTKInitialize);
     Window.UpdateFrame += new EventHandler <FrameEventArgs>(OpenTKUpdate);
     Window.RenderFrame += new EventHandler <FrameEventArgs>(OpenTKRender);
     Window.Unload      += new EventHandler <EventArgs>(OpenTKShutdown);
     Window.Title        = "Sample Application";
     Window.ClientSize   = new System.Drawing.Size(800, 600);
     Instance.Resize(800, 600);
     Window.VSync = VSyncMode.On;
     Window.Run(60.0f);
     Window.Dispose();
 }
コード例 #41
0
ファイル: Program.cs プロジェクト: xuri02/Xuri-OpenGl-CPP
        void InternalInit()
        {
            //Application.Run(new Form1());
            var g = new OpenTK.GameWindow(1000, 1000, GraphicsMode.Default, "Xuri´s OpenGl C#");

            OpenTK.Graphics.OpenGL.GL.MatrixMode(MatrixMode.Modelview);
            OpenTK.Graphics.OpenGL.GL.LoadIdentity();

            GL.Enable(EnableCap.Texture2D);
            GL.BindTexture(TextureTarget.Texture2D, 0);
            GL.Enable(EnableCap.Blend);
            GL.Enable(EnableCap.DepthTest);
            GL.ClearColor(Color.CadetBlue);

            g.Load += (sender, e) => {
                g.VSync = OpenTK.VSyncMode.On;
            };

            g.Resize += (sender, e) => {
                OpenTK.Graphics.OpenGL.GL.MatrixMode(MatrixMode.Projection);
                OpenTK.Graphics.OpenGL.GL.LoadIdentity();
                OpenTK.Graphics.OpenGL.GL.Ortho(0, g.ClientSize.Width, g.ClientSize.Height, 0, -1.0, 1.0);
                OpenTK.Graphics.OpenGL.GL.Viewport(0, 0, g.ClientSize.Width, g.ClientSize.Height);
                OpenTK.Graphics.OpenGL.GL.MatrixMode(MatrixMode.Modelview);
            };



            this.window    = g;
            g.UpdateFrame += GOnUpdateFrame;
            g.RenderFrame += GOnRenderFrame;
            g.KeyPress    += GOnKeyPress;
            g.KeyDown     += GOnKeyDown;
            g.KeyUp       += GOnKeyUp;
            g.MouseMove   += GOnMouseMove;
            g.MouseDown   += GOnMouseDown;

            int init_err = Setup.Init();

            if (init_err != 0)
            {
                Console.WriteLine("init error: " + init_err);
                Console.Read();
                Environment.Exit(init_err);
            }

            Console.WriteLine("OpenGl version: " + GL.GetString(StringName.Version));
        }
コード例 #42
0
        static void Main(string[] args)
        {
            Window              = new OpenTK.GameWindow();
            Window.Title        = "RayCaster";
            Window.ClientSize   = new System.Drawing.Size(800, 600);
            Window.Load        += new EventHandler <EventArgs>(Initialize);
            Window.UpdateFrame += new EventHandler <FrameEventArgs>(Update);
            Window.RenderFrame += new EventHandler <FrameEventArgs>(Render);
            Window.Unload      += new EventHandler <EventArgs>(Shutdown);
            Window.Run(60.0f);
            Window.Dispose();
#if DEBUG
            Console.WriteLine("\nFinished executing, press any key to exit...");
            Console.ReadKey();
#endif
        }
コード例 #43
0
        private void Initialize()
        {
            OpenTkGameWindow              = new OpenTK.GameWindow();
            OpenTkGameWindow.RenderFrame += OnRenderFrame;
            OpenTkGameWindow.UpdateFrame += OnUpdateFrame;
            OpenTkGameWindow.Resize      += OnResize;
            clientBounds = new Rectangle(0, 0, OpenTkGameWindow.Width, OpenTkGameWindow.Height);

            // Initialize GameTime
            _updateGameTime = new GameTime();
            _drawGameTime   = new GameTime();

            // Initialize _lastUpdate
            _lastUpdate = DateTime.Now;

            //Default no resizing
            AllowUserResizing = false;
        }
コード例 #44
0
        private void Task2Btn_Click(object sender, RoutedEventArgs e)
        {
            using (var visualWindow = new VisualWindow())
            {
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.VSync = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left  = 0,
                          right = 100,
                          down  = 0,
                          up    = 100;


                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(left, right, down, up, 0, 100);

                    GL.Begin(PrimitiveType.Lines);

                    GL.Color3(Color.Red);

                    DrawFromFile("points.txt");

                    GL.End();

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
コード例 #45
0
ファイル: GameContext.OpenTK.cs プロジェクト: tiomke/paradox
        /// <summary>
        /// Try to create the graphics context.
        /// </summary>
        /// <param name="requestedWidth">The requested width.</param>
        /// <param name="requestedHeight">The requested height.</param>
        /// <param name="graphicMode">The graphics mode.</param>
        /// <param name="versionMajor">The major version of OpenGL.</param>
        /// <param name="versionMinor">The minor version of OpenGL.</param>
        /// <param name="creationFlags">The creation flags.</param>
        /// <returns>The created GameWindow.</returns>
        private static OpenTK.GameWindow TryGameWindow(int requestedWidth, int requestedHeight, GraphicsMode graphicMode, int versionMajor, int versionMinor, GraphicsContextFlags creationFlags)
        {
            try
            {
#if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
                // Preload proper SDL native library (depending on CPU type)
                // This is for OpenGL ES on desktop
                Core.NativeLibrary.PreloadLibrary("SDL2.dll");
#endif

                var gameWindow = new OpenTK.GameWindow(requestedWidth, requestedHeight, graphicMode, "Paradox Game", GameWindowFlags.Default, DisplayDevice.Default, versionMajor, versionMinor,
                                                       creationFlags);
                return(gameWindow);
            }
            catch (Exception)
            {
                return(null);
            }
        }
コード例 #46
0
        private void Initialize()
        {
            OpenTkGameWindow                   = new OpenTK.GameWindow();
            OpenTkGameWindow.RenderFrame      += OnRenderFrame;
            OpenTkGameWindow.UpdateFrame      += OnUpdateFrame;
            OpenTkGameWindow.Closing          += new EventHandler <CancelEventArgs>(OpenTkGameWindow_Closing);
            OpenTkGameWindow.Resize           += OnResize;
            OpenTkGameWindow.Keyboard.KeyDown += new EventHandler <OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyDown);
            OpenTkGameWindow.Keyboard.KeyUp   += new EventHandler <OpenTK.Input.KeyboardKeyEventArgs>(Keyboard_KeyUp);
            clientBounds = new Rectangle(0, 0, OpenTkGameWindow.Width, OpenTkGameWindow.Height);

            // Initialize GameTime
            _updateGameTime = new GameTime();
            _drawGameTime   = new GameTime();

            // Initialize _lastUpdate
            _lastUpdate = DateTime.Now;

            //Default no resizing
            AllowUserResizing = false;
        }
コード例 #47
0
        public static void Main(string[] args)
        {
            //create new window
            Window  = new MainGameWindow();
            Axiis   = new Grid();
            TheGame = new CameraExample();
            TheGame.Resize(Window.Width, Window.Height);
            Window.Load        += new EventHandler <EventArgs>(Initialize);
            Window.UpdateFrame += new EventHandler <FrameEventArgs>(Update);
            Window.RenderFrame += new EventHandler <FrameEventArgs>(Render);
            Window.Unload      += new EventHandler <EventArgs>(Shutdown);

            Window.Title      = "Game Name";
            Window.ClientSize = new System.Drawing.Size(800, 600);
            Window.VSync      = VSyncMode.On;
            //run 60fps
            Window.Run(60.0f);

            //Dispose at end
            Window.Dispose();
        }
コード例 #48
0
        private void Task1Btn_Click(object sender, RoutedEventArgs e)
        {
            double xOffset = 0, yOffset = 0, zOffset = 0,
                   scale = 1, xRotate = 0, yRotate = 0, zRotate = 0;
            bool perspectiveMode = false;
            int  teaPotMode      = 1;

            using (var visualWindow = new VisualWindow())
            {
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.Width = visualWindow.Height = 400;
                    visualWindow.VSync = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                    var keyboardState = OpenTK.Input.Keyboard.GetState();

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Escape))
                    {
                        visualWindow.Exit();
                    }


                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Up))
                    {
                        yOffset += 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Down))
                    {
                        yOffset -= 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Right))
                    {
                        xOffset += 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Left))
                    {
                        xOffset -= 10;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Plus))
                    {
                        scale += 0.1;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Minus))
                    {
                        scale -= 0.1;
                    }


                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Home))
                    {
                        xRotate -= 5;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.End))
                    {
                        yRotate -= 5;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Delete))
                    {
                        zRotate -= 5;
                    }


                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.PageUp))
                    {
                        xRotate += 5;
                        yRotate += 5;
                        zRotate += 5;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.PageDown))
                    {
                        xRotate -= 5;
                        yRotate -= 5;
                        zRotate -= 5;
                    }


                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.P))
                    {
                        perspectiveMode = true;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.O))
                    {
                        perspectiveMode = false;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.F1))
                    {
                        teaPotMode = 1;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.F2))
                    {
                        teaPotMode = 2;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.F3))
                    {
                        teaPotMode = 3;
                    }
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left    = -1000,
                          right   = 1000,
                          down    = -1000,
                          up      = 1000,
                          forward = -1000,
                          back    = 1000;

                    float width  = right - left,
                          height = up - down,
                          depth  = back - forward;

                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();

                    if (perspectiveMode)
                    {
                        // GLU Perspective
                        Matrix4 perspectiveMatrix = Matrix4.CreatePerspectiveFieldOfView(
                            MathHelper.PiOver2,
                            width / height,
                            0.1f,
                            depth);
                        GL.LoadMatrix(ref perspectiveMatrix);
                        // GLU Look at
                        GL.Translate(0, 0, forward);
                    }
                    else
                    {
                        GL.Ortho(left, right, down, up, forward, back);
                    }

                    // Draw Axis
                    GL.Color3(255d, 0d, 0d);
                    GL.Begin(BeginMode.Lines);
                    GL.Vertex3(left, 0, 0);
                    GL.Vertex3(right, 0, 0);
                    GL.Vertex3(0, up, 0);
                    GL.Vertex3(0, down, 0);
                    GL.Vertex3(0, 0, forward);
                    GL.Vertex3(0, 0, back);
                    GL.End();

                    // Translations
                    GL.Translate(xOffset, yOffset, zOffset);
                    GL.Scale(scale, scale, scale);
                    GL.Rotate(xRotate, 1, 0, 0);
                    GL.Rotate(yRotate, 0, 1, 0);
                    GL.Rotate(zRotate, 0, 0, 1);


                    // Drawing
                    GL.Color3(0d, 0d, 0d);
                    switch (teaPotMode)
                    {
                    case 1:
                        Teapot.DrawWireTeapot(500);
                        break;

                    case 2:
                        Teapot.DrawSolidTeapot(500);
                        break;

                    case 3:
                        Teapot.DrawPointTeapot(500);
                        break;
                    }

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
コード例 #49
0
        private void Task1Btn_Click(object sender, RoutedEventArgs e)
        {
            double baseSpeed = 1, speedUp = 1.2, slowness = 0.95, maxSpeed = 40;
            double xOffset = 0, yOffset = 0, xSpeed = 0, ySpeed = 0;

            using (var visualWindow = new VisualWindow())
            {
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.Width = visualWindow.Height = 400;
                    visualWindow.VSync = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                    var keyboardState = OpenTK.Input.Keyboard.GetState();

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Escape))
                    {
                        visualWindow.Exit();
                    }

                    GL.MatrixMode(MatrixMode.Modelview);

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Up) || keyboardState.IsKeyDown(OpenTK.Input.Key.W))
                    {
                        ySpeed = baseSpeed + ySpeed * (ySpeed > 0 ? speedUp : 0);
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Down) || keyboardState.IsKeyDown(OpenTK.Input.Key.S))
                    {
                        ySpeed = -baseSpeed + ySpeed * (ySpeed < 0 ? speedUp : 0);
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Left) || keyboardState.IsKeyDown(OpenTK.Input.Key.A))
                    {
                        xSpeed = -baseSpeed + xSpeed * (xSpeed < 0 ? speedUp : 0);
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Right) || keyboardState.IsKeyDown(OpenTK.Input.Key.D))
                    {
                        xSpeed = baseSpeed + xSpeed * (xSpeed > 0 ? speedUp : 0);
                    }

                    // Max speed controll
                    xSpeed = Math.Abs(xSpeed) < maxSpeed ? xSpeed : maxSpeed * (xSpeed < 0 ? -1 : 1);
                    ySpeed = Math.Abs(ySpeed) < maxSpeed ? ySpeed : maxSpeed * (ySpeed < 0 ? -1 : 1);

                    // Small speed aprox to 0
                    if (Math.Abs(xSpeed) < 1)
                    {
                        xSpeed = 0;
                    }
                    if (Math.Abs(ySpeed) < 1)
                    {
                        ySpeed = 0;
                    }

                    // Auto slow speed
                    xSpeed *= slowness;
                    ySpeed *= slowness;

                    xOffset += xSpeed;
                    yOffset += ySpeed;
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left  = -1000,
                          right = 1000,
                          down  = -1000,
                          up    = 1000;

                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(left, right, down, up, 0, 100);


                    GL.Begin(BeginMode.Lines);
                    GL.Vertex2(left, 0);
                    GL.Vertex2(right, 0);
                    GL.Vertex2(0, up);
                    GL.Vertex2(0, down);
                    GL.End();

                    GL.PushMatrix();
                    GL.Translate(xOffset, yOffset, 0);

                    GL.Begin(BeginMode.Quads);

                    GL.Color3(1.0, 1.0, 1.0);
                    GL.Vertex2(250, 450);
                    GL.Color3(0.0, 0.0, 1.0);
                    GL.Vertex2(250, 150);
                    GL.Color3(0.0, 1.0, 0.0);
                    GL.Vertex2(550, 150);
                    GL.Color3(1.0, 0.0, 0.0);
                    GL.Vertex2(550, 450);

                    GL.End();

                    GL.PopMatrix();

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
コード例 #50
0
ファイル: Game.cs プロジェクト: jnz1k/Examples
 public Game()
 {
     this.window       = new GameWindow(640, 480);
     this.window.Title = "Game engine";
     Start();
 }
コード例 #51
0
ファイル: GameContext.OpenTK.cs プロジェクト: tiomke/paradox
        /// <summary>
        /// Initializes a new instance of the <see cref="GameContext" /> class.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="requestedWidth">Width of the requested.</param>
        /// <param name="requestedHeight">Height of the requested.</param>
        public GameContext(OpenTK.GameWindow control, int requestedWidth = 0, int requestedHeight = 0)
        {
            var creationFlags = GraphicsContextFlags.Default;

#if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
            creationFlags |= GraphicsContextFlags.Embedded;
#endif

            if (requestedWidth == 0 || requestedHeight == 0)
            {
                requestedWidth  = 1280;
                requestedHeight = 720;
            }

            // force the stencil buffer to be not null.
            var defaultMode = GraphicsMode.Default;
            var graphicMode = new GraphicsMode(defaultMode.ColorFormat, defaultMode.Depth, 8, defaultMode.Samples, defaultMode.AccumulatorFormat, defaultMode.Buffers, defaultMode.Stereo);

            GraphicsContext.ShareContexts = true;

            if (control == null)
            {
                int versionMajor, versionMinor;
                if (RequestedGraphicsProfile == null || RequestedGraphicsProfile.Length == 0)
                {
#if SILICONSTUDIO_PARADOX_GRAPHICS_API_OPENGLES
                    versionMajor = 3;
                    versionMinor = 0;
#else
                    // PC: 4.3 is commonly available (= compute shaders)
                    // MacOS X: 4.1 maximum
                    versionMajor = 4;
                    versionMinor = 1;
#endif
                    Control = TryGameWindow(requestedWidth, requestedHeight, graphicMode, versionMajor, versionMinor, creationFlags);
                }
                else
                {
                    foreach (var profile in RequestedGraphicsProfile)
                    {
                        OpenGLUtils.GetGLVersion(profile, out versionMajor, out versionMinor);
                        var gameWindow = TryGameWindow(requestedWidth, requestedHeight, graphicMode, versionMajor, versionMinor, creationFlags);
                        if (gameWindow != null)
                        {
                            Control = gameWindow;
                            break;
                        }
                    }
                }
            }
            else
            {
                Control = control;
            }

            if (Control == null)
            {
                throw new Exception("Unable to initialize graphics context.");
            }

            RequestedWidth  = requestedWidth;
            RequestedHeight = requestedHeight;
            ContextType     = AppContextType.DesktopOpenTK;
        }
コード例 #52
0
        private void Task2Btn_Click(object sender, RoutedEventArgs e)
        {
            using (var visualWindow = new VisualWindow())
            {
                double angle = 0, selfAngle = 0, xOffset = 0, yOffset = 0, scale = 1;
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.Width  = 600;
                    visualWindow.Height = 200;
                    visualWindow.VSync  = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                    var keyboardState = OpenTK.Input.Keyboard.GetState();

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Escape))
                    {
                        visualWindow.Exit();
                    }

                    GL.MatrixMode(MatrixMode.Modelview);

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Up))
                    {
                        yOffset += 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Down))
                    {
                        yOffset -= 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Left))
                    {
                        xOffset -= 10;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Right))
                    {
                        xOffset += 10;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Plus))
                    {
                        scale += 0.1;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Minus))
                    {
                        scale -= 0.1;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Home))
                    {
                        angle += 5;
                    }
                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.End))
                    {
                        angle -= 5;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.Q))
                    {
                        selfAngle += 3;
                    }

                    if (keyboardState.IsKeyDown(OpenTK.Input.Key.E))
                    {
                        selfAngle -= 3;
                    }
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left  = 0,
                          right = 300,
                          down  = 0,
                          up    = 100;

                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(left, right, down, up, 0, 100);

                    // Translations
                    GL.Translate(xOffset, yOffset, 0);
                    GL.Translate(150, 50, 0);
                    GL.Scale(scale, scale, 0);
                    GL.Rotate(angle, 0, 0, 1);
                    GL.Translate(-150, -50, 0);


                    GL.Color3(255.0, 0, 0);

                    // T
                    GL.PushMatrix();
                    GL.Translate(50, 50, 0);
                    GL.Rotate(selfAngle, 0, 0, 1);
                    GL.Translate(-50, -50, 0);

                    GL.Begin(BeginMode.LineLoop);
                    GL.Vertex2(10, 80);
                    GL.Vertex2(90, 80);
                    GL.Vertex2(90, 70);
                    GL.Vertex2(55, 70);
                    GL.Vertex2(55, 20);
                    GL.Vertex2(45, 20);
                    GL.Vertex2(45, 70);
                    GL.Vertex2(10, 70);
                    GL.End();

                    GL.PopMatrix();


                    // S
                    GL.PushMatrix();
                    GL.Translate(150, 50, 0);
                    GL.Rotate(-selfAngle, 0, 0, 1);
                    GL.Translate(-150, -50, 0);

                    GL.Begin(BeginMode.LineLoop);
                    GL.Vertex2(190, 80);
                    GL.Vertex2(110, 80);
                    GL.Vertex2(110, 45);
                    GL.Vertex2(180, 45);
                    GL.Vertex2(180, 30);
                    GL.Vertex2(110, 30);
                    GL.Vertex2(110, 20);
                    GL.Vertex2(190, 20);
                    GL.Vertex2(190, 55);
                    GL.Vertex2(120, 55);
                    GL.Vertex2(120, 70);
                    GL.Vertex2(190, 70);
                    GL.End();

                    GL.PopMatrix();

                    // I
                    GL.PushMatrix();
                    GL.Translate(250, 50, 0);
                    GL.Rotate(selfAngle, 0, 0, 1);
                    GL.Translate(-250, -50, 0);

                    GL.Begin(BeginMode.LineLoop);
                    GL.Vertex2(265, 80);
                    GL.Vertex2(265, 70);
                    GL.Vertex2(255, 70);
                    GL.Vertex2(255, 30);
                    GL.Vertex2(265, 30);
                    GL.Vertex2(265, 20);
                    GL.Vertex2(235, 20);
                    GL.Vertex2(235, 30);
                    GL.Vertex2(245, 30);
                    GL.Vertex2(245, 70);
                    GL.Vertex2(235, 70);
                    GL.Vertex2(235, 80);
                    GL.End();

                    GL.PopMatrix();

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
コード例 #53
0
        private void Task3Btn_Click(object sender, RoutedEventArgs e)
        {
            using (var visualWindow = new VisualWindow())
            {
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.VSync = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left  = 0,
                          right = 300,
                          down  = 0,
                          up    = 100;


                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(left, right, down, up, 0, 100);

                    // T
                    GL.Begin(PrimitiveType.LineLoop);

                    GL.Color3(Color.DarkBlue);
                    GL.Vertex2(10, 80);
                    GL.Vertex2(90, 80);
                    GL.Vertex2(90, 70);
                    GL.Vertex2(55, 70);
                    GL.Vertex2(55, 20);
                    GL.Vertex2(45, 20);
                    GL.Vertex2(45, 70);
                    GL.Vertex2(10, 70);

                    GL.End();

                    // S
                    GL.Begin(PrimitiveType.LineLoop);

                    GL.Color3(Color.DarkBlue);
                    GL.Vertex2(190, 80);
                    GL.Vertex2(110, 80);
                    GL.Vertex2(110, 45);
                    GL.Vertex2(180, 45);
                    GL.Vertex2(180, 30);
                    GL.Vertex2(110, 30);
                    GL.Vertex2(110, 20);
                    GL.Vertex2(190, 20);
                    GL.Vertex2(190, 55);
                    GL.Vertex2(120, 55);
                    GL.Vertex2(120, 70);
                    GL.Vertex2(190, 70);

                    GL.End();

                    // I
                    GL.Begin(PrimitiveType.LineLoop);

                    GL.Color3(Color.DarkBlue);
                    GL.Vertex2(235, 80);
                    GL.Vertex2(265, 80);
                    GL.Vertex2(265, 70);
                    GL.Vertex2(255, 70);
                    GL.Vertex2(255, 30);
                    GL.Vertex2(265, 30);
                    GL.Vertex2(265, 20);
                    GL.Vertex2(235, 20);
                    GL.Vertex2(235, 30);
                    GL.Vertex2(245, 30);
                    GL.Vertex2(245, 70);
                    GL.Vertex2(235, 70);

                    GL.End();

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
コード例 #54
0
        public Game(GameWindow window)
        {
            this.window = window;

            Start();
        }
コード例 #55
0
ファイル: OpenGL.cs プロジェクト: Meeji/SFML.Net
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            // NOTE : This is workaround to create a functioning opengl context for OpenTK (for current OpenTK version)
            var gameWindow = new OpenTK.GameWindow();

            // Request a 24-bits depth buffer when creating the window
            var contextSettings = new ContextSettings();

            contextSettings.DepthBits = 24;

            // Create the main window
            RenderWindow window = new RenderWindow(new VideoMode(800, 600), "SFML graphics with OpenGL", Styles.Default, contextSettings);

            window.SetVerticalSyncEnabled(true);

            // Initialize OpenTK
            // NOTE : next 2 lines are kept from old examples until we resolve proper OpenTK versioning
            //Toolkit.Init();
            //GraphicsContext context = new GraphicsContext(new ContextHandle(IntPtr.Zero), null);

            // Setup event handlers
            window.Closed     += new EventHandler(OnClosed);
            window.KeyPressed += new EventHandler <KeyEventArgs>(OnKeyPressed);
            window.Resized    += new EventHandler <SizeEventArgs>(OnResized);

            // Create a sprite for the background
            var background = new Sprite(new Texture("resources/background.jpg"));

            // Create a text to display on top of the OpenGL object
            var text = new Text("SFML / OpenGL demo", new Font("resources/sansation.ttf"));

            text.Position  = new Vector2f(250, 450);
            text.FillColor = new SFML.Graphics.Color(255, 255, 255, 170);

            // Make the window the active target for OpenGL calls
            window.SetActive();

            // Load an OpenGL texture.
            // We could directly use a SFML.Graphics.Texture as an OpenGL texture (with its Bind() member function),
            // but here we want more control on it (generate mipmaps, ...) so we create a new one
            int texture = 0;

            using (var image = new SFML.Graphics.Image("resources/texture.jpg"))
            {
                GL.GenTextures(1, out texture);
                GL.BindTexture(TextureTarget.Texture2D, texture);
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, (int)image.Size.X, (int)image.Size.Y, 0, PixelFormat.Rgba, PixelType.UnsignedByte, image.Pixels);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            }

            // Enable Z-buffer read and write
            GL.Enable(EnableCap.DepthTest);
            GL.DepthMask(true);
            GL.ClearDepth(1);

            // Disable lighting
            GL.Disable(EnableCap.Lighting);

            // Configure the viewport (the same size as the window)
            GL.Viewport(0, 0, (int)window.Size.X, (int)window.Size.Y);

            // Setup a perspective projection
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadIdentity();
            float ratio = (float)(window.Size.X) / window.Size.Y;

            GL.Frustum(-ratio, ratio, -1, 1, 1, 500);

            // Bind the texture
            GL.Enable(EnableCap.Texture2D);
            GL.BindTexture(TextureTarget.Texture2D, texture);

            // Define a 3D cube (6 faces made of 2 triangles composed by 3 vertices)
            float[] cube = new float[]
            {
                // positions    // texture coordinates
                -20, -20, -20, 0, 0,
                -20, 20, -20, 1, 0,
                -20, -20, 20, 0, 1,
                -20, -20, 20, 0, 1,
                -20, 20, -20, 1, 0,
                -20, 20, 20, 1, 1,

                20, -20, -20, 0, 0,
                20, 20, -20, 1, 0,
                20, -20, 20, 0, 1,
                20, -20, 20, 0, 1,
                20, 20, -20, 1, 0,
                20, 20, 20, 1, 1,

                -20, -20, -20, 0, 0,
                20, -20, -20, 1, 0,
                -20, -20, 20, 0, 1,
                -20, -20, 20, 0, 1,
                20, -20, -20, 1, 0,
                20, -20, 20, 1, 1,

                -20, 20, -20, 0, 0,
                20, 20, -20, 1, 0,
                -20, 20, 20, 0, 1,
                -20, 20, 20, 0, 1,
                20, 20, -20, 1, 0,
                20, 20, 20, 1, 1,

                -20, -20, -20, 0, 0,
                20, -20, -20, 1, 0,
                -20, 20, -20, 0, 1,
                -20, 20, -20, 0, 1,
                20, -20, -20, 1, 0,
                20, 20, -20, 1, 1,

                -20, -20, 20, 0, 0,
                20, -20, 20, 1, 0,
                -20, 20, 20, 0, 1,
                -20, 20, 20, 0, 1,
                20, -20, 20, 1, 0,
                20, 20, 20, 1, 1
            };

            // Enable position and texture coordinates vertex components
            GL.EnableClientState(ArrayCap.VertexArray);
            GL.EnableClientState(ArrayCap.TextureCoordArray);
            GL.VertexPointer(3, VertexPointerType.Float, 5 * sizeof(float), Marshal.UnsafeAddrOfPinnedArrayElement(cube, 0));
            GL.TexCoordPointer(2, TexCoordPointerType.Float, 5 * sizeof(float), Marshal.UnsafeAddrOfPinnedArrayElement(cube, 3));

            // Disable normal and color vertex components
            GL.DisableClientState(ArrayCap.NormalArray);
            GL.DisableClientState(ArrayCap.ColorArray);

            var clock = new Clock();

            // Start game loop
            while (window.IsOpen)
            {
                // Process events
                window.DispatchEvents();

                // Clear the window
                GL.Clear(ClearBufferMask.DepthBufferBit);

                // Draw background
                window.PushGLStates();
                window.Draw(background);
                window.PopGLStates();

                // Clear the depth buffer
                GL.Clear(ClearBufferMask.DepthBufferBit);

                // We get the position of the mouse cursor, so that we can move the box accordingly
                float x = Mouse.GetPosition(window).X * 200.0F / window.Size.X - 100.0F;
                float y = -Mouse.GetPosition(window).Y * 200.0F / window.Size.Y + 100.0F;

                // Apply some transformations
                GL.MatrixMode(MatrixMode.Modelview);
                GL.LoadIdentity();
                GL.Translate(x, y, -100.0F);
                GL.Rotate(clock.ElapsedTime.AsSeconds() * 50, 1.0F, 0.0F, 0.0F);
                GL.Rotate(clock.ElapsedTime.AsSeconds() * 30, 0.0F, 1.0F, 0.0F);
                GL.Rotate(clock.ElapsedTime.AsSeconds() * 90, 0.0F, 0.0F, 1.0F);

                // Draw the cube
                GL.DrawArrays(OpenTK.Graphics.OpenGL.PrimitiveType.Triangles, 0, 36);

                // Draw some text on top of our OpenGL object
                window.PushGLStates();
                window.Draw(text);
                window.PopGLStates();

                // Finally, display the rendered frame on screen
                window.Display();
            }

            // Don't forget to destroy our texture
            GL.DeleteTextures(1, ref texture);
        }
コード例 #56
0
        public void Start(string path = "")
        {
            // Configuration
            double xOffset = 0, yOffset = 0, zOffset = 0,
                   xRotate = 0, yRotate = 0, zRotate = 0,
                   scale = 1,
                   moveSpeed = 3, rotateSpeed = 3, scaleSpeed = 0.05;
            bool perspectiveMode = false, drawAxis = false;

            _drawPolygon = false;

            // Visual window init
            _visualWindow       = new VisualWindow();
            _visualWindow.Load += (s, args) =>
            {
                _visualWindow.Width = _visualWindow.Height = 400;
                _visualWindow.VSync = VSyncMode.On;

                if (string.IsNullOrEmpty(path))
                {
                    LoadDefaultScene();
                }
                else
                {
                    LoadFile(path);
                }
            };
            _visualWindow.Resize += (s, args) =>
            {
                GL.Viewport(0, 0, _visualWindow.Width, _visualWindow.Height);
            };
            _visualWindow.FileDrop += (s, args) =>
            {
                LoadFile(args.FileName);
            };
            _visualWindow.UpdateFrame += (s, args) =>
            {
                var keyboardState = Keyboard.GetState();

                if (keyboardState.IsKeyDown(Key.Escape))
                {
                    _visualWindow.Exit();
                }


                if (keyboardState.IsKeyDown(Key.Up))
                {
                    yOffset += moveSpeed;
                }
                if (keyboardState.IsKeyDown(Key.Down))
                {
                    yOffset -= moveSpeed;
                }
                if (keyboardState.IsKeyDown(Key.Right))
                {
                    xOffset += moveSpeed;
                }
                if (keyboardState.IsKeyDown(Key.Left))
                {
                    xOffset -= moveSpeed;
                }

                if (keyboardState.IsKeyDown(Key.Plus))
                {
                    scale += scaleSpeed;
                }
                if (keyboardState.IsKeyDown(Key.Minus))
                {
                    scale -= scaleSpeed;
                }

                if (keyboardState.IsKeyDown(Key.Home))
                {
                    xRotate -= rotateSpeed;
                }
                if (keyboardState.IsKeyDown(Key.End))
                {
                    yRotate -= rotateSpeed;
                }
                if (keyboardState.IsKeyDown(Key.Delete))
                {
                    zRotate -= rotateSpeed;
                }


                if (keyboardState.IsKeyDown(Key.PageUp))
                {
                    xRotate += rotateSpeed;
                    yRotate += rotateSpeed;
                    zRotate += rotateSpeed;
                }
                if (keyboardState.IsKeyDown(Key.PageDown))
                {
                    xRotate -= rotateSpeed;
                    yRotate -= rotateSpeed;
                    zRotate -= rotateSpeed;
                }

                if (keyboardState.IsKeyDown(Key.BackSpace))
                {
                    xOffset = 0; yOffset = 0; zOffset = 0;
                    xRotate = 0; yRotate = 0; zRotate = 0;
                    scale   = 1;
                }

                if (keyboardState.IsKeyDown(Key.P))
                {
                    perspectiveMode = true;
                }
                if (keyboardState.IsKeyDown(Key.O))
                {
                    perspectiveMode = false;
                }
                if (keyboardState.IsKeyDown(Key.Z))
                {
                    drawAxis = true;
                }
                if (keyboardState.IsKeyDown(Key.Z) && keyboardState.IsKeyDown(Key.ShiftLeft))
                {
                    drawAxis = false;
                }
                if (keyboardState.IsKeyDown(Key.L))
                {
                    _drawPolygon = true;
                }
                if (keyboardState.IsKeyDown(Key.L) && keyboardState.IsKeyDown(Key.ShiftLeft))
                {
                    _drawPolygon = false;
                }
            };
            _visualWindow.RenderFrame += (s, args) =>
            {
                float width  = _loadedScene.WorldRight - _loadedScene.WorldLeft,
                      height = _loadedScene.WorldTop - _loadedScene.WorldBottom,
                      depth  = _loadedScene.WorldForward - _loadedScene.WorldBack;

                float halfX = (_loadedScene.WorldRight + _loadedScene.WorldLeft) / 2,
                      halfY = (_loadedScene.WorldTop + _loadedScene.WorldBottom) / 2,
                      halfZ = (_loadedScene.WorldBack + _loadedScene.WorldForward) / 2;


                GL.ClearColor(255, 255, 255, 255);
                GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                GL.MatrixMode(MatrixMode.Projection);
                GL.LoadIdentity();

                if (perspectiveMode)
                {
                    // GLU Perspective
                    Matrix4 perspectiveMatrix = Matrix4.CreatePerspectiveFieldOfView(
                        MathHelper.DegreesToRadians(90),
                        width / height,
                        0.1f,
                        depth * 2);
                    GL.LoadMatrix(ref perspectiveMatrix);
                    // Look at
                    GL.Translate(-halfX, -halfY, -halfZ);
                }
                else
                {
                    GL.Ortho(_loadedScene.WorldLeft, _loadedScene.WorldRight,
                             _loadedScene.WorldBottom, _loadedScene.WorldTop,
                             _loadedScene.WorldForward, _loadedScene.WorldBack);
                }
                GL.Translate(0, 0, -depth);


                // Draw Axis
                if (drawAxis)
                {
                    GL.Color3(0f, 255f, 0f);
                    GL.Begin(BeginMode.Lines);
                    GL.Vertex3(-width, halfY, halfZ);
                    GL.Vertex3(width * 2, halfY, halfZ);
                    GL.Vertex3(halfX, -height, halfZ);
                    GL.Vertex3(halfX, height * 2, halfZ);
                    GL.Vertex3(halfX, halfY, -depth);
                    GL.Vertex3(halfX, halfY, depth);
                    GL.End();
                }

                // Translations
                GL.Translate(xOffset, yOffset, zOffset);
                GL.Translate(halfX, halfY, halfZ);
                GL.Rotate(xRotate, 1, 0, 0);
                GL.Rotate(yRotate, 0, 1, 0);
                GL.Rotate(zRotate, 0, 0, 1);
                GL.Scale(scale, scale, scale);
                GL.Translate(-halfX, -halfY, -halfZ);

                // Draw
                GL.Color3(255f, 0, 0);
                foreach (Parallelepiped parallelepiped in _loadedScene.Parallelepipeds)
                {
                    DrawParallelepiped(parallelepiped.FirstCoordinates, parallelepiped.SecondCoordinates);
                }


                _visualWindow.SwapBuffers();
            };

            _visualWindow.Run(60.0);
        }
コード例 #57
0
        private void Task4Btn_Click(object sender, RoutedEventArgs e)
        {
            using (var visualWindow = new VisualWindow())
            {
                visualWindow.Load += (s, args) =>
                {
                    visualWindow.Width  = 600;
                    visualWindow.Height = 200;
                    visualWindow.VSync  = VSyncMode.On;
                };
                visualWindow.Resize += (s, args) =>
                {
                    GL.Viewport(0, 0, visualWindow.Width, visualWindow.Height);
                };
                visualWindow.UpdateFrame += (s, args) =>
                {
                };
                visualWindow.RenderFrame += (s, args) =>
                {
                    float left  = 0,
                          right = 300,
                          down  = 0,
                          up    = 100;

                    GL.ClearColor(255, 255, 255, 255);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

                    GL.MatrixMode(MatrixMode.Projection);
                    GL.LoadIdentity();
                    GL.Ortho(left, right, down, up, 0, 100);

                    // T
                    DrawSplines(new List <Point>()
                    {
                        new Point(20, 70),
                        new Point(18, 70),
                        new Point(10, 75),
                        new Point(10, 85),
                        new Point(18, 90),
                        new Point(20, 90)
                    });
                    DrawLine(20, 90, 80, 90);
                    DrawSplines(new List <Point>()
                    {
                        new Point(80, 70),
                        new Point(82, 70),
                        new Point(90, 75),
                        new Point(90, 85),
                        new Point(82, 90),
                        new Point(80, 90)
                    });
                    DrawLine(20, 70, 40, 70);
                    DrawLine(60, 70, 80, 70);
                    DrawLine(40, 70, 40, 20);
                    DrawLine(60, 70, 60, 20);
                    DrawSplines(new List <Point>()
                    {
                        new Point(40, 20),
                        new Point(40, 18),
                        new Point(45, 10),
                        new Point(55, 10),
                        new Point(60, 18),
                        new Point(60, 20)
                    });

                    // S
                    DrawSplines(new List <Point>()
                    {
                        new Point(180, 90),
                        new Point(182, 90),
                        new Point(190, 85),
                        new Point(190, 75),
                        new Point(182, 70),
                        new Point(180, 70)
                    });
                    DrawLine(180, 70, 140, 70);
                    DrawLine(180, 90, 140, 90);
                    DrawSplines(new List <Point>()
                    {
                        new Point(140, 70),
                        new Point(138, 70),
                        new Point(130, 67),
                        new Point(130, 63),
                        new Point(138, 60),
                        new Point(140, 60),
                    });
                    DrawSplines(new List <Point>()
                    {
                        new Point(140, 90),
                        new Point(138, 90),
                        new Point(120, 85),
                        new Point(110, 70),
                        new Point(110, 60),
                        new Point(120, 45),
                        new Point(138, 40),
                        new Point(140, 40),
                    });
                    DrawLine(140, 40, 160, 40);
                    DrawLine(140, 60, 160, 60);
                    DrawSplines(new List <Point>()
                    {
                        new Point(120, 10),
                        new Point(118, 10),
                        new Point(110, 15),
                        new Point(110, 25),
                        new Point(118, 30),
                        new Point(120, 30)
                    });
                    DrawLine(120, 10, 160, 10);
                    DrawLine(120, 30, 160, 30);
                    DrawSplines(new List <Point>()
                    {
                        new Point(160, 30),
                        new Point(162, 30),
                        new Point(170, 33),
                        new Point(170, 37),
                        new Point(162, 40),
                        new Point(160, 40)
                    });
                    DrawSplines(new List <Point>()
                    {
                        new Point(160, 10),
                        new Point(162, 10),
                        new Point(180, 15),
                        new Point(190, 30),
                        new Point(190, 40),
                        new Point(180, 55),
                        new Point(162, 60),
                        new Point(160, 60),
                    });

                    // I
                    DrawSplines(new List <Point>()
                    {
                        new Point(220, 70),
                        new Point(218, 70),
                        new Point(210, 75),
                        new Point(210, 85),
                        new Point(218, 90),
                        new Point(220, 90)
                    });
                    DrawLine(220, 90, 280, 90);
                    DrawSplines(new List <Point>()
                    {
                        new Point(280, 70),
                        new Point(282, 70),
                        new Point(290, 75),
                        new Point(290, 85),
                        new Point(282, 90),
                        new Point(280, 90)
                    });
                    DrawLine(260, 70, 280, 70);
                    DrawLine(220, 70, 240, 70);

                    DrawLine(240, 70, 240, 30);
                    DrawLine(260, 70, 260, 30);

                    DrawLine(260, 30, 280, 30);
                    DrawLine(220, 30, 240, 30);

                    DrawSplines(new List <Point>()
                    {
                        new Point(220, 30),
                        new Point(218, 30),
                        new Point(210, 25),
                        new Point(210, 15),
                        new Point(218, 10),
                        new Point(220, 10)
                    });
                    DrawLine(220, 10, 280, 10);
                    DrawSplines(new List <Point>()
                    {
                        new Point(280, 30),
                        new Point(282, 30),
                        new Point(290, 25),
                        new Point(290, 15),
                        new Point(282, 10),
                        new Point(280, 10)
                    });

                    visualWindow.SwapBuffers();
                };

                visualWindow.Run(60.0);
            }
        }
コード例 #58
-1
        /// <summary>
        /// Initializes an instance of this class, along with the values for
        /// using it.
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="model"></param>
        /// <param name="blurStackSize"></param>
        public FlyingObject(GameWindow parent, OBJModel model, int blurStackSize)
        {
            Parent = parent;
            Lifespan = 50;

            //blur
            BlurStackSize = blurStackSize;
            BlurStack = new LinkedList<Vector>();
            EnableMotionBlur = true;
            alphaStep = .5f / BlurStackSize;

            PhysicalBody = new PhysicsObject();
            PhysicalBody.ParentObject = this;
            PhysicalBody.Velocity = new Vector(GeneralMath.RandomFloat(-0.7f, 0.7f),
                GeneralMath.RandomFloat(1.5f, 2.5f), GeneralMath.RandomFloat(-0.5f, 0.5f));

            angleIncrement = GeneralMath.RandomFloat(5.5f, 6.5f);

            Body = model;

            Location = new Vector(0.0f, 0.0f, 0.0f);
            MainTimer = new Timer();
            MainTimer.Interval = 10;
            MainTimer.Tick += AnimationStep;
        }
コード例 #59
-1
ファイル: Program.cs プロジェクト: danielscherzer/Framework
 private MyApplication()
 {
     //set waypoints of enemy
     wayPoints.Add(new Vector2(-.5f, -.5f));
     wayPoints.Add(new Vector2(.5f, -.5f));
     wayPoints.Add(new Vector2(.5f, .5f));
     wayPoints.Add(new Vector2(-.5f, .5f));
     //wayPoints.Add(new Vector2(.6f, -.7f));
     //wayPoints.Add(new Vector2(.5f, .8f));
     //wayPoints.Add(new Vector2(-.5f, .4f));
     //wayPoints.Add(new Vector2(0, 0));
     wayTangents = CatmullRomSpline.FiniteDifferenceLoop(wayPoints);
     //setup
     gameWindow = new GameWindow(700, 700);
     gameWindow.VSync = VSyncMode.On;
     gameWindow.KeyDown += (s, arg) => gameWindow.Close();
     gameWindow.Resize += (s, arg) => GL.Viewport(0, 0, gameWindow.Width, gameWindow.Height);
     gameWindow.UpdateFrame += GameWindow_UpdateFrame;
     gameWindow.RenderFrame += GameWindow_RenderFrame;
     gameWindow.RenderFrame += (s, arg) => gameWindow.SwapBuffers();
     texBird = TextureLoader.FromBitmap(Resourcen.bird1);
     //background clear color
     GL.ClearColor(Color.White);
     //for transparency in textures
     GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
     timeSource.Start();
 }