OpenTK Text rendering without GL.Begin() - c#

I am writing an application with OpenTK and got to the point where i want to render text. From examples i patched together a version that creates a bitmap with the characters i need, using Graphics.DrawString(). That version works quite okay, but i am annoyed that it relies on GL.Begin(BeginMode.Quads) and GL.End() to render the text, which is why i want to use VAOs and VBOs from now on.
I am having a problem somewhere in my program, because i always get single colored squares, where the text should appear.
What i did so far to update my functions is the following:
I create the bitmap the same as before, i don't see why the problem should lie there.
After that i create a list of "Char" Objects, each creating a VBO, storing the position and texture coordinates like this:
float u_step = (float)GlyphWidth / (float)TextureWidth;
float v_step = (float)GlyphHeight / (float)TextureHeight;
float u = (float)(character % GlyphsPerLine) * u_step;
float v = (float)(character / GlyphsPerLine) * v_step;
float x = -GlyphWidth / 2, y = 0;
_vertices = new float[]{
x/rect.Width, -GlyphHeight/rect.Height, u, v,
-x/rect.Width, -GlyphHeight/rect.Height, u + u_step, v,
-x/rect.Width, y/rect.Height, u + u_step, v + v_step,
x/rect.Width, -GlyphHeight/rect.Height, u, v,
-x/rect.Width, y/rect.Height, u + u_step, v + v_step,
x/rect.Width, y/rect.Height, u, v + v_step
};
_VBO = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, _VBO);
GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr)(sizeof(float) * _vertices.Length),
_vertices, BufferUsageHint.DynamicDraw);
Next i generate a Texture, set texture0 as active and bind the Texture as TextureTarget.Texture2D. Then i load the bitmap to the texture doing the following:
_shader.Use();
_vertexLocation = _shader.GetAttribLocation("aPosition");
_texCoordLocation = _shader.GetAttribLocation("aTexCoord");
_fontTextureID = GL.GenTexture();
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, _fontTextureID);
using (var image = new Bitmap("container.png")) //_fontBitmapFilename))//
{
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.OpenGL.PixelFormat.Bgra,
PixelType.UnsignedByte,
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);
I create a VAO now, bind it, and bind one VBO to it. Then i set up the VertexAttribPointers to interpret the VBO Data:
_VAO = GL.GenVertexArray();
GL.BindVertexArray(_VAO);
GL.BindBuffer(BufferTarget.ArrayBuffer, _charSheet[87].VBO);
GL.EnableVertexAttribArray(_vertexLocation);
GL.VertexAttribPointer(_vertexLocation, 2, VertexAttribPointerType.Float, false, 4 * sizeof(float), 0);
GL.EnableVertexAttribArray(_texCoordLocation);
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, _fontTextureID);
GL.VertexAttribPointer(_texCoordLocation, 2, VertexAttribPointerType.Float, false, 4 * sizeof(float), 2);
GL.BindVertexArray(0);
_shader.StopUse();
My Render function starts by using the shader, binding the VAO and enabling the VertexAttribArrays. Then i bind the VBO, in this function a fixed one for testing, and reuse the VertexAttribPointer functions, so that the VAO updates its data (i might also be wrong thinking so..). At the end i draw two triangles, which makes a square, where the letter should appear.
_shader.Use();
GL.BindVertexArray(_VAO);
GL.EnableVertexAttribArray(_texCoordLocation);
GL.EnableVertexAttribArray(_vertexLocation);
GL.BindBuffer(BufferTarget.ArrayBuffer, _charSheet[87].VBO);
GL.VertexAttribPointer(_vertexLocation, 2, VertexAttribPointerType.Float, false, 4 * sizeof(float), 0);
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, _fontTextureID);
GL.VertexAttribPointer(_texCoordLocation, 2, VertexAttribPointerType.Float, false, 4 * sizeof(float), 2);
GL.DrawArrays(PrimitiveType.Triangles, 0, 6);
GL.BindVertexArray(0);
_shader.StopUse();
I do not know, where I'm doing something wrong in my program, maybe someone has a tip for me.
Vertex Shader
#version 330 core
layout(location = 0) in vec2 aPosition;
layout(location = 1) in vec2 aTexCoord;
out vec2 texCoord;
void main(void)
{
texCoord = aTexCoord;
gl_Position = vec4(aPosition, 0.0, 1.0);
}
Fragment Shader:
#version 330
out vec4 outputColor;
in vec2 texCoord;
uniform sampler2D texture0;
void main()
{
outputColor = texture(texture0, texCoord);
}

