Texture with unwanted colour - c

I'm trying to learn how to use textures in OpenGL.I don't have freeimage installed so I had to create the bitmap with a for loop.
What I'm trying to do is to simply take a texture with all red points, and to map it inside a square:
#import <OpenGL/OpenGL.h>
#import <GLUT/GLUT.h>
#import <stdlib.h>
#import <string.h>
#import <math.h>
GLuint texture;
GLfloat (*pixels) [3];
void init()
{
// Inizializzazione
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, 1, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, -100, 0, 0, 0, 0, 1, 0);
// Inizializzazione della texture
glGenTextures(1, &texture);
pixels= malloc(256*256*sizeof(GLfloat[3]));
for(GLuint i=0; i<256*256;i++)
{
pixels[i][0]=1.0;
pixels[i][1]= pixels[i][2]= 0.0;
}
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_FLOAT, pixels);
}
void display()
{
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
glPushMatrix();
glBegin(GL_QUADS);
glVertex3f(0, 0, 0);
glTexCoord2f(0.0, 0.0);
glVertex3f(10, 0, 0);
glTexCoord2f(0.0, 1.0);
glVertex3f(10, 10, 0);
glTexCoord2f(1.0, 1.0);
glVertex3f(0, 10, 0);
glTexCoord2f(0.0, 1.0);
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(600, 600);
glutCreateWindow(argv[0]);
glutDisplayFunc(display);
init();
glutMainLoop();
free(pixels);
return 0;
}
The problem is that all the pixels are red, but I get a white square instead of a red one:

You need to bind the texture before you upload data to it, so use glBindTexture before glTexImage2D. Also as it stands the texture will be incomplete, since it has no mipmaps and the default values for minification and magnification filters require them. Use glTexParameter to set the filters to linear, or otherwise create mipmaps.

Give this a shot:
#include <GL/glut.h>
GLuint texture;
void init()
{
// Inizializzazione della texture
unsigned int i;
GLfloat* pixels = (GLfloat*)malloc( 256 * 256 * sizeof( GLfloat ) * 3 );
for( i = 0; i < 256 * 256; i++ )
{
GLuint base = i * 3;
pixels[ base + 0 ] = 1.0f;
pixels[ base + 1 ] = 0.0f;
pixels[ base + 2 ] = 0.0f;
}
glGenTextures(1, &texture);
glBindTexture( GL_TEXTURE_2D, texture );
// disable mipmap filtering since we aren't uploading mipmaps
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, 256, 256, 0, GL_RGB, GL_FLOAT, pixels );
free( pixels);
}
void display( void )
{
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, 1, 1, 1000);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0, 0, -100, 0, 0, 0, 0, 1, 0);
glEnable(GL_DEPTH_TEST);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture);
// important because GL_TEXTURE_ENV defaults to GL_MODULATE
glColor3ub(255,255,255);
glPushMatrix();
glBegin(GL_QUADS);
glVertex3f(0, 0, 0);
glTexCoord2f(0.0, 0.0);
glVertex3f(10, 0, 0);
glTexCoord2f(0.0, 1.0);
glVertex3f(10, 10, 0);
glTexCoord2f(1.0, 1.0);
glVertex3f(0, 10, 0);
glTexCoord2f(0.0, 1.0);
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowPosition(100, 100);
glutInitWindowSize(600, 600);
glutCreateWindow(argv[0]);
init();
glutDisplayFunc(display);
glutMainLoop();
return 0;
}

Related

Opengl is not using the correct texture

