private void modelPanel1_PreRender(object sender, GLContext context)
        {
            if (pnlOptions.RenderFloor)
            {
                GLTexture _bgTex = context.FindOrCreate <GLTexture>("TexBG", GLTexturePanel.CreateBG);

                float s = 10.0f, t = 10.0f;
                float e = 30.0f;

                context.glDisable((uint)GLEnableCap.Lighting);
                context.glEnable(GLEnableCap.DepthTest);
                context.glPolygonMode(GLFace.Front, GLPolygonMode.Fill);
                context.glPolygonMode(GLFace.Back, GLPolygonMode.Line);

                context.glEnable(GLEnableCap.Texture2D);
                _bgTex.Bind();

                context.glColor(0.5f, 0.5f, 0.75f, 1.0f);
                context.glBegin(GLPrimitiveType.Quads);

                context.glTexCoord(0.0f, 0.0f);
                context.glVertex(-e, 0.0f, -e);
                context.glTexCoord(s, 0.0f);
                context.glVertex(e, 0.0f, -e);
                context.glTexCoord(s, t);
                context.glVertex(e, 0.0f, e);
                context.glTexCoord(0, t);
                context.glVertex(-e, 0.0f, e);

                context.glEnd();
            }
        }
Beispiel #2
0
        //public TextureRef() { }
        //public TextureRef(string name)
        //{
        //    Name = name;
        //    if (Name == "TShadow1")
        //        Enabled = false;
        //}

        internal unsafe void Prepare(GLContext ctx)
        {
            if (_context == null)
            {
                _context = ctx;
            }


            if (Texture != null)
            {
                Texture.Bind();
            }
            else
            {
                Load();
            }

            float *p = stackalloc float[4];

            p[0] = p[1] = p[2] = p[3] = 1.0f;
            if (Selected)
            {
                p[0] = -1.0f;
            }

            ctx.glLight(GLLightTarget.Light0, GLLightParameter.SPECULAR, p);
            ctx.glLight(GLLightTarget.Light0, GLLightParameter.DIFFUSE, p);
        }
Beispiel #3
0
        internal static unsafe GLTexture CreateBG(GLContext ctx)
        {
            GLTexture tex = new GLTexture(ctx, 16, 16);

            tex.Bind();

            //Create BG texture
            ABGRPixel left  = new ABGRPixel(255, 192, 192, 192);
            ABGRPixel right = new ABGRPixel(255, 240, 240, 240);

            int *      pixelData = stackalloc int[16 * 16];
            ABGRPixel *p         = (ABGRPixel *)pixelData;

            for (int y = 0; y < 16; y++)
            {
                for (int x = 0; x < 16; x++)
                {
                    *p++ = ((x & 8) == (y & 8)) ? left : right;
                }
            }


            //ctx.glEnable(GLEnableCap.Texture2D);
            //ctx.glBindTexture(GLTextureTarget.Texture2D, _backTex._id);
            ctx.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.WrapS, (int)GLTextureWrapMode.REPEAT);
            ctx.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.WrapT, (int)GLTextureWrapMode.REPEAT);
            ctx.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MinFilter, (int)GLTextureMinFilter.NEAREST);
            ctx.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MagFilter, (int)GLTextureMagFilter.NEAREST);
            ctx.glTexImage2D(GLTexImageTarget.Texture2D, 0, GLInternalPixelFormat._4, 16, 16, 0, GLPixelDataFormat.RGBA, GLPixelDataType.UNSIGNED_BYTE, pixelData);

            return(tex);
        }
        private void DrawMesh()
        {
            if (glTexture != null)
            {
                GL.Enable(EnableCap.Texture2D);
                GLTexture.Bind(glTexture);
            }
            GL.Begin(PrimitiveType.Triangles);

            foreach (var face in Mesh.Faces)
            {
                foreach (var vertexInfo in face)
                {
                    var   texture = Mesh.TextureCoordinates[vertexInfo.TextureIndex];
                    var   vertex  = Mesh.Vertices[vertexInfo.VertexIndex];
                    float u       = texture.X;
                    float v       = 1 - texture.Y;
                    float x       = vertex.X / 2;
                    float y       = vertex.Y / 2;
                    float z       = vertex.Z / 2;
                    GL.TexCoord2(u, v);
                    GL.Vertex3(x, y, z);
                }
            }

            GL.End();
            GL.Disable(EnableCap.Texture2D);
        }
Beispiel #5
0
        static void DrawBlur(GLContext control, GLTexture texture)
        {
            GL.ActiveTexture(TextureUnit.Texture0);
            texture.Bind();
            control.CurrentShader.SetInt("image", 0);

            GLFrameworkEngine.ScreenQuadRender.Draw();

            GL.BindTexture(TextureTarget.Texture2D, 0);
        }
