Following is my code.
I am getting multiple error
like:
Severity Code Description Project File Line Suppression State
Error C2995 'glm::detail::component_count_t
glm::detail::component_count(const genType &)': function template has
already been
defined Project103 c:\users\onedrive\desktop\r\glm\gtx\setup.hpp 918
Severity Code Description Project File Line Suppression State
Error C2995 'size_t glm::countof(const T (&)[N])': function template
has already been
defined Project103 c:\users\onedrive\desktop\r\glm\gtx\setup.hpp 947
Severity Code Description Project File Line Suppression State
Error C2011 'glm::ctor': 'enum' type
redefinition Project103 c:\users\onedrive\desktop\r\glm\gtx\setup.hpp 961
Severity Code Description Project File Line Suppression State
Error C2011 'glm::precision': 'enum' type
redefinition Project103 c:\users\onedrive\desktop\r\glm\gtx\precision.hpp 38
Severity Code Description Project File Line Suppression State Error
(active) E0458 argument of type "glm::precision" is incompatible with
template parameter of type
"glm::precision" Project103 C:\Users\OneDrive\Desktop\r\glm\gtc\matrix_transform.inl 261
#include <GL/glut.h>
#include <glm.hpp>
#include <gtx/component_wise.hpp>
#include <gtc/matrix_transform.hpp>
#include <vector>
#include <map>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
using namespace glm;
struct Vertex
{
vec3 position;
vec3 normal;
};
vector< Vertex > LoadM(istream& in)
{
vector< Vertex > verts;
map< int, vec3 > positions;
string lineStr;
while (getline(in, lineStr))
{
istringstream lineSS(lineStr);
string lineType;
lineSS >> lineType;
// parse vertex line
if (lineType == "Vertex")
{
int idx = 0;
float x = 0, y = 0, z = 0;
lineSS >> idx >> x >> y >> z;
positions.insert(make_pair(idx, vec3(x, y, z)));
}
// parse face line
if (lineType == "Face")
{
int indexes[3] = { 0 };
int idx = 0;
lineSS >> idx >> indexes[0] >> indexes[1] >> indexes[2];
// http://www.opengl.org/wiki/Calculating_a_Surface_Normal
vec3 U(positions[indexes[1]] - positions[indexes[0]]);
vec3 V(positions[indexes[2]] - positions[indexes[0]]);
vec3 faceNormal = normalize(cross(U, V));
for (size_t j = 0; j < 3; ++j)
{
Vertex vert;
vert.position = vec3(positions[indexes[j]]);
vert.normal = faceNormal;
verts.push_back(vert);
}
}
}
return verts;
}
// mouse state
int btn;
ivec2 startMouse;
ivec2 startRot, curRot;
ivec2 startTrans, curTrans;
void mouse(int button, int state, int x, int y)
{
y = glutGet(GLUT_WINDOW_HEIGHT) - y;
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
btn = button;
startMouse = ivec2(x, y);
startRot = curRot;
}
if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
{
btn = button;
startMouse = ivec2(x, y);
startTrans = curTrans;
}
}
void motion(int x, int y)
{
y = glutGet(GLUT_WINDOW_HEIGHT) - y;
ivec2 curMouse(x, y);
if (btn == GLUT_LEFT_BUTTON)
{
curRot = startRot + (curMouse - startMouse);
}
else if (btn == GLUT_RIGHT_BUTTON)
{
curTrans = startTrans + (curMouse - startMouse);
}
glutPostRedisplay();
}
vector< Vertex > model;
void display()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double w = glutGet(GLUT_WINDOW_WIDTH);
double h = glutGet(GLUT_WINDOW_HEIGHT);
double ar = w / h;
// "pan"
glTranslatef(curTrans.x / w * 2, curTrans.y / h * 2, 0);
gluPerspective(60, ar, 0.1, 20);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -10);
glPushMatrix();
// apply mouse rotation
glRotatef(curRot.x % 360, 0, 1, 0);
glRotatef(-curRot.y % 360, 1, 0, 0);
glColor3ub(255, 0, 0);
// draw model
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &model[0].position);
glNormalPointer(GL_FLOAT, sizeof(Vertex), &model[0].normal);
glDrawArrays(GL_TRIANGLES, 0, model.size());
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
// draw bounding cube
glDisable(GL_LIGHTING);
glColor3ub(255, 255, 255);
glutWireCube(7);
glEnable(GL_LIGHTING);
glPopMatrix();
glutSwapBuffers();
}
// return the x/y/z min/max of some geometry
template< typename Vec >
pair< Vec, Vec > GetExtents
(
const Vec* pts,
size_t stride,
size_t count
)
{
typedef typename Vec::value_type Scalar;
Vec pmin(std::numeric_limits< Scalar >::max());
Vec pmax(std::min(std::numeric_limits< Scalar >::min(),
(Scalar)-std::numeric_limits< Scalar >::max()));
// find extents
unsigned char* base = (unsigned char*)pts;
for (size_t i = 0; i < count; ++i)
{
const Vec& pt = *(Vec*)base;
pmin = glm::min(pmin, pt);
pmax = glm::max(pmax, pt);
base += stride;
}
return make_pair(pmin, pmax);
}
// centers geometry around the origin
// and scales it to fit in a size^3 box
template< typename Vec >
void CenterAndScale
(
Vec* pts,
size_t stride,
size_t count,
const typename Vec::value_type& size
)
{
typedef typename Vec::value_type Scalar;
// get min/max extents
pair< Vec, Vec > exts = GetExtents(pts, stride, count);
// center and scale
const Vec center = (exts.first * Scalar(0.5)) + (exts.second * Scalar(0.5f));
const Scalar factor = size / glm::compMax(exts.second - exts.first);
unsigned char* base = (unsigned char*)pts;
for (size_t i = 0; i < count; ++i)
{
Vec& pt = *(Vec*)base;
pt = ((pt - center) * factor);
base += stride;
}
}
int main(int argc, char **argv)
{
ifstream ifile("bunny.m");
model = LoadM(ifile);
if (model.empty())
{
cerr << "Empty model!" << endl;
return -1;
}
CenterAndScale(&model[0].position, sizeof(Vertex), model.size(), 7);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
glutInitWindowSize(640, 480);
glutCreateWindow("GLUT");
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glEnable(GL_DEPTH_TEST);
// set up "headlamp"-like light
glShadeModel(GL_SMOOTH);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
GLfloat position[] = { 0, 0, 1, 0 };
glLightfv(GL_LIGHT0, GL_POSITION, position);
glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_LINE);
glutMainLoop();
return 0;
}
I would like to plot 3D point specified by the value from column[0] in text file. For example, column[0] equals to 2,then displays 3D point(xyz) following these: (1.529, 0.25,-2.038 ), (1.530,0.253,-2.040), (1.530,0.253,-2.044)
test.txt
1 1.529 0.253 -2.038
1 1.529 0.253 -2.038
2 1.529 0.253 -2.038
2 1.530 0.253 -2.040
2 1.530 0.253 -2.044
3 1.532 0.254 -2.038
3 1.533 0.255 -2.036
3 1.533 0.255 -2.036
3 1.534 0.255 -2.036
3 1.534 0.255 -2.036
This is my code
#include <Windows.h>
#include <GL\glew.h>
#include <GL\freeglut.h>
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
char title[] = "Point";
void initGL() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black
glClearDepth(1.0f); // Set background depth to farthest
glEnable(GL_DEPTH_TEST); // Enable depth testing for z-culling
glDepthFunc(GL_LEQUAL); // Set the type of depth-test
glShadeModel(GL_SMOOTH); // Enable smooth shading
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}
void display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color and depth buffers
glMatrixMode(GL_MODELVIEW); // To operate on model-view matrix
glLoadIdentity(); // Reset the model-view matrix
glTranslatef(1.5f, 0.0f, -7.0f); // Move right and into the screen
vector<vector<double>> tempdouble;
ifstream in("test.txt");
string line;
double Dstage1x = 0.0;
double Dstage1y = 0.0;
double Dstage1z = 0.0;
double Dstage2x = 0.0;
double Dstage2y = 0.0;
double Dstage2z = 0.0;
double Dstage3x = 0.0;
double Dstage3y = 0.0;
double Dstage3z = 0.0;
int ii = 0;
int stage1 = 0;
int stage2 = 0;
int stage3 = 0;
while (std::getline(in, line))
{
tempdouble.push_back(vector<double>());
stringstream ss(line);
double num;
while (ss >> num)
{
tempdouble.back().push_back(num);
}
}
for (int i = 0; i < tempdouble.size(); i++)
{
for (int j = 0; j < tempdouble[i].size(); j++)
{
int st1_x=0; int st1_y=0; int st1_z=0;
int st2_x=0; int st2_y=0; int st2_z=0;
int st3_x=0; int st3_y=0; int st3_z=0;
if(tempdouble[i][0]==1 )
{
glPointSize(5);glColor3f(1.0f, 0.5f, 0.0f);
glBegin(GL_POINTS);
st1_x += Dstage1x*0; st1_y += Dstage1y*0; st1_z += Dstage1z*0; //set value
Dstage1x = st1_x + tempdouble[i][1];
Dstage1y = st1_y + tempdouble[i][2];
Dstage1z = st1_z + tempdouble[i][3];
stage1++;
//cout <<"Check tempdouble[i][0] state1 : " << tempdouble[i][0] <<"\t"<<endl;
cout << "state1(xyz) : " << "( " << Dstage1x << " ," << Dstage1y << "," << Dstage1z << ")"<< endl;
glVertex3f(Dstage1x, Dstage1y, Dstage1z);
//glVertex3f(tempdouble[i][1], tempdouble[i][2], tempdouble[i][3]);
//glVertex3f(tempdouble[i][j], tempdouble[i][j], tempdouble[i][j]);
glEnd();
break;
}
if (tempdouble[i][0] == 2) {
glPointSize(5);glColor3f(0.0f, 0.0f, 1.0f);
glBegin(GL_POINTS);
st2_x += Dstage2x * 0; st2_y += Dstage2y*0; st2_z += Dstage2z*0; //set value
Dstage2x = st2_x + tempdouble[i][1];
Dstage2y = st2_y + tempdouble[i][2];
Dstage2z = st2_z + tempdouble[i][3];
stage2++;
cout << "state2(xyz) : " << "( " << Dstage2x << " ," << Dstage2y << "," << Dstage2z << ")"<< endl;
glVertex3f(Dstage2x,Dstage2y,Dstage2z);
//glVertex3f(tempdouble[i][1], tempdouble[i][2], tempdouble[i][3]);
//glVertex3f(tempdouble[i][j], tempdouble[i][j], tempdouble[i][j]);
glEnd();
break;
}
if (tempdouble[i][0] == 3) {
glPointSize(5); glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_POINTS);
st3_x += Dstage3x*0; st3_y += Dstage3y*0; st3_z += Dstage3z*0; //set value
Dstage3x = st3_x + tempdouble[i][1];
Dstage3y = st3_y + tempdouble[i][2];
Dstage3z = st3_z + tempdouble[i][3];
stage3++;
cout << "state3(xyz) : " << "( " << Dstage3x << " ," << Dstage3y << "," << Dstage3z << ")"<< endl;
glVertex3f(Dstage3x,Dstage3y,Dstage3z);
//glVertex3f(tempdouble[i][0],tempdouble[i][1],tempdouble[i][2]);
//glVertex3f(tempdouble[i][j], tempdouble[i][j], tempdouble[i][j]);
glEnd();
break;
}
}
}
cout << "stage 1: "<< stage1 << endl;
cout << "stage 2: "<<stage2 << endl;
cout << "stage 3: "<<stage3 << endl;
glutSwapBuffers(); // Swap the front and back frame buffers (double buffering)
}
void reshape(GLsizei width, GLsizei height) { // GLsizei for non-negative integer
// Compute aspect ratio of the new window
if (height == 0) height = 1; // To prevent divide by 0
GLfloat aspect = (GLfloat)width / (GLfloat)height;
// Set the viewport to cover the new window
glViewport(0, 0, width, height);
// Set the aspect ratio of the clipping volume to match the viewport
glMatrixMode(GL_PROJECTION); // To operate on the Projection matrix
glLoadIdentity(); // Reset
// Enable perspective projection with fovy, aspect, zNear and zFar
gluPerspective(45.0f, aspect, 0.1f, 100.0f);
}
void changeViewPort(int w, int h)
{
glViewport(0, 0, w, h);
}
void render()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glutSwapBuffers();
}
int main(int argc, char* argv[]) {
void display();
glutInit(&argc, argv); // Initialize GLUT
glutInitDisplayMode(GLUT_DOUBLE); // Enable double buffered mode
glutInitWindowSize(640, 480); // Set the window's initial width & height
glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
glutCreateWindow(title); // Create window with the given title
glutDisplayFunc(display); // Register callback handler for window re-paint event
glutReshapeFunc(reshape); // Register callback handler for window re-size event
initGL(); // Our own OpenGL initialization
glutMainLoop();
return 0;
}
My problem is that the point shown in the wrong position. It is impossible that column[0](equal to 1,2,3) have all the same points.Can someone help me with this
setlocale( LC_NUMERIC, "C");
.
https://rocketgit.com/user/bowler17/gl/source/tree/branch/wrench/blob/t.c
line just before big do while
Im having a problem with glutKeyboardUpFunc. Everytime I press a key and don't release it, the callback of glutKeyboardUpFunc stills gets called, the longer I hold the key the more times the callback executes.
Here is a quick example I put up:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <time.h>
#include <GL/glut.h>
#define DEBUG 1
/* VARI�VEIS GLOBAIS */
typedef struct {
GLboolean doubleBuffer;
GLint delay;
} Estado;
typedef struct {
GLfloat x;
GLfloat y;
GLfloat height;
GLfloat width;
GLfloat y_accelaration;
} Plataforma;
//save stage coordinates
typedef struct {
GLfloat top;
GLfloat bottom;
GLfloat right;
GLfloat left;
} Screen;
Estado estado;
Screen ecra;
Plataforma plataforma;
GLfloat tab_speed = 2.0 / 20.0;
GLfloat y_accelaration = 0.001;
void Init(void) {
struct tm *current_time;
time_t timer = time(0);
estado.delay = 42;
estado.doubleBuffer = GL_TRUE;
plataforma.height = 0.3;
plataforma.width = 0.05;
plataforma.y_accelaration = 0;
plataforma.y = 0;
// L� hora do Sistema
current_time = localtime(&timer);
glClearColor(0.3, 0.3, 0.3, 0.0);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POLYGON_SMOOTH);
}
void Reshape(int width, int height) {
GLint size;
GLfloat ratio = (GLfloat) width / height;
GLfloat ratio1 = (GLfloat) height / width;
if (width < height)
size = width;
else
size = height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (width < height) {
ecra.left = -1;
ecra.right = 1;
ecra.bottom = -1 * ratio1;
ecra.top = 1 * ratio1;
gluOrtho2D(-1, 1, -1 * ratio1, 1 * ratio1);
} else {
ecra.left = -1 * ratio;
ecra.right = 1 * ratio;
ecra.bottom = -1;
ecra.top = 1;
gluOrtho2D(-1 * ratio, 1 * ratio, -1, 1);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void desenhar_plataforma(Plataforma pf) {
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_POLYGON);
glVertex2f(pf.x - pf.width / 2, pf.y - pf.height / 2);
glVertex2f(pf.x + pf.width / 2, pf.y - pf.height / 2);
glVertex2f(pf.x + pf.width / 2, pf.y + pf.height / 2);
glVertex2f(pf.x - pf.width / 2, pf.y + pf.height / 2);
glEnd();
}
void Draw(void) {
glClear(GL_COLOR_BUFFER_BIT);
plataforma.x = ecra.left + 0.1;
desenhar_plataforma(plataforma);
glFlush();
if (estado.doubleBuffer)
glutSwapBuffers();
}
void Key(unsigned char key, int x, int y) {
switch (key) {
case 'a':
plataforma.y += tab_speed;
glutPostRedisplay();
break;
case 's':
plataforma.y -= tab_speed;
glutPostRedisplay();
break;
}
}
void KeyUp(unsigned char key, int x, int y) {
if (DEBUG)
printf("Key Up %c\n", key);
}
int main(int argc, char **argv) {
estado.doubleBuffer = GL_TRUE;
glutInit(&argc, argv);
glutInitWindowPosition(0, 0);
glutInitWindowSize(800, 600);
glutInitDisplayMode(((estado.doubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE) | GLUT_RGB);
if (glutCreateWindow("No Man's Pong") == GL_FALSE)
exit(1);
Init();
glutReshapeFunc(Reshape);
glutDisplayFunc(Draw);
// Callbacks de teclado
glutKeyboardFunc(Key);
glutKeyboardUpFunc(KeyUp);
glutMainLoop();
return 0;
}
Here's the ouput when pressing 'a':
Key Up a
Key Up a
Key Up a
Key Up a
Key Up a
Key Up a
Key Up a
......
Needless to say im not releasing 'a'.
Im using linux mint 17.3 and g++, shutting off key repeat or setting glutIgnoreKeyRepeat(true), stops this issue, but also makes glutKeyboardFunc execute only once per key press, and I realy don't want that.
Does anyone know how to fix this, or whats causing this?
I also compiled the same code under windows 8.1 and the keyUp only fires when there's an actual key release.
I'm having trouble mapping a texture to an object imported into Opengl. I found a tutorial to import an obj file, but I can't figure out mapping a texture.
This is the code I have written:
class Model
{
public:
Model();
Model(string modelFilename, string textureFilename);
void LoadTexture(string fileName);
void LoadObj(const string& filename, vector<glm::vec4> &vertices, vector<glm::vec3> &normals, vector<GLushort> &elements);
void Draw();
private:
vector<glm::vec4> m_Vertices;
vector<glm::vec3> m_Normals;
vector<GLushort> m_Elements;
string m_ModelFilename;
int m_Texture;
string m_TextureName;
};
Model::Model(string modelFilename, string textureFilename)
{
m_ModelFilename = modelFilename;
m_TextureName = textureFilename;
LoadObj(m_ModelFilename, m_Vertices, m_Normals, m_Elements);
LoadTexture(m_TextureName);
}
void Model::LoadTexture(string TextureName)
{
// Local storage for bmp image data.
BitMapFile *image[1];
string filename = TextureName;
filename.append(".bmp");
// Load the texture.
image[0] = getBMPData(filename);
// Bind grass image to texture index[i].
glBindTexture(GL_TEXTURE_2D, m_Texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image[0]->sizeX, image[0]->sizeY, 0,
GL_RGB, GL_UNSIGNED_BYTE, image[0]->data);
}
void Model::LoadObj(const string& filename, vector<glm::vec4> &vertices, vector<glm::vec3> &normals, vector<GLushort> &elements) {
ifstream in(filename, ios::in);
if (!in) { cerr << "Cannot open " << filename << endl; exit(1); }
string line;
while (getline(in, line)) {
if (line.substr(0,2) == "v ") {
istringstream s(line.substr(2));
glm::vec4 v; s >> v.x; s >> v.y; s >> v.z; v.w = 1.0f;
vertices.push_back(v);
} else if (line.substr(0,2) == "f ") {
istringstream s(line.substr(2));
GLushort a,b,c;
s >> a; s >> b; s >> c;
a--; b--; c--;
elements.push_back(a); elements.push_back(b); elements.push_back(c);
}
else if (line[0] == '#') { /* ignoring this line */}
// else { /* ignoring this line */ }
}
normals.resize(vertices.size(), glm::vec3(0.0, 0.0, 0.0));
for (int i = 0; i < elements.size(); i+=3) {
GLushort ia = elements[i];
GLushort ib = elements[i+1];
GLushort ic = elements[i+2];
glm::vec3 normal = glm::normalize(glm::cross(glm::vec3(vertices[ib]) - glm::vec3(vertices[ia]), glm::vec3(vertices[ic]) - glm::vec3(vertices[ia])));
normals[ia] = normals[ib] = normals[ic] = normal;
}
}
void Model::Draw()
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_Texture);
for (int i = 0; i < m_Elements.size(); i+=3)
{
GLushort ia = m_Elements[i];
GLushort ib = m_Elements[i+1];
GLushort ic = m_Elements[i+2];
glBegin(GL_TRIANGLES);
glBegin(GL_TRIANGLES);
glNormal3f(m_Normals[ia].x,m_Normals[ia].y,m_Normals[ia].z);//
glNormal3f(m_Normals[ib].x,m_Normals[ib].y,m_Normals[ib].z);//
glNormal3f(m_Normals[ic].x,m_Normals[ic].y,m_Normals[ic].z);//
glTexCoord2f(0.0, 0.0);glVertex3f(m_Vertices[ia].x,m_Vertices[ia].y,m_Vertices[ia].z);
glTexCoord2f(1.0, 1.0);glVertex3f(m_Vertices[ib].x,m_Vertices[ib].y,m_Vertices[ib].z);
glTexCoord2f(0.0, 1.0);glVertex3f(m_Vertices[ic].x,m_Vertices[ic].y,m_Vertices[ic].z);
glEnd();
glEnd();
}
glDisable(GL_TEXTURE_2D);
}
Model model;
void setup(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
model = Model("monkey.obj", "launch");
// Specify how texture values combine with current surface color values.
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glEnable(GL_BLEND); // Enable blending.
// Cull back faces.
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
// stops GL_QUAD from showing faces by priority
glEnable(GL_DEPTH_TEST);
}
// Drawing routine.
void drawScene(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
model.Draw();
glutSwapBuffers();
}
When i run the program this is what happens: http://imgur.com/okMul77
It seems to be mapping the entire image to each triangle, but I don't know how to fix it. Anyone have any ideas? Thank you in advance
I'm working on porting my open source particle engine test from SDL to SDL + OpenGL. I've managed to get it compiling, and running, but the screen stays black no matter what I do.
main.cpp:
#include "glengine.h"
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
//Create a glengine instance
ultragl::glengine *gle = new ultragl::glengine();
if(gle->init())
gle->run();
else
std::cout << "glengine initializiation failed!" << std::endl;
//If we can't initialize, or the lesson has quit we delete the instance
delete gle;
return 0;
};
glengine.h:
//we need to include window first because GLee needs to be included before GL.h
#include "window.h"
#include <math.h> // Math Library Header File
#include <vector>
#include <stdio.h>
using namespace std;
namespace ultragl
{
class glengine
{
protected:
window m_Window; ///< The window for this lesson
unsigned int m_Keys[SDLK_LAST]; ///< Stores keys that are pressed
float piover180;
virtual void draw();
virtual void resize(int x, int y);
virtual bool processEvents();
void controls();
private:
/*
* We need a structure to store our vertices in, otherwise we
* just had a huge bunch of floats in the end
*/
struct Vertex
{
float x, y, z;
Vertex(){}
Vertex(float x, float y, float z)
{
this->x = x;
this->y = y;
this->z = z;
}
};
struct particle
{
public :
double angle;
double speed;
Vertex v;
int r;
int g;
int b;
int a;
particle(double angle, double speed, Vertex v, int r, int g, int b, int a)
{
this->angle = angle;
this->speed = speed;
this->v = v;
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
particle()
{
}
};
particle p[500];
float particlesize;
public:
glengine();
~glengine();
virtual void run();
virtual bool init();
void glengine::test2(int num);
void glengine::update();
};
};
window.h:
#include <string>
#include <iostream>
#include "GLee/GLee.h"
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>
#include <GL/glu.h>
using namespace std;
namespace ultragl
{
class window
{
private:
int w_height;
int w_width;
int w_bpp;
bool w_fullscreen;
string w_title;
public:
window();
~window();
bool createWindow(int width, int height, int bpp, bool fullscreen, const string& title);
void setSize(int width, int height);
int getHeight();
int getWidth();
};
};
glengine.cpp (the main one to look at):
#include "glengine.h"
namespace ultragl{
glengine::glengine()
{
piover180 = 0.0174532925f;
}
glengine::~glengine()
{
}
void glengine::resize(int x, int y)
{
std::cout << "Resizing Window to " << x << "x" << y << std::endl;
if (y <= 0)
{
y = 1;
}
glViewport(0,0,x,y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)x/(GLfloat)y,1.0f,100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
bool glengine::processEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))//get all events
{
switch (event.type)
{
// Quit event
case SDL_QUIT:
{
// Return false because we are quitting.
return false;
}
case SDL_KEYDOWN:
{
SDLKey sym = event.key.keysym.sym;
if(sym == SDLK_ESCAPE) //Quit if escape was pressed
{
return false;
}
m_Keys[sym] = 1;
break;
}
case SDL_KEYUP:
{
SDLKey sym = event.key.keysym.sym;
m_Keys[sym] = 0;
break;
}
case SDL_VIDEORESIZE:
{
//the window has been resized so we need to set up our viewport and projection according to the new size
resize(event.resize.w, event.resize.h);
break;
}
// Default case
default:
{
break;
}
}
}
return true;
}
bool glengine::init()
{
srand( time( NULL ) );
for(int i = 0; i < 500; i++)
p[i] = particle(0, 0, Vertex(0.0f, 0.0f, 0.0f), 0, 0, 0, 0);
if (!m_Window.createWindow(640, 480, 32, false, "Paricle Test GL"))
{
return false;
}
particlesize = 0.01;
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glEnable(GL_BLEND);
glBlendFunc(GL_ONE , GL_ONE_MINUS_SRC_ALPHA);
return true;
}
void glengine::test2(int num)
{
glPushMatrix();
glTranslatef(p[num].v.x, p[num].v.y, p[num].v.z);
glBegin(GL_QUADS);
glColor4i(p[num].r, p[num].g, p[num].b, p[num].a); // Green for x axis
glVertex3f(-particlesize, -particlesize, particlesize);
glVertex3f( particlesize, -particlesize, particlesize);
glVertex3f( particlesize, particlesize, particlesize);
glVertex3f(-particlesize, particlesize, particlesize);
glEnd();
glPopMatrix();
}
void glengine::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
gluLookAt(0, 5, 20, 0, 0, 0, 0, 0, 0);
for(int i = 0; i < 500; i++)
test2(i);
}
void glengine::update()
{
for(int i = 0; i < 500; i++)
{
if(p[i].a <= 0)
p[i] = particle(5 + rand() % 360, (rand() % 10) * 0.1, Vertex(0.0f, 0.0f, 0.0f), 0, 255, 255, 255);
else
p[i].a -= 1;
p[i].v.x += (sin(p[i].angle * (3.14159265/180)) * p[i].speed);
p[i].v.y -= (cos(p[i].angle * (3.14159265/180)) * p[i].speed);
}
}
void glengine::run()
{
while(processEvents())
{
update();
draw();
SDL_GL_SwapBuffers();
}
}
};
And finally window.cpp:
#include "window.h"
namespace ultragl
{
window::window(): w_width(0), w_height(0), w_bpp(0), w_fullscreen(false)
{
}
window::~window()
{
SDL_Quit();
}
bool window::createWindow(int width, int height, int bpp, bool fullscreen, const string& title)
{
if( SDL_Init( SDL_INIT_VIDEO ) != 0 )
return false;
w_height = height;
w_width = width;
w_title = title;
w_fullscreen = fullscreen;
w_bpp = bpp;
//Set lowest possiable values.
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
//Set title.
SDL_WM_SetCaption(title.c_str(), title.c_str());
// Flags tell SDL about the type of window we are creating.
int flags = SDL_OPENGL;
if(fullscreen == true)
flags |= SDL_FULLSCREEN;
// Create window
SDL_Surface * screen = SDL_SetVideoMode( width, height, bpp, flags );
if(screen == 0)
return false;
//SDL doesn't trigger off a ResizeEvent at startup, but as we need this for OpenGL, we do this ourself
SDL_Event resizeEvent;
resizeEvent.type = SDL_VIDEORESIZE;
resizeEvent.resize.w = width;
resizeEvent.resize.h = height;
SDL_PushEvent(&resizeEvent);
return true;
}
void window::setSize(int width, int height)
{
w_height = height;
w_width = width;
}
int window::getHeight()
{
return w_height;
}
int window::getWidth()
{
return w_width;
}
};
Anyway, I really need to finish this, but I've already tried everything I could think of. I tested the glengine file many different ways to where it looked like this at one point:
#include "glengine.h"
#include "SOIL/SOIL.h"
#include "SOIL/stb_image_aug.h"
#include "SOIL/image_helper.h"
#include "SOIL/image_DXT.h"
namespace ultragl{
glengine::glengine()
{
piover180 = 0.0174532925f;
}
glengine::~glengine()
{
}
void glengine::resize(int x, int y)
{
std::cout << "Resizing Window to " << x << "x" << y << std::endl;
if (y <= 0)
{
y = 1;
}
glViewport(0,0,x,y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)x/(GLfloat)y,1.0f,1000.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
bool glengine::processEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event))//get all events
{
switch (event.type)
{
// Quit event
case SDL_QUIT:
{
// Return false because we are quitting.
return false;
}
case SDL_KEYDOWN:
{
SDLKey sym = event.key.keysym.sym;
if(sym == SDLK_ESCAPE) //Quit if escape was pressed
{
return false;
}
m_Keys[sym] = 1;
break;
}
case SDL_KEYUP:
{
SDLKey sym = event.key.keysym.sym;
m_Keys[sym] = 0;
break;
}
case SDL_VIDEORESIZE:
{
//the window has been resized so we need to set up our viewport and projection according to the new size
resize(event.resize.w, event.resize.h);
break;
}
// Default case
default:
{
break;
}
}
}
return true;
}
bool glengine::init()
{
srand( time( NULL ) );
for(int i = 0; i < 500; i++)
p[i] = particle(0, 0, Vertex(0.0f, 0.0f, 0.0f), 0, 0, 0, 0);
if (!m_Window.createWindow(640, 480, 32, false, "Paricle Test GL"))
{
return false;
}
particlesize = 10.01;
glShadeModel(GL_SMOOTH); // Enable Smooth Shading
glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background
glClearDepth(1.0f); // Depth Buffer Setup
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do
glEnable(GL_BLEND);
glBlendFunc(GL_ONE , GL_ONE_MINUS_SRC_ALPHA);
return true;
}
void glengine::test2(int num)
{
//glPushMatrix();
//glTranslatef(p[num].v.x, p[num].v.y, p[num].v.z);
glColor4i(255, 255, 255, 255);
glBegin(GL_QUADS);
glNormal3f( 0.0f, 0.0f, 1.0f);
glVertex3f(-particlesize, -particlesize, particlesize);
glVertex3f( particlesize, -particlesize, particlesize);
glVertex3f( particlesize, particlesize, particlesize);
glVertex3f(-particlesize, particlesize, particlesize);
glEnd();
// Back Face
glBegin(GL_QUADS);
glNormal3f( 0.0f, 0.0f,-1.0f);
glVertex3f(-particlesize, -particlesize, -particlesize);
glVertex3f(-particlesize, particlesize, -particlesize);
glVertex3f( particlesize, particlesize, -particlesize);
glVertex3f( particlesize, -particlesize, -particlesize);
glEnd();
// Top Face
glBegin(GL_QUADS);
glNormal3f( 0.0f, 1.0f, 0.0f);
glVertex3f(-particlesize, particlesize, -particlesize);
glVertex3f(-particlesize, particlesize, particlesize);
glVertex3f( particlesize, particlesize, particlesize);
glVertex3f( particlesize, particlesize, -particlesize);
glEnd();
// Bottom Face
glBegin(GL_QUADS);
glNormal3f( 0.0f,-1.0f, 0.0f);
glVertex3f(-particlesize, -particlesize, -particlesize);
glVertex3f( particlesize, -particlesize, -particlesize);
glVertex3f( particlesize, -particlesize, particlesize);
glVertex3f(-particlesize, -particlesize, particlesize);
glEnd();
// Right face
glBegin(GL_QUADS);
glNormal3f( 1.0f, 0.0f, 0.0f);
glVertex3f( particlesize, -particlesize, -particlesize);
glVertex3f( particlesize, particlesize, -particlesize);
glVertex3f( particlesize, particlesize, particlesize);
glVertex3f( particlesize, -particlesize, particlesize);
glEnd();
// Left Face
glBegin(GL_QUADS);
glNormal3f(-1.0f, 0.0f, 0.0f);
glVertex3f(-particlesize, -particlesize, -particlesize);
glVertex3f(-particlesize, -particlesize, particlesize);
glVertex3f(-particlesize, particlesize, particlesize);
glVertex3f(-particlesize, particlesize, -particlesize);
glEnd();
//glPopMatrix();
}
void glengine::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer
glLoadIdentity(); // Reset The Current Modelview Matrix
gluLookAt(0, 5, 20, 0, 0, 0, 0, 1, 0);
for(int i = 0; i < 500; i++)
test2(i);
}
void glengine::update()
{
for(int i = 0; i < 500; i++)
{
if(p[i].a <= 0)
p[i] = particle(5 + rand() % 360, (rand() % 10) * 0.1, Vertex(0.0f, 0.0f, -5.0f), 0, 255, 255, 255);
else
p[i].a -= 1;
p[i].v.x += (sin(p[i].angle * (3.14159265/180)) * p[i].speed);
p[i].v.y -= (cos(p[i].angle * (3.14159265/180)) * p[i].speed);
}
}
void glengine::run()
{
while(processEvents())
{
update();
draw();
SDL_GL_SwapBuffers();
}
}
};
It still didn't work. I'm really at my wits end on this one.
I haven't checked your code, but one thing I always do when debugging this kind of problems is to set the clear color to something colorful like (1, 0, 1) or so.
This will help you see if the problem is that your drawn object is completely black or if it's not drawn at all.
EDIT:
As someone mentioned in the comment: It also shows if you have a correct GL context if the clear operation clears to the right color or if it stays black.
Okay, I managed to fix it using a lot of your suggestions, and some other source code I had laying around. Turns out the problem was from 3 different lines.
particlesize = 0.01; should have been bigger: particlesize = 1.01;
glColor4i(255, 255, 255, 255) was turning the cube the same color as the clear color because I was using it wrong. I couldn't figure out how to use it right, so I'm using glColor4f(0.0f,1.0f,1.0f,0.5f) instead, and that works.
Last of all gluLookAt(0, 5, 20, 0, 0, 0, 0, 0, 0) needed to be gluLookAt(0, 5, 20, 0, 0, 0, 0, 1, 0)
Thank you all for your help, and your time.
You're not checking the return values of the SDL-GL-SetAttribute() calls.
And is 5/5/5/5 20-bpp color supported by your video card?
Check OpenGL for error states. Use glslDevil, glIntercept or gDebugger. Check the glGetError function. Can you test whether SDL actually acquired a device context?
Does the Window reflect changes in the glClearColor call? Don't use 0.5 as an alpha value in glClearColor.
Try these suggestions and report back with a minimal example as Simucal suggested.