I have recently started learning opengl on learnopengl.com. I am the chapter about textures. I have managed to load 2 textures however when I tell opengl to render the texture currently bound to GL_TEXTURE0 it instead draws the texture currently bound to GL_TEXTURE1.
My main.c file looks like this:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "glad/glad.h"
#include "GLFW/glfw3.h"
#include "stb/stb_image_init.h"
#define WIDTH 1080
#define HEIGHT 720
typedef unsigned int uint;
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void process_input(GLFWwindow* window);
void check_shader_compilation(GLuint shader_object, GLenum shader_type);
void check_shader_linking(GLuint shader_program);
char* get_shader_code(const char* path);
int main(void) {
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "Triangle", NULL, NULL);
if (window == NULL) {
printf("Unable to create glfw window!\n");
return -1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
printf("Couldn't initialize glad!\n");
return -1;
}
glViewport(0, 0, WIDTH, HEIGHT);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
char* vertex_shader_code = get_shader_code("shaders/vertex.glsl");
GLuint vertex_shader_object = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader_object, 1, &vertex_shader_code, NULL);
glCompileShader(vertex_shader_object);
check_shader_compilation(vertex_shader_object, GL_VERTEX_SHADER);
free(vertex_shader_code);
char* fragment_shader_code = get_shader_code("shaders/fragment.glsl");
GLuint fragment_shader_object = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader_object, 1, &fragment_shader_code, NULL);
glCompileShader(fragment_shader_object);
check_shader_compilation(fragment_shader_object, GL_FRAGMENT_SHADER);
free(fragment_shader_code);
uint shader_program = glCreateProgram();
glAttachShader(shader_program, vertex_shader_object);
glAttachShader(shader_program, fragment_shader_object);
glLinkProgram(shader_program);
glUseProgram(shader_program);
check_shader_linking(shader_program);
float rectangle_data[] = {
// Coords Colors Texture coords
-0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // Bottom Left
0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Bottom Right
-0.5f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, // Top Left
0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, // Top Right
};
unsigned int indicies[] = {
0, 2, 3,
0, 1, 3,
};
uint vao, vbo, ebo;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glGenBuffers(1, &ebo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ARRAY_BUFFER, sizeof(rectangle_data), rectangle_data, GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indicies), indicies, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float)*8, (void*)0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(float)*8, (void*)(sizeof(float)*3));
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(float)*8, (void*)(sizeof(float)*6));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
float border_color[] = { 1.0f, 0.0f, 0.0f, 1.0f };
uint texture_buffer, texture2_buffer;
glGenBuffers(1, &texture_buffer);
glBindTexture(GL_TEXTURE_2D, texture_buffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border_color);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
stbi_set_flip_vertically_on_load(true);
int width = 0, height = 0, n_channels = 0;
unsigned char* texture_image = stbi_load("assets/textures/luffy.jpg", &width, &height, &n_channels, 0);
if (texture_image) {
printf("Loaded texture0!\n");
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, texture_image);
glGenerateMipmap(GL_TEXTURE_2D);
}
else {
printf("Couldn't find the image for the texture\n");
exit(-1);
}
stbi_image_free(texture_image);
glGenBuffers(1, &texture2_buffer);
glBindTexture(GL_TEXTURE_2D, texture2_buffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border_color);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
int t2_width = 0, t2_height = 0, t2_n_channels = 0;
unsigned char* texture2_image = stbi_load("assets/textures/face.png", &t2_width, &t2_height, &t2_n_channels, 0);
if (texture2_image) {
printf("Loaded texture1!\n");
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, t2_width, t2_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture2_image);
glGenerateMipmap(GL_TEXTURE_2D);
}
else {
printf("Couldn't find the image for texture2\n");
exit(-1);
}
stbi_image_free(texture2_image);
glUseProgram(shader_program);
glUniform1i(glGetUniformLocation(shader_program, "luffy"), 0);
glUniform1i(glGetUniformLocation(shader_program, "face"), 1);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
while (!glfwWindowShouldClose(window)) {
process_input(window);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture_buffer);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2_buffer);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glfwPollEvents();
glfwSwapBuffers(window);
}
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
glDeleteBuffers(1, &ebo);
glDeleteShader(vertex_shader_object);
glDeleteShader(fragment_shader_object);
glDeleteProgram(shader_program);
glfwTerminate();
return 0;
}
void framebuffer_size_callback(GLFWwindow* window, int width, int height) {
glViewport(0, 0, width, height);
}
void process_input(GLFWwindow* window) {
if (glfwGetKey(window, GLFW_KEY_Q) == true) {
glfwSetWindowShouldClose(window, true);
}
}
void check_shader_compilation(GLuint shader_object, GLenum shader_type) {
char* print_shader_type;
switch (shader_type) {
case GL_VERTEX_SHADER:
print_shader_type = "vertex";
break;
case GL_FRAGMENT_SHADER:
print_shader_type = "fragment";
break;
default:
printf("Cannot check for shader compilation, the shader_type is not GL_VERTEX_SHADER or GL_FRAGMENT_SHADER!\n");
exit(-1);
}
int shader_status;
glGetShaderiv(shader_object, GL_COMPILE_STATUS, &shader_status);
if (!shader_status) {
int message_length;
GLchar error[1024];
glGetShaderInfoLog(shader_object, 1024, &message_length, error);
printf("Could not compile the %s shader: \n %s\n", print_shader_type, error);
exit(-1);
}
else {
printf("Compiled the %s shader!\n", print_shader_type);
}
}
void check_shader_linking(GLuint shader_program) {
int linking_status;
glGetProgramiv(shader_program, GL_LINK_STATUS, &linking_status);
if (!linking_status) {
int message_length;
GLchar error[1024];
glGetProgramInfoLog(shader_program, 1024, &message_length, error);
printf("Could not link the shader program:\n %s\n", error);
exit(-1);
}
else {
printf("Linked the shader program!\n");
}
}
char* get_shader_code(const char* path) {
FILE* shader_file = fopen(path, "rb");
if (!shader_file) {
printf("Incorrect file path for shader: %s\n", path);
exit(-1);
}
fseek(shader_file, 0, SEEK_END);
int file_size = ftell(shader_file);
rewind(shader_file);
char* shader_code = malloc(file_size + 1);
shader_code[file_size] = '\0';
fread(shader_code, sizeof(char), file_size, shader_file);
return shader_code;
}
My Vertex shader is:
#version 330
layout (location = 0) in vec3 pos;
layout (location = 1) in vec3 colors;
layout (location = 2) in vec2 texCoords;
out vec3 vertex_colors;
out vec2 tex_coords;
void main() {
gl_Position = vec4(pos.x, pos.y, pos.z, 1.0);
vertex_colors = colors;
tex_coords = texCoords;
}
And my fragment shader is:
#version 330 core
out vec4 fragColor;
in vec3 vertex_colors;
in vec2 tex_coords;
uniform sampler2D luffy;
uniform sampler2D face;
void main() {
fragColor = texture(luffy, tex_coords);
}
Whenever I run the program, it texture it uses is the image in face.png, whereas I told it to use the image in luffy.jpg.
You never create any texture objects:
glGenBuffers(1, &texture_buffer);
glBindTexture(GL_TEXTURE_2D, texture_buffer);
glGenBuffers is for buffer objects, not for texture objects. You have to use glGenTextures. (Also calling your variable texture_buffer here is very confusing. There are buffer textures in the GL, but you're not using those here).
And since you use a core profile, the glBindTexture() call will just generate a GL error and have no other effect, becuase the object name you try to bind never was generated by glGenTextures. So in effect, you are working with texture object 0 here, and load both images to that texture object, with the latter overwriting the former. In a core profiler, using texture object 0 actually shouldn't work, but many drivers still allow it (as it was allowed in legacy GL), so that you actually see any texture at all is not guaranteed either.

Texture Mapping disappeared when added 3D models

I am trying to make a background using SOIL_load_OGL_texture but when I added my 3D models the texture disappeared. The code for 3D models were separated from the texture code but when I combine it, the background becomes black and my 3D models is facing back. Is the problem here because of the coordination?
I expect the output would be the 3D models facing front and it is in front of the texture.
#include <stdlib.h>
#include <stdio.h>
#include <GL/glut.h>
#include "SOIL2.h"
GLuint myTexture;
const GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
static int head = 0, rear = -90, lear = -90, body = 0, lleg = -90, rleg = -90, ball = 0, stage = 0;
GLfloat ballRadius = 0.1f;
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(0.5, 0.85, 0.9); // head
glPushMatrix();
glTranslated(0, 0.25, 0.15);
glRotated((GLfloat)head, 0, 1, 0);
glutSolidSphere(0.2, 40, 50);
glPopMatrix();
glPushMatrix(); //ear
glTranslated(0.11, 0.3, 0.18);
glRotated((GLfloat)rear, 1, 0, 0);
glutSolidCone(0.08, 0.2, 16, 16);
glPopMatrix();
glPushMatrix(); //ear
glTranslated(-0.11, 0.3, 0.18);
glRotated((GLfloat)lear, 1, 0, 0);
glutSolidCone(0.08, 0.2, 16, 16);
glPopMatrix();
glColor3d(0.0, 0.0, 0.0); //eyes
glPushMatrix();
glTranslated(0.07, 0.3, 0.33);
glRotated(-5, 0, 0, 1);
glScalef(0.5, 0.1, 0.1);
glutSolidCube(0.1);
glPopMatrix();
glPushMatrix(); //eyes
glTranslated(-0.07, 0.3, 0.33);
glRotated(-5, 0, 0, -1);
glScalef(0.5, 0.1, 0.1);
glutSolidCube(0.1);
glPopMatrix();
glPushMatrix(); //mouth
glTranslated(0.0, 0.25, 0.35);
glRotated(0, 0, 0, 0);
glScalef(1, 0.1, 0.1);
glutSolidCube(0.1);
glPopMatrix();
glColor3d(1.0, 1.0, 1.0);
glPushMatrix(); // teeth
glTranslated(-0.045, 0.255, 0.34);
glRotated(-90, 1, 0, 0);
glutSolidCone(0.01, 0.02, 16, 16);
glPopMatrix();
glPushMatrix(); // teeth
glTranslated(0.045, 0.255, 0.34);
glRotated(-90, 1, 0, 0);
glutSolidCone(0.01, 0.02, 16, 16);
glPopMatrix();
glColor3d(0.5, 0.85, 0.88); // body
glTranslatef(0, 0, 0.1);
glPushMatrix();
glRotated((GLfloat)body, 1, 0, 0);
glutSolidSphere(0.3, 40, 50);
glPopMatrix();
glPushMatrix();
glTranslatef(0, 0.7, 0.0);
glRotatef((GLfloat)stage, 0.0, 1.0, 0.0);
glTranslatef(1.0, 0.0, 0.0);
glPushMatrix();
glScalef(2.0, 0.4, 1.0);
glutWireCube(1.0);
glPopMatrix();
//glFlush();
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glBindTexture(GL_TEXTURE_2D, myTexture);
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
/*glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f); */
glNormal3f(0.0, 1.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-2.5f, -2.5f, 2.5f);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(2.5f, -2.5f, 2.5f);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(2.5f, -2.5f, -2.5f);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-2.5f, -2.5f, -2.5f);
glEnd();
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
glutSwapBuffers();
}
void reshape(int width, int height)
{
if (height == 0) height = 1; // To prevent divide by 0
GLfloat aspect = (GLfloat)width / (GLfloat)height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//glFrustum(-ar + 1, ar - 1, -1.0, 1.0, 2.0, 90.0);
//gluOrtho2D(0, width, 0, height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(640, 480);
glutCreateWindow("SOIL test");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
myTexture = SOIL_load_OGL_texture("background.png", 0, 1, SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_INVERT_Y);
if (!myTexture)
{
printf("soil failed to load texture\n");
}
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glutMainLoop();
return EXIT_SUCCESS;
}
If you want that the background image is draw in the back, then you've to draw the background first, but disable the Depth Test (The depth buffer has to be cleared before).
This causes that the other geometry covers the background.
When the background is drawn no projection matrix is set, the projection matrix is the identity matrix. So the z-coordinate of the background has to be in [-1, 1], else it wold be clipped by the near or far plane.
If texturing is enabled, then by default the color of the texel is multiplied by the current color, because by default the texture environment mode (GL_TEXTURE_ENV_MODE) is GL_MODULATE. See glTexEnv.
This causes that the color of the texels of the texture is "mixed" by the last color which you have set by glColor3d.
Set a "white" color before you render the texture:
glColor3d(1.0, 1.0, 1.0);
Note, OpenGL is a state engine. If a color was set, the color is kept until it is changed again, even beyond frames. So this might not be an issue in the first frame, but it would be in the further frames.
The fixed function light model is applied on the background, too. This will cause a bad look with fixed function gouraud light model. I recommend to disable lighting before you draw the background.
glDisable(GL_LIGHTING);
and to enable lighting before you draw the geometry
glEnable(GL_LIGHTING);
The function display may look like this:
void display(void)
{
// clear color buffer and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// prepare for drawing the back ground
glDisable(GL_DEPTH_TEST);
glDisable(GL_LIGHTING);
glColor3d(1.0, 1.0, 1.0);
// projection and model view for the background
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// draw the background
glBindTexture(GL_TEXTURE_2D, myTexture);
glEnable(GL_TEXTURE_2D);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glEnd();
// prepare for drawing the geometry
glDisable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
// projection and model view for the geoemtry
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//glFrustum(-ar + 1, ar - 1, -1.0, 1.0, 2.0, 90.0);
//gluOrtho2D(0, width, 0, height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// draw geometry
glColor3d(0.5, 0.85, 0.9); // head
// ...
glFlush();
glutSwapBuffers();
glutPostRedisplay();
}