If a named buffer object is bound, then the last parameter of GL.VertexAttribPointer is treated as byte offset to the buffer object's data store.
The offset has to be 2*sizeof(float) rather than 2:
GL.VertexAttribPointer(_texCoordLocation, 2, VertexAttribPointerType.Float, false, 4 * sizeof(float), 2);
GL.VertexAttribPointer(_texCoordLocation, 2,
VertexAttribPointerType.Float, false, 4 * sizeof(float), 2*sizeof(float));
See glVertexAttribPointer and Vertex Specification.

Related

Why does my OpenGL ES app crash on glDrawElements?

I have developed a mobile game with OpenGL ES 3 on Xamarin (Which uses OpenTK). It's running fine on most devices, but crashes on some devices (HUAWEI Y5 lite). Unfortunately I don't get a detailed log of the error:
#00 pc 0000000000093d2a /vendor/lib/egl/libGLESv2_mtk.so
#01 pc 000000000001c137 /vendor/lib/egl/libGLESv2_mtk.so
#02 pc 000000000001eddf /vendor/lib/egl/libGLESv2_mtk.so
#03 pc 000000000001af75 /vendor/lib/egl/libGLESv2_mtk.so
#04 pc 000000000001aabf /vendor/lib/egl/libGLESv2_mtk.so (glDrawElements+54)
#05 pc 000000000000ca0c <anonymous>
I'm guessing it has something to do with my draw code or worse with some driver issues of the phone. I'm using the following code to render quads:
public void BeforeRender()
{
// Use shader program.
GL.UseProgram(shader.Program);
// Enable transparency
GL.Enable(EnableCap.Blend);
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
// Use texture
GL.ActiveTexture(TextureUnit.Texture0);
GL.Uniform1(shader.UniformTexture, 0);
// Only bind once for all quads
GL.BindBuffer(BufferTarget.ElementArrayBuffer, indexBufferId);
}
public void Render(Sprite sprite, Vector4 color, Matrix4 modelViewProjection)
{
// Set model view projection
GL.UniformMatrix4(shader.UniformModelViewProjection, false, ref modelViewProjection);
// Set color
GL.Uniform4(shader.UniformColor, color);
// Set texture
GL.BindTexture(TextureTarget.Texture2D, sprite.TextureId);
// Update attribute value Position
GL.BindBuffer(BufferTarget.ArrayBuffer, sprite.Vbo);
GL.VertexAttribPointer(shader.AttribVertex, 3, VertexAttribPointerType.Float, false, sizeof(float) * 5, IntPtr.Zero); // 3 + 2 = 5
GL.EnableVertexAttribArray(shader.AttribVertex);
// Update attribute value TexCoord
GL.VertexAttribPointer(shader.AttribTexCoord, 2, VertexAttribPointerType.Float, false, sizeof(float) * 5, new IntPtr(sizeof(float) * 3));
GL.EnableVertexAttribArray(shader.AttribTexCoord);
// Draw quad
GL.DrawElements(BeginMode.Triangles, faceIndexes.Length, DrawElementsType.UnsignedShort, IntPtr.Zero);
}
public void AfterRender()
{
// Unbind / Disable
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
GL.Disable(EnableCap.Blend);
}
To draw multiple quads I just call the methods like this:
BeforeRender();
foreach(var sprite in sprites)
{
Render(sprite);
}
AfterRender();
Is there something wrong with my code in general which might cause problems on some devices which other devices "tolerate"?
Thanks in advance!
Update:
Here is how I create the buffers:
public int Load<T>(T[] data)
where T : struct
{
int bufferId;
GL.GenBuffers(1, out bufferId);
bufferIds.Add(bufferId);
GL.BindBuffer(BufferTarget.ArrayBuffer, bufferId);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(data.Length * Marshal.SizeOf(default(T))), data, BufferUsage.StaticDraw);
GL.BindBuffer(BufferTarget.ArrayBuffer, 0);
return bufferId;
}
For the index buffer i use:
ushort[] faceIndexes =
{
0, 1, 2, 1, 3, 2
};
indexBufferId = bufferManager.Load(faceIndexes);
For the vertex buffer I use:
float[] vertices =
{
0f, 0f, 0f, 0f, ty,
width, 0f, 0f, tx, ty,
0f, height, 0f, 0f, 0f,
width, height, 0f, tx, 0f
};
int vboId = bufferManager.Load(vertices);
The indices have to be store to an ElementArrayBuffer rather than an ArrayBuffer:
GL.BindBuffer(BufferTarget.ArrayBuffer, bufferId); ...
GL.BindBuffer(BufferTarget.ElementArrayBuffer, bufferId);
GL.BufferData(BufferTarget.ElementArrayBuffer, (IntPtr)(data.Length * Marshal.SizeOf(default(T))), data, BufferUsage.StaticDraw);
GL.BindBuffer(BufferTarget.ElementArrayBuffer, 0);
Add a target argument to the generic Load method. For instance:
public int Load<T>(T[] data, BufferTarget target)
where T : struct
{
int bufferId;
GL.GenBuffers(1, out bufferId);
bufferIds.Add(bufferId);
GL.BindBuffer(target, bufferId);
GL.BufferData(target, (IntPtr)(data.Length * Marshal.SizeOf(default(T))), data, BufferUsage.StaticDraw);
GL.BindBuffer(target, 0);
return bufferId;
}
indexBufferId = bufferManager.Load(faceIndexes, BufferTarget.ElementArrayBuffer);
int vboId = bufferManager.Load(vertices, BufferTarget.ArrayBuffer);
I have found the issue, that was causing my app to crash on some devices. Apparently there was an item slipping in to the drawing routine, which was passing a buffer id 0 into GL.BindBuffer. On some devices this was causing the following error when Gl.DrawElements was called: emuglGLESv2_enc: sendVertexAttributes: bad offset / len!!!!!
The solution was of course to not execute this code anymore whenever the buffer id is 0 or no buffer for the id was created.
In my case the 0 was not returned by GL.GenBuffers. I had some sprites which should be empty (not rendered), and my orignal solution was to set the buffer id to 0.

