Esempio n. 1
0
 /**
  * Set Sampler
  **/
 public void SetSampler(TextureUnit sindex, ITexture tex)
 {
     GL.ActiveTexture(sindex);
 }
Esempio n. 2
0
        private void RenderImDrawData(ImDrawDataPtr draw_data)
        {
            uint vertexOffsetInVertices = 0;
            uint indexOffsetInElements  = 0;

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

            uint totalVBSize = (uint)(draw_data.TotalVtxCount * Unsafe.SizeOf <ImDrawVert>());

            if (totalVBSize > _vertexBufferSize)
            {
                int newSize = (int)Math.Max(_vertexBufferSize * 1.5f, totalVBSize);
                GL.NamedBufferData(_vertexBuffer, newSize, IntPtr.Zero, BufferUsageHint.DynamicDraw);
                _vertexBufferSize = newSize;

                Console.WriteLine($"Resized vertex buffer to new size {_vertexBufferSize}");
            }

            uint totalIBSize = (uint)(draw_data.TotalIdxCount * sizeof(ushort));

            if (totalIBSize > _indexBufferSize)
            {
                int newSize = (int)Math.Max(_indexBufferSize * 1.5f, totalIBSize);
                GL.NamedBufferData(_indexBuffer, newSize, IntPtr.Zero, BufferUsageHint.DynamicDraw);
                _indexBufferSize = newSize;

                Console.WriteLine($"Resized index buffer to new size {_indexBufferSize}");
            }


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

                GL.NamedBufferSubData(_vertexBuffer, (IntPtr)(vertexOffsetInVertices * Unsafe.SizeOf <ImDrawVert>()), cmd_list.VtxBuffer.Size * Unsafe.SizeOf <ImDrawVert>(), cmd_list.VtxBuffer.Data);
                Util.CheckGLError($"Data Vert {i}");
                GL.NamedBufferSubData(_indexBuffer, (IntPtr)(indexOffsetInElements * sizeof(ushort)), cmd_list.IdxBuffer.Size * sizeof(ushort), cmd_list.IdxBuffer.Data);

                Util.CheckGLError($"Data Idx {i}");

                vertexOffsetInVertices += (uint)cmd_list.VtxBuffer.Size;
                indexOffsetInElements  += (uint)cmd_list.IdxBuffer.Size;
            }

            // Setup orthographic projection matrix into our constant buffer
            ImGuiIOPtr io  = ImGui.GetIO();
            Matrix4    mvp = Matrix4.CreateOrthographicOffCenter(
                -1.0f,
                io.DisplaySize.X,
                io.DisplaySize.Y,
                0.0f,
                -1.0f,
                1.0f);

            _shader.UseShader();
            GL.ProgramUniformMatrix4(_shader.Program, _shader.GetUniformLocation("projection_matrix"), false, ref mvp);
            GL.ProgramUniform1(_shader.Program, _shader.GetUniformLocation("in_fontTexture"), 0);
            Util.CheckGLError("Projection");

            GL.BindVertexArray(_vertexArray);
            Util.CheckGLError("VAO");

            draw_data.ScaleClipRects(io.DisplayFramebufferScale);

            GL.Enable(EnableCap.Blend);
            GL.Enable(EnableCap.ScissorTest);
            GL.BlendEquation(BlendEquationMode.FuncAdd);
            GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
            GL.Disable(EnableCap.CullFace);
            GL.Disable(EnableCap.DepthTest);

            // Render command lists
            int vtx_offset = 0;
            int idx_offset = 0;

            for (int n = 0; n < draw_data.CmdListsCount; n++)
            {
                ImDrawListPtr cmd_list = draw_data.CmdListsRange[n];
                for (int cmd_i = 0; cmd_i < cmd_list.CmdBuffer.Size; cmd_i++)
                {
                    ImDrawCmdPtr pcmd = cmd_list.CmdBuffer[cmd_i];
                    if (pcmd.UserCallback != IntPtr.Zero)
                    {
                        throw new NotImplementedException();
                    }
                    else
                    {
                        GL.ActiveTexture(TextureUnit.Texture0);
                        GL.BindTexture(TextureTarget.Texture2D, (int)pcmd.TextureId);
                        Util.CheckGLError("Texture");

                        // We do _windowHeight - (int)clip.W instead of (int)clip.Y because gl has flipped Y when it comes to these coordinates
                        var clip = pcmd.ClipRect;
                        GL.Scissor((int)clip.X, _windowHeight - (int)clip.W, (int)(clip.Z - clip.X), (int)(clip.W - clip.Y));
                        Util.CheckGLError("Scissor");

                        GL.DrawElementsBaseVertex(PrimitiveType.Triangles, (int)pcmd.ElemCount, DrawElementsType.UnsignedShort, (IntPtr)(idx_offset * sizeof(ushort)), vtx_offset);
                        Util.CheckGLError("Draw");
                    }

                    idx_offset += (int)pcmd.ElemCount;
                }
                vtx_offset += cmd_list.VtxBuffer.Size;
            }

            GL.Disable(EnableCap.Blend);
            GL.Disable(EnableCap.ScissorTest);
        }
Esempio n. 3
0
        /// <summary>
        /// Generates the font image, the VAO and the <see cref="CharSheet"/> storing all <see cref="Character"/>
        /// </summary>
        /// <param name="rect">The rect.</param>
        public void GenerateFontImage(GLRectangleF rect)
        {
            int bitmapWidth  = _glyphsPerLine * _glyphWidth;    //calculate bitmap dimensions
            int bitmapHeight = _glyphLineCount * _glyphHeight;

            //generating the bitmap and setting it up first
            using (Bitmap bitmap = new Bitmap(bitmapWidth, bitmapHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb))
            {
                Font font;
                font = new Font(new FontFamily(_fontName), _fontSize, FontStyle.Regular, GraphicsUnit.Pixel);

                using (var g = Graphics.FromImage(bitmap))
                {
                    if (_bitmapFont)
                    {
                        g.SmoothingMode     = SmoothingMode.None;
                        g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
                    }
                    else
                    {
                        g.SmoothingMode     = SmoothingMode.HighQuality;
                        g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
                    }
                    //draw each character onto the bitmap
                    for (int p = 0; p < _glyphLineCount; p++)
                    {
                        for (int n = 0; n < _glyphsPerLine; n++)
                        {
                            char c = (char)(n + p * _glyphsPerLine);
                            g.DrawString(c.ToString(), font, Brushes.Black,
                                         n * _glyphWidth + _atlasOffsetX, p * _glyphHeight + _atlasOffsetY);
                        }
                    }
                }
                bitmap.Save(_fontBitmapFilename);//save the bitmap
                _textureWidth = bitmap.Width; _textureHeight = bitmap.Height;
            }

            _shaders.TextShader.Use();
            //bind the bitmap to an OpenGL Texture
            _fontTextureID = GL.GenTexture();

            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, _fontTextureID);

            using (var image = new Bitmap(_fontBitmapFilename))
            {//load the bitmap into OpenGL
                var data = image.LockBits(
                    new Rectangle(0, 0, image.Width, image.Height),
                    ImageLockMode.ReadOnly,
                    System.Drawing.Imaging.PixelFormat.Format32bppArgb);

                GL.TexImage2D(TextureTarget.Texture2D,
                              0,
                              PixelInternalFormat.Rgba,
                              image.Width,
                              image.Height,
                              0,
                              OpenTK.Graphics.OpenGL4.PixelFormat.Bgra,
                              PixelType.UnsignedByte,
                              data.Scan0);
            }
            //set up the filters for the bitmap
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
            //generate the VAO and bind it
            _VAO = GL.GenVertexArray();
            GL.BindVertexArray(_VAO);
            //enable the vertex attribute arrays, very important otherwise no vertix can be loaded into OpenGL
            GL.EnableVertexAttribArray(_shaders.TextShader.TexCoordLocation);
            GL.EnableVertexAttribArray(_shaders.TextShader.VertexLocation);
            //generate the CharSheet from the information about the bitmap
            _charSheet = new CharSheet(_glyphLineCount, _glyphsPerLine, _glyphHeight, _glyphWidth, _textureWidth, _textureHeight, rect);
            //set the attribpointers to tell the Shader how the Vertices will be passed.
            GL.VertexAttribPointer(_shaders.TextShader.VertexLocation, 2, VertexAttribPointerType.Float, false, 4 * sizeof(float), 0);

            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, _fontTextureID);
            GL.VertexAttribPointer(_shaders.TextShader.TexCoordLocation, 2, VertexAttribPointerType.Float, false, 4 * sizeof(float), 2 * sizeof(float));

            GL.BindVertexArray(0);
            _shaders.TextShader.StopUse();
            GL.Enable(EnableCap.Blend);//enable blending for the bitmap
            GL.BlendFunc(BlendingFactor.SrcAlpha, BlendingFactor.OneMinusSrcAlpha);
        }
Esempio n. 4
0
 public void Bind(TextureUnit texU)
 {
     GL.ActiveTexture(texU);
     GL.BindTexture(textureTarget, _texture);
 }