Beispiel #6
0
        public static void DrawSceneLights(Camera camera, GLTexture gbuffer, GLTexture linearDepth)
        {
            return;

            var shader = GlobalShaders.GetShader("LIGHTPREPASS");

            shader.Enable();

            GL.ActiveTexture(TextureUnit.Texture0 + 1);
            gbuffer.Bind();
            shader.SetInt("normalsTexture", 1);

            GL.ActiveTexture(TextureUnit.Texture0 + 2);
            linearDepth.Bind();
            shader.SetInt("depthTexture", 2);

            int programID = shader.program;

            var projectionMatrixInverse = camera.ProjectionMatrix.Inverted();
            var viewMatrixInverse       = camera.ViewMatrix.Inverted();
            var mtxProjView             = camera.ProjectionMatrix * camera.ViewMatrix;

            shader.SetMatrix4x4("mtxProjInv", ref projectionMatrixInverse);
            shader.SetMatrix4x4("mtxViewInv", ref viewMatrixInverse);
            shader.SetVector3("cameraPosition", camera.TargetPosition);


            float projectionA = camera.ZFar / (camera.ZFar - camera.ZNear);
            float projectionB = (-camera.ZFar * camera.ZNear) / (camera.ZFar - camera.ZNear);

            shader.SetFloat("projectionA", projectionA);
            shader.SetFloat("projectionB", projectionB);
            shader.SetFloat("z_range", camera.ZFar - camera.ZNear);
            shader.SetFloat("fov_x", camera.Fov);
            shader.SetFloat("fov_y", camera.Fov);

            PointLight[] pointLights = new PointLight[32];
            for (int i = 0; i < 32; i++)
            {
                pointLights[i] = new PointLight();
                if (i == 0)
                {
                    pointLights[i].Position = PointPosition;
                    pointLights[i].Color    = new Vector4(1, 0, 0, 1);
                }

                GL.Uniform4(GL.GetUniformLocation(programID, $"pointLights[{i}].uColor"), pointLights[i].Color);
                GL.Uniform3(GL.GetUniformLocation(programID, $"pointLights[{i}].uPosition"), pointLights[i].Position);
            }

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

            ScreenQuadRender.Draw();
        }
        static void InitTextures()
        {
            //Reflective cubemap
            var cubemap = GLTextureCubeArray.FromDDS(
                new DDS($"Resources\\CubemapHDR.dds"));

            CubemapManager.InitDefault(cubemap);

            CubemapManager.CubeMapTextureArray = GLTexture2DArray.FromDDS(new DDS($"Resources\\CubemapHDR.dds"));
            DiffuseLightmapTextureArray        = GLTexture2DArray.FromDDS(new DDS[2]
            {
                new DDS(new MemoryStream(Resources.CubemapLightmap)),
                new DDS(new MemoryStream(Resources.CubemapLightmapShadow))
            });

            //Diffuse cubemap lighting
            //Map gets updated when an object moves using probe lighting.
            DiffuseLightmapTexture = GLTextureCube.FromDDS(
                new DDS(new MemoryStream(Resources.CubemapLightmap)),
                new DDS(new MemoryStream(Resources.CubemapLightmapShadow)));

            LightingEngine.LightSettings.InitTextures();

            DepthShadowCascadeTexture = GLTexture2D.CreateWhiteTexture(4, 4);

            //Tire marks
            ProjectionTexture = GLTexture2D.CreateWhiteTexture(4, 4);

            //Depth information. Likely for shadows
            NormalizedLinearDepth = GLTexture2D.FromBitmap(Resources.black);

            //Adjust mip levels

            CubemapManager.CubeMapTexture.Bind();
            GL.TexParameter(CubemapManager.CubeMapTexture.Target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(CubemapManager.CubeMapTexture.Target, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            GL.TexParameter(CubemapManager.CubeMapTexture.Target, TextureParameterName.TextureBaseLevel, 0);
            GL.TexParameter(CubemapManager.CubeMapTexture.Target, TextureParameterName.TextureMaxLevel, 13);
            GL.TexParameter(CubemapManager.CubeMapTexture.Target, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
            GL.TexParameter(CubemapManager.CubeMapTexture.Target, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
            GL.TexParameter(CubemapManager.CubeMapTexture.Target, TextureParameterName.TextureWrapR, (int)TextureWrapMode.ClampToEdge);
            CubemapManager.CubeMapTexture.Unbind();

            DiffuseLightmapTexture.Bind();
            GL.TexParameter(DiffuseLightmapTexture.Target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(DiffuseLightmapTexture.Target, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            GL.TexParameter(DiffuseLightmapTexture.Target, TextureParameterName.TextureBaseLevel, 0);
            GL.TexParameter(DiffuseLightmapTexture.Target, TextureParameterName.TextureMaxLevel, 2);
            GL.TexParameter(DiffuseLightmapTexture.Target, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
            GL.TexParameter(DiffuseLightmapTexture.Target, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
            GL.TexParameter(DiffuseLightmapTexture.Target, TextureParameterName.TextureWrapR, (int)TextureWrapMode.ClampToEdge);
            DiffuseLightmapTexture.Unbind();
        }
Beispiel #8
0
        void BindTexture(ShaderProgram shader, GLTexture texture, int slot, int id)
        {
            if (texture is GLTextureCube)
            {
                GL.TexParameter(texture.Target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                GL.TexParameter(texture.Target, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
                GL.TexParameter(texture.Target, TextureParameterName.TextureBaseLevel, 0);
                GL.TexParameter(texture.Target, TextureParameterName.TextureMaxLevel, 13);
            }

            GL.ActiveTexture(TextureUnit.Texture0 + id);
            texture.Bind();
            shader.SetInt($"{ConvertSamplerID(slot)}", id);
        }
Beispiel #9
0
        public static void OnRenderFloor()
        {
            float s = 10.0f, t = 10.0f;
            float e = 30.0f;

            GL.PushAttrib(AttribMask.AllAttribBits);

            GL.Disable(EnableCap.CullFace);
            GL.Disable(EnableCap.Blend);
            GL.Disable(EnableCap.Lighting);
            GL.PolygonMode(MaterialFace.Front, PolygonMode.Line);
            GL.PolygonMode(MaterialFace.Back, PolygonMode.Fill);

            //So that the model clips with the floor
            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.Texture2D);
            GL.MatrixMode(MatrixMode.Texture);
            GL.LoadIdentity();

            GLTexture bgTex = TKContext.FindOrCreate("TexBG", GLTexturePanel.CreateBG);

            bgTex.Bind();

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter,
                            (int)TextureMinFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter,
                            (int)TextureMagFilter.Nearest);

            GL.Color4(_floorHue);

            GL.Begin(BeginMode.Quads);

            GL.TexCoord2(0.0f, 0.0f);
            GL.Vertex3(-e, 0.0f, -e);
            GL.TexCoord2(s, 0.0f);
            GL.Vertex3(e, 0.0f, -e);
            GL.TexCoord2(s, t);
            GL.Vertex3(e, 0.0f, e);
            GL.TexCoord2(0.0f, t);
            GL.Vertex3(-e, 0.0f, e);

            GL.End();

            GL.Disable(EnableCap.Texture2D);

            GL.PopAttrib();
        }
Beispiel #10
0
        public static void Draw(GLContext control, GLTexture colorPass, GLTexture bloomPass)
        {
            Initialize(control);

            GL.Disable(EnableCap.Blend);
            GL.Disable(EnableCap.CullFace);

            control.CurrentShader = DefaultShaderProgram;

            DefaultShaderProgram.SetInt("ENABLE_BLOOM", 0);
            DefaultShaderProgram.SetInt("ENABLE_LUT", 0);
            DefaultShaderProgram.SetBoolToInt("ENABLE_SRGB", control.UseSRBFrameBuffer);

            GL.ActiveTexture(TextureUnit.Texture1);
            colorPass.Bind();
            DefaultShaderProgram.SetInt("uColorTex", 1);

            if (bloomPass != null && control.EnableBloom)
            {
                DefaultShaderProgram.SetInt("ENABLE_BLOOM", 1);

                GL.ActiveTexture(TextureUnit.Texture24);
                bloomPass.Bind();
                DefaultShaderProgram.SetInt("uBloomTex", 24);
            }

            /*
             *
             *
             *          if (LightingEngine.LightSettings.ColorCorrectionTable != null)
             *          {
             *              DefaultShaderProgram.SetInt("ENABLE_LUT", 1);
             *
             *              GL.ActiveTexture(TextureUnit.Texture25);
             *              LightingEngine.LightSettings.ColorCorrectionTable.Bind();
             *              DefaultShaderProgram.SetInt("uLutTex", 25);
             *          }
             */

            vao.Enable(DefaultShaderProgram);
            vao.Use();
            GL.DrawArrays(PrimitiveType.TriangleStrip, 0, Length);
            GL.BindTexture(TextureTarget.Texture2D, 0);

            GL.UseProgram(0);
        }
Beispiel #11
0
        private void CreateTexture()
        {
            ImGuiIOPtr io = ImGui.GetIO();

            io.Fonts.GetTexDataAsRGBA32(out IntPtr pixels, out int width, out int height, out int bytesPerPixel);

            texture = new GLTexture();
            texture.Bind();

            GL.TextureStorage2D((int)texture.Handle, 1, SizedInternalFormat.Rgba8, width, height);
            GL.TextureSubImage2D((int)texture.Handle, 0, 0, 0, width, height, PixelFormat.Bgra, PixelType.UnsignedByte, pixels);

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);

            io.Fonts.SetTexID((IntPtr)texture.Handle);
            io.Fonts.ClearTexData();
        }
Beispiel #12
0
        internal unsafe void Prepare(MDL0MaterialRefNode mRef, int shaderProgramHandle, string palette = null)
        {
            string plt = !String.IsNullOrEmpty(palette) ? palette : mRef.Palette;

            if (!String.IsNullOrEmpty(plt))
            {
                if (_palette == null || _palette.Name != plt)
                {
                    SetPalette(mRef.RootNode.FindChild("Palettes(NW4R)/" + plt, true) as PLT0Node);
                }
            }
            else if (_palette != null)
            {
                SetPalette(null);
            }

            if (Texture != null)
            {
                Texture.Bind(mRef.Index, shaderProgramHandle);
            }
            else
            {
                Load(mRef.Index, shaderProgramHandle);
            }

            ApplyGLTextureParameters(mRef);

            if (shaderProgramHandle <= 0)
            {
                float *p = stackalloc float[4];
                p[0] = p[1] = p[2] = p[3] = 1.0f;
                if (Selected && !ObjOnly)
                {
                    p[0] = -1.0f;
                }

                GL.Light(LightName.Light0, LightParameter.Specular, p);
                GL.Light(LightName.Light0, LightParameter.Diffuse, p);
            }
        }
Beispiel #13
0
        private unsafe void modelPanel1_PreRender(object sender, TKContext ctx)
        {
            if (RenderFloor)
            {
                GLTexture _bgTex = ctx.FindOrCreate <GLTexture>("TexBG", GLTexturePanel.CreateBG);

                float s = 10.0f, t = 10.0f;
                float e = 30.0f;

                GL.Disable(EnableCap.CullFace);
                GL.Disable(EnableCap.Blend);
                GL.Disable(EnableCap.Lighting);
                GL.PolygonMode(MaterialFace.Front, PolygonMode.Line);
                GL.PolygonMode(MaterialFace.Back, PolygonMode.Fill);

                GL.Enable(EnableCap.Texture2D);

                GL.Color4(StaticMainWindow._floorHue);

                _bgTex.Bind();

                GL.Begin(BeginMode.Quads);

                GL.TexCoord2(0.0f, 0.0f);
                GL.Vertex3(-e, 0.0f, -e);
                GL.TexCoord2(s, 0.0f);
                GL.Vertex3(e, 0.0f, -e);
                GL.TexCoord2(s, t);
                GL.Vertex3(e, 0.0f, e);
                GL.TexCoord2(0, t);
                GL.Vertex3(-e, 0.0f, e);

                GL.End();

                GL.Disable(EnableCap.Texture2D);
            }

            Attributes.PreRender();
        }
        public static void Draw(GLContext control, GLTexture screen, GLTexture brightnessTexture)
        {
            Initialize(control);

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();

            control.CurrentShader = DefaultShaderProgram;

            DefaultShaderProgram.SetFloat("exposure", 1.0f);

            GL.ActiveTexture(TextureUnit.Texture23);
            screen.Bind();
            DefaultShaderProgram.SetInt("scene", 23);

            GL.ActiveTexture(TextureUnit.Texture24);
            brightnessTexture.Bind();
            DefaultShaderProgram.SetInt("bloomBlur", 24);

            vao.Enable(DefaultShaderProgram);
            vao.Use();
            GL.DrawArrays(PrimitiveType.QuadStrip, 0, Length);
        }
        static void InitTextures()
        {
            //SMOCubemapLoader.LoadCubemap();

            MaterialLightCube = GLTextureCube.FromDDS(new DDS($"Resources\\CubemapHDR2.dds"), false, true);

            MaterialLightSphere     = GLTexture2D.FromBitmap(Resources.black);
            DirectionalLightTexture = GLTexture2D.FromGeneric(
                new DDS(new MemoryStream(Resources.HalfMap)), new ImageParameters());

            MaterialLightCube.Bind();
            GL.TexParameter(MaterialLightCube.Target, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(MaterialLightCube.Target, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
            GL.TexParameter(MaterialLightCube.Target, TextureParameterName.TextureBaseLevel, 0);
            GL.TexParameter(MaterialLightCube.Target, TextureParameterName.TextureMaxLevel, 5);
            MaterialLightCube.Unbind();

            ColorBufferTexture      = GLTexture2D.FromBitmap(Resources.black);
            DepthShadowTexture      = GLTexture2D.FromBitmap(Resources.white);
            LinearDepthTexture      = GLTexture2D.FromBitmap(Resources.black);
            ExposureTexture         = GLTexture2D.FromBitmap(Resources.white);
            RoughnessCubemapTexture = MaterialLightCube;
            Uniform0Texture         = GLTexture2D.FromBitmap(Resources.black);
        }
        //public void SetData(byte[] Data, int Width, int Height)
        //{
        //	fixed (byte* DataPtr = Data)
        //	{
        //		SetData((OutputPixel*)DataPtr, Width, Height);
        //	}
        //}

        public override void Bind()
        {
            Texture.Bind();
        }
        private void RenderBackgroundImage()
        {
            GL.PushAttrib(AttribMask.AllAttribBits);

            GL.Disable(EnableCap.DepthTest);
            GL.Disable(EnableCap.Lighting);
            GL.Disable(EnableCap.CullFace);

            GL.MatrixMode(MatrixMode.Projection);
            GL.PushMatrix();
            {
                GL.LoadIdentity();
                Matrix p = Matrix.OrthographicMatrix(0, Region.Width, 0, Region.Height, -1, 1);
                GL.LoadMatrix((float *)&p);

                GL.MatrixMode(MatrixMode.Modelview);
                GL.PushMatrix();
                {
                    GL.LoadIdentity();

                    GL.Color4(Color.White);
                    GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);

                    GL.Enable(EnableCap.Texture2D);

                    if (_updateImage)
                    {
                        if (_bgImage != null)
                        {
                            _bgImage.Delete();
                            _bgImage = null;
                        }

                        GL.ClearColor(Color.Black);

                        Bitmap bmp = BackgroundImage as Bitmap;

                        _bgImage = new GLTexture(bmp);
                        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.GenerateMipmap, 1);
                        _bgImage.Bind();

                        _updateImage = false;
                    }
                    else
                    {
                        GL.BindTexture(TextureTarget.Texture2D, _bgImage._texId);
                    }

                    float *points  = stackalloc float[8];
                    float  tAspect = (float)_bgImage.Width / (float)_bgImage.Height;
                    float  wAspect = (float)Width / (float)Height;

                    switch (_bgType)
                    {
                    case BGImageType.Stretch:

                        points[0] = points[1] = points[3] = points[6] = 0.0f;
                        points[2] = points[4] = Width;
                        points[5] = points[7] = Height;

                        break;

                    case BGImageType.Center:

                        if (tAspect > wAspect)
                        {
                            points[1] = points[3] = 0.0f;
                            points[5] = points[7] = Height;

                            points[0] = points[6] = Width * ((Width - ((float)Height / _bgImage.Height * _bgImage.Width)) / Width / 2.0f);
                            points[2] = points[4] = Width - points[0];
                        }
                        else
                        {
                            points[0] = points[6] = 0.0f;
                            points[2] = points[4] = Width;

                            points[1] = points[3] = Height * (((Height - ((float)Width / _bgImage.Width * _bgImage.Height))) / Height / 2.0f);
                            points[5] = points[7] = Height - points[1];
                        }
                        break;

                    case BGImageType.ResizeWithBars:

                        if (tAspect > wAspect)
                        {
                            points[0] = points[6] = 0.0f;
                            points[2] = points[4] = Width;

                            points[1] = points[3] = Height * (((Height - ((float)Width / _bgImage.Width * _bgImage.Height))) / Height / 2.0f);
                            points[5] = points[7] = Height - points[1];
                        }
                        else
                        {
                            points[1] = points[3] = 0.0f;
                            points[5] = points[7] = Height;

                            points[0] = points[6] = Width * ((Width - ((float)Height / _bgImage.Height * _bgImage.Width)) / Width / 2.0f);
                            points[2] = points[4] = Width - points[0];
                        }

                        break;
                    }

                    GL.Begin(BeginMode.Quads);

                    GL.TexCoord2(0.0f, 0.0f);
                    GL.Vertex2(&points[0]);
                    GL.TexCoord2(1.0f, 0.0f);
                    GL.Vertex2(&points[2]);
                    GL.TexCoord2(1.0f, 1.0f);
                    GL.Vertex2(&points[4]);
                    GL.TexCoord2(0.0f, 1.0f);
                    GL.Vertex2(&points[6]);

                    GL.End();

                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)MatTextureMinFilter.Linear);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)MatTextureMagFilter.Linear);

                    GL.Disable(EnableCap.Texture2D);
                }
                GL.PopMatrix();
            }
            GL.MatrixMode(MatrixMode.Projection);
            GL.PopMatrix();

            GL.PopAttrib();
        }
        private void GetTexVram(Action <TexturePair> Action)
        {
            if (TexVram == null)
            {
                TexVram = GLTexture.Create().SetFormat(TextureFormat.RGBA).SetSize(1, 1);
            }

            //Console.WriteLine(TexVram);

            TexVram.Bind();

            if (BufferGraphics == null)
            {
                BufferGraphics = Graphics.FromImage(Buffer);
                //BufferGraphics.Clear(Color.Red);
                BufferGraphics.Clear(Color.Black);
            }

            //if (PspDisplayForm.Singleton.WindowState == FormWindowState.Minimized)
            //{
            //	return;
            //}
            //
            //if (!PspDisplayForm.Singleton.EnableRefreshing)
            //{
            //	return;
            //}

            if (IGuiWindowInfo.EnableRefreshing)
            {
                try
                {
                    int   Width        = 512;
                    int   Height       = 272;
                    var   FrameAddress = PspDisplay.CurrentInfo.FrameAddress;
                    byte *FrameBuffer  = null;
                    byte *DepthBuffer  = null;
                    try
                    {
                        FrameBuffer = (byte *)Memory.PspAddressToPointerSafe(
                            FrameAddress,
                            PixelFormatDecoder.GetPixelsSize(PspDisplay.CurrentInfo.PixelFormat, Width * Height)
                            );
                    }
                    catch (Exception Exception)
                    {
                        Console.Error.WriteLine(Exception);
                    }

                    //Console.Error.WriteLine("FrameBuffer == 0x{0:X}!!", (long)FrameBuffer);

                    if (FrameBuffer == null)
                    {
                        //Console.Error.WriteLine("FrameBuffer == null!!");
                    }

                    //Console.WriteLine("{0:X}", Address);

                    var Hash = PixelFormatDecoder.Hash(
                        PspDisplay.CurrentInfo.PixelFormat,
                        (void *)FrameBuffer,
                        Width, Height
                        );

                    if (Hash != LastHash)
                    {
                        LastHash = Hash;
                        Buffer.LockBitsUnlock(System.Drawing.Imaging.PixelFormat.Format32bppArgb, (BitmapData) =>
                        {
                            var Count = Width * Height;
                            fixed(OutputPixel * BitmapDataDecodePtr = BitmapDataDecode)
                            {
                                var BitmapDataPtr = (BGRA *)BitmapData.Scan0.ToPointer();

                                //var LastRow = (FrameBuffer + 512 * 260 * 4 + 4 * 10);
                                //Console.WriteLine("{0},{1},{2},{3}", LastRow[0], LastRow[1], LastRow[2], LastRow[3]);

                                if (FrameBuffer == null)
                                {
                                    if (OldFrameBuffer != null)
                                    {
                                        Console.Error.WriteLine("FrameBuffer == null");
                                    }
                                }
                                else if (BitmapDataPtr == null)
                                {
                                    Console.Error.WriteLine("BitmapDataPtr == null");
                                }
                                else
                                {
                                    PixelFormatDecoder.Decode(
                                        PspDisplay.CurrentInfo.PixelFormat,
                                        (void *)FrameBuffer,
                                        BitmapDataDecodePtr,
                                        Width, Height
                                        );
                                }

                                // Converts the decoded data to Window's format.
                                for (int n = 0; n < Count; n++)
                                {
                                    BitmapDataPtr[n].R = BitmapDataDecodePtr[n].B;
                                    BitmapDataPtr[n].G = BitmapDataDecodePtr[n].G;
                                    BitmapDataPtr[n].B = BitmapDataDecodePtr[n].R;
                                    BitmapDataPtr[n].A = 0xFF;
                                }

                                OldFrameBuffer = FrameBuffer;

                                GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, 512, 272, 0, GL.GL_RGBA,
                                                GL.GL_UNSIGNED_BYTE, BitmapDataPtr);
                                TextureVerticalFlip = true;
                            }
                        });
                    }
                    //else
                    {
                        //Console.WriteLine("Display not updated!");
                    }
                }
                catch (Exception Exception)
                {
                    Console.Error.WriteLine(Exception);
                }
            }

            Action(new TexturePair()
            {
                Color = TexVram, Depth = GLTexture.Wrap(0)
            });
            return;
        }
Beispiel #19
0
        public static void CreateCubemap(GLContext control, GLTextureCube cubemapInput,
                                         GLTexture cubemapOutput, int layer)
        {
            int size = cubemapOutput.Width;

            Matrix4 projection = Matrix4.CreatePerspectiveFieldOfView(MathHelper.DegreesToRadians(90), 1.0f, 0.1f, 10.0f);

            Matrix4[] captureViews =
            {
                Matrix4.LookAt(new Vector3(0.0f, 0.0f, 0.0f), new Vector3(1.0f,   0.0f,  0.0f), new Vector3(0.0f, -1.0f,  0.0f)),
                Matrix4.LookAt(new Vector3(0.0f, 0.0f, 0.0f), new Vector3(-1.0f,  0.0f,  0.0f), new Vector3(0.0f, -1.0f,  0.0f)),
                Matrix4.LookAt(new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f,   1.0f,  0.0f), new Vector3(0.0f,  0.0f,  1.0f)),
                Matrix4.LookAt(new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f,  -1.0f,  0.0f), new Vector3(0.0f,  0.0f, -1.0f)),
                Matrix4.LookAt(new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f,   0.0f,  1.0f), new Vector3(0.0f, -1.0f,  0.0f)),
                Matrix4.LookAt(new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f,   0.0f, -1.0f), new Vector3(0.0f, -1.0f,  0.0f)),
            };

            GL.BindTexture(TextureTarget.TextureCubeMap, 0);

            //Bind the cubemap's texture into a filtered quad.
            //Bind the drawn filter to a cubemap array layer
            Framebuffer frameBuffer = new Framebuffer(FramebufferTarget.Framebuffer, size, size, PixelInternalFormat.Rgba32f);

            frameBuffer.Bind();

            GL.Disable(EnableCap.Blend);

            var cubemapFilter = GlobalShaders.GetShader("CUBEMAP_PREFILTER");

            cubemapFilter.Enable();

            //Allocate mipmaps
            cubemapOutput.Bind();
            cubemapOutput.GenerateMipmaps();
            cubemapOutput.Unbind();

            GL.ActiveTexture(TextureUnit.Texture0 + 1);
            cubemapInput.Bind();
            cubemapFilter.SetInt("environmentMap", 1);
            cubemapFilter.SetMatrix4x4("projection", ref projection);

            //Quick hack, draw once before rendering (first buffer not updating for some reason??)
            RenderTools.DrawCube();

            GL.Disable(EnableCap.CullFace);
            for (int mip = 0; mip < cubemapOutput.MipCount; mip++)
            {
                int mipWidth  = (int)(size * Math.Pow(0.5, mip));
                int mipHeight = (int)(size * Math.Pow(0.5, mip));

                frameBuffer.Resize(mipWidth, mipHeight);
                GL.Viewport(0, 0, mipWidth, mipHeight);

                float roughness = (float)mip / (float)(cubemapOutput.MipCount - 1);
                cubemapFilter.SetFloat("roughness", roughness);

                for (int i = 0; i < 6; i++)
                {
                    //attach face to fbo as color attachment 0
                    if (cubemapOutput is GLTextureCubeArray)
                    {
                        GL.FramebufferTextureLayer(FramebufferTarget.Framebuffer,
                                                   FramebufferAttachment.ColorAttachment0, cubemapOutput.ID, mip, (layer * 6) + i);
                    }
                    else
                    {
                        GL.FramebufferTexture2D(FramebufferTarget.Framebuffer,
                                                FramebufferAttachment.ColorAttachment0,
                                                TextureTarget.TextureCubeMapPositiveX + i, cubemapOutput.ID, mip);
                    }

                    cubemapFilter.SetMatrix4x4("view", ref captureViews[i]);

                    GL.ClearColor(0, 0, 0, 1);
                    GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
                    RenderTools.DrawCube();
                }
            }

            var errorcheck = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);

            if (errorcheck != FramebufferErrorCode.FramebufferComplete)
            {
                throw new Exception(errorcheck.ToString());
            }

            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
            GL.Enable(EnableCap.CullFace);
            GL.Enable(EnableCap.Blend);

            frameBuffer.Dispoe();
            frameBuffer.DisposeRenderBuffer();

            GL.UseProgram(0);
        }
