public ForwardPipeline(MasterRenderer renderer)
            : base(renderer)
        {
            GLError.Begin();

            forwardShader        = new WorldShader();
            shadowShader         = new ShadowShader();
            shadowMap            = new ShadowMap(GFXSettings.ShadowResolution, GFXSettings.ShadowResolution);
            shadowCamera         = new ShadowCamera();
            ppBuffer             = new PostProcessBuffer(ScreenWidth, ScreenHeight);
            ppShader             = new PostProcessShader();
            skyRenderTarg        = new TexRenderTarget(ScreenWidth, ScreenHeight);
            screenshotRenderTarg = new TexRenderTarget(1, 1);

            screenshotRenderTarg.Bind();
            GL.ReadBuffer(ReadBufferMode.ColorAttachment0);
            screenshotRenderTarg.Unbind();

            ErrorCode err = GLError.End();

            if (err != ErrorCode.NoError)
            {
                throw new Exception(string.Format("Failed to initialize forward pipeline. OpenGL Error: {0}", err));
            }
        }
Exemplo n.º 2
0
        public static void Disable(EnableCap cap)
        {
            if (states[cap])
            {
                if (CheckForErrors)
                {
                    GLError.Begin();
                }

                states[cap] = false;
                GL.Disable(cap);

                if (CheckForErrors)
                {
                    ErrorCode glError = GLError.End();
                    if (glError == ErrorCode.InvalidEnum)
                    {
                        throw new Exception(string.Format("Invalid glEnable Enum: {0}", cap));
                    }
                    else if (glError == ErrorCode.InvalidValue)
                    {
                        throw new Exception(string.Format("Invalid glEnable Value: {0}", cap));
                    }
                }
            }
        }
Exemplo n.º 3
0
        protected BufferObject InitializeArrayBuffer(uint index, int components, VertexAttribPointerType type, bool normalized,
                                                     int stride, int offset, BufferUsageHint hint)
        {
            if (index < 0 || index >= ArrayBufferObjects.Length)
            {
                throw new IndexOutOfRangeException(
                          "Index must be within range of the number of array buffer objects for this vertex buffer!");
            }

            if (ArrayBufferObjects[index] != null)
            {
                throw new InvalidOperationException(
                          string.Format("ArrayBuffer {0} was already initialized for this vertex buffer!", index));
            }

            GLError.Begin();

            BufferObject buffer = new BufferObject(BufferTarget.ArrayBuffer, hint);

            buffer.Bind();
            GL.VertexAttribPointer(index, components, type, normalized, stride, new IntPtr(offset));
            GL.EnableVertexAttribArray(index);

            ErrorCode err = GLError.End();

            if (err != ErrorCode.NoError)
            {
                throw new Exception(string.Format("Failed to initialize array buffer: {0}", err));
            }

            ArrayBufferObjects[index] = buffer;
            return(buffer);
        }
        public MasterRenderer(int screenWidth, int screenHeight, GraphicsOptions options = null)
        {
            Instance    = this;
            GFXSettings = options ?? new GraphicsOptions();

            ScreenWidth  = screenWidth;
            ScreenHeight = screenHeight;

            if (GLVersion == 0)
            {
                int major = GL.GetInteger(GetPName.MajorVersion);
                int minor = GL.GetInteger(GetPName.MinorVersion);
                GLVersion = major + minor * 0.1f;

                //if (major < 4)
                //    throw new Exception(string.Format("OpenGL 4.0 or later is required to run this game. This machine is running: {0}", GLVersion));
                if (major < 4)
                {
                    DashCMD.WriteWarning("[OpenGL] OpenGL 4.0 or later is required to run this game properly!. This machine is running: {0}", GLVersion);
                }
                else
                {
                    DashCMD.WriteLine("[OpenGL] Version: {0}", ConsoleColor.DarkGray, GLVersion);
                }
            }

            GLError.Begin();

            Camera camera = new Camera(this);

            camera.MakeActive();

            Lights = new LightList();

            Texture.Blank = GLoader.LoadBlankTexture(Color.White);

            Renderer3Ds = new Dictionary <Type, Renderer3D>();
            Renderer2Ds = new Dictionary <Type, Renderer2D>();

            Gui     = new GuiRenderer(this);
            Sprites = new SpriteRenderer(this);
            Sky     = new SkyboxRenderer(this);

            AddRenderer(Gui);
            AddRenderer(Sprites);

            activePipeline = new ForwardPipeline(this);

            StateManager.Enable(EnableCap.CullFace);
            StateManager.Enable(EnableCap.DepthTest);

            GL.CullFace(CullFaceMode.Back);

            ErrorCode mInitError = GLError.End();

            if (mInitError != ErrorCode.NoError)
            {
                throw new Exception(string.Format("Uncaught master renderer init opengl error: {0}", mInitError));
            }
        }