Esempio n. 5
0
        private void PrepareBoneInformation(SepdChunk sepd, PrmsChunk prms)
        {
            /* TODO!! B/C HURR DURR, DON'T KNOW  https://www.the-gcn.com/topic/2859-oot-3d-3ds-model-format-discussion/page-3#entry46121 */
            if (prms.SkinningMode == PrmsChunk.SkinningModes.PerVertex)
            {
                uint[] lookupInts = new uint[(int)(Root.VatrChunk.BoneIndexLookup.Length - sepd.BoneIndexLookupArrayOffset) / sepd.BoneIndexLookupSize];
                for (int i = 0; i < lookupInts.Length; i++)
                {
                    switch (sepd.BoneIndexLookupArrayDataType)
                    {
                    case Constants.PicaDataType.Byte:
                    case Constants.PicaDataType.UnsignedByte:
                        lookupInts[i] = (uint)Root.VatrChunk.BoneIndexLookup[sepd.BoneIndexLookupArrayOffset + (i * sizeof(byte))];
                        break;

                    case Constants.PicaDataType.Short:
                    case Constants.PicaDataType.UnsignedShort:
                        lookupInts[i] = (uint)BitConverter.ToUInt16(Root.VatrChunk.BoneIndexLookup, (int)(sepd.BoneIndexLookupArrayOffset + (i * sizeof(ushort))));
                        break;

                    case Constants.PicaDataType.Int:
                    case Constants.PicaDataType.UnsignedInt:
                        lookupInts[i] = (uint)BitConverter.ToUInt32(Root.VatrChunk.BoneIndexLookup, (int)(sepd.BoneIndexLookupArrayOffset + (i * sizeof(uint))));
                        break;

                    case Constants.PicaDataType.Float:
                        lookupInts[i] = (uint)BitConverter.ToSingle(Root.VatrChunk.BoneIndexLookup, (int)(sepd.BoneIndexLookupArrayOffset + (i * sizeof(float))));
                        break;
                    }
                }

                GL.ActiveTexture(TextureUnit.Texture0 + vertBoneTexUnit);
                GL.BindTexture(TextureTarget.TextureBuffer, vertBoneTexId);

                GL.BindBuffer(BufferTarget.TextureBuffer, vertBoneBufferId);
                GL.BufferData <uint>(BufferTarget.TextureBuffer, new IntPtr(lookupInts.Length * sizeof(uint)), lookupInts, BufferUsageHint.StaticDraw);
                GL.BindBuffer(BufferTarget.TextureBuffer, 0);
            }

            /* Maaaaaaybe? I dunno... not using this yet either */
            Vector2[] weights = new Vector2[(int)(Root.VatrChunk.BoneWeights.Length - sepd.BoneWeightArrayOffset) / 2];
            for (int i = 0, j = 0; i < weights.Length; i++, j += 2)
            {
                weights[i] = new Vector2(
                    Root.VatrChunk.BoneWeights[sepd.BoneWeightArrayOffset + j],
                    Root.VatrChunk.BoneWeights[sepd.BoneWeightArrayOffset + (j + 1)]);
            }

            for (int i = 0; i < prms.BoneIndexCount; i++)
            {
                Matrix4 matrix = Matrix4.Identity;

                SklChunk.Bone bone = Root.SklChunk.Bones.FirstOrDefault(x => x.BoneID == prms.BoneIndices[i]);
                if (bone != null)
                {
                    matrix = bone.GetMatrix(prms.SkinningMode != PrmsChunk.SkinningModes.PerVertexNoTrans);
                }

                GL.UniformMatrix4(GL.GetUniformLocation(program, string.Format("boneMatrix[{0}]", i)), false, ref matrix);
            }
        }
Esempio n. 6
0
 public void BindBuffers(ref Texture tex)
 {
     GL.ActiveTexture(TextureUnit.Texture0);
     GL.BindTexture(TextureTarget.Texture2D, tex.TBO);           //was 0
 }