Beispiel #20
0
        internal unsafe void Prepare(MDL0MaterialRefNode mRef, int shaderProgramHandle)
        {
            if (mRef.PaletteNode != null && palette == null)
            {
                palette = mRef.RootNode.FindChild("Palettes(NW4R)/" + mRef.Palette, true) as PLT0Node;
            }

            try
            {
                if (Texture != null)
                {
                    Texture.Bind(mRef.Index, shaderProgramHandle, _context);
                }
                else
                {
                    Load(mRef.Index, shaderProgramHandle, palette);
                }
            }
            catch { }

            int filter = 0;

            switch (mRef.MagFilter)
            {
            case MDL0MaterialRefNode.TextureMagFilter.Nearest:
                filter = (int)TextureMagFilter.Nearest; break;

            case MDL0MaterialRefNode.TextureMagFilter.Linear:
                filter = (int)TextureMagFilter.Linear; break;
            }
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, filter);
            switch (mRef.MinFilter)
            {
            case MDL0MaterialRefNode.TextureMinFilter.Nearest:
                filter = (int)TextureMinFilter.Nearest; break;

            case MDL0MaterialRefNode.TextureMinFilter.Linear:
                filter = (int)TextureMinFilter.Linear; break;

            case MDL0MaterialRefNode.TextureMinFilter.Nearest_Mipmap_Nearest:
                filter = (int)TextureMinFilter.NearestMipmapNearest; break;

            case MDL0MaterialRefNode.TextureMinFilter.Nearest_Mipmap_Linear:
                filter = (int)TextureMinFilter.NearestMipmapLinear; break;

            case MDL0MaterialRefNode.TextureMinFilter.Linear_Mipmap_Nearest:
                filter = (int)TextureMinFilter.LinearMipmapNearest; break;

            case MDL0MaterialRefNode.TextureMinFilter.Linear_Mipmap_Linear:
                filter = (int)TextureMinFilter.LinearMipmapLinear; break;
            }
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, filter);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureLodBias, mRef.LODBias);

            switch ((int)mRef.UWrapMode)
            {
            case 0: GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge); break;

            case 1: GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat); break;

            case 2: GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.MirroredRepeat); break;
            }

            switch ((int)mRef.VWrapMode)
            {
            case 0: GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge); break;

            case 1: GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat); break;

            case 2: GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.MirroredRepeat); break;
            }

            float *p = stackalloc float[4];

            p[0] = p[1] = p[2] = p[3] = 1.0f;
            if (Selected && !ObjOnly)
            {
                p[0] = -1.0f;
            }

            GL.Light(LightName.Light0, LightParameter.Specular, p);
            GL.Light(LightName.Light0, LightParameter.Diffuse, p);
        }