Exemplo n.º 5
0
        public ShadowMap(int width, int height)
        {
            Width  = width;
            Height = height;

            GLError.Begin();

            fbo      = GL.GenFramebuffer();
            depthTex = GL.GenTexture();

            BindTex();

            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.DepthComponent, width, height, 0,
                          PixelFormat.DepthComponent, PixelType.Float, IntPtr.Zero);
            GL.TexParameteri(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
            GL.TexParameteri(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
            GL.TexParameteri(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToBorder);
            GL.TexParameteri(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToBorder);
            GL.TexParameterfv(TextureTarget.Texture2D, TextureParameterName.TextureBorderColor, new float[] { 1, 1, 1, 1 });

            // Bind the FBO
            Bind();

            GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment,
                                    TextureTarget.Texture2D, depthTex, 0);

            GL.DrawBuffer(DrawBufferMode.None);
            GL.ReadBuffer(ReadBufferMode.None);

            // Check for errors
            FramebufferErrorCode ec = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);

            if (ec != FramebufferErrorCode.FramebufferComplete)
            {
                throw new GPUResourceException("Failed to create FBO. Reason: " + ec.ToString());
            }

            // Unbind
            Unbind();

            ErrorCode err = GLError.End();

            if (err != ErrorCode.NoError)
            {
                throw new Exception(string.Format("Failed to initialize shadow map: OpenGL error: {0}", err));
            }
        }
Exemplo n.º 6
0
        public static Texture LoadTexture(string filePath,
                                          TextureMinFilter minFilter = TextureMinFilter.Linear, TextureMagFilter magFilter = TextureMagFilter.Linear, bool keepPath = false)
        {
            // Get full path
            string actualPath = keepPath ? filePath : GetContentRelativePath(filePath);

            if (!File.Exists(actualPath))
            {
                throw new FileNotFoundException(string.Format("Could not find texture file \"{0}\"", actualPath), actualPath);
            }

            GLError.Begin();

            // Generate bitmap and get it's data
            Bitmap     bitmap  = new Bitmap(actualPath);
            BitmapData texData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
                                                 ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            // Create texture id and bind it
            Texture texture = new Texture();

            texture.Bind();

            // Set the texture data, min mag, and mipmap lod
            texture.SetData(texData.Width, texData.Height, PixelType.UnsignedByte,
                            OpenGL.PixelFormat.Bgra, texData.Scan0);
            texture.GenerateMipmap();
            texture.SetLODBias(-1);
            texture.SetMinMag(minFilter, magFilter);

            // Unbind the texture
            texture.Unbind();

            // Unlock the bitmap file
            bitmap.UnlockBits(texData);

            ErrorCode err = GLError.End();

            if (err != ErrorCode.NoError)
            {
                throw new Exception(string.Format("Failed to load texture. OpenGL Error: {0}", err));
            }

            return(texture);
        }
        public PostProcessBuffer(int width, int height)
            : base(width, height)
        {
            GLError.Begin();

            // Bind the FBO
            Bind();

            // Create the textures
            TextureParamPack texParams = new TextureParamPack(TextureMagFilter.Nearest, TextureMinFilter.Nearest, TextureWrapMode.ClampToEdge);

            ColorTexture = new FramebufferTexture(width, height, texParams, FramebufferAttachment.ColorAttachment0,
                                                  PixelInternalFormat.Rgba16f, PixelFormat.Rgba, PixelType.HalfFloat);

            // Create the depth buffer
            depthBuffer = GL.GenRenderbuffer();
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, depthBuffer);
            GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, RenderbufferStorage.DepthComponent24, Width, Height);
            GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment,
                                       RenderbufferTarget.Renderbuffer, depthBuffer);
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0);

            // Set and enable the draw buffers
            SetDrawBuffers(DrawBuffersEnum.ColorAttachment0);
            EnableDrawBuffers();

            // Check for errors
            CheckForErrors();

            // Unbind
            Unbind();

            ErrorCode err = GLError.End();

            if (err != ErrorCode.NoError)
            {
                throw new Exception(string.Format("Failed to create PostProcessBuffer. OpenGL Error: {0}", err));
            }
        }