Esempio n. 7
0
        float UniformOffsetY = 1.8f;             // fractal vertical offset

        #endregion private Fields

        #region OnLoad

        /// <summary>
        /// Setup OpenGL and load resources here.
        /// </summary>
        /// <param name="e">Not used.</param>
        protected override void OnLoad(EventArgs e)
        {
            // Check for necessary capabilities:
            string version = GL.GetString(StringName.Version);
            int    major   = (int)version[0];
            int    minor   = (int)version[2];

            if (major < 2)
            {
                MessageBox.Show("You need at least OpenGL 2.0 to run this example. Aborting.",
                                "GLSL not supported", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                this.Exit();
            }

            this.VSync = VSyncMode.On;

            GL.Disable(EnableCap.Dither);
            GL.ClearColor(0.2f, 0f, 0.4f, 0f);

            // declare some variables for tracking which shader did compile, and which texture to use
            string[] ShaderFilenames = new string[2];
            ShaderFilenames[0] = "Data/Shaders/JuliaSet_SM3_FS.glsl";
            ShaderFilenames[1] = "Data/Shaders/JuliaSet_SM2_FS.glsl";

            byte   CurrentOption = 0;
            string LogInfo;

            #region Shaders
            // Load&Compile Vertex Shader
            using (StreamReader sr = new StreamReader("Data/Shaders/JuliaSet_VS.glsl"))
            {
                VertexShaderObject = GL.CreateShader(ShaderType.VertexShader);
                GL.ShaderSource(VertexShaderObject, sr.ReadToEnd());
                GL.CompileShader(VertexShaderObject);
            }

            GL.GetShaderInfoLog(VertexShaderObject, out LogInfo);
            if (LogInfo.Length > 0 && !LogInfo.Contains("hardware"))
            {
                Trace.WriteLine("Vertex Shader Log:\n" + LogInfo);
            }
            else
            {
                Trace.WriteLine("Vertex Shader compiled without complaint.");
            }

            // Load&Compile Fragment Shader


            FragmentShaderObject = GL.CreateShader(ShaderType.FragmentShader);
            do
            {
                using (StreamReader sr = new StreamReader(ShaderFilenames[CurrentOption]))
                {
                    GL.ShaderSource(FragmentShaderObject, sr.ReadToEnd());
                    GL.CompileShader(FragmentShaderObject);
                }
                GL.GetShaderInfoLog(FragmentShaderObject, out LogInfo);

                if (LogInfo.Length > 0 && !LogInfo.Contains("hardware"))
                {
                    Trace.WriteLine("Compiling " + ShaderFilenames[CurrentOption] + " failed!\nLog:\n" + LogInfo);
                }
                else
                {
                    Trace.WriteLine("Fragment Shader compiled without complaint.");
                    break;
                }

                if (++CurrentOption > 1)
                {
                    MessageBox.Show("Neither SM2 nor SM3 Fragment Shader compiled successfully. Aborting.",
                                    "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Exit();
                }
            } while (true);

            // Link the Shaders to a usable Program
            ProgramObject = GL.CreateProgram();
            GL.AttachShader(ProgramObject, VertexShaderObject);
            GL.AttachShader(ProgramObject, FragmentShaderObject);
            GL.LinkProgram(ProgramObject);

            // make current
            GL.UseProgram(ProgramObject);

            // Flag ShaderObjects for delete when app exits
            GL.DeleteShader(VertexShaderObject);
            GL.DeleteShader(FragmentShaderObject);
            #endregion Shaders

            #region Textures

            // Load&Bind the 1D texture for color lookups
            GL.ActiveTexture(TextureUnit.Texture0); // select TMU0
            GL.GenTextures(1, out TextureObject);
            GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
            GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
            GL.TexParameter(TextureTarget.Texture1D, TextureParameterName.TextureWrapS, (int)(TextureWrapMode)All.ClampToEdge);

            using (Bitmap bitmap = new Bitmap("Data/Textures/JuliaColorTable.bmp"))
            {
                BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly,
                                                  System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                GL.TexImage1D(TextureTarget.Texture1D, 0, PixelInternalFormat.Rgb8, data.Width, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgr,
                              PixelType.UnsignedByte, data.Scan0);
                bitmap.UnlockBits(data);
            }
            #endregion Textures

            Keyboard.KeyUp += KeyUp;
        }
        public override void Draw(GL_ControlModern control, Pass pass)
        {
            if (!Runtime.OpenTKInitialized || !Runtime.PBR.UseSkybox || pass == Pass.TRANSPARENT)
            {
                return;
            }

            GL.Disable(EnableCap.CullFace);

            GL.Enable(EnableCap.DepthTest);
            GL.DepthFunc(DepthFunction.Lequal);

            //    GL.Enable(EnableCap.LineSmooth);

            //   GL.Enable(EnableCap.StencilTest);
            //  GL.StencilOp(StencilOp.Keep, StencilOp.Keep, StencilOp.Replace);


            control.CurrentShader = defaultShaderProgram;
            // enable seamless cubemap sampling for lower mip levels in the pre-filter map.
            GL.Enable(EnableCap.TextureCubeMapSeamless);

            Matrix4 proj = control.ProjectionMatrix;
            //  Matrix4 rot = Matrix4.CreateFromQuaternion(control.ModelMatrix.ExtractRotation());
            Matrix4 rot = new Matrix4(new Matrix3(control.CameraMatrix));

            defaultShaderProgram.SetMatrix4x4("projection", ref proj);
            defaultShaderProgram.SetMatrix4x4("rotView", ref rot);

            if (CustomCubemap != null)
            {
                GL.ActiveTexture(TextureUnit.Texture0);
                CustomCubemap.Bind();
            }
            else
            {
                if (Runtime.PBR.UseDiffuseSkyTexture)
                {
                    //Load Cubemap
                    if (RenderTools.diffusePbr != null)
                    {
                        GL.ActiveTexture(TextureUnit.Texture0);

                        RenderTools.diffusePbr.Bind();
                    }
                }
                else
                {
                    //Load Cubemap
                    if (RenderTools.specularPbr != null)
                    {
                        GL.ActiveTexture(TextureUnit.Texture0);
                        RenderTools.specularPbr.Bind();
                    }
                }
            }

            int cubeVBO = 0;

            if (cubeVBO == 0)
            {
                float[] vertices =
                {
                    // back face
                    -1.0f, -1.0f, -1.0f,  0.0f,  0.0f, -1.0f, 0.0f, 0.0f, // bottom-left
                    1.0f,   1.0f, -1.0f,  0.0f,  0.0f, -1.0f, 1.0f, 1.0f, // top-right
                    1.0f,  -1.0f, -1.0f,  0.0f,  0.0f, -1.0f, 1.0f, 0.0f, // bottom-right
                    1.0f,   1.0f, -1.0f,  0.0f,  0.0f, -1.0f, 1.0f, 1.0f, // top-right
                    -1.0f, -1.0f, -1.0f,  0.0f,  0.0f, -1.0f, 0.0f, 0.0f, // bottom-left
                    -1.0f,  1.0f, -1.0f,  0.0f,  0.0f, -1.0f, 0.0f, 1.0f, // top-left
                    // front face
                    -1.0f, -1.0f,  1.0f,  0.0f,  0.0f,  1.0f, 0.0f, 0.0f, // bottom-left
                    1.0f,  -1.0f,  1.0f,  0.0f,  0.0f,  1.0f, 1.0f, 0.0f, // bottom-right
                    1.0f,   1.0f,  1.0f,  0.0f,  0.0f,  1.0f, 1.0f, 1.0f, // top-right
                    1.0f,   1.0f,  1.0f,  0.0f,  0.0f,  1.0f, 1.0f, 1.0f, // top-right
                    -1.0f,  1.0f,  1.0f,  0.0f,  0.0f,  1.0f, 0.0f, 1.0f, // top-left
                    -1.0f, -1.0f,  1.0f,  0.0f,  0.0f,  1.0f, 0.0f, 0.0f, // bottom-left
                    // left face
                    -1.0f,  1.0f,  1.0f, -1.0f,  0.0f,  0.0f, 1.0f, 0.0f, // top-right
                    -1.0f,  1.0f, -1.0f, -1.0f,  0.0f,  0.0f, 1.0f, 1.0f, // top-left
                    -1.0f, -1.0f, -1.0f, -1.0f,  0.0f,  0.0f, 0.0f, 1.0f, // bottom-left
                    -1.0f, -1.0f, -1.0f, -1.0f,  0.0f,  0.0f, 0.0f, 1.0f, // bottom-left
                    -1.0f, -1.0f,  1.0f, -1.0f,  0.0f,  0.0f, 0.0f, 0.0f, // bottom-right
                    -1.0f,  1.0f,  1.0f, -1.0f,  0.0f,  0.0f, 1.0f, 0.0f, // top-right
                    // right face
                    1.0f,   1.0f,  1.0f,  1.0f,  0.0f,  0.0f, 1.0f, 0.0f, // top-left
                    1.0f,  -1.0f, -1.0f,  1.0f,  0.0f,  0.0f, 0.0f, 1.0f, // bottom-right
                    1.0f,   1.0f, -1.0f,  1.0f,  0.0f,  0.0f, 1.0f, 1.0f, // top-right
                    1.0f,  -1.0f, -1.0f,  1.0f,  0.0f,  0.0f, 0.0f, 1.0f, // bottom-right
                    1.0f,   1.0f,  1.0f,  1.0f,  0.0f,  0.0f, 1.0f, 0.0f, // top-left
                    1.0f,  -1.0f,  1.0f,  1.0f,  0.0f,  0.0f, 0.0f, 0.0f, // bottom-left
                    // bottom face
                    -1.0f, -1.0f, -1.0f,  0.0f, -1.0f,  0.0f, 0.0f, 1.0f, // top-right
                    1.0f,  -1.0f, -1.0f,  0.0f, -1.0f,  0.0f, 1.0f, 1.0f, // top-left
                    1.0f,  -1.0f,  1.0f,  0.0f, -1.0f,  0.0f, 1.0f, 0.0f, // bottom-left
                    1.0f,  -1.0f,  1.0f,  0.0f, -1.0f,  0.0f, 1.0f, 0.0f, // bottom-left
                    -1.0f, -1.0f,  1.0f,  0.0f, -1.0f,  0.0f, 0.0f, 0.0f, // bottom-right
                    -1.0f, -1.0f, -1.0f,  0.0f, -1.0f,  0.0f, 0.0f, 1.0f, // top-right
                    // top face
                    -1.0f,  1.0f, -1.0f,  0.0f,  1.0f,  0.0f, 0.0f, 1.0f, // top-left
                    1.0f,   1.0f,  1.0f,  0.0f,  1.0f,  0.0f, 1.0f, 0.0f, // bottom-right
                    1.0f,   1.0f, -1.0f,  0.0f,  1.0f,  0.0f, 1.0f, 1.0f, // top-right
                    1.0f,   1.0f,  1.0f,  0.0f,  1.0f,  0.0f, 1.0f, 0.0f, // bottom-right
                    -1.0f,  1.0f, -1.0f,  0.0f,  1.0f,  0.0f, 0.0f, 1.0f, // top-left
                    -1.0f,  1.0f,  1.0f,  0.0f,  1.0f,  0.0f, 0.0f, 0.0f  // bottom-left
                };

                GL.GenVertexArrays(1, out cubeVBO);
                GL.GenBuffers(1, out cubeVBO);
                GL.BindBuffer(BufferTarget.ArrayBuffer, cubeVBO);
                GL.BufferData(BufferTarget.ArrayBuffer, 4 * vertices.Length, vertices, BufferUsageHint.StaticDraw);
                GL.BindVertexArray(cubeVBO);
                GL.EnableVertexAttribArray(0);
                GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 8 * sizeof(float), (IntPtr)0);
                GL.EnableVertexAttribArray(1);
                GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 8 * sizeof(float), (IntPtr)(3 * sizeof(float)));
                GL.EnableVertexAttribArray(2);
                GL.VertexAttribPointer(2, 2, VertexAttribPointerType.Float, false, 8 * sizeof(float), (IntPtr)(6 * sizeof(float)));
                GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
                GL.BindVertexArray(0);
            }
            GL.BindVertexArray(cubeVBO);
            GL.DrawArrays(PrimitiveType.Triangles, 0, 36);
            GL.BindVertexArray(0);

            GL.Enable(EnableCap.CullFace);
        }
Esempio n. 9
0
 public override void Bind(int texu)
 {
     GL.ActiveTexture(TextureUnit.Texture0 + texu);
     GL.Enable(EnableCap.TextureCubeMap);
     GL.BindTexture(TextureTarget.TextureCubeMap, ID);
 }
Esempio n. 10
0
        private void SetTextureUniforms(ShaderProgram shader, HSFMaterialWrapper mat)
        {
            if (uboAtt == -1)
            {
                SetAttributeUBO();
            }

            var index = GL.GetUniformBlockIndex(shader.program, "AttributeBlock");

            GL.UniformBlockBinding(shader.program, index, 0);

            GL.BindBuffer(BufferTarget.UniformBuffer, uboAtt);
            GL.BufferData(BufferTarget.UniformBuffer, TextureAttribute.Size, IntPtr.Zero, BufferUsageHint.StaticDraw);
            GL.BindBufferBase(BufferRangeTarget.UniformBuffer, index, uboAtt);
            GL.BindBuffer(BufferTarget.UniformBuffer, 0);

            LoadDebugTextureMaps(shader);

            GL.ActiveTexture(TextureUnit.Texture0 + 1);
            GL.BindTexture(TextureTarget.Texture2D, RenderTools.defaultTex.RenderableTex.TexID);

            shader.SetInt("textureCount", mat.TextureMaps.Count);
            Console.WriteLine($"textureCount {mat.TextureMaps.Count}");

            TextureAttribute[] attriutes = new TextureAttribute[6];
            for (int i = 0; i < 6; i++)
            {
                if (i == 1)
                {
                    attriutes[i].texPositionStart = new Vector2(0.5f, 1);
                    attriutes[i].texPositionEnd   = new Vector2(1, 1);
                    attriutes[i].texScaleStart    = new Vector2(1, 1);
                    attriutes[i].texScaleEnd      = new Vector2(0, 0);
                }
                else
                {
                    attriutes[i].texPositionStart = new Vector2(0, 0);
                    attriutes[i].texPositionEnd   = new Vector2(1, 1);
                    attriutes[i].texScaleStart    = new Vector2(1, 1);
                    attriutes[i].texScaleEnd      = new Vector2(0, 0);
                }
            }

            var attributeData = mat.ParentHSF.Header.AttributeData;

            for (int i = 0; i < mat.TextureMaps.Count; i++)
            {
                var hsfTexture = (HSFMatTexture)mat.TextureMaps[i];
                var texStart   = hsfTexture.Attribute.TexAnimStart;
                var texEnd     = hsfTexture.Attribute.TexAnimEnd;
                attriutes[i].texPositionStart = new Vector2(texStart.Position.X, texStart.Position.Y);
                attriutes[i].texPositionEnd   = new Vector2(texEnd.Position.X, texEnd.Position.Y);
                attriutes[i].texScaleStart    = new Vector2(texStart.Scale.X, texStart.Scale.Y);
                attriutes[i].texScaleEnd      = new Vector2(texEnd.Scale.X, texEnd.Scale.Y);
                // attriutes[i].texParam = hsfTexture.Attribute.NbtEnable;
                //  attriutes[i].blendingFlag = hsfTexture.Attribute.BlendingFlag;
                // attriutes[i].alphaFlag = hsfTexture.Attribute.AlphaFlag;

                int attIndex = attributeData.Attributes.IndexOf(hsfTexture.Attribute);
                if (HSFParent.Header.AttributeAnimControllers.ContainsKey(attIndex))
                {
                    var controller = HSFParent.Header.AttributeAnimControllers[attIndex];
                    attriutes[i].texPositionStart.X = controller.TranslateX;
                    attriutes[i].texPositionStart.Y = controller.TranslateY;
                }

                var binded = BindTexture(shader, Scene.Models[0].Textures, (HSFMatTexture)mat.TextureMaps[i], i + 1);
                shader.SetInt($"texture{i}", i + 1);
            }

            GL.BindBuffer(BufferTarget.UniformBuffer, uboAtt);
            GL.BufferSubData(BufferTarget.UniformBuffer, IntPtr.Zero, TextureAttribute.Size, attriutes);
            GL.BindBuffer(BufferTarget.UniformBuffer, 0);
        }