Beispiel #21
0
        public void Draw(float elapsedTime)
        {
            ImGuiIOPtr io = ImGui.GetIO();

            ImGui.NewFrame();
            ImGui.PushFont(defaultFont);

            ImGui.SetNextWindowPos(new Vector2(8, 8));

            ImGui.Begin("fps", ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoInputs
                        | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoScrollbar);

            // Apply exponential smoothing to the FPS.
            float fps = 1.0f / elapsedTime;

            avgFPS += 0.1f * (fps - avgFPS);

            ImGui.Text($"FPS {Math.Round(avgFPS)}");

            if (showInfo)
            {
                var    position  = camera.Position;
                var    direction = camera.Front;
                string posStr    = $"Pos {position.X:0.00}, {position.Y:0.00}, {position.Z:0.00}\n"
                                   + $"Dir {direction.X:0.00}, {direction.Y:0.00}, {direction.Z:0.00}\n";
                ImGui.Text(posStr);
            }

            ImGui.End();

            if (showInfo)
            {
                ImGui.SetNextWindowPos(new Vector2(width - 400 - 8, 8));
                ImGui.SetNextWindowSize(new Vector2(400, 0));

                ImGui.Begin("info", ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoSavedSettings | ImGuiWindowFlags.NoInputs
                            | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoScrollbar);

                string info = $"{vendor}\n{renderer}\n{version}\n{glsl}";
                ImGui.Text(info);

                ImGui.End();
            }

            ImGui.PopFont();
            ImGui.Render();

            ImDrawDataPtr data = ImGui.GetDrawData();

            if (data.CmdListsCount == 0)
            {
                return;
            }

            vertexArray.Bind();

            uint requiredVertexBufferSize = (uint)(data.TotalVtxCount * Unsafe.SizeOf <ImDrawVert>());

            if (requiredVertexBufferSize > vertexBufferSize)
            {
                vertexBufferSize = Math.Max(2 * vertexBufferSize, requiredVertexBufferSize);
                vertexBuffer.SetData(IntPtr.Zero, (int)vertexBufferSize, BufferUsageHint.DynamicDraw);
            }

            uint requiredIndexBufferSize = (uint)(data.TotalIdxCount * sizeof(ushort));

            if (requiredIndexBufferSize > indexBufferSize)
            {
                indexBufferSize = Math.Max(2 * indexBufferSize, requiredIndexBufferSize);
                indexBuffer.SetData(IntPtr.Zero, (int)indexBufferSize, BufferUsageHint.DynamicDraw);
            }

            uint vertexBufferOffset = 0;
            uint indexBufferOffset  = 0;

            for (int i = 0; i < data.CmdListsCount; ++i)
            {
                ImDrawListPtr list = data.CmdListsRange[i];

                uint vertexDataSize = (uint)(list.VtxBuffer.Size * Unsafe.SizeOf <ImDrawVert>());
                uint indexDataSize  = (uint)(list.IdxBuffer.Size * sizeof(ushort));

                vertexBuffer.Bind();
                GL.BufferSubData(vertexBuffer.BufferTarget, (IntPtr)vertexBufferOffset, (int)vertexDataSize, list.VtxBuffer.Data);

                indexBuffer.Bind();
                GL.BufferSubData(indexBuffer.BufferTarget, (IntPtr)indexBufferOffset, (int)indexDataSize, list.IdxBuffer.Data);

                vertexBufferOffset += vertexDataSize;
                indexBufferOffset  += indexDataSize;
            }

            Matrix4 projection = Matrix4.CreateOrthographicOffCenter(0, io.DisplaySize.X, io.DisplaySize.Y, 0, -1, 1);

            shaderProgram.Use();
            shaderProgram.SetUniform("font_texture", 0);
            shaderProgram.SetUniform("projection", ref projection);

            data.ScaleClipRects(io.DisplayFramebufferScale);

            GL.Enable(EnableCap.Blend);
            GL.Enable(EnableCap.ScissorTest);

            GL.Disable(EnableCap.CullFace);
            GL.Disable(EnableCap.DepthTest);
            GL.Disable(EnableCap.StencilTest);

            GL.BlendEquation(BlendEquationMode.FuncAdd);
            GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);

            GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);

            uint indexOffset  = 0;
            uint vertexOffset = 0;

            for (int i = 0; i < data.CmdListsCount; ++i)
            {
                ImDrawListPtr list = data.CmdListsRange[i];
                for (int j = 0; j < list.CmdBuffer.Size; ++j)
                {
                    ImDrawCmdPtr cmd = list.CmdBuffer[j];
                    if (cmd.UserCallback != IntPtr.Zero)
                    {
                        throw new NotImplementedException();
                    }
                    else
                    {
                        texture.Bind();

                        Vector4 clip = cmd.ClipRect;
                        GL.Scissor((int)clip.X, (int)height - (int)clip.W, (int)(clip.Z - clip.X), (int)(clip.W - clip.Y));

                        GL.DrawElementsBaseVertex(PrimitiveType.Triangles, (int)cmd.ElemCount, DrawElementsType.UnsignedShort, (IntPtr)(indexOffset * sizeof(ushort)), (int)vertexOffset);
                    }

                    indexOffset += cmd.ElemCount;
                }

                vertexOffset += (uint)list.VtxBuffer.Size;
            }

            VertexArray.Unbind();
        }
        private unsafe void Load(int index, int program, PLT0Node palette)
        {
            if (_context == null)
            {
                return;
            }

            Source = null;

            if (Texture != null)
            {
                Texture.Delete();
            }
            Texture = new GLTexture(_context, 0, 0);
            Texture.Bind(index, program);

            //ctx._states[String.Format("{0}_TexRef", Name)] = Texture;

            Bitmap   bmp   = null;
            TEX0Node tNode = null;

            if (_context._states.ContainsKey("_Node_Refs"))
            {
                List <ResourceNode> nodes    = _context._states["_Node_Refs"] as List <ResourceNode>;
                List <ResourceNode> searched = new List <ResourceNode>(nodes.Count);

                foreach (ResourceNode n in nodes)
                {
                    ResourceNode node = n.RootNode;
                    if (searched.Contains(node))
                    {
                        continue;
                    }
                    searched.Add(node);

                    //Search node itself first
                    if ((tNode = node.FindChild("Textures(NW4R)/" + Name, true) as TEX0Node) != null)
                    {
                        Source = tNode;
                        if (palette != null)
                        {
                            bmp = tNode.GetImage(0, palette);
                        }
                        else
                        {
                            bmp = tNode.GetImage(0);
                        }
                    }
                    else
                    {
                        //Then search node directory
                        string path = node._origPath;
                        if (path != null)
                        {
                            DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(path));
                            foreach (FileInfo file in dir.GetFiles(Name + ".*"))
                            {
                                if (file.Name.EndsWith(".tga"))
                                {
                                    Source = file.FullName;
                                    bmp    = TGA.FromFile(file.FullName);
                                    break;
                                }
                                else if (file.Name.EndsWith(".png") || file.Name.EndsWith(".tiff") || file.Name.EndsWith(".tif"))
                                {
                                    Source = file.FullName;
                                    bmp    = (Bitmap)Bitmap.FromFile(file.FullName);
                                    break;
                                }
                            }
                        }
                    }
                    if (bmp != null)
                    {
                        break;
                    }
                }
                searched.Clear();

                if (bmp != null)
                {
                    int w = bmp.Width, h = bmp.Height, size = w * h;

                    Texture._width  = w;
                    Texture._height = h;
                    //_context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MagFilter, (int)GLTextureFilter.LINEAR);
                    //_context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MinFilter, (int)GLTextureFilter.NEAREST_MIPMAP_LINEAR);
                    //_context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.BaseLevel, 0);

                    //if (tNode != null)
                    //    _context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MaxLevel, tNode.LevelOfDetail);
                    //else
                    //    _context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MaxLevel, 0);

                    BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                    try
                    {
                        using (UnsafeBuffer buffer = new UnsafeBuffer(size << 2))
                        {
                            ARGBPixel *sPtr = (ARGBPixel *)data.Scan0;
                            ABGRPixel *dPtr = (ABGRPixel *)buffer.Address;

                            for (int i = 0; i < size; i++)
                            {
                                *dPtr++ = (ABGRPixel)(*sPtr++);
                            }

                            int res = _context.gluBuild2DMipmaps(GLTextureTarget.Texture2D, GLInternalPixelFormat._4, w, h, GLPixelDataFormat.RGBA, GLPixelDataType.UNSIGNED_BYTE, buffer.Address);
                            if (res != 0)
                            {
                            }
                        }
                    }
                    finally
                    {
                        bmp.UnlockBits(data);
                        bmp.Dispose();
                    }
                }
            }
        }
