flopoloco's picture

Spiral Galaxy

using System;
using System.Drawing;
using OpenTK;
using graph = OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
 
namespace HelloOpenTK
{
	public static class Fps
	{
		static double _time = 0.0, _frames = 0.0;
		static int _fps = 0;
 
		public static int GetFps(double time) {
			_time += time;
			if (_time < 1.0) {
				_frames++;
				return _fps;
			}
			else {
				_fps = (int)_frames;
				_time = 0.0;
				_frames = 0.0;
				return _fps;
			}
		}
	}
 
	public class Program : GameWindow
	{	
		private IntPtr qdr;
		private float perimeter = 0f;
 
		public Program() : base(800, 600, graph.GraphicsMode.Default, "Hello OpenTK")
		{
			Keyboard.KeyDown += new EventHandler<KeyboardKeyEventArgs>(Keyboard_KeyDown);
		}
 
		void Keyboard_KeyDown(object sender, KeyboardKeyEventArgs e)
		{
			if (e.Key == Key.Escape)
				Exit();
		}
 
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);
 
			// Set opengl view options
			GL.ClearColor(Color.Black);
			GL.Enable(EnableCap.DepthTest);
 
			// Create a quadric
			qdr = graph.Glu.NewQuadric();
		}
 
		protected override void OnUpdateFrame(FrameEventArgs e)
		{
			base.OnUpdateFrame(e);
 
			perimeter += (float)(1 * e.Time);
			if (perimeter > 360) perimeter = 0;
 
			Title = Fps.GetFps(e.Time).ToString();
		}
 
		protected override void OnResize(EventArgs e)
		{
			// Standard OpenTK code for window resize
			base.OnResize(e);
			GL.Viewport(0, 0, Width, Height);
			Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI / 4, Width / (float)Height, 1.0f, 64.0f);
			GL.MatrixMode(MatrixMode.Projection);
			GL.LoadMatrix(ref projection);
		}
 
 
		protected override void OnRenderFrame(FrameEventArgs e)
		{
			base.OnRenderFrame(e);
 
			// Camera
			GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
			GL.MatrixMode(MatrixMode.Modelview);
			Matrix4 modelview = Matrix4.RotateY(perimeter);							// Rotate
			modelview *= Matrix4.LookAt(20f, 20f, -20f , 0f, 0f, 0f , 0f, 1f, 0f);	// Set eye and target
			GL.LoadMatrix(ref modelview);
 
			// Display spiral galaxy
			for (int i = 0; i <= 500; i += 5) {
				GL.PushMatrix();
				GL.Translate(Math.Sin(i) * (double)(i / 25), 0f, Math.Cos(i) * (double)(i / 25));
				graph.Glu.Sphere(qdr, 0.2f, 4, 4);
				GL.PopMatrix();
			}
 
			SwapBuffers();
		}
 
		[STAThread]
		public static void Main()
		{
			using (Program p = new Program())
			{
				p.Run(80f);
			}
		}
	}
}
Inline Images

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
lid6j86's picture

flop, thank you so much. because of this example I was FINALLY able to get perspective mode working.

I'm now working through trying to figure out how to move through it, but this was a life saver

flopoloco's picture

Good to know it worked.