Opengl OpenTK - White screen when drawing depth Buffer [duplicate]

This question already has an answer here:
OpenGL 4.2 LookAt matrix only works with -z value for eye position
(1 answer)
Closed 2 years ago.
I am currently trying to add shadows with Shadow Mapping to my 3D Engine.
First I render the scene from the light's point of view, and save the depth values in a texture. Then I use the defeault FBO to draw from the texture. Just like in this tutorial.
The problem is that my screen stays white, no matter where I move.
GL.GetError() outputs noError and the SSBO's which I use in vertex shader have the right values. GL.CheckFramebufferStatus() returns FramebufferCompleteExt.
This is how I create the FBO for depth values:
_depthMapFBO = GL.GenFramebuffer();
_depthMapFBOColorBuffer = BufferObjects.FBO_TextureAttachment(_depthMapFBO, PixelInternalFormat.DepthComponent, PixelFormat.DepthComponent, FramebufferAttachment.DepthAttachment, 1024, 1024);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, _depthMapFBO);
GL.DrawBuffer(DrawBufferMode.None);
GL.ReadBuffer(ReadBufferMode.None);
====================================
public static int FBO_TextureAttachment(int FrameBuffer, PixelInternalFormat PixelInternalFormat, PixelFormat PixelFormat, FramebufferAttachment FramebufferAttachment, int Width, int Height)
{
// PixelInternalFormat = DepthComponent && PixelFormat = DepthComponent && FramebufferAttachment = DepthAttachment && Width, Height = 1024,
GL.BindFramebuffer(FramebufferTarget.Framebuffer, FrameBuffer);
int _texture = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, _texture);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat, Width, Height, 0, PixelFormat, PixelType.Float, IntPtr.Zero);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Nearest);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Nearest);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.Repeat);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.Repeat);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment, TextureTarget.Texture2D, _texture, 0);
return _texture;
}
In my Render function it looks like this:
GL.BindFramebuffer(FramebufferTarget.Framebuffer, _depthMapFBO);
GL.Clear(ClearBufferMask.DepthBufferBit);
GL.Viewport(0, 0, 1024, 1024);
_simpleDepthProgram.Use();
float _nearPlane = 1.0f, _farPlane = 100f;
_lightProjection = Matrix4.CreateOrthographicOffCenter(-100.0f, 100.0f, -100.0f, 100.0f, _nearPlane, _farPlane);
_ligthView = Matrix4.LookAt(_allLamps[0].Position, new Vector3(0f), new Vector3(0.0f, 1.0f, 0.0f));
_lightSpaceMatrix = _lightProjection * _ligthView;
GL.UniformMatrix4(21, false, ref _lightSpaceMatrix);
// Copy all SSBO's
GL.ActiveTexture(TextureUnit.Texture2);
GL.BindTexture(TextureTarget.Texture2D, _depthMapFBOColorBuffer);
Scene();
And the shader where I draw the depthMap:
#version 450 core
out vec4 FragColor;
uniform sampler2D scene;
uniform sampler2D bloomed;
uniform sampler2D depthMap;
uniform float zNear;
uniform float zFar;
float LinearizeDepth(float depth)
{
float z = depth * 2.0 - 1.0; // Back to NDC
return (2.0 * zNear * zFar) / (zFar + zNear - z * (zFar - zNear));
}
in vec2 TexCoord;
void main()
{
float depthValue = texture(depthMap, TexCoord).r;
//float depth = LinearizeDepth(gl_FragCoord.z) / far; // only for perspective
FragColor = vec4(vec3(depthValue), 1.0);
}
The computation of the _lightSpaceMatrix is wrong. The OpenTK matrix multiplication is reversed. See Problem with matrices #687:
Because of how matrices are treated in C# and OpenTK, multiplication order is inverted from what you might expect in C/C++ and GLSL. This is an old artefact in the library, and it's too late to change now, unfortunately.
Swap the _ligthView and _lightProjection when you multiply the matrices:
_lightSpaceMatrix = _lightProjection * _ligthView;
_lightSpaceMatrix = _ligthView * _lightProjection;