Calc texcoord for some pixmap

I have a pixmap for some app in Xephyr and I need draw this pixmap on rectangle openGL. I seen example from khronos for pixmap when created in code but it's not working for me:
mPixmap = XCreatePixmap(dpy, client->getWindow(), static_cast<unsigned int>(attr.width),
static_cast<unsigned int>(attr.height), static_cast<unsigned int>(attr.depth));
And code where I drawed:
void startPluginPixmap() {
XEvent xev;
GLuint texture_id;
GLint pix_att[5] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
vi = glXChooseVisual(dpy, 0, pix_att);
swa.event_mask = ExposureMask | KeyPressMask;
swa.colormap = XCreateColormap(dpy, root, vi->visual, AllocNone);
uint64_t window_width = 300;
uint64_t window_height = 400;
uint32_t window_depth = vi->depth;
win = XCreateWindow(dpy, root, 0, 0, window_width, window_height, 0, window_depth, InputOutput, vi->visual, CWEventMask | CWColormap, &swa);
XMapWindow(dpy, win);
XStoreName(dpy, win, "PIXMAP TEST");
glc = glXCreateContext(dpy, vi, NULL, GL_TRUE);
if (!glc) {
exit(0);
}
glXMakeCurrent(dpy, win, glc);
glEnable(GL_DEPTH_TEST);
uint64_t pixmap_width = 150;
uint64_t pixmap_height = 100;
GC gc = DefaultGC(dpy, 0);
XFlush(dpy);
XImage * xim = XGetImage(dpy, mPixmap, 0, 0, pixmap_width, pixmap_height, AllPlanes, ZPixmap);
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &texture_id);
glBindTexture(GL_TEXTURE_2D, texture_id);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, pixmap_width, pixmap_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, (void *)(&(xim->data[0])));
XDestroyImage(xim);
while(true) {
XNextEvent(dpy, &xev);
if (xev.type == Expose) {
redrawPixmapImage();
}
else if (xev.type == KeyPress && xev.xkeymap.type == 0x19) {
glXMakeCurrent(dpy, None, NULL);
glXDestroyContext(dpy, glc);
XDestroyWindow(dpy, win);
XCloseDisplay(dpy);
exit(0);
}
}
}
void Cube::redrawPixmapImage() {
XWindowAttributes gwa;
XGetWindowAttributes(dpy, win, &gwa);
glViewport(0, 0, gwa.width, gwa.height);
glClearColor(.0, 1.0, .0, .5);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.25, 1.25, -1.25, 1.25, 1., 20.);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0., 0., 10., 0., 0., 0., 0., 1., 0.);
glColor3f(1.f, 1.f, 1.f);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 0.0);
//glColor3f(1.f, 0.f, 0.f);
glVertex3f(-1.0, 1.0, 0.0);
glTexCoord2f(1.0, 0.0);
glVertex3f( 1.0, 1.0, 0.0);
glTexCoord2f(1.0, 1.0);
glVertex3f( 1.0, -1.0, 0.0);
glTexCoord2f(0.0, 1.0);
glVertex3f(-1.0, -1.0, 0.0);
glTexCoord2f(1.0, 1.0);
glVertex3f(-1.0, 1.0, 0.0);
glEnd();
glXSwapBuffers(dpy, win);
}
In this code I enter width and height manual because get it in debug info.
And for me this calculation of textcoord doesn't work (When I run in Xephyr xeyes, and then this code, I seeing artifacts and green area).
So, how I can calculate texcoords for pixmap some app?