Esempio n. 11
0
        Font(byte[] fontData)
        {
            atlasWidth  = 0;
            atlasHeight = 0;

            int roww = 0;
            int rowh = 0;

            fntFace = new Face(fntLibrary, fontData, 0);
            fntFace.SetPixelSizes(0, FONT_SIZE);

            for (uint i = 0; i < 512; i++)
            {
                fntFace.LoadChar(i, LoadFlags.Render, LoadTarget.Normal);
                if (roww + fntFace.Glyph.Bitmap.Width + 1 >= MAX_SIZE)
                {
                    atlasWidth   = Math.Max(atlasWidth, roww);
                    atlasHeight += rowh;
                    roww         = 0;
                    rowh         = 0;
                }

                roww += fntFace.Glyph.Bitmap.Width + 1;
                rowh  = Math.Max(rowh, fntFace.Glyph.Bitmap.Rows);
            }

            atlasWidth   = Math.Max(atlasWidth, roww);
            atlasHeight += rowh;

            GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1);

            AtlasTexture = new Texture(atlasWidth, atlasHeight);

            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, AtlasTexture.Handle);
            int ox = 0, oy = 0;

            rowh = 0;

            characters = new Dictionary <char, Character>();

            for (uint i = 32; i < 512; i++)
            {
                fntFace.LoadChar(i, LoadFlags.Render, LoadTarget.Normal);

                if (ox + fntFace.Glyph.Bitmap.Width + 1 >= MAX_SIZE)
                {
                    oy  += rowh;
                    rowh = 0;
                    ox   = 0;
                }

                GL.TexSubImage2D(TextureTarget.Texture2D, 0, ox, oy, fntFace.Glyph.Bitmap.Width, fntFace.Glyph.Bitmap.Rows, PixelFormat.Alpha, PixelType.UnsignedByte, fntFace.Glyph.Bitmap.Buffer);
                var chara = new Character
                {
                    AdvanceX     = fntFace.Glyph.Advance.X.Value >> 6,
                    AdvanceY     = fntFace.Glyph.Advance.Y.Value >> 6,
                    BitmapWidth  = fntFace.Glyph.Bitmap.Width,
                    BitmapHeight = fntFace.Glyph.Bitmap.Rows,
                    BitmapLeft   = fntFace.Glyph.BitmapLeft,
                    BitmapTop    = fntFace.Glyph.BitmapTop,
                    TexCoordX    = (float)ox / (float)atlasWidth,
                    TexCoordY    = (float)oy / (float)atlasHeight
                };

                rowh = Math.Max(rowh, fntFace.Glyph.Bitmap.Rows);
                ox  += fntFace.Glyph.Bitmap.Width + 1;
                characters.Add((char)i, chara);
                if (fntFace.Glyph.Bitmap.Rows > LineHeight)
                {
                    LineHeight = fntFace.Glyph.Bitmap.Rows;
                }
            }

            GL.PixelStore(PixelStoreParameter.UnpackAlignment, 4);
        }
Esempio n. 12
0
 public void EnableTextureOne()
 {
     GL.ActiveTexture(TextureUnit.Texture0);
     GL.Enable(EnableCap.Texture2D);
 }
Esempio n. 13
0
        private void CreateImmutableStorage()
        {
            TextureTarget target = Info.Target.Convert();

            GL.ActiveTexture(TextureUnit.Texture0);

            GL.BindTexture(target, Handle);

            FormatInfo format = FormatTable.GetFormatInfo(Info.Format);

            SizedInternalFormat internalFormat;

            if (format.IsCompressed)
            {
                internalFormat = (SizedInternalFormat)format.PixelFormat;
            }
            else
            {
                internalFormat = (SizedInternalFormat)format.PixelInternalFormat;
            }

            int levels = Info.GetLevelsClamped();

            switch (Info.Target)
            {
            case Target.Texture1D:
                GL.TexStorage1D(
                    TextureTarget1d.Texture1D,
                    levels,
                    internalFormat,
                    Info.Width);
                break;

            case Target.Texture1DArray:
                GL.TexStorage2D(
                    TextureTarget2d.Texture1DArray,
                    levels,
                    internalFormat,
                    Info.Width,
                    Info.Height);
                break;

            case Target.Texture2D:
                GL.TexStorage2D(
                    TextureTarget2d.Texture2D,
                    levels,
                    internalFormat,
                    Info.Width,
                    Info.Height);
                break;

            case Target.Texture2DArray:
                GL.TexStorage3D(
                    TextureTarget3d.Texture2DArray,
                    levels,
                    internalFormat,
                    Info.Width,
                    Info.Height,
                    Info.Depth);
                break;

            case Target.Texture2DMultisample:
                GL.TexStorage2DMultisample(
                    TextureTargetMultisample2d.Texture2DMultisample,
                    Info.Samples,
                    internalFormat,
                    Info.Width,
                    Info.Height,
                    true);
                break;

            case Target.Texture2DMultisampleArray:
                GL.TexStorage3DMultisample(
                    TextureTargetMultisample3d.Texture2DMultisampleArray,
                    Info.Samples,
                    internalFormat,
                    Info.Width,
                    Info.Height,
                    Info.Depth,
                    true);
                break;

            case Target.Texture3D:
                GL.TexStorage3D(
                    TextureTarget3d.Texture3D,
                    levels,
                    internalFormat,
                    Info.Width,
                    Info.Height,
                    Info.Depth);
                break;

            case Target.Cubemap:
                GL.TexStorage2D(
                    TextureTarget2d.TextureCubeMap,
                    levels,
                    internalFormat,
                    Info.Width,
                    Info.Height);
                break;

            case Target.CubemapArray:
                GL.TexStorage3D(
                    (TextureTarget3d)All.TextureCubeMapArray,
                    levels,
                    internalFormat,
                    Info.Width,
                    Info.Height,
                    Info.Depth);
                break;

            default:
                Logger.Debug?.Print(LogClass.Gpu, $"Invalid or unsupported texture target: {target}.");
                break;
            }
        }
Esempio n. 14
0
        protected override void OnLoad(EventArgs e)
        {
            Vertex[] vertices =
            {
                new Vertex(new Vector2(-0.5f,  0.5f), Color.Red,    new Vector2(0.0f, 0.0f)),
                new Vertex(new Vector2(0.5f,   0.5f), Color.Green,  new Vector2(1.0f, 0.0f)),
                new Vertex(new Vector2(0.5f,  -0.5f), Color.Yellow, new Vector2(1.0f, 1.0f)),
                new Vertex(new Vector2(-0.5f, -0.5f), Color.Blue,   new Vector2(0.0f, 1.0f))
            };

            uint[] elements =
            {
                0, 1, 2,
                2, 3, 0
            };

            //vbo
            GL.GenBuffers(1, out uint vboHandle);                                                                         //speicher reservieren auf GK
            GL.BindBuffer(BufferTarget.ArrayBuffer, vboHandle);                                                           //buffer "aktivieren"
            GL.BufferData(BufferTarget.ArrayBuffer, vertices.Length * Vertex.SIZE, vertices, BufferUsageHint.StaticDraw); //vertices array auf GK schreiben

            //vao
            GL.GenVertexArrays(1, out vaoHandle);
            GL.BindVertexArray(vaoHandle);

            //eao
            GL.GenBuffers(1, out uint eaoHandle);
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, eaoHandle);
            GL.BufferData(BufferTarget.ElementArrayBuffer, elements.Length * sizeof(uint), elements, BufferUsageHint.StaticDraw);

            //shaders
            #region shadercode
            string vertShaderSource = @"#version 450

in vec2 position;
in vec4 color;
in vec2 texCoord;

out vec4 Color;
out vec2 TexCoord;

void main(){
    Color = color;
    TexCoord = texCoord;
    gl_Position = vec4(position , 0.0, 1.0);
}";
            string fragShaderSource = @"#version 450
uniform sampler2D texKatze;
uniform sampler2D texPuppy;

in vec4 Color;
in vec2 TexCoord;