Beispiel #23
0
        protected internal unsafe override void OnRender()
        {
            GLTexture _bgTex = _context.FindOrCreate <GLTexture>("TexBG", CreateBG);

            _bgTex.Bind();

            //Draw BG
            float s = (float)Width / _bgTex.Width, t = (float)Height / _bgTex.Height;

            _context.glBegin(GLPrimitiveType.Quads);

            _context.glTexCoord(0.0f, 0.0f);
            _context.glVertex(0.0f, 0.0f);
            _context.glTexCoord(s, 0.0f);
            _context.glVertex(1.0, 0.0f);
            _context.glTexCoord(s, t);
            _context.glVertex(1.0, 1.0);
            _context.glTexCoord(0, t);
            _context.glVertex(0.0f, 1.0);

            _context.glEnd();

            //Draw texture
            if ((_currentTexture != null) && (_currentTexture._id != 0))
            {
                float  tAspect = (float)_currentTexture.Width / _currentTexture.Height;
                float  wAspect = (float)Width / Height;
                float *points  = stackalloc float[8];

                if (tAspect > wAspect) //Texture is wider, use horizontal fit
                {
                    points[0] = points[6] = 0.0f;
                    points[2] = points[4] = 1.0f;

                    points[1] = points[3] = ((Height - ((float)Width / _currentTexture.Width * _currentTexture.Height))) / Height / 2.0f;
                    points[5] = points[7] = 1.0f - points[1];
                }
                else
                {
                    points[1] = points[3] = 0.0f;
                    points[5] = points[7] = 1.0f;

                    points[0] = points[6] = (Width - ((float)Height / _currentTexture.Height * _currentTexture.Width)) / Width / 2.0f;
                    points[2] = points[4] = 1.0f - points[0];
                }

                _context.glBindTexture(GLTextureTarget.Texture2D, _currentTexture._id);
                _context.glBegin(GLPrimitiveType.Quads);

                _context.glTexCoord(0.0f, 0.0f);
                _context.glVertex2v(&points[0]);
                _context.glTexCoord(1.0f, 0.0f);
                _context.glVertex2v(&points[2]);
                _context.glTexCoord(1.0f, 1.0f);
                _context.glVertex2v(&points[4]);
                _context.glTexCoord(0.0f, 1.0f);
                _context.glVertex2v(&points[6]);

                _context.glEnd();
            }
        }