C#/OpenTK - Problems applying shaders to loaded texture. Texture is scaled down and flipped

I've been trying to figure out how to get this to work. I'm using OpenTK for C# to modify images. Right now I'm able to load an image successfully, but when I try to modify the image with shaders is where I begin to have problems. I have 3 basic methods:
1) LoadTexture (sets the texture to GL)
2) DrawImage (actually draws the texture)
3) AddShaders (this method is called inside DrawImage.It applies the
shaders)
So here are the 2 problems I'm having:
1) I'm trying to create 2 triangles that span the entire texture.
This is because I want my fragment shader to do work over the entire
texture. What I'm actually getting is a large triangle that covers
the left side of the screen, and a rectangle on the right side of the
screen. EDIT: Made some progress! But still looking weird...Shader scripts updated..EDIT2: Newer progress pic uploaded
2) The shapes are showing up green, when I want them to use the
colors from the texture but red channel modified. What's important to
know is that I need to be able to analyze each pixel. Changing the
red channel of every pixel is JUST a proof of concept for what I want
to actually do (using color distance formulas, hue shifting, etc. but
I need to start simpler first)
This is the image I've successfully loaded as a texture:Loaded Texture
Here's the code for LoadTexture:
public int LoadTexture(string file)
{
Bitmap bitmap = new Bitmap(file);
int tex;
GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
GL.GenTextures(1, out tex);
GL.BindTexture(TextureTarget.Texture2D, tex);
BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
bitmap.UnlockBits(data);
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);
return tex;
}
Here's the code for DrawImage:
public static void DrawImage(int image)
{
GL.MatrixMode(MatrixMode.Projection);
GL.PushMatrix();
GL.LoadIdentity();
GL.Ortho(0, 1920, 0, 1080, -1, 1);
GL.MatrixMode(MatrixMode.Modelview);
GL.PushMatrix();
GL.LoadIdentity();
GL.Disable(EnableCap.Lighting);
GL.Enable(EnableCap.Texture2D);
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, image);
GL.Begin(PrimitiveType.Quads);
GL.TexCoord2(0,1);
GL.Vertex3(0, 0, 0);
GL.TexCoord2(1, 1);
GL.Vertex3(1920, 0, 0);
GL.TexCoord2(1, 0);
GL.Vertex3(1920, 1080, 0);
GL.TexCoord2(0, 0);
GL.Vertex3(0, 1080, 0);
GL.End();
AddShaders();
GL.Disable(EnableCap.Texture2D);
GL.PopMatrix();
GL.MatrixMode(MatrixMode.Projection);
GL.PopMatrix();
GL.MatrixMode(MatrixMode.Modelview);
ErrorCode ec = GL.GetError();
if (ec != 0)
System.Console.WriteLine(ec.ToString());
Console.Read();
}
And here's the code for AddShaders:
private static void AddShaders()
{
/***********Vert Shader********************/
var vertShader = GL.CreateShader(ShaderType.VertexShader);
GL.ShaderSource(vertShader, #"attribute vec3 a_position;
varying vec2 vTexCoord;
void main() {
vTexCoord = a_position.xy;
gl_Position = vec4(a_position, 1);
}");
GL.CompileShader(vertShader);
/***********Frag Shader ****************/
var fragShader = GL.CreateShader(ShaderType.FragmentShader);
GL.ShaderSource(fragShader, #"uniform sampler2D sTexture;
varying vec2 vTexCoord;
void main ()
{
vec4 color = texture2D (sTexture, vTexCoord);
color.r = 0.5;
// Save the result
gl_FragColor = color;
}");
GL.CompileShader(fragShader);
var program = GL.CreateProgram();
GL.AttachShader(program, vertShader);
GL.AttachShader(program, fragShader);
GL.LinkProgram(program);
GL.ClearColor(Color.AliceBlue);
// OpenGL expects vertices to be defined counter clockwise by default
float[] vertices = {
// Left bottom triangle
-1f, 1f, 0f,
-1f, -1f, 0f,
1f, -1, 0f,
// Right top triangle
1f, -1f, 0f,
1f, 1f, 0f,
-1f, 1f, 0f
};
var buffer = GL.GenBuffer();
var positionLocation = GL.GetAttribLocation(program, "a_position");
GL.EnableVertexAttribArray(positionLocation);
GL.BindBuffer(BufferTarget.ArrayBuffer, buffer);
GL.VertexAttribPointer(positionLocation, 3, VertexAttribPointerType.Float,false,0,0);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * sizeof(ushort)), vertices, BufferUsageHint.StaticDraw);
GL.DrawArrays(PrimitiveType.Triangles, 0, vertices.Length);
GL.UseProgram(program);
}
I've researched this for a few days and I'm just completely stuck. Thanks to anyone who can see what I'm doing wrong. It HAS to be something small and dumb on my part!
EDIT: When I remove ALL vertex related code in AddShaders, I get the output I want, except its 1/4 the size and flipped in the top right of the screen. So, somehow my shaders don't even care about the vertices. Why is it being scaled down to 1/4 size and flipped?
EDIT2: Ok so thanks to Robert Rouhani, I've ALMOST got this working! Progress It looks like the triangle vertices might be messed up??
Here's my new code. I refactored functionality into methods, stopped creating programs / buffers every frame, etc. Now I have class level variables to hold the GL specific data, methods to create the GL program for the app, create the shaders, create the buffers, etc. Also I know that the 1920x1080 hardcode is, well, hardcoded. That is on my plate to make dynamic.
string file = "lambo2.png";
int program;
int vertShader;
int fragShader;
int buffer;
int positionLocation;
int texture;
float[] vertices = {
// Left bottom triangle
-1f, -1f, 0f,
1f, -1f, 0f,
1f, 1f, 0f,
// Right top triangle
1f, 1f, 0f,
-1f, 1f, 0f,
-1f, -1f, 0f
};
private void CreateProgram()
{
program = GL.CreateProgram();
GL.AttachShader(program, vertShader);
GL.AttachShader(program, fragShader);
GL.LinkProgram(program);
}
private void CreateShaders()
{
/***********Vert Shader********************/
vertShader = GL.CreateShader(ShaderType.VertexShader);
GL.ShaderSource(vertShader, #"attribute vec3 a_position;
varying vec2 vTexCoord;
void main() {
vTexCoord = (a_position.xy + 1) / 2;
gl_Position = vec4(a_position, 1);
}");
GL.CompileShader(vertShader);
/***********Frag Shader ****************/
fragShader = GL.CreateShader(ShaderType.FragmentShader);
GL.ShaderSource(fragShader, #"precision highp float;
uniform sampler2D sTexture;
varying vec2 vTexCoord;
void main ()
{
vec4 color = texture2D (sTexture, vTexCoord);
if(color.r < 0.3){color.r = 1.0;}
// Save the result
gl_FragColor = color;
}");
// GL.ShaderSource(fragShader, System.IO.File.ReadAllText(#"C:\Users\Matt\Desktop\hue-shader-backup.ps"));
GL.CompileShader(fragShader);
}
private void InitBuffers()
{
buffer = GL.GenBuffer();
positionLocation = GL.GetAttribLocation(program, "a_position");
GL.EnableVertexAttribArray(positionLocation);
GL.BindBuffer(BufferTarget.ArrayBuffer, buffer);
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * sizeof(ushort)), vertices, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(positionLocation, 3, VertexAttribPointerType.Float, false, 0, 0);
}
private void Init()
{
texture = LoadTexture(file);
CreateShaders();
CreateProgram();
InitBuffers();
}
public int LoadTexture(string file)
{
Bitmap bitmap = new Bitmap(file);
int tex;
GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
GL.GenTextures(1, out tex);
GL.BindTexture(TextureTarget.Texture2D, tex);
bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
bitmap.UnlockBits(data);
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.ClampToEdge);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.ClampToEdge);
return tex;
}
public void DrawImage(int image)
{
GL.Viewport(new Rectangle(0, 0, 1920, 1080));
GL.MatrixMode(MatrixMode.Projection);
GL.PushMatrix();
GL.LoadIdentity();
GL.Ortho(0, 1920, 0, 1080, 0, 1);
GL.MatrixMode(MatrixMode.Modelview);
GL.PushMatrix();
GL.LoadIdentity();
GL.Disable(EnableCap.Lighting);
GL.Enable(EnableCap.Texture2D);
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, image);
GL.Begin(PrimitiveType.Quads);
GL.TexCoord2(0, 1);
GL.Vertex3(0, 0, 0);
GL.TexCoord2(1, 1);
GL.Vertex3(1920, 0, 0);
GL.TexCoord2(1, 0);
GL.Vertex3(1920, 1080, 0);
GL.TexCoord2(0, 0);
GL.Vertex3(0, 1080, 0);
GL.End();
RunShaders();
GL.Disable(EnableCap.Texture2D);
GL.PopMatrix();
GL.MatrixMode(MatrixMode.Projection);
GL.PopMatrix();
GL.MatrixMode(MatrixMode.Modelview);
ErrorCode ec = GL.GetError();
if (ec != 0)
System.Console.WriteLine(ec.ToString());
Console.Read();
}
private void RunShaders()
{
GL.ClearColor(Color.AliceBlue);
GL.UseProgram(program);
GL.DrawArrays(PrimitiveType.Triangles, 0, vertices.Length / 3);
ErrorCode ec = GL.GetError();
if (ec != 0)
System.Console.WriteLine(ec.ToString());
Console.Read();
}
Going to start an answer instead of continuing the comments. You've still got a few minor issues that are compounding. You should comment out everything between and including GL.Begin and GL.End as the RunShaders function should do draw everything you need to the screen. Also comment out the GL.Ortho line, you don't need it if you're working with the vertices in the [-1, 1] range.
Second, your issue is that you're only uploading half your vertex buffer to the GPU. In InitBuffers on the GL.BufferData line, change sizeof(ushort) to sizeof(float), since your vertices are floats (4 bytes long) and not ushorts (2 bytes long).
GL.BufferData(BufferTarget.ArrayBuffer, (IntPtr)(vertices.Length * sizeof(float)), vertices, BufferUsageHint.StaticDraw);
Together this should get your program working.