Exemplo n.º 8
0
        public void Run(float targetFPS)
        {
            TargetFrameRate = targetFPS;

            if (!Glfw.Init())
            {
                throw new Exception("Failed to initialize glfw!");
            }

            try
            {
                // Setup the error callback
                Glfw.SetErrorCallback(OnError);

                // Configure the window settings
                Glfw.WindowHint(WindowHint.Resizeable, startResizable ? 1 : 0);
                Glfw.WindowHint(WindowHint.Samples, 0);

                // Create the window
                handle = Glfw.CreateWindow(startWidth, startHeight, title,
                                           GlfwMonitorPtr.Null, GlfwWindowPtr.Null);
                HasFocus = true;

                // TODO: check if window was initialized correctly

                // Set the gl context
                Glfw.MakeContextCurrent(handle);

                // Get the primary monitor
                primaryMonitor          = Glfw.GetMonitors()[0];
                primaryMonitorVideoMode = Glfw.GetVideoMode(primaryMonitor);

                Glfw.GetWindowSize(handle, out width, out height);
                Center();

                // Setup window events
                Glfw.SetScrollCallback(handle, OnInputScroll);
                Glfw.SetCursorPosCallback(handle, OnMouseMove);
                Glfw.SetWindowSizeCallback(handle, OnSizeChanged);
                Glfw.SetWindowFocusCallback(handle, OnWindowFocusChanged);
                Glfw.SetKeyCallback(handle, OnInputKeyChanged);
                Input.Initialize(this);

                // Set defaults and load
                SetVSync(false);

                Renderer = new MasterRenderer(width, height, startOptions);
                InitOpenAL();

                GLError.Begin();
                Load();
                ErrorCode initError = GLError.End();
                if (initError != ErrorCode.NoError)
                {
                    throw new Exception(string.Format("Uncaught opengl initialization error! {0}", initError));
                }

                // Begin game loop
                double lastTime = Glfw.GetTime();

                while (!Glfw.WindowShouldClose(handle))
                {
                    double now = Glfw.GetTime();
                    float  dt  = (float)(now - lastTime);
                    lastTime = now;

                    // Process current deltatime
                    HandleFPS(dt);

                    // Check for input events before we call Input.Begin
                    Glfw.PollEvents();

                    // Check for window size change.
                    // We only call the OnResized event here so that
                    // when a user is custom resizing it doesn't get invoked
                    // a thousand times.
                    if (lastDrawnWidth != width || lastDrawnHeight != height)
                    {
                        lastDrawnWidth  = width;
                        lastDrawnHeight = height;
                        OnSafeResized();
                    }

                    // Update
                    Input.Begin();
                    Renderer.Update(dt);
                    Update(dt);
                    Input.End();

                    // Draw
                    Renderer.Prepare(dt);
                    Draw(dt);
                    Renderer.Render(dt);

                    // Check for any uncaught opengl exceptions
                    ErrorCode glError = GL.GetError();
                    if (glError != ErrorCode.NoError)
                    {
                        throw new Exception(string.Format("Uncaught OpenGL Error: {0}", glError));
                    }

                    // Draw the buffers
                    Glfw.SwapBuffers(handle);

                    if (!vsyncEnabled)
                    {
                        // Sleep to avoid cpu cycle burning
                        double startSleepNow = Glfw.GetTime();
                        double timeToWait    = targetDeltaTime - (startSleepNow - now);

                        while (timeToWait > 0)
                        {
                            Thread.Sleep(0);
                            double sleepNow = Glfw.GetTime();
                            timeToWait   -= (sleepNow - startSleepNow);
                            startSleepNow = sleepNow;
                        }
                    }
                }

                Unload();
            }
            finally
            {
                Glfw.DestroyWindow(handle);
            }
        }