Beispiel #24
0
        private unsafe void Load(int index, int program, PLT0Node palette)
        {
            if (_context == null)
            {
                return;
            }

            Source = null;

            if (Texture != null)
            {
                Texture.Delete();
            }
            Texture = new GLTexture();
            Texture.Bind(index, program, _context);

            //ctx._states[String.Format("{0}_TexRef", Name)] = Texture;

            Bitmap   bmp   = null;
            TEX0Node tNode = null;

            if (_context._states.ContainsKey("_Node_Refs"))
            {
                List <ResourceNode> nodes    = _context._states["_Node_Refs"] as List <ResourceNode>;
                List <ResourceNode> searched = new List <ResourceNode>(nodes.Count);

                foreach (ResourceNode n in nodes)
                {
                    ResourceNode node = n.RootNode;
                    if (searched.Contains(node))
                    {
                        continue;
                    }
                    searched.Add(node);

                    //Search node itself first
                    if ((tNode = node.FindChild("Textures(NW4R)/" + Name, true) as TEX0Node) != null)
                    {
                        Source = tNode;
                        if (palette != null)
                        {
                            Texture.Attach(tNode, palette);
                        }
                        else
                        {
                            Texture.Attach(tNode);
                        }
                        return;
                    }
                    else
                    {
                        //Then search node directory
                        string path = node._origPath;
                        if (path != null)
                        {
                            DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(path));
                            if (dir.Exists && Name != "<null>")
                            {
                                foreach (FileInfo file in dir.GetFiles(Name + ".*"))
                                {
                                    if (file.Name.EndsWith(".tga"))
                                    {
                                        Source = file.FullName;
                                        bmp    = TGA.FromFile(file.FullName);
                                        break;
                                    }
                                    else if (file.Name.EndsWith(".png") || file.Name.EndsWith(".tiff") || file.Name.EndsWith(".tif"))
                                    {
                                        Source = file.FullName;
                                        bmp    = (Bitmap)Bitmap.FromFile(file.FullName);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (bmp != null)
                    {
                        break;
                    }
                }
                searched.Clear();

                if (bmp != null)
                {
                    Texture.Attach(bmp);
                }
            }
        }
Beispiel #25
0
        private unsafe void Load(int index, int program)
        {
            if (TKContext.CurrentContext == null)
            {
                return;
            }

            Source = null;

            if (Texture != null)
            {
                Texture.Delete();
            }
            Texture = new GLTexture();
            Texture.Bind(index, program);

            Bitmap bmp = null;

            if (_folderWatcher.EnableRaisingEvents && !String.IsNullOrEmpty(_folderWatcher.Path))
            {
                bmp = SearchDirectory(_folderWatcher.Path + Name);
            }

            if (bmp == null && TKContext.CurrentContext._states.ContainsKey("_Node_Refs"))
            {
                List <ResourceNode> nodes    = TKContext.CurrentContext._states["_Node_Refs"] as List <ResourceNode>;
                List <ResourceNode> searched = new List <ResourceNode>(nodes.Count);
                TEX0Node            tNode    = null;

                foreach (ResourceNode n in nodes)
                {
                    ResourceNode node = n.RootNode;
                    if (searched.Contains(node))
                    {
                        continue;
                    }
                    searched.Add(node);

                    //Search node itself first
                    if ((tNode = node.FindChild("Textures(NW4R)/" + Name, true) as TEX0Node) != null)
                    {
                        Source = tNode;
                        Texture.Attach(tNode, _palette);
                        return;
                    }
                    else //Then search the directory
                    {
                        bmp = SearchDirectory(node._origPath);
                    }

                    if (bmp != null)
                    {
                        break;
                    }
                }
                searched.Clear();
            }

            if (bmp != null)
            {
                Texture.Attach(bmp);
            }
            else
            {
                Texture.Default();
            }
        }
Beispiel #26
0
 void BindTextureVertex(ShaderProgram shader, GLTexture texture, int slot, int id)
 {
     GL.ActiveTexture(TextureUnit.Texture0 + id);
     texture.Bind();
     shader.SetInt($"{ConvertSamplerID(slot, true)}", id);
 }
        internal unsafe void Prepare(GLContext ctx, MDL0MaterialRefNode mRef)
        {
            if (_context == null)
            {
                _context = ctx;
            }

            if (palette == null && mRef.PaletteNode != null)
            {
                palette = mRef.RootNode.FindChild("Palettes(NW4R)/" + mRef.Palette, true) as PLT0Node;
            }

            try
            {
                if (Texture != null)
                {
                    Texture.Bind(mRef.Index, (int)((MDL0MaterialNode)mRef.Parent).ShaderNode.programHandle);
                }
                else
                {
                    Load(mRef.Index, (int)((MDL0MaterialNode)mRef.Parent).ShaderNode.programHandle, palette);
                }
            }
            catch { }

            int filter = 0;

            switch (mRef.MagFilter)
            {
            case MDL0MaterialRefNode.TextureMagFilter.Nearest:
                filter = (int)GLTextureFilter.NEAREST; break;

            case MDL0MaterialRefNode.TextureMagFilter.Linear:
                filter = (int)GLTextureFilter.LINEAR; break;
            }
            _context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MagFilter, filter);
            switch (mRef.MinFilter)
            {
            case MDL0MaterialRefNode.TextureMinFilter.Nearest:
                filter = (int)GLTextureFilter.NEAREST; break;

            case MDL0MaterialRefNode.TextureMinFilter.Linear:
                filter = (int)GLTextureFilter.LINEAR; break;

            case MDL0MaterialRefNode.TextureMinFilter.Nearest_Mipmap_Nearest:
                filter = (int)GLTextureFilter.NEAREST_MIPMAP_NEAREST; break;

            case MDL0MaterialRefNode.TextureMinFilter.Nearest_Mipmap_Linear:
                filter = (int)GLTextureFilter.NEAREST_MIPMAP_LINEAR; break;

            case MDL0MaterialRefNode.TextureMinFilter.Linear_Mipmap_Nearest:
                filter = (int)GLTextureFilter.LINEAR_MIPMAP_NEAREST; break;

            case MDL0MaterialRefNode.TextureMinFilter.Linear_Mipmap_Linear:
                filter = (int)GLTextureFilter.LINEAR_MIPMAP_LINEAR; break;
            }
            _context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.MinFilter, filter);
            _context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.LODBias, mRef.LODBias);

            //_context.glTexParameter(GLTextureTarget.Texture2D, GLTextureParameter.BaseLevel, 0);

            float *p = stackalloc float[4];

            p[0] = p[1] = p[2] = p[3] = 1.0f;
            if (Selected && !ObjOnly)
            {
                p[0] = -1.0f;
            }

            _context.glLight(GLLightTarget.Light0, GLLightParameter.SPECULAR, p);
            _context.glLight(GLLightTarget.Light0, GLLightParameter.DIFFUSE, p);
        }
        public void Render(GLCamera cam, bool renderBG)
        {
            cam.LoadProjection();

            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Fill);
            GL.Color4(Color.White);
            GL.Enable(EnableCap.Texture2D);

            float
                halfW = (float)Width / 2.0f,
                halfH = (float)Height / 2.0f;

            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();
            GL.MatrixMode(MatrixMode.Texture);
            GL.LoadIdentity();

            if (renderBG)
            {
                GL.PushAttrib(AttribMask.TextureBit);

                GLTexture bgTex = TKContext.FindOrCreate <GLTexture>("TexBG", GLTexturePanel.CreateBG);
                bgTex.Bind();

                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);

                float
                    s = (float)Width / (float)bgTex.Width,
                    t = (float)Height / (float)bgTex.Height;

                GL.Begin(BeginMode.Quads);

                GL.TexCoord2(0.0f, 0.0f);
                GL.Vertex2(-halfW, -halfH);
                GL.TexCoord2(s, 0.0f);
                GL.Vertex2(halfW, -halfH);
                GL.TexCoord2(s, t);
                GL.Vertex2(halfW, halfH);
                GL.TexCoord2(0.0f, t);
                GL.Vertex2(-halfW, halfH);

                GL.End();

                GL.PopAttrib();
            }

            if (Tex0 == null)
            {
                return;
            }
            Tex0.Prepare(_targetMatRef, -1);
            GLTexture texture = GLTex;

            if (texture == null || texture._texId <= 0)
            {
                return;
            }

            MDL0TextureNode.ApplyGLTextureParameters(_targetMatRef);

            //These are used to match up the UV overlay to the texture underneath
            Vector2 topLeft     = new Vector2();
            Vector2 bottomRight = new Vector2();

            float texWidth  = texture.Width;
            float texHeight = texture.Height;

            float tAspect = (float)texWidth / texHeight;
            float wAspect = (float)Width / Height;

            float[] texCoord = new float[8];

            //These are used to compensate for padding added on an axis
            float xCorrect = 1.0f, yCorrect = 1.0f;

            if (tAspect > wAspect)
            {
                //Texture is wider, use horizontal fit
                //X touches the edges of the window, Y has top and bottom padding

                //X
                texCoord[0] = texCoord[6] = 0.0f;
                texCoord[2] = texCoord[4] = 1.0f;

                //Y
                texCoord[1] = texCoord[3] = (yCorrect = tAspect / wAspect) / 2.0f + 0.5f;
                texCoord[5] = texCoord[7] = 1.0f - texCoord[1];

                bottomRight = new Vector2(halfW, (((float)Height - ((float)Width / texWidth * texHeight)) / (float)Height / 2.0f - 0.5f) * (float)Height);
                topLeft     = new Vector2(-halfW, -bottomRight._y);
            }
            else
            {
                //Window is wider, use vertical fit
                //Y touches the edges of the window, X has left and right padding

                //Y
                texCoord[1] = texCoord[3] = 1.0f;
                texCoord[5] = texCoord[7] = 0.0f;

                //X
                texCoord[2] = texCoord[4] = (xCorrect = wAspect / tAspect) / 2.0f + 0.5f;
                texCoord[0] = texCoord[6] = 1.0f - texCoord[2];

                bottomRight = new Vector2(1.0f - (((float)Width - ((float)Height / texHeight * texWidth)) / Width / 2.0f - 0.5f) * (float)Width, -halfH);
                topLeft     = new Vector2(-bottomRight._x, halfH);
            }

            //Apply the texcoord bind transform first
            TextureFrameState state = _targetMatRef._bindState;

            GL.MultMatrix((float *)&state._transform);

            //Translate the texture coordinates to match where the user dragged the camera
            //Divide by width and height to convert window units (0 to w, 0 to h) to texcoord units (0 to 1)
            //Then multiply by the correction value if the window is bigger than the texture on an axis
            Vector3 point = cam.GetPoint();

            GL.Translate(point._x / Width * xCorrect, -point._y / Height * yCorrect, 0);

            //Now to scale the texture after translating.
            //The scale origin is the top left of the texture on the window (not of the window itself),
            //so we need to translate the center of the texture to that origin,
            //scale it up or down, then translate it back to where it was.
            OpenTK.Vector3 trans = new OpenTK.Vector3(-topLeft._x / Width * xCorrect, topLeft._y / Height * yCorrect, 0.0f);
            GL.Translate(trans);
            GL.Scale((OpenTK.Vector3)cam._scale);
            GL.Translate(-trans);

            //Bind the material ref's texture
            GL.BindTexture(TextureTarget.Texture2D, texture._texId);

            //Draw a quad across the screen and render the texture with the calculated texcoords
            GL.Begin(BeginMode.Quads);

            GL.TexCoord2(texCoord[0], texCoord[1]);
            GL.Vertex2(-halfW, -halfH);
            GL.TexCoord2(texCoord[2], texCoord[3]);
            GL.Vertex2(halfW, -halfH);
            GL.TexCoord2(texCoord[4], texCoord[5]);
            GL.Vertex2(halfW, halfH);
            GL.TexCoord2(texCoord[6], texCoord[7]);
            GL.Vertex2(-halfW, halfH);

            GL.End();
            GL.Disable(EnableCap.Texture2D);

            //Now load the camera transform and draw the UV overlay over the texture
            cam.LoadModelView();

            //Color the lines limegreen, a bright color that probably won't be in a texture
            GL.Color4(Color.LimeGreen);

            Vector2 mdlScale = new Vector2(bottomRight._x - topLeft._x, bottomRight._y - topLeft._y);

            GL.Translate(topLeft._x, topLeft._y, 0.0f);
            GL.Scale(mdlScale._x, mdlScale._y, 1.0f);

            GL.PolygonMode(MaterialFace.FrontAndBack, PolygonMode.Line);
            GL.LineWidth(1);

            //Render texture coordinates as vertex points
            foreach (RenderInfo info in _renderInfo)
            {
                info.PrepareStream();
            }
        }