out vec4 outColor;
void main(){
    //outColor = color;
    vec4 colKatze = texture(texKatze, TexCoord);
    vec4 colPuppy = texture(texPuppy, TexCoord);

    outColor = mix(colPuppy,colKatze, 0.5) * (0.5* Color);
}";
            #endregion

            int vertShaderHandle = GL.CreateShader(ShaderType.VertexShader);           //reserve some mem for shader
            GL.ShaderSource(vertShaderHandle, vertShaderSource);                       //load glsl code to shader
            GL.CompileShader(vertShaderHandle);                                        //compile shader
            Console.WriteLine("VertShader: " + GL.GetShaderInfoLog(vertShaderHandle)); //write log to output

            int fragShaderHandle = GL.CreateShader(ShaderType.FragmentShader);
            GL.ShaderSource(fragShaderHandle, fragShaderSource);
            GL.CompileShader(fragShaderHandle);
            Console.WriteLine("FragShader: " + GL.GetShaderInfoLog(fragShaderHandle));

            shaderProgHandle = GL.CreateProgram();
            GL.AttachShader(shaderProgHandle, vertShaderHandle);
            GL.AttachShader(shaderProgHandle, fragShaderHandle);

            GL.BindFragDataLocation(shaderProgHandle, 0, "outColor");

            GL.LinkProgram(shaderProgHandle);
            GL.UseProgram(shaderProgHandle);

            GL.DetachShader(shaderProgHandle, vertShaderHandle);
            GL.DetachShader(shaderProgHandle, fragShaderHandle);

            //attributes
            int posAttrLoc = GL.GetAttribLocation(shaderProgHandle, "position");                         //handle des attributs finden
            GL.EnableVertexAttribArray(posAttrLoc);                                                      //attribut aktivieren (abwehrkräfte)
            GL.VertexAttribPointer(posAttrLoc, 2, VertexAttribPointerType.Float, false, Vertex.SIZE, 0); //attribut "lesbar machen2

            int colAttrLoc = GL.GetAttribLocation(shaderProgHandle, "color");
            GL.EnableVertexAttribArray(colAttrLoc);
            GL.VertexAttribPointer(colAttrLoc, 4, VertexAttribPointerType.Float, false, Vertex.SIZE, 2 * sizeof(float));

            int texAttrLoc = GL.GetAttribLocation(shaderProgHandle, "texCoord");
            GL.EnableVertexAttribArray(texAttrLoc);
            GL.VertexAttribPointer(texAttrLoc, 2, VertexAttribPointerType.Float, false, Vertex.SIZE, 6 * sizeof(float));

            //texture
            uint[] textureHandles = new uint[2];
            GL.GenTextures(2, textureHandles);

            //katze
            GL.ActiveTexture(TextureUnit.Texture0);
            Bitmap bmpKatze = (Bitmap)Bitmap.FromFile("sample.png");    //load texture
            System.Drawing.Imaging.BitmapData dataKatze = bmpKatze.LockBits(new Rectangle(0, 0, bmpKatze.Width, bmpKatze.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            GL.BindTexture(TextureTarget.Texture2D, textureHandles[0]); //bind texture to operate on it
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmpKatze.Width, bmpKatze.Height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, dataKatze.Scan0);
            bmpKatze.UnlockBits(dataKatze);
            GL.Uniform1(GL.GetUniformLocation(shaderProgHandle, "texKatze"), 0);                                         //set texKatze to texture 0
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);            //set texture parameter
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge);

            //hund
            GL.ActiveTexture(TextureUnit.Texture1);
            Bitmap bmpHund = (Bitmap)Bitmap.FromFile("sample2.png"); //lade textur
            System.Drawing.Imaging.BitmapData dataHund = bmpHund.LockBits(new Rectangle(0, 0, bmpHund.Width, bmpHund.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            GL.BindTexture(TextureTarget.Texture2D, textureHandles[1]);
            GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmpHund.Width, bmpHund.Height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, dataHund.Scan0);
            bmpHund.UnlockBits(dataHund);
            GL.Uniform1(GL.GetUniformLocation(shaderProgHandle, "texPuppy"), 1);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);            //set texture parameter
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge);
            GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge);

            Console.WriteLine(GL.GetError());
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
        }
Esempio n. 15
0
        public void DrawBatch(SpriteSortMode sortMode, SamplerState samplerState)
        {
            // nothing to do
            if (_batchItemList.Count == 0)
            {
                return;
            }

            // sort the batch items
            switch (sortMode)
            {
            case SpriteSortMode.Texture:
                _batchItemList.Sort(CompareTexture);
                break;

            case SpriteSortMode.FrontToBack:
                _batchItemList.Sort(CompareDepth);
                break;

            case SpriteSortMode.BackToFront:
                _batchItemList.Sort(CompareReverseDepth);
                break;
            }

            int size = sizeof(float) * 4 + sizeof(uint);

            GL.VertexPointer(2, VertexPointerType.Float, size, _vertexHandle.AddrOfPinnedObject());
            GL.ColorPointer(4, ColorPointerType.UnsignedByte, size, (IntPtr)((UInt64)_vertexHandle.AddrOfPinnedObject() + sizeof(float) * 2));
            GL.TexCoordPointer(2, TexCoordPointerType.Float, size, (IntPtr)((UInt64)_vertexHandle.AddrOfPinnedObject() + sizeof(float) * 2 + sizeof(uint)));

            // setup the vertexArray array
            int startIndex = 0;
            int index      = 0;
            int texID      = -1;

            // make sure the vertexArray has enough space
            if (_batchItemList.Count * 4 > _vertexArray.Length)
            {
                ExpandVertexArray(_batchItemList.Count);
            }

            foreach (SpriteBatchItem item in _batchItemList)
            {
                // if the texture changed, we need to flush and bind the new texture
                if (item.TextureID != texID)
                {
                    FlushVertexArray(startIndex, index);
                    startIndex = index;
                    texID      = item.TextureID;

                    GL.ActiveTexture(TextureUnit.Texture0);
                    GL.BindTexture(TextureTarget.Texture2D, texID);

                    samplerState.Activate();
                }
                // store the SpriteBatchItem data in our vertexArray
                _vertexArray[index++] = item.vertexTL;
                _vertexArray[index++] = item.vertexTR;
                _vertexArray[index++] = item.vertexBL;
                _vertexArray[index++] = item.vertexBR;

                _freeBatchItemQueue.Enqueue(item);
            }
            // flush the remaining vertexArray data
            FlushVertexArray(startIndex, index);
            _batchItemList.Clear();
        }
Esempio n. 16
0
 public void Bind(TextureUnit textureSlot = TextureUnit.Texture0)
 {
     //When we bind a texture we can choose which textureslot we can bind it to.
     _gl.ActiveTexture(textureSlot);
     _gl.BindTexture(TextureTarget.Texture2D, _handle);
 }
        // This gets called when the drawing surface is ready
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try {
                // Clear the current Context
                GraphicsContext.MakeCurrent(null);
                // Create a secondary context using the same information the primary
                // context was created with
                backgroundContext = new AndroidGraphicsContext(GraphicsMode, WindowInfo, GraphicsContext, ContextRenderingApi, GraphicsContextFlags.Embedded);
            }catch {
                // secondary context not supported
                backgroundContext = null;
            }

            MakeCurrent();

            var vertexShader   = LoadShader(ShaderType.VertexShader, vertexShaderCode);
            var fragmentShader = LoadShader(ShaderType.FragmentShader, fragmentShaderCode);

            program = GL.CreateProgram();                          // create empty OpenGL Program
            GL.AttachShader(program, vertexShader);                // add the vertex shader to program
            GL.AttachShader(program, fragmentShader);              // add the fragment shader to program

            GL.BindAttribLocation(program, ATTRIB_VERTEX, "position");
            GL.BindAttribLocation(program, ATTRIB_TEXCOORD, "texcoord");

            GL.LinkProgram(program);                               // create OpenGL program executables

            uniformTextureLocation = GL.GetUniformLocation(program, "texture");

            if (vertexShader != 0)
            {
                GL.DetachShader(program, vertexShader);
                GL.DeleteShader(vertexShader);
            }

            if (fragmentShader != 0)
            {
                GL.DetachShader(program, fragmentShader);
                GL.DeleteShader(fragmentShader);
            }

            GL.Viewport(0, 0, Width, Height);

            // Run the render loop
            Run();

            Task.Factory.StartNew(() => {
                //Thread.Sleep(500);
                // load the bitmap
                bitmap = BitmapFactory.DecodeResource(Context.Resources, Resource.Drawable.f_spot);

                // the device may or may not support a background Context. But rather than
                // duplicating this code we just create an Action which we can invoke on this
                // background thread later or queue to be executed on the rendering thread.
                Action acton = new Action(() => {
                    GL.Enable(EnableCap.Texture2D);
                    GL.GenTextures(1, out textureid);
                    GL.ActiveTexture(TextureUnit.Texture0);
                    GL.BindTexture(TextureTarget.Texture2D, textureid);
                    // setup texture parameters
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.ClampToEdge);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
                    Android.Opengl.GLUtils.TexImage2D((int)TextureTarget.Texture2D, 0, bitmap, 0);
                    // make sure the texture is pushed to the GPU.
                    GL.Flush();

                    // make sure we free resources
                    bitmap.Recycle();
                    bitmap.Dispose();
                    bitmap = null;
                });


                // take a lock so the main rendering thread does not try to draw anything
                // there are other ways to do this, but its is probably the simplest
                lock (lockobject) {
                    if (backgroundContext != null)
                    {
                        // Clear the current context bound to the Display
                        backgroundContext.MakeCurrent(null);
                        // make this context active
                        backgroundContext.MakeCurrent(WindowInfo);
                        // do our processing
                        acton.Invoke();
                        // clear the current context again so we don't error on the main thread
                        backgroundContext.MakeCurrent(null);
                    }
                    else
                    {
                        // Secondary Context's are not supported on this device
                        // queue the action for execution later.
                        actions.Enqueue(acton);
                    }
                }
            });
        }
