public static HeightMapData LoadHeightmapData(string filename)
        {
            using (TracedStopwatch.Start("Loading Heightmap: " + filename))
            {
                var rv = new HeightMapData();

                IntPtr intPtr      = SDL2.SDL_image.IMG_Load(filename);
                var    surface     = Marshal.PtrToStructure <SDL.SDL_Surface>(intPtr);
                var    pixelFormat = Marshal.PtrToStructure <SDL.SDL_PixelFormat>(surface.format);
                if (pixelFormat.BytesPerPixel != 1)
                {
                    throw new Exception("Only 8bit textures support atm!");
                }

                var width  = surface.w;
                var height = surface.h;
                var size   = width * height;

                byte[] managedArray = new byte[size];
                Marshal.Copy(surface.pixels, managedArray, 0, size);

                rv.SetData(width, height, managedArray);

                return(rv);
            }
        }
        public GameWindow(String windowName, Int32 screenWidth, Int32 screenHeight)
        {
            m_WindowName   = windowName;
            m_ScreenWidth  = screenWidth;
            m_ScreenHeight = screenHeight;

            using (TracedStopwatch.Start("Init Stopwatch"))
            {
                // This is here just to init the traced stopwatch
            }
        }
Beispiel #3
0
 public static void InitaliseOpenGLEntryPoints()
 {
     using (TracedStopwatch.Start("Init OpenGL Bindings"))
     {
         // Load EntryPoints via refelction
         var fields = typeof(GlBindings).GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
         foreach (var fieldInfo in fields)
         {
             if (fieldInfo.IsDefined(typeof(BindMethod), false))
             {
                 var attribute       = fieldInfo.GetCustomAttributes(typeof(BindMethod), false)[0] as BindMethod;
                 var delegateBinding = LoadEntryPoint(attribute.MethodName, fieldInfo.FieldType, true);
                 fieldInfo.SetValue(null, delegateBinding);
             }
         }
     }
 }
Beispiel #4
0
        internal static Texture2D CreateFromFile(string filename, bool generateMipmaps = false)
        {
            using (TracedStopwatch.Start("Loading Texture: " + filename))
            {
                IntPtr intPtr      = SDL2.SDL_image.IMG_Load(filename);
                var    surface     = Marshal.PtrToStructure <SDL.SDL_Surface>(intPtr);
                var    pixelFormat = Marshal.PtrToStructure <SDL.SDL_PixelFormat>(surface.format);

                var mode = OpenGL.PixelFormat.Rgba;
                if (pixelFormat.BytesPerPixel == 3)
                {
                    mode = OpenGL.PixelFormat.Rgb;
                }
                if (pixelFormat.BytesPerPixel == 1)
                {
                    mode = OpenGL.PixelFormat.Red;
                }

                var rv = new Texture2D();

                // TODO Pass in wraping styles
                GlBindings.GenTextures(1, out rv.m_TextureId);
                GlBindings.BindTexture(TextureType.GL_TEXTURE_2D, rv.m_TextureId);
                GlBindings.TexParameteri(TextureType.GL_TEXTURE_2D, TextureAttribute.GL_TEXTURE_WRAP_S, TextureAttributeValue.GL_REPEAT);
                GlBindings.TexParameteri(TextureType.GL_TEXTURE_2D, TextureAttribute.GL_TEXTURE_WRAP_T, TextureAttributeValue.GL_REPEAT);
                GlBindings.TexParameteri(TextureType.GL_TEXTURE_2D, TextureAttribute.GL_TEXTURE_MIN_FILTER, TextureAttributeValue.GL_LINEAR);
                GlBindings.TexParameteri(TextureType.GL_TEXTURE_2D, TextureAttribute.GL_TEXTURE_MAG_FILTER, TextureAttributeValue.GL_LINEAR);

                var internalFormat = OpenGL.PixelInternalFormat.Rgba;
                if (mode == PixelFormat.Luminance)
                {
                    internalFormat = PixelInternalFormat.Red;
                }

                GlBindings.TexImage2D(TextureType.GL_TEXTURE_2D, 0, internalFormat, surface.w, surface.h, 0, mode, PixelType.UnsignedByte, surface.pixels);

                if (generateMipmaps)
                {
                    GlBindings.GenerateMipmap(TextureType.GL_TEXTURE_2D);
                }

                SDL2.SDL.SDL_free(intPtr);

                return(rv);
            }
        }