Beispiel #29
0
        public static unsafe void RenderBGTexture(int width, int height, GLTexture texture, ref float[] points)
        {
            GLTexture bgTex = TKContext.FindOrCreate <GLTexture>("TexBG", CreateBG);

            bgTex.Bind();

            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);

            //Draw BG
            float s = (float)width / (float)bgTex.Width, t = (float)height / (float)bgTex.Height;

            GL.Begin(BeginMode.Quads);

            GL.TexCoord2(0.0f, 0.0f);
            GL.Vertex2(0.0f, 0.0f);
            GL.TexCoord2(s, 0.0f);
            GL.Vertex2(1.0, 0.0f);
            GL.TexCoord2(s, t);
            GL.Vertex2(1.0, 1.0);
            GL.TexCoord2(0, t);
            GL.Vertex2(0.0f, 1.0);

            GL.End();

            //Draw texture
            if ((texture != null) && (texture._texId != 0))
            {
                float tAspect = (float)texture.Width / texture.Height;
                float wAspect = (float)width / height;

                if (tAspect > wAspect) //Texture is wider, use horizontal fit
                {
                    points[0] = points[6] = 0.0f;
                    points[2] = points[4] = 1.0f;

                    points[1] = points[3] = ((height - ((float)width / texture.Width * texture.Height))) / height / 2.0f;
                    points[5] = points[7] = 1.0f - points[1];
                }
                else
                {
                    points[1] = points[3] = 0.0f;
                    points[5] = points[7] = 1.0f;

                    points[0] = points[6] = (width - ((float)height / texture.Height * texture.Width)) / width / 2.0f;
                    points[2] = points[4] = 1.0f - points[0];
                }

                GL.BindTexture(TextureTarget.Texture2D, texture._texId);

                GL.Begin(BeginMode.Quads);

                GL.TexCoord2(0.0f, 0.0f);
                GL.Vertex2(points[0], points[1]);
                GL.TexCoord2(1.0f, 0.0f);
                GL.Vertex2(points[2], points[3]);
                GL.TexCoord2(1.0f, 1.0f);
                GL.Vertex2(points[4], points[5]);
                GL.TexCoord2(0.0f, 1.0f);
                GL.Vertex2(points[6], points[7]);

                GL.End();
            }
        }