Esempio n. 18
0
        // render the mesh using the supplied shader and matrix
        public void Render(Shader shader, Matrix4 transform, int texture, bool specular)
        {
            
            // on first run, prepare buffers
            Prepare(shader);

            // safety dance
            GL.PushClientAttrib(ClientAttribMask.ClientVertexArrayBit);

            // enable texture
            int texLoc = GL.GetUniformLocation(shader.programID, "pixels");
            GL.Uniform1(texLoc, 0);
            GL.ActiveTexture(TextureUnit.Texture0);
			GL.BindTexture(TextureTarget.Texture2D, texture);
			int spec = GL.GetUniformLocation(shader.programID, "specular");
			GL.UseProgram(shader.programID);
			GL.Uniform1(spec, specular ? 1 : 0);

			// enable shader
			GL.UseProgram(shader.programID);

			// pass transform to vertex shader
			//transform.Row1 = new Vector4(0,transform.Row1.Y,0,1);
			//Console.WriteLine(transform.Row1);

			Matrix4 toWorld = transform;
			transform *= Matrix4.CreateTranslation(-Game.CamPos);
			transform *= Matrix4.CreateFromAxisAngle(new Vector3(0, 0, 1), Game.z);
            transform *= Matrix4.CreateFromAxisAngle(new Vector3(0, 1, 0), Game.y); 
            transform *= Matrix4.CreateFromAxisAngle(new Vector3(1, 0, 0), Game.x);
			transform *= Matrix4.CreatePerspectiveFieldOfView(1.2f, 1.3f, .1f, 1000);
			GL.UniformMatrix4(shader.uniform_mview, false, ref transform);
            GL.UniformMatrix4(shader.uniform_2wrld, false, ref toWorld);

			// enable position, normal and uv attributes
			GL.EnableVertexAttribArray(shader.attribute_vpos);
            GL.EnableVertexAttribArray(shader.attribute_vnrm);
            GL.EnableVertexAttribArray(shader.attribute_vuvs);

            // bind interleaved vertex data
            GL.EnableClientState(ArrayCap.VertexArray);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vertexBufferId);
            GL.InterleavedArrays(InterleavedArrayFormat.T2fN3fV3f, Marshal.SizeOf(typeof(ObjVertex)), IntPtr.Zero);

            // link vertex attributes to shader parameters 
            GL.VertexAttribPointer(shader.attribute_vuvs, 2, VertexAttribPointerType.Float, false, 32, 0);
            GL.VertexAttribPointer(shader.attribute_vnrm, 3, VertexAttribPointerType.Float, true, 32, 2 * 4);
            GL.VertexAttribPointer(shader.attribute_vpos, 3, VertexAttribPointerType.Float, false, 32, 5 * 4);

            // bind triangle index data and render
            GL.BindBuffer(BufferTarget.ElementArrayBuffer, triangleBufferId);
            GL.DrawArrays(PrimitiveType.Triangles, 0, triangles.Length * 3);

            // bind quad index data and render
            if (quads.Length > 0)
            {
                GL.BindBuffer(BufferTarget.ElementArrayBuffer, quadBufferId);
                GL.DrawArrays(PrimitiveType.Quads, 0, quads.Length * 4);
            }

            // restore previous OpenGL state
            GL.UseProgram(0);
            GL.PopClientAttrib();
        }
Esempio n. 19
0
        public void DisplayPixelBuffer(CVPixelBuffer pixelBuffer)
        {
            DrawTextInCorner(pixelBuffer);
            CVReturn error;

            if (pixelBuffer != null)
            {
                int frameWidth  = (int)pixelBuffer.Width;
                int frameHeight = (int)pixelBuffer.Height;

                if (videoTextureCache == null)
                {
                    Console.WriteLine("No video texture cache");
                    return;
                }

                CleanUpTextures();
                CVAttachmentMode attachmentMode;
                var colorAttachments = pixelBuffer.GetAttachment <NSString> (CVImageBuffer.YCbCrMatrixKey, out attachmentMode);

                if (colorAttachments == CVImageBuffer.YCbCrMatrix_ITU_R_601_4)
                {
                    preferredConversion = colorConversion601;
                }
                else
                {
                    preferredConversion = colorConversion709;
                }

                GL.ActiveTexture(TextureUnit.Texture0);
                lumaTexture = videoTextureCache.TextureFromImage(pixelBuffer, true, All.RedExt, frameWidth, frameHeight,
                                                                 All.RedExt, DataType.UnsignedByte, 0, out error);

                if (lumaTexture == null)
                {
                    Console.WriteLine("Error at CVOpenGLESTextureCach.TextureFromImage");
                }

                GL.BindTexture(lumaTexture.Target, lumaTexture.Name);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge);

                GL.ActiveTexture(TextureUnit.Texture1);
                chromaTexture = videoTextureCache.TextureFromImage(pixelBuffer, true, All.RgExt, frameWidth / 2, frameHeight / 2,
                                                                   All.RgExt, DataType.UnsignedByte, 1, out error);

                if (chromaTexture == null)
                {
                    Console.WriteLine("Error at CVOpenGLESTextureCach.TextureFromImage");
                }

                GL.BindTexture(chromaTexture.Target, chromaTexture.Name);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToEdge);
                GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToEdge);

                GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBufferHandle);
                GL.Viewport(0, 0, backingWidth, backingHeight);
            }

            GL.ClearColor(0f, 0f, 0f, 1f);
            GL.Clear(ClearBufferMask.ColorBufferBit);

            GL.UseProgram(Program);
            GL.Uniform1(uniforms [(int)UniformIndex.RotationAngle], 0f);
            GL.UniformMatrix3(uniforms [(int)UniformIndex.ColorConversionMatrix], 1, false, preferredConversion);

            CGRect vertexSamplingRect = AVUtilities.WithAspectRatio(Bounds, PresentationRect);

            var normalizedSamplingSize = new CGSize(0f, 0f);
            var cropScaleAmount        = new CGSize(vertexSamplingRect.Width / Bounds.Width, vertexSamplingRect.Height / Bounds.Height);

            if (cropScaleAmount.Width > cropScaleAmount.Height)
            {
                normalizedSamplingSize.Width  = 1f;
                normalizedSamplingSize.Height = cropScaleAmount.Height / cropScaleAmount.Width;
            }
            else
            {
                normalizedSamplingSize.Width  = 1f;
                normalizedSamplingSize.Height = cropScaleAmount.Width / cropScaleAmount.Height;
            }

            float[] quadVertexData =
            {
                -1f * (float)normalizedSamplingSize.Width, -1f * (float)normalizedSamplingSize.Height,
                (float)normalizedSamplingSize.Width,       -1f * (float)normalizedSamplingSize.Height,
                -1f * (float)normalizedSamplingSize.Width, (float)normalizedSamplingSize.Height,
                (float)normalizedSamplingSize.Width,       (float)normalizedSamplingSize.Height,
            };

            GL.VertexAttribPointer((int)AttributeIndex.Vertex, 2, VertexAttribPointerType.Float, false, 0, quadVertexData);
            GL.EnableVertexAttribArray((int)AttributeIndex.Vertex);

            var textureSamplingRect = new CGRect(0, 0, 1, 1);

            float[] quadTextureData =
            {
                (float)textureSamplingRect.GetMinX(), (float)textureSamplingRect.GetMaxY(),
                (float)textureSamplingRect.GetMaxX(), (float)textureSamplingRect.GetMaxY(),
                (float)textureSamplingRect.GetMinX(), (float)textureSamplingRect.GetMinY(),
                (float)textureSamplingRect.GetMaxX(), (float)textureSamplingRect.GetMinY()
            };

            GL.VertexAttribPointer((int)AttributeIndex.TextureCoordinates, 2, VertexAttribPointerType.Float, false, 0, quadTextureData);
            GL.EnableVertexAttribArray((int)AttributeIndex.TextureCoordinates);

            GL.DrawArrays(BeginMode.TriangleStrip, 0, 4);
            GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, colorBufferHandle);
            context.PresentRenderBuffer((int)RenderbufferTarget.Renderbuffer);
        }