OpenGL texture rendering - only upper left pixel is displayed

I working with C# and OpenTK.
Currently I only want to map a texture on a triangle.
It seems to be working but on nearest texture filter, the whole triangle is only colored with the upper left pixel color of the bmp image and if I set the texture filter to linear the triangle shows still only one color, but it seems whether it is now mixed with the other pixels.
Can someone find the error in the code ?
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
GL.Enable(EnableCap.Texture2D);
GL.ClearColor(0.5F, 0.5F, 0.5F, 1.0F);
int vertexShaderHandle = GL.CreateShader(ShaderType.VertexShader);
int fragmentShaderHandle = GL.CreateShader(ShaderType.FragmentShader);
string vertexShaderSource = #"#version 400
layout(location = 0) in vec3 position;
layout(location = 1) in vec2 uv;
out vec2 texture_uv;
void main()
{
gl_Position = vec4(inPosition.xyz, 1);
texture_uv = uv;
}";
string fragmentShaderSource = #"#version 400
in vec2 texture_uv;
out vec3 outColor;
uniform sampler2D uniSampler;
void main()
{
outColor = texture( uniSampler, texture_uv ).rgb;
}";
GL.ShaderSource(vertexShaderHandle, vertexShaderSource);
GL.ShaderSource(fragmentShaderHandle, fragmentShaderSource);
GL.CompileShader(vertexShaderHandle);
GL.CompileShader(fragmentShaderHandle);
prgHandle = GL.CreateProgram();
GL.AttachShader(prgHandle, vertexShaderHandle);
GL.AttachShader(prgHandle, fragmentShaderHandle);
GL.LinkProgram(prgHandle);
GL.DetachShader(prgHandle, vertexShaderHandle);
GL.DetachShader(prgHandle, fragmentShaderHandle);
GL.DeleteShader(vertexShaderHandle);
GL.DeleteShader(fragmentShaderHandle);
uniSamplerLoc = GL.GetUniformLocation(prgHandle, "uniSampler");
texHandle = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, texHandle);
Bitmap bmp = new Bitmap("C:/Users/Michael/Desktop/Test.bmp");
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, bmpData.Width, bmpData.Height, 0,
OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0);
bmp.UnlockBits(bmpData);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);
vaoHandle = GL.GenVertexArray();
GL.BindVertexArray(vaoHandle);
vboHandle = GL.GenBuffer();
GL.BindBuffer(BufferTarget.ArrayBuffer, vboHandle);
float[] bufferData = { 0.5F, 1, 0, 1, 1,
0, 0, 0, 0, 0,
1, 0, 0, 1, 0 };
GL.BufferData<float>(BufferTarget.ArrayBuffer, (IntPtr) (15 * sizeof(float)), bufferData, BufferUsageHint.StaticDraw);
GL.EnableVertexAttribArray(0);
GL.EnableVertexAttribArray(1);
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 5 * sizeof(float), 0);
GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 5 * sizeof(float), 3 * sizeof(float));
}
protected override void OnUnload(EventArgs e)
{
base.OnUnload(e);
GL.DeleteTexture(texHandle);
GL.DeleteProgram(prgHandle);
GL.DeleteBuffer(vboHandle);
GL.DeleteVertexArray(vaoHandle);
}
protected override void OnRenderFrame(FrameEventArgs e)
{
base.OnRenderFrame(e);
GL.Clear(ClearBufferMask.ColorBufferBit);
GL.UseProgram(prgHandle);
GL.Uniform1(uniSamplerLoc, texHandle);
GL.BindVertexArray(vaoHandle);
GL.DrawArrays(PrimitiveType.Triangles, 0, 3);
SwapBuffers();
}
EDIT:
I tried this:
protected override void OnRenderFrame(FrameEventArgs e)
{
base.OnRenderFrame(e);
GL.Clear(ClearBufferMask.ColorBufferBit);
GL.UseProgram(prgHandle);
GL.BindVertexArray(vaoHandle);
GL.ActiveTexture(TextureUnit.Texture3);
GL.BindTexture(TextureTarget.Texture2D, texHandle);
GL.Uniform1(uniSamplerLoc, 3);
GL.DrawArrays(PrimitiveType.Triangles, 0, 3);
SwapBuffers();
}
But nothing changed :(
The value of a sampler uniform variable needs to be the texture unit it should sample from. In your code, it is set to the texture name (aka texture id, aka texture handle) instead:
GL.Uniform1(uniSamplerLoc, texHandle);
The texture unit can be set with ActiveTexture(). When glBindTexture() is called, the value of the currently active texture unit determines which unit the texture is bound to. The default for the active texture unit is 0. So if you never called ActiveTexture(), the uniform should be set as:
GL.Uniform1(uniSamplerLoc, 0);
Just as a heads-up, another related source of errors is that the value of the uniform is a 0-based index of the texture unit, while the glActiveTexture() call takes an enum starting with GL_TEXTURE0. For example with the C bindings (not sure how exactly this looks with C# and OpenTK, but it should be similar enough), this would bind a texture to texture unit 3, and set a uniform sampler variable to use it:
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, texId);
glUniform1i(texUniformLoc, 3);
Note how GL_TEXTURE3 is used in the argument for glActiveTexture(), but a plain 3 in glUniform1i().

OpenGL 2d sprite not rendering (OpenTK)

I have been working on a render and it has been working OK for one texture but would not render a second. I seemed to have changed something and it stopped rendering anything but the background color. I am not sure what I changed and I cannot get it back to the way it was. I try not to post lots of code at once onto here but I do not know enough OpenGL to isolate the issue. If you can offer any help or hints, I would greatly appreciate it!
My guess is that it is either coming from the way I am binding the coordinate or the shader.
The following is the code:
Shaders:
string vertexShaderSource = #"
#version 330
layout (location = 0) in vec3 Position;
uniform mat4 projectionmatrix;
uniform mat4 ModelMatrix;
uniform mat4 ViewMatrix;
attribute vec2 texcoord;
varying vec2 f_texcoord;
uniform vec2 pos;
void main()
{
f_texcoord = texcoord;
gl_Position = projectionmatrix * vec4(Position, 1);
//gl_Position = projectionmatrix * vec4(Position.xyz, 1.0);
}
";
string fragmentShaderSource = #"
#version 330
out vec4 FragColor;
varying vec2 f_texcoord;
uniform sampler2D mytexture;
void main()
{
FragColor = texture2D(mytexture, f_texcoord);
//FragColor = Vec4(0,0,0, 1);
}";
Vertexes:
Vector2[] g_vertex_buffer_data ={
new Vector2(-1.0f, 1.0f),
new Vector2(1.0f, 1.0f),
new Vector2(1.0f, -1.0f),
new Vector2(-1.0f, -1.0f)
};
Vector2[] g_texture_coords = {
new Vector2(0.0f, 0.0f),
new Vector2(1.0f, 0.0f),
new Vector2(1.0f, -1.0f),
new Vector2(0.0f, -1.0f)
};
Shader setup:
shaderProgramHandle = GL.CreateProgram();
vertexShaderHandle = GL.CreateShader(ShaderType.VertexShader);
fragmentShaderHandle = GL.CreateShader(ShaderType.FragmentShader);
GL.ShaderSource(vertexShaderHandle, vertexShaderSource);
GL.ShaderSource(fragmentShaderHandle, fragmentShaderSource);
GL.CompileShader(vertexShaderHandle);
GL.CompileShader(fragmentShaderHandle);
GL.AttachShader(shaderProgramHandle, vertexShaderHandle);
GL.AttachShader(shaderProgramHandle, fragmentShaderHandle);
GL.LinkProgram(shaderProgramHandle);
GL.UseProgram(shaderProgramHandle);
Basic setup and binding:
GL.ClearColor(Color4.Red);
//GL.LoadMatrix(ref projectionMatrix);
GL.GenBuffers(2, out vertexbuffer);
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexbuffer);
GL.BufferData<Vector2>(BufferTarget.ArrayBuffer,
new IntPtr(g_vertex_buffer_data.Length * Vector2.SizeInBytes),
g_vertex_buffer_data, BufferUsageHint.StaticDraw);
//Shader Setup
CreateShaders();
Matrix4 projectionMatrix = Matrix4.CreateOrthographic(control.Width, control.Height, -1, 1);
vertexShaderProjectionHandle = GL.GetUniformLocation(shaderProgramHandle, "projectionmatrix");
GL.UniformMatrix4(vertexShaderProjectionHandle, false, ref projectionMatrix);
GL.EnableVertexAttribArray(0);
GL.BindBuffer(BufferTarget.ArrayBuffer, vertexbuffer);
GL.VertexAttribPointer(0, 2, VertexAttribPointerType.Float, false, 0, 0);
Loading and binding the texture:
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
GL.Enable(EnableCap.Blend);
GL.ActiveTexture(TextureUnit.Texture0 + texture.textureID);
GL.BindTexture(TextureTarget.Texture2D, texture.textureID);
textureHandle = GL.GetAttribLocation(shaderProgramHandle, "texcoord");
GL.GenBuffers(1, out textureBufferHandle);
GL.BindBuffer(BufferTarget.ArrayBuffer, textureBufferHandle);
GL.BufferData<Vector2>(BufferTarget.ArrayBuffer, new IntPtr(Vector2.SizeInBytes * 4), g_texture_coords, BufferUsageHint.StaticDraw);
Matrix Setup:
//rotation += MathHelper.DegreesToRadians(1);
float displayRatio = ((float)control.Height / (float)control.Width);
Matrix4 ViewMatrix = Matrix4.Identity;
int ViewMatrixHandle = GL.GetUniformLocation(shaderProgramHandle, "ViewMatrix");
GL.UniformMatrix4(ViewMatrixHandle, true, ref ViewMatrix);
Matrix4 ModelMatrix = Matrix4.Identity;
int modelMatrixHandle = GL.GetUniformLocation(shaderProgramHandle, "ModelMatrix");
GL.UniformMatrix4(modelMatrixHandle, true, ref ModelMatrix);
int posHandle = GL.GetUniformLocation(shaderProgramHandle, "pos");
GL.Uniform2(posHandle, ref offset);
Rendering
GL.Viewport(0, 0, control.Width, control.Height);
//GL.Enable(EnableCap.Texture2D);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
GL.BindVertexArray(0);
GL.EnableVertexAttribArray(textureHandle);
GL.BindBuffer(BufferTarget.ArrayBuffer, textureBufferHandle);
GL.VertexAttribPointer(textureHandle, 2, VertexAttribPointerType.Float, false, 0, 0);
GL.DrawArrays(BeginMode.Quads, 0, 4);
GL.Flush();
control.SwapBuffers();
You are using the old attribute qualifier to declare texcoord in your vertex shader. This is invalid in GLSL 330, and I suspect if you read the program/shader info logs when you compile/link your GLSL program it includes this information in the log.
To correct this, replace attribute vec2 texcoord with in vec2 texcoord. Then you should get a valid location when you query the attribute location, which is required to set your vertex attribute pointer correctly.
varying is also invalid in GLSL 330. You need to declare f_texcoord as out in your vertex shader and in in your fragment shader for your program to properly link.
There is no error detecting code at all in your code listings. You should read the manual pages for glValidateProgram (...), glGetProgramInfoLog (...) and glGetShaderInfoLog (...), because I am pretty sure the GLSL compiler would have told you your exact problem if you read its output log.

Categories