Beispiel #30
0
        protected internal unsafe override void OnRender(TKContext ctx, PaintEventArgs e)
        {
            GLTexture _bgTex = ctx.FindOrCreate <GLTexture>("TexBG", CreateBG);

            _bgTex.Bind();

            //Draw BG
            float s = (float)Width / (float)_bgTex.Width, t = (float)Height / (float)_bgTex.Height;

            GL.Begin(BeginMode.Quads);

            GL.TexCoord2(0.0f, 0.0f);
            GL.Vertex2(0.0f, 0.0f);
            GL.TexCoord2(s, 0.0f);
            GL.Vertex2(1.0, 0.0f);
            GL.TexCoord2(s, t);
            GL.Vertex2(1.0, 1.0);
            GL.TexCoord2(0, t);
            GL.Vertex2(0.0f, 1.0);

            GL.End();

            //Draw texture
            if ((_currentTexture != null) && (_currentTexture._texId != 0))
            {
                float  tAspect = (float)_currentTexture.Width / _currentTexture.Height;
                float  wAspect = (float)Width / Height;
                float *points  = stackalloc float[8];

                if (tAspect > wAspect) //Texture is wider, use horizontal fit
                {
                    points[0] = points[6] = 0.0f;
                    points[2] = points[4] = 1.0f;

                    points[1] = points[3] = ((Height - ((float)Width / _currentTexture.Width * _currentTexture.Height))) / Height / 2.0f;
                    points[5] = points[7] = 1.0f - points[1];
                }
                else
                {
                    points[1] = points[3] = 0.0f;
                    points[5] = points[7] = 1.0f;

                    points[0] = points[6] = (Width - ((float)Height / _currentTexture.Height * _currentTexture.Width)) / Width / 2.0f;
                    points[2] = points[4] = 1.0f - points[0];
                }

                GL.BindTexture(TextureTarget.Texture2D, _currentTexture._texId);

                GL.Begin(BeginMode.Quads);

                GL.TexCoord2(0.0f, 0.0f);
                GL.Vertex2(&points[0]);
                GL.TexCoord2(1.0f, 0.0f);
                GL.Vertex2(&points[2]);
                GL.TexCoord2(1.0f, 1.0f);
                GL.Vertex2(&points[4]);
                GL.TexCoord2(0.0f, 1.0f);
                GL.Vertex2(&points[6]);

                GL.End();
            }
        }
 protected virtual void BindTexture(GLTextureUnit aUnit, GLTexture aTexture)
 {
     // We want to turn off filtering.  We do that by using 'nearest'
     // we also clamp the coordinates instead of replicating at the edges
     aUnit.Bind();
     aTexture.Bind();
     GI.TexParameter(TextureParameterTarget.Texture2d, TextureParameterName.TextureMinFilter, TextureMinFilter.Nearest);
     GI.TexParameter(TextureParameterTarget.Texture2d, TextureParameterName.TextureMagFilter, TextureMagFilter.Nearest);
     GI.TexParameter(TextureParameterTarget.Texture2d, TextureParameterName.TextureWrapS, TextureWrapMode.Clamp);
     GI.TexParameter(TextureParameterTarget.Texture2d, TextureParameterName.TextureWrapT, TextureWrapMode.Clamp);
 }