Beispiel #5
0
        internal static ShaderProgram CreateFromFile(string vertexShaderFileName, string fragmentShaderFileName)
        {
            using (TracedStopwatch.Start("load shader from file: "))
            {
                Console.WriteLine("VERT:" + vertexShaderFileName);
                Console.WriteLine("FRAG:" + fragmentShaderFileName);

                // Vertex Shader
                var vertShader = File.ReadAllText(vertexShaderFileName);
                var fragShader = File.ReadAllText(fragmentShaderFileName);

                var rv = CreateFromString(vertShader, fragShader);

                rv.VertexShaderFileName   = vertexShaderFileName;
                rv.FragmentShaderFileName = fragmentShaderFileName;
                return(rv);
            }
        }
        public static Model LoadObj(string fileName)
        {
            using (TracedStopwatch.Start("Load obj:" + fileName))
            {
                var rv    = new Model();
                var text  = File.ReadAllText(fileName);
                var items = text.Split(new string[] { Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries);

                int vertCount   = 0;
                int faceCount   = 0;
                int normalCount = 0;

                // Need to know num verts/faces
                for (int i = 0; i < items.Length; i++)
                {
                    if (items[i].StartsWith("vn"))
                    {
                        normalCount++;
                    }
                    else if (items[i].StartsWith("v"))
                    {
                        vertCount++;
                    }
                    else if (items[i].StartsWith("f"))
                    {
                        faceCount++;
                    }
                }

                var verts = new Vector3[vertCount];
                var faces = new uint[faceCount * 3];

                // Bunny.obj
                // # vertex count = 2503
                // # face count = 4968
                var fIndex = 0;
                var vIndex = 0;

                for (int i = 0; i < items.Length; i++)
                {
                    if (items[i].StartsWith("vn"))
                    {
                        // Skip for now
                    }
                    else if (items[i].StartsWith("v"))
                    {
                        var vsplit = items[i].Split(new char[] { ' ' });
                        verts[vIndex].X = float.Parse(vsplit[1], CultureInfo.InvariantCulture);
                        verts[vIndex].Y = float.Parse(vsplit[2], CultureInfo.InvariantCulture);
                        verts[vIndex].Z = float.Parse(vsplit[3], CultureInfo.InvariantCulture);

                        vIndex++;
                    }
                    else if (items[i].StartsWith("f"))
                    {
                        var vsplit = items[i].Split(new char[] { ' ' });
                        faces[fIndex]     = uint.Parse(vsplit[1], CultureInfo.InvariantCulture) - 1;
                        faces[fIndex + 1] = uint.Parse(vsplit[2], CultureInfo.InvariantCulture) - 1;
                        faces[fIndex + 2] = uint.Parse(vsplit[3], CultureInfo.InvariantCulture) - 1;

                        fIndex += 3;
                    }
                }

                // TODO Compute normals


                // Verticies

                rv.Verts = new VertexPositionColorTextureNormal[vertCount];
                for (int i = 0; i < vertCount; i++)
                {
                    var v1 = verts[i];
                    rv.Verts[i].Position = v1;
                    rv.Verts[i].Color    = new Vector4(1, 1, 1, 1);
                    rv.Verts[i].Texture  = new Vector2(1, 1);
                }



                // Compute Face Normals
                for (int i = 0; i < faces.Length - 1; i += 3)
                {
                    var id1 = faces[i];
                    var id2 = faces[i + 1];
                    var id3 = faces[i + 2];

                    var v1 = verts[id1];
                    var v2 = verts[id2];
                    var v3 = verts[id3];

                    var e1 = v2 - v1;
                    var e2 = v3 - v1;

                    var n = Vector3.Cross(e1, e2);

                    // Smooth normals
                    rv.Verts[id1].Normal += n;
                    rv.Verts[id2].Normal += n;
                    rv.Verts[id3].Normal += n;

                    // Face Normals

                    /*
                     *  rv.Verts[id1].Normal = n;
                     *  rv.Verts[id2].Normal = n;
                     *  rv.Verts[id3].Normal = n;
                     */
                }

                for (int i = 0; i < rv.Verts.Length; i++)
                {
                    rv.Verts[i].Normal = Vector3.Normalize(rv.Verts[i].Normal);
                }

                // Indicies
                rv.Indicies = faces;

                // If using no indicies
                // rv.Indicies

                return(rv);
            }
        }
        public void RunGame(Game game, bool borderless = false, Action a = null)
        {
            NativeLibraryLoader.SetNativeLibaryFolder();


            SDL.SDL_Init(SDL.SDL_INIT_VIDEO);

            var imgFlags = SDL_image.IMG_InitFlags.IMG_INIT_PNG | SDL_image.IMG_InitFlags.IMG_INIT_JPG;

            if ((SDL_image.IMG_Init(imgFlags) > 0 & imgFlags > 0) == false)
            {
                Console.WriteLine("SDL_image could not initialize! SDL_image Error: {0}", SDL.SDL_GetError());
                return;
            }



            var cpus = SDL.SDL_GetCPUCount();

            Console.WriteLine("SYSTEM: CPU Count:" + cpus);

            var ramMb = SDL.SDL_GetSystemRAM();

            Console.WriteLine("SYSTEM: RAM MB:" + ramMb);

            // Init OpenAL
            var audioDevice = new AudioDevice();

            audioDevice.Initalise();

            GameInput = new GameInput();

            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_PROFILE_MASK, SDL.SDL_GLprofile.SDL_GL_CONTEXT_PROFILE_CORE);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_MAJOR_VERSION, 3);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_CONTEXT_MINOR_VERSION, 3);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_DOUBLEBUFFER, 1);

            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_MULTISAMPLEBUFFERS, 1);
            SDL.SDL_GL_SetAttribute(SDL.SDL_GLattr.SDL_GL_MULTISAMPLESAMPLES, 8);

            // TODO Register the Audio device in the dependancy locator
            var windowStyle = /*SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS |*/ SDL.SDL_WindowFlags.SDL_WINDOW_RESIZABLE | SDL.SDL_WindowFlags.SDL_WINDOW_OPENGL;

            if (borderless == true)
            {
                windowStyle = windowStyle | SDL.SDL_WindowFlags.SDL_WINDOW_BORDERLESS;
            }
            WindowPtr = SDL.SDL_CreateWindow(m_WindowName, SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED, ScreenWidth, ScreenHeight, windowStyle);
            OpenGLPtr = SDL.SDL_GL_CreateContext(WindowPtr);

            // Get the Win32 HWND from the SDL2 window
            SDL.SDL_SysWMinfo info = new SDL.SDL_SysWMinfo();
            SDL.SDL_GetWindowWMInfo(WindowPtr, ref info);
            Win32Ptr = info.info.win.window;

            OpenGL.GlBindings.InitaliseOpenGLEntryPoints();



            var graphicsDevice = new OpenGLGraphicsDevice(OpenGLPtr);

            SetVSync(VSyncStatus.VSYNC_ENABLE);

            GraphicsDevice = graphicsDevice;
            AudioDevice    = audioDevice;

            game.Init(audioDevice, graphicsDevice, this, GameInput);

            // TODO Rename to OnLoadedWindow
            if (a != null)
            {
                a.Invoke();
            }

            // TODO Embed these as resources
            QuadBatchShader  = ShaderProgram.CreateFromFile("Resources/Shaders/Vertex/v.quadbatch.glsl", "Resources/Shaders/Fragment/f.quadbatch.glsl");
            FullScreenShader = ShaderProgram.CreateFromFile("Resources/Shaders/Vertex/v.fullscreenquad.glsl", "Resources/Shaders/Fragment/f.fullscreenquad.glsl");
            using (TracedStopwatch.Start("Loading Game Resources"))
            {
                game.Load();
            }

            var stopwatch = new Stopwatch();
            var isRunning = true;

            while (isRunning)
            {
                // TODO Reset stats counters

                stopwatch.Restart();
                ProcessEvents();

                if (this.HasQuit)
                {
                    break;
                }
                game.Update();
                game.UpdateCoroutines();


                GraphicsDevice.Enable(OpenGL.Enable.GL_DEPTH_TEST);
                game.RenderScene();

                GraphicsDevice.Disable(OpenGL.Enable.GL_DEPTH_TEST);
                game.Render2D();

                // TODO Multimedia Timer or sleep for time...
                // TODO Stats for frame time and fps

                // Update window with OpenGL rendering
                SDL.SDL_GL_SwapWindow(WindowPtr);
                GameInput.Swap();

                stopwatch.Stop();
                GameTime.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
                GameTime.ElapsedSeconds      = stopwatch.Elapsed.TotalSeconds;
                GameTime.TotalSeconds       += GameTime.ElapsedSeconds;
            }

            // Unload Resources
            SDL.SDL_Quit();
        }
        internal static TextureCubeMap CreateFromFile(string front, string back, string bottom, string top, string left, string right, bool generateMipmaps = false)
        {
            using (TracedStopwatch.Start("Loading Cubemap: " + front))
            {
                var rv = new TextureCubeMap();

                // Generate the cube map
                GlBindings.GenTextures(1, out rv.m_TextureId);
                GlBindings.BindTexture(TextureType.GL_TEXTURE_CUBE_MAP, rv.m_TextureId);

                var items = new List <string>
                {
                    right,
                    left,
                    top,
                    bottom,
                    front,
                    back
                };
                var i = 0;
                foreach (var item in items)
                {
                    var fi = new FileInfo(item);
                    if (!fi.Exists)
                    {
                        throw new Exception("File not found");
                    }

                    // Load each image from disk
                    IntPtr intPtr  = SDL2.SDL_image.IMG_Load(item);
                    var    surface = Marshal.PtrToStructure <SDL.SDL_Surface>(intPtr);

                    var pixelFormat = Marshal.PtrToStructure <SDL.SDL_PixelFormat>(surface.format);

                    var mode = OpenGL.PixelFormat.Rgba;
                    if (pixelFormat.BytesPerPixel == 3)
                    {
                        mode = OpenGL.PixelFormat.Rgb;
                    }
                    if (pixelFormat.BytesPerPixel == 1)
                    {
                        mode = OpenGL.PixelFormat.Red;
                    }


                    var internalFormat = OpenGL.PixelInternalFormat.Rgba;
                    if (mode == PixelFormat.Luminance)
                    {
                        internalFormat = PixelInternalFormat.Red;
                    }

                    GlBindings.TexImage2D(TextureType.GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, internalFormat, surface.w, surface.h, 0, mode, PixelType.UnsignedByte, surface.pixels);

                    // Free the managed resource
                    SDL2.SDL.SDL_free(intPtr);
                    i++;
                }

                // Texture Sampling and Filtering
                GlBindings.TexParameteri(TextureType.GL_TEXTURE_CUBE_MAP, TextureAttribute.GL_TEXTURE_WRAP_S, TextureAttributeValue.GL_CLAMP_TO_EDGE);
                GlBindings.TexParameteri(TextureType.GL_TEXTURE_CUBE_MAP, TextureAttribute.GL_TEXTURE_WRAP_T, TextureAttributeValue.GL_CLAMP_TO_EDGE);
                GlBindings.TexParameteri(TextureType.GL_TEXTURE_CUBE_MAP, TextureAttribute.GL_TEXTURE_WRAP_R, TextureAttributeValue.GL_CLAMP_TO_EDGE);

                GlBindings.TexParameteri(TextureType.GL_TEXTURE_CUBE_MAP, TextureAttribute.GL_TEXTURE_MIN_FILTER, TextureAttributeValue.GL_LINEAR);
                GlBindings.TexParameteri(TextureType.GL_TEXTURE_CUBE_MAP, TextureAttribute.GL_TEXTURE_MAG_FILTER, TextureAttributeValue.GL_LINEAR);

                return(rv);
            }
        }