Esempio n. 20
0
        public static int LoadTexture(string filename, CacheStorage cache)
        {
            GL.ActiveTexture(TextureUnit.Texture0);

            filename = filename.ToLower();

            if (cache.materials.ContainsKey(filename))
            {
                return(cache.materials[filename]);
            }

            int textureId = GL.GenTexture();

            using (var blp = new BlpFile(CASC.cascHandler.OpenFile(filename)))
            {
                switch (blp.encoding)
                {
                case 1:
                case 2:     // Temporary
                case 3:
                    var bmp = blp.GetBitmap(0);

                    if (bmp == null)
                    {
                        throw new Exception("BMP is null!");
                    }

                    GL.BindTexture(TextureTarget.Texture2D, textureId);
                    cache.materials.Add(filename, textureId);
                    System.Drawing.Imaging.BitmapData bmp_data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmp_data.Width, bmp_data.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, bmp_data.Scan0);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
                    GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
                    bmp.UnlockBits(bmp_data);

                    break;

                /*case 2:
                 *  DXTDecompression.DXTFlags flags = (blp.alphaDepth > 1) ? ((blp.alphaEncoding == 7) ? DXTDecompression.DXTFlags.DXT5 : DXTDecompression.DXTFlags.DXT3) : DXTDecompression.DXTFlags.DXT1;
                 *
                 *  var width = blp.width / (int)Math.Pow(2.0, blp.MipMapCount);
                 *  var height = blp.height / (int)Math.Pow(2.0, blp.MipMapCount);
                 *
                 *  int blockSize;
                 *  PixelInternalFormat format;
                 *
                 *  if ((flags & DXTDecompression.DXTFlags.DXT1) != 0)
                 *  {
                 *      blockSize = 8;
                 *      format = PixelInternalFormat.CompressedRgbaS3tcDxt1Ext;
                 *  }
                 *  else if((flags & DXTDecompression.DXTFlags.DXT3) != 0)
                 *  {
                 *      blockSize = 16;
                 *      format = PixelInternalFormat.CompressedRgbaS3tcDxt3Ext;
                 *  }
                 *  else if((flags & DXTDecompression.DXTFlags.DXT5) != 0)
                 *  {
                 *      blockSize = 16;
                 *      format = PixelInternalFormat.CompressedRgbaS3tcDxt5Ext;
                 *  }
                 *  else
                 *  {
                 *      throw new Exception("Unsupported DXT format!");
                 *  }
                 *
                 *  GL.BindTexture(TextureTarget.Texture2D, textureId);
                 *  cache.materials.Add(filename, textureId);
                 *
                 *  for (var i = blp.MipMapCount - 1; i >= 0; i--)
                 *  {
                 *      if ((width *= 2) == 0)
                 *      {
                 *          width = 1;
                 *      }
                 *
                 *      if ((height *= 2) == 0)
                 *      {
                 *          height = 1;
                 *      }
                 *
                 *      var size = ((width + 3) / 4) * ((height + 3) / 4) * blockSize;
                 *
                 *      var data = blp.GetPictureData(i);
                 *
                 *      GL.CompressedTexImage2D(TextureTarget.Texture2D, i, format, width, height, 0, size, );
                 *  }
                 *
                 *  GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.LinearMipmapLinear);
                 *  GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
                 *  GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
                 *  GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
                 *
                 *  break;
                 */
                default:
                    throw new Exception("BLP error!");
                }
            }

            return(textureId);
        }
Esempio n. 21
0
        private void _drawGrids()
        {
            var mapId = _eyeManager.CurrentMap;

            if (!_mapManager.TryGetMap(mapId, out var map))
            {
                // fall back to the default eye's map
                _eyeManager.CurrentEye = null;
                map = _mapManager.GetMap(_eyeManager.CurrentMap);
            }

            var atlasTexture = _tileDefinitionManager.TileTextureAtlas;
            var loadedTex    = _loadedTextures[((ClydeTexture)atlasTexture).TextureId];

            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, loadedTex.OpenGLObject.Handle);

            GL.ActiveTexture(TextureUnit.Texture1);
            if (_lightingReady)
            {
                var lightTexture = _loadedTextures[LightRenderTarget.Texture.TextureId].OpenGLObject;
                GL.BindTexture(TextureTarget.Texture2D, lightTexture.Handle);
            }
            else
            {
                var white = _loadedTextures[((ClydeTexture)Texture.White).TextureId].OpenGLObject;
                GL.BindTexture(TextureTarget.Texture2D, white.Handle);
            }

            var gridProgram = _loadedShaders[_defaultShader.Handle].Program;

            gridProgram.Use();
            gridProgram.SetUniformTextureMaybe(UniIMainTexture, TextureUnit.Texture0);
            gridProgram.SetUniformTextureMaybe(UniILightTexture, TextureUnit.Texture1);
            gridProgram.SetUniform(UniIModUV, new Vector4(0, 0, 1, 1));
            gridProgram.SetUniform(UniIModulate, Color.White);

            foreach (var mapGrid in map.GetAllGrids())
            {
                var grid = (IMapGridInternal)mapGrid;

                if (!_mapChunkData.ContainsKey(grid.Index))
                {
                    continue;
                }
                var model = Matrix3.Identity;
                model.R0C2 = grid.WorldPosition.X;
                model.R1C2 = grid.WorldPosition.Y;
                gridProgram.SetUniform(UniIModelMatrix, model);

                foreach (var(index, chunk) in grid.GetMapChunks())
                {
                    if (_isChunkDirty(grid, chunk))
                    {
                        _updateChunkMesh(grid, chunk);
                    }

                    var datum = _mapChunkData[grid.Index][chunk.Indices];

                    if (datum.TileCount == 0)
                    {
                        continue;
                    }

                    GL.BindVertexArray(datum.VAO);
                    datum.EBO.Use();
                    datum.VBO.Use();

                    GL.DrawElements(BeginMode.TriangleStrip, datum.TileCount * 5, DrawElementsType.UnsignedShort, 0);
                }
            }
        }
Esempio n. 22
0
 public void PrepareForRead()
 {
     GL.ActiveTexture(TextureUnit);
     GL.Enable(EnableCap.Texture2D);
     GL.BindTexture(TextureTarget.Texture2D, TextureID);
 }
Esempio n. 23
0
        public void PrepareGL()
        {
            if (!Root.TexChunk.AreTexturesLoaded)
            {
                Root.TexChunk.LoadTextures();
            }

            if (!GL.IsTexture(emptyTexture))
            {
                emptyTexture = GL.GenTexture();
                GL.BindTexture(TextureTarget.Texture2D, emptyTexture);
                byte[] empty = new byte[]
                {
                    255, 255, 255, 255,
                    255, 255, 255, 255,
                    255, 255, 255, 255,
                    255, 255, 255, 255
                };
                GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, 2, 2, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, empty);

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

            if (!GL.IsProgram(program))
            {
                string fsOverlay =
                    "#version 110\n" +
                    "\n" +
                    "void main()\n" +
                    "{\n" +
                    "    gl_FragColor = vec4(1.0, 1.0, 1.0, 0.5);\n" +
                    "}\n";

                Aglex.GLSL.CreateFragmentShader(ref fragmentObject, File.Open("general-fs.glsl", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite));
                Aglex.GLSL.CreateFragmentShader(ref fragmentObjectOverlay, fsOverlay);
                Aglex.GLSL.CreateVertexShader(ref vertexObject, File.Open("general-vs.glsl", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite));

                Aglex.GLSL.CreateProgram(ref program, fragmentObject, vertexObject);

                skinningModeLocation    = GL.GetUniformLocation(program, "skinningMode");
                boneIdLocation          = GL.GetUniformLocation(program, "boneId");
                vertBoneSamplerLocation = GL.GetUniformLocation(program, "vertBoneSampler");

                tex0Location = GL.GetUniformLocation(program, "tex0");
                tex1Location = GL.GetUniformLocation(program, "tex1");
                tex2Location = GL.GetUniformLocation(program, "tex2");

                materialColorLocation = GL.GetUniformLocation(program, "materialColor");

                vertexScaleLocation         = GL.GetUniformLocation(program, "vertexScale");
                texCoordScaleLocation       = GL.GetUniformLocation(program, "texCoordScale");
                normalScaleLocation         = GL.GetUniformLocation(program, "normalScale");
                disableAlphaLocation        = GL.GetUniformLocation(program, "disableAlpha");
                enableLightingLocation      = GL.GetUniformLocation(program, "enableLighting");
                enableSkeletalStuffLocation = GL.GetUniformLocation(program, "enableSkeletalStuff");

                Aglex.GLSL.CreateProgram(ref programOverlay, fragmentObjectOverlay, vertexObject);
                vertexScaleLocationOverlay         = GL.GetUniformLocation(programOverlay, "vertexScale");
                skinningModeLocationOverlay        = GL.GetUniformLocation(programOverlay, "skinningMode");
                boneIdLocationOverlay              = GL.GetUniformLocation(programOverlay, "boneId");
                vertBoneSamplerLocationOverlay     = GL.GetUniformLocation(programOverlay, "vertBoneSampler");
                enableSkeletalStuffLocationOverlay = GL.GetUniformLocation(programOverlay, "enableSkeletalStuff");
            }

            if (vertBoneBufferId == -1)
            {
                vertBoneBufferId = GL.GenBuffer();
                GL.BindBuffer(BufferTarget.TextureBuffer, vertBoneBufferId);
                GL.BufferData(BufferTarget.TextureBuffer, new IntPtr(0x10000), IntPtr.Zero, BufferUsageHint.StaticDraw);
                GL.BindBuffer(BufferTarget.TextureBuffer, 0);
            }

            if (vertBoneTexId == -1)
            {
                vertBoneTexId = GL.GenTexture();
                GL.ActiveTexture(TextureUnit.Texture0 + vertBoneTexUnit);
                GL.BindTexture(TextureTarget.TextureBuffer, vertBoneTexId);
                GL.TexBuffer(TextureBufferTarget.TextureBuffer, SizedInternalFormat.R32ui, vertBoneBufferId);
                GL.BindTexture(TextureTarget.TextureBuffer, 0);
            }

            if (vertexBufferObjects == null)
            {
                PrepareBuffers();
            }

            ready = true;
        }
Esempio n. 24
0
 public void FinishRead()
 {
     GL.ActiveTexture(TextureUnit);
     GL.Disable(EnableCap.Texture2D);
 }