Draw multiple copies of same object in opengl

I can't seem to understand how multiple copies of same object are being drawn using array of objects. Below you see both my draw and display methods:
void display()
{
SolidSphere **spheres = createSpheres();
float const win_aspect = (float)win_width / (float)win_height;
glViewport(0, 0, win_width, win_height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3f(.6, 0, 0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45, win_aspect, 1, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
for (int i = 0; i < n; i++)
{
spheres[i]->draw(posX,posY,posZ);
}
glutSwapBuffers();
}
void draw(GLfloat x, GLfloat y, GLfloat z)
{
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef(x,y,z);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, &vertices[0]);
glNormalPointer(GL_FLOAT, 0, &normals[0]);
glTexCoordPointer(2, GL_FLOAT, 0, &texcoords[0]);
glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_SHORT, &indices[0]);
glPopMatrix();
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
As a result I only get 1 instead of n spheres.

Using Multiple Textures in OpenGL only One Displayed

I've modified my original code (previous post) to use two textures. Here they are:
#include <GL/glut.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "support.h"
using namespace std;
GLuint *images;
GLubyte *image;
GLuint texture1=0;
GLuint texture2=0;
GLuint LoadTexture(int width, int height, char *fName);
int n=200;
int m=200;
void showPictureW();
void showPictureR();
float rX=0;
float rY=0;
float rZ=0;
float tX=0;
float tY=0;
float tZ=-3.5;
float nr = -5.0;
float fr = -4.0;
float tpx = 1.0;
float tpy = 1.0;
float btx = -1.0;
float bty = -1.0;
float dZ =-2.0;
void showPictureW()
{
/* clear all pixels */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(1,1,1);
//face 1
glBegin( GL_POLYGON );
glTexCoord2d(1.0,1.0); glVertex3d(-1.0,1.0,-2.0);
glTexCoord2d(1.0,0.0); glVertex3d(-1,-1.0,-2.0);
glTexCoord2d(0.0,0.0); glVertex3d(1.0,-1.0,-2.0);
glEnd();
//face 2
glBegin( GL_POLYGON );
glTexCoord2d(0.0,0.0); glVertex3d(1.0,-1.0,-2.0);
glTexCoord2d(0.0,1.0); glVertex3d(1.0,1.0,-2.0);
glTexCoord2d(1.0,1.0); glVertex3d(-1.0,1.0,-2.0);
glEnd();
}
void showPictureR()
{
//clear all pixels
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(1,1,1);
//face 1
glBegin( GL_POLYGON );
glTexCoord2d(1.0,1.0); glVertex3d(-1.2,1.0,-2.0);
glTexCoord2d(1.0,0.0); glVertex3d(0.0,1.0,-2.0);
glTexCoord2d(0.0,0.0); glVertex3d(0.0,2.0,-2.0);
glEnd();
//face 2
glBegin( GL_POLYGON );
glTexCoord2d(0.0,0.0); glVertex3d(0.0,2.0,-2.0);
glTexCoord2d(0.0,1.0); glVertex3d(0.0,1.0,-2.0);
glTexCoord2d(1.0,1.0); glVertex3d(1.2,1.0,-2.0);
glEnd();
}
static void resize(int width, int height)
{
const float ar = (float) width / (float) height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity() ;
}
static void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(1,0,0);
glEnable( GL_TEXTURE_2D );
glBindTexture( GL_TEXTURE_2D, texture1 );
glPushMatrix();
glTranslated(0,0,0);
glRotated(rX,0,0,1);
glRotated(rY,0,1,0);
glRotated(rZ,1,0,0);
showPictureW();
glPopMatrix();
glBindTexture( GL_TEXTURE_2D, texture2 );
glPushMatrix();
glTranslated(0,0,0);
glRotated(rX,0,0,1);
glRotated(rY,0,1,0);
glRotated(rZ,1,0,0);
showPictureR();
glPopMatrix();
glutSwapBuffers();
}
static void key(unsigned char key, int x, int y)
{
switch (key)
{
case 27 :
case 'q':
exit(0);
break;
case '+':
break;
...
}
glutPostRedisplay();
}
static void idle(void)
{
glutPostRedisplay();
}
const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const GLfloat light_diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat light_position[] = { 2.0f, 5.0f, 5.0f, 0.0f };
const GLfloat mat_ambient[] = { 0.7f, 0.7f, 0.7f, 1.0f };
const GLfloat mat_diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
const GLfloat mat_specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
const GLfloat high_shininess[] = { 100.0f };
/* Program entry point */
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(640,480);
glutInitWindowPosition(10,10);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("FreeGLUT Shapes");
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutKeyboardFunc(key);
glutIdleFunc(idle);
glClearColor(1,1,1,1);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_SHININESS, high_shininess);
texture1 = LoadTexture( 200, 200, "wall.ppm" );
texture2 = LoadTexture( 200, 200, "roof.ppm" );
glutMainLoop();
return EXIT_SUCCESS;
}
GLuint LoadTexture(int width, int height, char *fName)
{
FILE *fd;
int k, nm;
int i;
char bc[71];
float s;
unsigned int red, green, blue;
char c;
fd = fopen(fName,"r");
fscanf(fd,"%[^\n]",bc); // reads data from stream
printf("Nilai %s \n\n",bc);
if(bc[0]!='P'|| bc[1]!='3')
{
printf("%s Not a PPM file\n",bc);
exit(0);
}
printf("%s is a PPM file\n",bc);
fscanf(fd,"%s",bc);
printf("line 1 %s \n",bc);
fscanf(fd,"%s",bc);
printf("line 2 %s \n",bc);
fscanf(fd,"%s",bc);
printf("line 3 %s \n",bc);
fscanf(fd,"%s",bc);
printf("line 4 %s \n",bc);
fscanf(fd,"%c",&c);
ungetc(c,fd);
fscanf(fd,"%d %d %d", &n,&m,&k);
nm = n*m;
images = new GLuint[3*sizeof(GLuint)*nm];
for (i=0;i<nm;i++)
{
fscanf(fd,"%u %u %u", &red, &green, &blue);
images[3*nm-3*i-3] = red;
images[3*nm-3*i-2] = green;
images[3*nm-3*i-1] = blue;
}
int totSize = 3*nm;
int tot=0;
for(i=0;i<nm;i++)
{
tot++;
}
image = new BYTE[width*height*3*sizeof(BYTE)];
int nmOne = width*height;
for(int i=0;i<nmOne*3;i++)//copy each value 3 times
{
image[i] = (GLubyte)images[i];
image[i] = (GLubyte)images[i];
image[i] = (GLubyte)images[i];
}
bool wrap = true;
GLuint texture = 0;
glGenTextures( 1, &texture );
// select our current texture
glBindTexture( GL_TEXTURE_2D, texture );
// select modulate to mix texture with color for shading
glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
// when texture area is small, bilinear filter the closest mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST );
// when texture area is large, bilinear filter the first mipmap
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// if wrap is true, the texture wraps over at the edges (repeat)
// ... false, the texture ends at the edges (clamp)
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap ? GL_REPEAT : GL_CLAMP );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,wrap ? GL_REPEAT : GL_CLAMP );
// build our texture mipmaps
gluBuild2DMipmaps( GL_TEXTURE_2D, 3, width, height,
GL_RGB, GL_UNSIGNED_BYTE, image );
return texture;
}
My problem is that it won't load both textures at once. I've tried using one at a time and they're okay. But with the above code only the second texture ("roof.ppm") appears. I found the code below in another post which seems quite similar to my problem but I'm not sure how to use it.
void DrawFrame()
{
...
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D(0, this.Width, 0, this.Height);
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
// "camera" transform(s)
foreach object
{
glPushMatrix();
// per-object matrix transform(s)
// draw object
glPopMatrix();
}
}
You do call
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
in both of your showPictureW and showPictureR functions, so it should not surprise you that only the effects last of these calls can be seen in the end.

Resources