Beispiel #9
0
        // TODO Store Shader Code


        internal static ShaderProgram CreateFromString(string vertexShaderCode, string fragmentShaderCode)
        {
            using (TracedStopwatch.Start("load shader from string: "))
            {
                var rv = new ShaderProgram
                {
                    VertexShaderFileName   = "Created From String",
                    FragmentShaderFileName = "Created From String",
                    VertexShaderCode       = vertexShaderCode,
                    FragmentShaderCode     = fragmentShaderCode
                };

                var vertexShader = OpenGL.GlBindings.CreateShader(ShaderType.VertexShader);
                GlBindings.ShaderSource(vertexShader, vertexShaderCode);
                GlBindings.CompileShader(vertexShader);

                int result;

                GlBindings.GetShaderInfo(vertexShader, ShaderParameter.CompileStatus, out result);
                if (result != (int)Result.Ok)
                {
                    var error = GlBindings.GetShaderInfoLog(vertexShader);
                    Console.WriteLine("Shader Compilation Failed:/r/n" + error);
                }

                // Fragment Shader

                var fragmentShader = OpenGL.GlBindings.CreateShader(ShaderType.FragmentShader);
                GlBindings.ShaderSource(fragmentShader, fragmentShaderCode);
                GlBindings.CompileShader(fragmentShader);
                GlBindings.GetShaderInfo(fragmentShader, ShaderParameter.CompileStatus, out result);
                if (result != (int)Result.Ok)
                {
                    var error = OpenGL.GlBindings.GetShaderInfoLog(fragmentShader);
                    Console.WriteLine("Shader Compilation Failed:/r/n" + error);
                }



                // Link Shaders
                rv.ShaderProgramId = OpenGL.GlBindings.CreateProgram();
                GlBindings.AttachShader(rv.ShaderProgramId, vertexShader);
                GlBindings.AttachShader(rv.ShaderProgramId, fragmentShader);
                GlBindings.LinkProgram(rv.ShaderProgramId);

                GlBindings.GetProgramInfo(rv.ShaderProgramId, ProgramParameter.LinkStatus, out result);
                if (result != (int)Result.Ok)
                {
                    var error = OpenGL.GlBindings.GetProgramInfoLog(rv.ShaderProgramId);
                    Console.WriteLine("Shader Link Failed:/r/n" + error);
                }

                GlBindings.GetProgramInfo(rv.ShaderProgramId, ProgramParameter.GL_ACTIVE_UNIFORMS, out result);
                //if (result != (int)Result.Ok)
                {
                    Console.WriteLine("Active Uniform Count:" + (int)result);
                }

                for (var i = 0; i < result; i++)
                {
                    var uniformInfo = GlBindings.GetActiveUniformInfo(rv.ShaderProgramId, i);
                    Console.WriteLine("Active Uniform: " + uniformInfo);
                }

                /*
                 * glGetProgramiv(program, GL_ACTIVE_UNIFORMS, &count);
                 *  printf("Active Uniforms: %d\n", count);
                 *
                 */

                GlBindings.DeleteShader(fragmentShader);
                GlBindings.DeleteShader(vertexShader);

                return(rv);
            }
        }