Esempio n. 25
0
        protected override void OnRenderFrame(FrameEventArgs e)
        {
            base.OnRenderFrame(e);

            GL.Enable(EnableCap.DepthTest);
            GL.Enable(EnableCap.LineSmooth);

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

            modelShader.UseProgram();

            // directional light
            modelShader.SetVec3("dirLight.direction", -0.2f, -1.0f, -0.3f);
            modelShader.SetVec3("dirLight.ambient", 0.05f, 0.05f, 0.05f);
            modelShader.SetVec3("dirLight.diffuse", 0.4f, 0.4f, 0.4f);
            modelShader.SetVec3("dirLight.specular", 0.5f, 0.5f, 0.5f);

            // point light 1
            modelShader.SetVec3("pointLights[0].position", pointLightPositions[0]);
            modelShader.SetVec3("pointLights[0].ambient", 0.05f, 0.05f, 0.05f);
            modelShader.SetVec3("pointLights[0].diffuse", 0.8f, 0.8f, 0.8f);
            modelShader.SetVec3("pointLights[0].specular", 1.0f, 1.0f, 1.0f);
            modelShader.SetFloat("pointLights[0].constant", 1.0f);
            modelShader.SetFloat("pointLights[0].linear", 0.09f);
            modelShader.SetFloat("pointLights[0].quadratic", 0.032f);
            // point light 2
            modelShader.SetVec3("pointLights[1].position", pointLightPositions[1]);
            modelShader.SetVec3("pointLights[1].ambient", 0.05f, 0.05f, 0.05f);
            modelShader.SetVec3("pointLights[1].diffuse", 0.8f, 0.8f, 0.8f);
            modelShader.SetVec3("pointLights[1].specular", 1.0f, 1.0f, 1.0f);
            modelShader.SetFloat("pointLights[1].constant", 1.0f);
            modelShader.SetFloat("pointLights[1].linear", 0.09f);
            modelShader.SetFloat("pointLights[1].quadratic", 0.032f);
            // point light 3
            modelShader.SetVec3("pointLights[2].position", pointLightPositions[2]);
            modelShader.SetVec3("pointLights[2].ambient", 0.05f, 0.05f, 0.05f);
            modelShader.SetVec3("pointLights[2].diffuse", 0.8f, 0.8f, 0.8f);
            modelShader.SetVec3("pointLights[2].specular", 1.0f, 1.0f, 1.0f);
            modelShader.SetFloat("pointLights[2].constant", 1.0f);
            modelShader.SetFloat("pointLights[2].linear", 0.09f);
            modelShader.SetFloat("pointLights[2].quadratic", 0.032f);
            // point light 4
            modelShader.SetVec3("pointLights[3].position", pointLightPositions[3]);
            modelShader.SetVec3("pointLights[3].ambient", 0.05f, 0.05f, 0.05f);
            modelShader.SetVec3("pointLights[3].diffuse", 0.8f, 0.8f, 0.8f);
            modelShader.SetVec3("pointLights[3].specular", 1.0f, 1.0f, 1.0f);
            modelShader.SetFloat("pointLights[3].constant", 1.0f);
            modelShader.SetFloat("pointLights[3].linear", 0.09f);
            modelShader.SetFloat("pointLights[3].quadratic", 0.032f);

            // spotLight
            modelShader.SetVec3("spotLight.position", camera.Position);
            modelShader.SetVec3("spotLight.direction", camera.Front);
            modelShader.SetVec3("spotLight.ambient", 0.0f, 0.0f, 0.0f);
            modelShader.SetVec3("spotLight.diffuse", 1.0f, 1.0f, 1.0f);
            modelShader.SetVec3("spotLight.specular", 1.0f, 1.0f, 1.0f);
            modelShader.SetFloat("spotLight.constant", 1.0f);
            modelShader.SetFloat("spotLight.linear", 0.09f);
            modelShader.SetFloat("spotLight.quadratic", 0.032f);
            modelShader.SetFloat("spotLight.cutOff", (float)Math.Cos(MathUtil.ToRadian(12.5f)));
            modelShader.SetFloat("spotLight.outerCutOff", (float)Math.Cos(MathUtil.ToRadian(15.0f)));

            modelShader.SetFloat("material.shininess", 32.0f);
            modelShader.SetVec3("viewPos", camera.Position);

            modelShader.SetMat4("view", camera.ViewMatrix);

            var projection = Matrix4.CreatePerspectiveFieldOfView((float)(45.0f * Math.PI / 180),
                                                                  Width / Height, 0.1f, 100.0f);

            modelShader.SetMat4("projection", projection);

            GL.ActiveTexture(TextureUnit.Texture0);
            GL.BindTexture(TextureTarget.Texture2D, diffuseMap);

            GL.ActiveTexture(TextureUnit.Texture1);
            GL.BindTexture(TextureTarget.Texture2D, specularMap);

            GL.BindVertexArray(cubeVAO);

            // draw container box
            for (int i = 0; i < cubePositions.Length; i++)
            {
                float angle = 20.0f * i;

                var translation = Matrix4.CreateTranslation(cubePositions[i]);
                var rotation    = Matrix4.CreateFromAxisAngle(new Vector3(1.0f, 0.3f, 0.5f), MathUtil.ToRadian(angle));
                var model       = rotation * translation;

                modelShader.SetMat4("model", model);

                GL.DrawArrays(PrimitiveType.Triangles, 0, 36);
            }

            // draw point light
            lampShader.UseProgram();
            lampShader.SetMat4("projection", projection);
            lampShader.SetMat4("view", camera.ViewMatrix);
            for (int i = 0; i < pointLightPositions.Length; i++)
            {
                var lampModel = Matrix4.CreateScale(0.2f) * Matrix4.CreateTranslation(pointLightPositions[i]);
                lampShader.SetMat4("model", lampModel);

                GL.BindVertexArray(lightVAO);
                GL.DrawArrays(PrimitiveType.Triangles, 0, 36);
            }

            SwapBuffers();
        }
Esempio n. 26
0
 private void BindShadowMapToTexture()
 {
     GL.ActiveTexture(m_textureUnit);
     GL.BindTexture(TextureTarget.Texture2D, m_textureID);
 }
Esempio n. 27
0
 public void BindAndActivate(int unit)
 {
     GL.BindTexture(TextureTarget.Texture2D, GlHandle);
     GL.ActiveTexture(TextureUnit.Texture0 + unit);
 }
Esempio n. 28
0
        public SSShadowMapBase(TextureUnit texUnit, int textureWidth, int textureHeight)
        {
            if (!OpenTKHelper.areFramebuffersSupported())
            {
                m_isValid = false;
                return;
            }
            #if false
            if (s_numberOfShadowMaps >= c_maxNumberOfShadowMaps)
            {
                throw new Exception("Unsupported number of shadow maps: "
                                    + (c_maxNumberOfShadowMaps + 1));
            }
            #endif
            ++s_numberOfShadowMaps;

            m_frameBufferID = GL.Ext.GenFramebuffer();
            if (m_frameBufferID < 0)
            {
                throw new Exception("gen fb failed");
            }
            m_textureID     = GL.GenTexture();
            m_textureWidth  = textureWidth;
            m_textureHeight = textureHeight;

            // bind the texture and set it up...
            m_textureUnit = texUnit;
            BindShadowMapToTexture();
            GL.TexParameter(TextureTarget.Texture2D,
                            TextureParameterName.TextureMagFilter,
                            (int)TextureMagFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture2D,
                            TextureParameterName.TextureMinFilter,
                            (int)TextureMinFilter.Nearest);
            GL.TexParameter(TextureTarget.Texture2D,
                            TextureParameterName.TextureWrapS,
                            (int)TextureWrapMode.ClampToEdge);
            GL.TexParameter(TextureTarget.Texture2D,
                            TextureParameterName.TextureWrapT,
                            (int)TextureWrapMode.ClampToEdge);

            GL.TexImage2D(TextureTarget.Texture2D, 0,
                          PixelInternalFormat.DepthComponent32f,
                          m_textureWidth, m_textureHeight, 0,
                          PixelFormat.DepthComponent, PixelType.Float, IntPtr.Zero);
            // done creating texture, unbind
            GL.BindTexture(TextureTarget.Texture2D, 0);


            // ----------------------------
            // now bind the texture to framebuffer..
            GL.Ext.BindFramebuffer(FramebufferTarget.DrawFramebuffer, m_frameBufferID);
            GL.Ext.BindFramebuffer(FramebufferTarget.ReadFramebuffer, m_frameBufferID);

            GL.Ext.FramebufferTexture2D(FramebufferTarget.DrawFramebuffer, FramebufferAttachment.DepthAttachment,
                                        TextureTarget.Texture2D, m_textureID, 0);
            //GL.Ext.FramebufferTexture (FramebufferTarget.FramebufferExt, FramebufferAttachment.Color,
            //(int)All.None, 0);

            GL.Viewport(0, 0, m_textureWidth, m_textureHeight);
            GL.DrawBuffer(DrawBufferMode.None);
            GL.ReadBuffer(ReadBufferMode.None);

            if (!assertFramebufferOK(FramebufferTarget.DrawFramebuffer))
            {
                throw new Exception("failed to create-and-bind shadowmap FBO");
            }

            // leave in a sane state...
            unbindFramebuffer();
            GL.ActiveTexture(TextureUnit.Texture0);
            if (!assertFramebufferOK(FramebufferTarget.DrawFramebuffer))
            {
                throw new Exception("failed to ubind shadowmap FBO");
            }
        }
Esempio n. 29
0
 public void Use(TextureUnit unit = TextureUnit.Texture0)
 {
     GL.ActiveTexture(unit);
     GL.BindTexture(TextureTarget.Texture2D, texture);
 }
Esempio n. 30
0
 public void BindTexture(int textureId)
 {
     GL.ActiveTexture(TextureUnit.Texture0);
     GL.BindTexture(TextureTarget.Texture2D, textureId);
     GL.Uniform1(_id, 0);             // bind the shader to "Texture0"
 }