Auto Gen Vertices not working? - c++

I am creating a program using opengl to define 4 vertices (creating a box) and then shifting it over and generating a new one effectively creating a larger box of smaller boxes. But when I run it, the vertices go crazy and I reduced it down so you guys can understand what I mean. I want it to be 3 seperate boxes but using wireframe you can clearly tell that it is 2 boxes connected by one.
Here is my code:
#include "stdafx.h"
#include <GL/freeglut.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>
#include <GL/glut.h>
using namespace std;
//variables
const float bork = 0.2;
const float blep = -0.2;
float a = 0.2;
float b = -0.2;
float c = 0.2;
float d = -0.2;
float e = 0.2;
float f = -0.2;
float i = 0.2;
float h = 0.2;
float x = 0;
float y = 0;
float z = 0;
float r = 0;
float g = 0;
float u = 0;
float base = 0;
void stopGen() {
cout << "stopped generating" << endl;
}
//Functions for generating he vertices!
void generateVerticesYu() {
glVertex2f(bork, c);
glVertex2f(bork, d);
glVertex2f(blep, c);
glVertex2f(blep, d);
glColor3ub(r, g, u);
}
void generateVerticesXr() {
glVertex2f(e, c);
glVertex2f(e, d);
glVertex2f(f, c);
glVertex2f(f, d);
glColor3ub(r, g, u);
}
void generateVerticesXl() {
glVertex2f(a, c);
glVertex2f(a, d);
glVertex2f(b, c);
glVertex2f(b, d);
glColor3ub(r, g, u);
}
void generateVerticesYd() {
glVertex2f(bork, c);
glVertex2f(bork, d);
glVertex2f(blep, c);
glVertex2f(blep, d);
glColor3ub(r, g, u);
}
//Keybinds for wireframe and camera movement
void special(int key, int, int)
{
const float step = 0.1;
if (GLUT_KEY_LEFT == key)//camera left
x -= step;
if (GLUT_KEY_RIGHT == key)//camera right
x += step;
if (GLUT_KEY_UP == key)//camera up
y += step;
if (GLUT_KEY_DOWN == key)//camera down
y -= step;
if (GLUT_KEY_SHIFT_L == key)//wireframe ON
cout << "Wireframe Enabled" << endl;
/*
if (GLUT_KEY_CTRL_L == key)//wireframe OFF
//glPolygonMode(GL_FRONT, GL_FILL);
glPolygonMode(GL_BACK, GL_FILL);
glPolygonMode(GL_FRONT, GL_FILL);
cout << "Wireframe Disabled" << endl;
*/
if (GLUT_KEY_END == key)//RED rgb value UP
++r;
cout << "Red:";
cout << r << endl;
if ((GLUT_KEY_END + GLUT_KEY_SHIFT_R) == key)//RED rgb value DOWN
--r;
if (GLUT_KEY_PAGE_UP == key)//GREEN rgb value UP
++g;
if ((GLUT_KEY_PAGE_UP + GLUT_KEY_SHIFT_R) == key)//GREEN rgb value DOWN
--g;
if (GLUT_KEY_PAGE_DOWN == key)//BLUE rgb value UP
++u;
if ((GLUT_KEY_PAGE_DOWN + GLUT_KEY_SHIFT_R) == key)//BLUE rgb value DOWN
--u;
glutPostRedisplay();
}
//renders the vertices
void display()
{
glPolygonMode(GL_FRONT, GL_LINE);
glPolygonMode(GL_BACK, GL_LINE);
glClearColor(0.5, 0.5, 0.5, 1);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-2, 2, -2, 2, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(x, y, z);
//actual rendering starts here
glBegin(GL_TRIANGLE_STRIP);
if (base != 5) {
base += 1;
generateVerticesXl();
a -= 0.4;
cout << "a:";
cout << (a) << endl;
b -= 0.4;
cout << "b:";
cout << (b) << endl;
generateVerticesXr();
e += 0.4;
cout << "e";
cout << (e) << endl;
f += 0.4;
cout << "f";
cout << (f) << endl;
}
/* do {
generateVerticesYd();
c += 0.4;
cout << "c:";
cout << (c) << endl;
d += 0.4;
cout << "d:";
cout << (d) << endl;
generateVerticesYu();
i += 0.4;
cout << "i";
cout << (i) << endl;
h += 0.4;
cout << "h";
cout << (h) << endl;
} while (base != 6);*/
glEnd();
glutSwapBuffers();
}
//main loop for everything!
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(600, 600);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE);
glutCreateWindow("McDank");
glutSpecialFunc(special);
glutDisplayFunc(display);
//glutIdleFunc();<----TO BE DETERMINED!
glutMainLoop();
return 0;
}
There may be better ways of doing this but this is how I want to do it right now, but im getting this: screenshot
Also, if I press any key, it expands it like it is trying to generate another square: screenshot2

Related

OpenGL: Shading/Interpolation not working

The purpose of this code is to generate a 'surface' with random Y variation, and then have a light source shine on it and generate areas of brightness and perform shading on darker areas. The problem is, this isn't really happening. The light either illuminates one side or the other, and those sides are all uniformly bright or dark. What am I missing with this? Keep in mind there is a good bit of code that has yet to be removed, but it is not my priority, I'm just trying to get shading functional at this point.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#ifdef MAC
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
//Camera variables
int xangle = -270;
int yangle = 0;
//Control Mode (Rotate mode by default)
int mode = 0;
//Player Position (Y offset so it would not be straddling the grid)
float cubeX = 0;
float cubeY = 0.5;
float cubeZ = 0;
//Vertex arrays for surface
float surfaceX [11][11];
float surfaceY [11][11];
float surfaceZ [11][11];
//Surface Normal arrays
float Nx[11][11];
float Ny[11][11];
float Nz[11][11];
//Color arrays
float R[11][11];
float G[11][11];
float B[11][11];
// Material properties
float Ka = 0.2;
float Kd = 0.4;
float Ks = 0.4;
float Kp = 0.5;
//Random number generator
float RandomNumber(float Min, float Max)
{
return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min;
}
//---------------------------------------
// Initialize material properties
//---------------------------------------
void init_material(float Ka, float Kd, float Ks, float Kp,
float Mr, float Mg, float Mb)
{
// Material variables
float ambient[] = { Ka * Mr, Ka * Mg, Ka * Mb, 1.0 };
float diffuse[] = { Kd * Mr, Kd * Mg, Kd * Mb, 1.0 };
float specular[] = { Ks * Mr, Ks * Mg, Ks * Mb, 1.0 };
// Initialize material
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse);
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular);
glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, Kp);
}
//---------------------------------------
// Initialize light source
//---------------------------------------
void init_light(int light_source, float Lx, float Ly, float Lz,
float Lr, float Lg, float Lb)
{
// Light variables
float light_position[] = { Lx, Ly, Lz, 0.0 };
float light_color[] = { Lr, Lg, Lb, 1.0 };
// Initialize light source
glEnable(GL_LIGHTING);
glEnable(light_source);
glLightfv(light_source, GL_POSITION, light_position);
glLightfv(light_source, GL_AMBIENT, light_color);
glLightfv(light_source, GL_DIFFUSE, light_color);
glLightfv(light_source, GL_SPECULAR, light_color);
glLightf(light_source, GL_CONSTANT_ATTENUATION, 1.0);
glLightf(light_source, GL_LINEAR_ATTENUATION, 0.0);
glLightf(light_source, GL_QUADRATIC_ATTENUATION, 0.0);
glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_FALSE);
glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
}
//---------------------------------------
// Initialize surface
//---------------------------------------
void init_surface()
{
//Initialize X, select column
for (int i = 0; i < 11; i++)
{
//Select row
for (int j = 0; j < 11; j++)
{
surfaceX[i][j] = i-5;
surfaceY[i][j] = RandomNumber(5, 7) - 5;
surfaceZ[i][j] = j-5;
//std::cout << "Coordinate "<< i << "," << j << std::endl;
}
//std::cout << "Hello world "<< std::endl;
}
//std::cout << "Coordinate -5,-5" << surfaceX[-5][-5] << std::endl;
}
void define_normals()
{
//Define surface normals
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
//Get two tangent vectors
float Ix = surfaceX[i+1][j] - surfaceX[i][j];
float Iy = surfaceY[i+1][j] - surfaceY[i][j];
float Iz = surfaceZ[i+1][j] - surfaceZ[i][j];
float Jx = surfaceX[i][j+1] - surfaceX[i][j];
float Jy = surfaceY[i][j+1] - surfaceY[i][j];
float Jz = surfaceZ[i][j+1] - surfaceZ[i][j];
//Get two tangent vectors
//float Ix = Px[i+1][j] - Px[i][j];
//float Iy = Py[i+1][j] - Py[i][j];
//float Iz = Pz[i+1][j] - Pz[i][j];
//float Jx = Px[i][j+1] - Px[i][j];
//float Jy = Py[i][j+1] - Py[i][j];
//float Jz = Pz[i][j+1] - Pz[i][j];
//Do cross product
Nx[i][j] = Iy * Jz - Iz * Jy;
Ny[i][j] = Iz * Jx - Ix * Jz;
Nz[i][j] = Ix * Jy - Iy * Jx;
//Nx[i][j] = Nx[i][j] * -1;
//Ny[i][j] = Ny[i][j] * -1;
//Nz[i][j] = Nz[i][j] * -1;
float length = sqrt(
Nx[i][j] * Nx[i][j] +
Ny[i][j] * Ny[i][j] +
Nz[i][j] * Nz[i][j]);
if (length > 0)
{
Nx[i][j] /= length;
Ny[j][j] /= length;
Nz[i][j] /= length;
}
}
}
//std::cout << "Surface normal for 0,0: "<< Nx[0][0] << "," << Ny[0][0] << "," << Nz[0][0] << std::endl;
}
void calc_color()
{
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
//Calculate light vector
//Light position, hardcoded for now 0,1,1
float Lx = -1 - surfaceX[i][j];
float Ly = -1 - surfaceY[i][j];
float Lz = -1 - surfaceZ[i][j];
std::cout << "Lx: " << Lx << std::endl;
std::cout << "Ly: " << Ly << std::endl;
std::cout << "Lz: " << Lz << std::endl;
//Grab surface normals
//These are Nx,Ny,Nz due to compiler issues
float Na = Nx[i][j];
float Nb = Ny[i][j];
float Nc = Nz[i][j];
std::cout << "Na: " << Na << std::endl;
std::cout << "Nb: " << Nb << std::endl;
std::cout << "Nc: " << Nc << std::endl;
//Do cross product
float Color = (Na * Lx) + (Nb * Ly) + (Nc * Lz);
std::cout << "Color: " << Color << std::endl;
//Color = Color * -1;
R[i][j] = Color;
G[i][j] = Color;
B[i][j] = Color;
//std::cout << "Color Value: " << std::endl;
////std::cout << "R: " << R[i][j] << std::endl;
//std::cout << "G: " << G[i][j] << std::endl;
//std::cout << "B: " << B[i][j] << std::endl;
}
}
}
//---------------------------------------
// Init function for OpenGL
//---------------------------------------
void init()
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
//Viewing Window Modified
glOrtho(-7.0, 7.0, -7.0, 7.0, -7.0, 7.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
//Rotates camera
//glRotatef(30.0, 1.0, 1.0, 1.0);
glEnable(GL_DEPTH_TEST);
//Project 3 code
init_surface();
define_normals();
//Shading code
glShadeModel(GL_SMOOTH);
glEnable(GL_NORMALIZE);
init_light(GL_LIGHT0, 0, 1, 1, 0.5, 0.5, 0.5);
//init_light(GL_LIGHT1, 0, 0, 1, 0.5, 0.5, 0.5);
//init_light(GL_LIGHT2, 0, 1, 0, 0.5, 0.5, 0.5);
}
void keyboard(unsigned char key, int x, int y)
{
//Controls
//Toggle Mode
if (key == 'q')
{
if(mode == 0)
{
mode = 1;
std::cout << "Switched to Move mode (" << mode << ")" << std::endl;
}
else if(mode == 1)
{
mode = 0;
std::cout << "Switched to Rotate mode (" << mode << ")" << std::endl;
}
}
////Rotate Camera (mode 0)
//Up & Down
else if (key == 's' && mode == 0)
xangle += 5;
else if (key == 'w' && mode == 0)
xangle -= 5;
//Left & Right
else if (key == 'a' && mode == 0)
yangle -= 5;
else if (key == 'd' && mode == 0)
yangle += 5;
////Move Cube (mode 1)
//Forward & Back
else if (key == 'w' && mode == 1)
{
if (cubeZ > -5)
cubeZ = cubeZ - 1;
else
std::cout << "You have struck an invisible wall! (Min Z bounds)" << std::endl;
}
else if (key == 's' && mode == 1)
{
if (cubeZ < 5)
cubeZ = cubeZ + 1;
else
std::cout << "You have struck an invisible wall! (Max Z bounds)" << std::endl;
}
//Strafe
else if (key == 'd' && mode == 1)
{
if (cubeX < 5)
cubeX = cubeX + 1;
else
std::cout << "You have struck an invisible wall! (Max X bounds)" << std::endl;
}
else if (key == 'a' && mode == 1)
{
if (cubeX > -5)
cubeX = cubeX - 1;
else
std::cout << "You have struck an invisible wall! (Min X bounds)" << std::endl;
}
//Up & Down (Cube offset by +0.5 in Y)
else if (key == 'z' && mode == 1)
{
if (cubeY < 5)
cubeY = cubeY + 1;
else
std::cout << "You've gone too high! Come back! (Max Y bounds)" << std::endl;
}
else if (key == 'x' && mode == 1)
{
if (cubeY > 0.5)
cubeY = cubeY - 1;
else
std::cout << "You've reached bedrock! (Min Y bounds)" << std::endl;
}
//Place/Remove block
else if (key == 'e' && mode == 1)
{
//Occupied(cubeX,cubeY,cubeZ);
}
//Redraw objects
glutPostRedisplay();
}
//---------------------------------------
// Display callback for OpenGL
//---------------------------------------
void display()
{
// Clear the screen
//std::cout << "xangle: " << xangle << std::endl;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Rotation Code
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(xangle, 1.0, 0.0, 0.0);
glRotatef(yangle, 0.0, 1.0, 0.0);
//Light Code
init_material(Ka, Kd, Ks, 100 * Kp, 0.8, 0.6, 0.4);
calc_color();
//Draw the squares, select column
for (int i = 0; i <= 9; i++)
{
//Select row
for (int j = 0; j <= 9; j++)
{
glBegin(GL_POLYGON);
//Surface starts at top left
//Counter clockwise
// CALCULATE COLOR HERE
// - calculate direction from surface to light
// - calculate dot product of normal and light direction vector
// - call glColor function
//Calculate light vector
//Light position, hardcoded for now 0,1,1
///float Lx = 0 - surfaceX[i][j];
//float Ly = 1 - surfaceY[i][j];
//float Lz = 1 - surfaceZ[i][j];
//Grab surface normals
//These are Nx,Ny,Nz due to compiler issues
//float Na = Nx[i][j];
//float Nb = Ny[i][j];
//float Nc = Nz[i][j];
//Do cross product
//float Color = (Na * Lx) + (Nb * Ly) + (Nc * Lz);
//???
//glColor3fv(Color);
//glColor3f(0.5*Color,0.5*Color,0.5*Color);
glColor3f(R[i][j], G[i][j], B[i][j]);
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glColor3f(R[i][j+1], G[i][j+1], B[i][j+1]);
glVertex3f(surfaceX[i][j+1], surfaceY[i][j+1], surfaceZ[i][j+1]);
glColor3f(R[i+1][j+1], G[i+1][j+1], B[i+1][j+1]);
glVertex3f(surfaceX[i+1][j+1], surfaceY[i+1][j+1], surfaceZ[i+1][j+1]);
glColor3f(R[i+1][j], G[i+1][j], B[i+1][j]);
glVertex3f(surfaceX[i+1][j], surfaceY[i+1][j], surfaceZ[i+1][j]);
glEnd();
}
}
//Draw the normals
for (int i = 0; i <= 10; i++)
{
for (int j = 0; j <= 10; j++)
{
glBegin(GL_LINES);
//glColor3f(0.0, 1.0, 1.0);
float length = 1;
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glVertex3f(surfaceX[i][j]+length*Nx[i][j],
surfaceY[i][j]+length*Ny[i][j],
surfaceZ[i][j]+length*Nz[i][j]);
glEnd();
}
}
glEnd();
glFlush();
//Player Cube
//Cube: midx, midy, midz, size
//+Z = Moving TOWARD camera in opengl
//Origin point for reference
glPointSize(10);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
glVertex3f(0, 0, 0);
glEnd();
//Assign Color of Lines
float R = 1;
float G = 1;
float B = 1;
glBegin(GL_LINES);
glColor3f(R, G, B);
////Drawing the grid
//Vertical lines
for (int i = 0; i < 11; i++)
{
int b = -5 + i;
glVertex3f(b, 0, -5);
glVertex3f(b, 0, 5);
}
//Horizontal lines
for (int i = 0; i < 11; i++)
{
int b = -5 + i;
glVertex3f(-5,0,b);
glVertex3f(5,0,b);
}
glEnd();
glEnd();
glFlush();
}
//---------------------------------------
// Main program
//---------------------------------------
int main(int argc, char *argv[])
{
srand(time(NULL));
//Print Instructions
std::cout << "Project 3 Controls: " << std::endl;
std::cout << "q switches control mode" << std::endl;
std::cout << "w,a,s,d for camera rotation" << std::endl;
//Required
glutInit(&argc, argv);
//Window will default to a different size without
glutInitWindowSize(500, 500);
//Window will default to a different position without
glutInitWindowPosition(250, 250);
//
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE | GLUT_DEPTH);
//Required
glutCreateWindow("Project 3");
//Required, calls display function
glutDisplayFunc(display);
glutKeyboardFunc(keyboard);
//Required
init();
glutMainLoop();
return 0;
}
Both the surface and normals are being generated as well as the color for the given vertex, I'm just not understanding why it isn't working.
The light or brightness of the surface is a function of the incident light vector the view direction and the normal vector of the surface.
You missed to set the normal vector attributes when you render the plane. Set the normal vector attribute by glNormal, before the vertex coordinate is specified:
for (int i = 0; i <= 9; i++)
{
for (int j = 0; j <= 9; j++)
{
glBegin(GL_POLYGON);
glColor3f(R[i][j], G[i][j], B[i][j]);
glNormal3f(Nx[i][j], Ny[i][j], Nz[i][j]);
glVertex3f(surfaceX[i][j], surfaceY[i][j], surfaceZ[i][j]);
glColor3f(R[i][j+1], G[i][j+1], B[i][j+1]);
glNormal3f(Nx[i][j+1], Ny[i][j+1], Nz[i][j+1]);
glVertex3f(surfaceX[i][j+1], surfaceY[i][j+1], surfaceZ[i][j+1]);
glColor3f(R[i+1][j+1], G[i+1][j+1], B[i+1][j+1]);
glNormal3f(Nx[i+1][j+1], Ny[i+1][j+1], Nz[i+1][j+1]);
glVertex3f(surfaceX[i+1][j+1], surfaceY[i+1][j+1], surfaceZ[i+1][j+1]);
glColor3f(R[i+1][j], G[i+1][j], B[i+1][j]);
glNormal3f(Nx[i+1][j], Ny[i+1][j], Nz[i+1][j]);
glVertex3f(surfaceX[i+1][j], surfaceY[i+1][j], surfaceZ[i+1][j]);
glEnd();
}
}
But note, that the quality of the light will be low, because of the Gouraud shading of the Legacy OpenGL standard light model.
See also OpenGL Lighting on texture plane is not working.
Further, the normal vectors are inverted. You can change the direction by swapping the vectors in the cross product:
Nx[i][j] = Iz * Jy - Iy * Jz;
Ny[i][j] = Ix * Jz - Iz * Jx;
Nz[i][j] = Iy * Jx - Ix * Jy;
Side note:
Note, that drawing by glBegin/glEnd sequences, the fixed function matrix stack and fixed function, per vertex light model, is deprecated since decades. See Fixed Function Pipeline and Legacy OpenGL.
Read about Vertex Specification and Shader for a state of the art way of rendering.

glreadpixel() not giving output

Firstly thanks for giving your time.This is one of question which has a lot of answers but it does not work, here I am trying to take an example and let's see if we can solve this and maybe someone will get benefited again in future.
So the problem is we have glreadpixel() calling on a point on a circle, which is drawn by bresenham function.
But the thing is its not even giving any value than 0,0,0 for RGB on changing the background colour of the window.
Here is the big code, enjoy experimenting. I have tried everything. By the way, I am developing n macOS (OpenGL is hardware independent )
using namespace std;
#include <GLUT/glut.h>
#include <iostream>
#include <vector>
#include <CoreGraphics/CoreGraphics.h>
int r = 40;
int flag = 0;
int cordinates [50][3]=
{
{50, 50} , //0 station
{400, 450} , //1 station
{750, 250} //2 station
};
int matrix[50][50] = {
{0,1,1},
{1,0,1},
{1,1,0}
};
int trains[50][50] = {
{3,4,0,1,999},
{11,1,1,2,999},
{0,0,0,999}
};
int x,y;
int *x1, *y3, x2, y2;
int xx,yy,xxx,yyy,p,q,vertexcount,counter;
int xinc,xinc3,i,j,system_time,flag1,time_chekcer_cnt,dda =0;
char buf3[12],buf[12];
float tempx0,tempy0,tempx1,tempy1;
int train0 = 999 ;int start0,speed0,next0,nextx0,nexty0,final0 = 999 ;//999 signifies invalid
int train1 ,start1, speed1,next1,nextx1,nexty1,final1 = 999 ;//999 signifies invalid
int train2 ,start2, speed2,next2,final2 = 999 ;//999 signifies invalid
void init2D()
{
glClearColor(0,0,0,0.0);
glMatrixMode (GL_PROJECTION);
glLoadIdentity();
gluOrtho2D (0.0, 900.0, 0.0, 900.0);
}
;
void bresenham_circle(const int h, const int k,const int r)
{
int x=0,y=r,p=(3-(2*r));
do{
//Read pixel
unsigned char pixelub[3];
// glReadPixels(<#GLint x#>, <#GLint y#>, <#GLsizei width#>, <#GLsizei height#>, <#GLenum format#>, <#GLenum type#>, <#GLvoid *pixels#>)
glPointSize(1);
//draw two points
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
glVertex2i((h+x),(k+y));
glEnd();
//color detection start
glReadPixels
(
(h+x),(k+y),
1, 1,
GLUT_RGB, GL_UNSIGNED_BYTE, &pixelub
);
//print
cout <<"reading pixel : "<<(h+x)<<" "<<(k+y);
printf("r: %u g: %u b: %u\n", pixelub[0], pixelub[1], pixelub[2]);
cout << endl;
//end
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POINTS);
glVertex2i((h+y),(k+x));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h+y),(k-x));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h+x),(k-y));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h-x),(k-y));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h-y),(k-x));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h-y),(k+x));
glEnd();
glBegin(GL_POINTS);
glVertex2i((h-x),(k+y));
glEnd();
x++;
if(p<0){
p+= ((4*x)+6);
}else {
y--;
p+=(4*(x-y)+10);
}
}
while (x<=y);
}
void drawBitmapText(char *string,float x,float y,float z)
{
char *c;
glRasterPos3f(x, y,z);
for (c=string; *c != NULL; c++)
{
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, *c);
}
}
void systemtime(){
sprintf(buf, "%d", system_time); // puts string into buffer
printf("%s\n", buf);
sprintf(buf3, "%d", system_time-1); // puts string into buffer
if(system_time >1){
glColor3f(1.0, 1.0, 1.0);
drawBitmapText(buf3,200,200,0);
glColor3f(0.0, 1.0, 0.0);
drawBitmapText(buf,200,200,0);
system_time =system_time+1;
}else {
drawBitmapText(buf,200,200,0);
system_time =system_time+1;
}
};
void draw_pixel(int x, int y){
glPointSize(5);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_POINTS);
cout << "\n THIS IS PRINTING X and Y :"<<x<<" & "<<y<<endl;
glVertex2i(x, y);
glEnd();
glFlush();
}
//bresenham ..... i vant DDA
void draw_dda( float *x0, float *y0, int x1, int y1,int speed) {
//cout << "\n LOOPING FOR START CORDIANTES : X0 and Y0 "<<*x0<<*y0<<endl;
int dx = x1 - *x0;
int dy = y1 - *y0;
//GLfloat x1 = p1.x; GLfloat y1 = p1.y;
GLfloat step = 0;
if(abs(dx) > abs(dy)) {
step = abs(dx);
} else {
step = abs(dy);
}
GLfloat xInc = dx/step;
GLfloat yInc = dy/step;
for (int speed_count = 0 ; speed_count < speed ; speed_count++){
glPointSize(5);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_POINTS);
//cout << "\n THIS IS PRINTING X and Y :"<<xInc<<" & "<<yInc<<endl;
glVertex2i(*x0, *y0);
glEnd();
int cy1 = *y0;
int cx1 = *x0;
//cout << "\n calling bresenham";
glColor3f(1.0, 1.0, 1.0);
bresenham_circle(cx1, cy1, r);
//cout << " \n" <<cx1<<" "<<cy1<<" "<<r;
while (flag != 1){
r--;
//cout <<"\n r is "<<r<<endl;
if (r == 0){
flag = 1;
}
}
r =40;flag= 0;
*x0 = *x0+xInc;
*y0 = *y0+yInc;
glColor3f(1.0, 0.0, 0.0);
int cy = *y0;
int cx = *x0;
//cout << "\n calling bresenham";
bresenham_circle(cx, cy, r);
//cout << " \n" <<cx<<" "<<cy<<" "<<r;
while (flag != 1){
r--;
//cout <<"\n r is "<<r<<endl;
if (r == 0){
flag = 1;
}
}
r =40;flag= 0;
//cout << "\n THIS IS PRINTING X and Y :"<<xInc<<" & "<<yInc<<endl;
}
}
void drawline(float *x0, float *y0, int x1, int y1)
{ cout << "\n LOOPING FOR START CORDIANTES : ("<<*x0<<","<<*y0<<") To ("<<x1<<","<<y1<<")"<<endl;
int dx, dy, p, x, y;
dx=x1-*x0;
dy=y1-*y0;
x=*x0;
y=*y0;
p=2*dy-dx;
//cout << "X and X1 "<<x<<x1<<endl;
if (x<x1)
{
if(p>=0)
{
draw_pixel(x,y);
//cout << ">>>>>. Y INCREMENTED >>>>> "<<y<<endl;
y=y+1;
p=p+2*dy-2*dx;
}
else
{ //cout << "\n >>>>>NOT Y INCREMENTED >>>>> "<<y<<endl;
draw_pixel(x,y);
//cout << "X and Y "<<x<<y<<endl;
p=p+2*dy;
}
x=x+1;
}
*x0=x;
*y0=y;
//cout << "\n X "<<x<<" and Y "<<y<<endl;
//cout << "\n X0 "<<*x0<<" and Y0 "<<*y0<<endl;
}
void display_ndots()
{glClear(GL_COLOR_BUFFER_BIT);
glPointSize(5);
glColor3f(1.0, 0.0, 0.0);
//draw two points
glBegin(GL_POINTS);
for(int i = 0; i < 10; i++)
{ xx = cordinates[i][0];
yy = cordinates[i][1];
glVertex2i(xx,yy);
//printf("%i",xx);
}
glEnd();
glColor3f(0.0, 1.0, 0.0);
//draw a line
glLineWidth(3);
glBegin(GL_LINES);
for(counter = 0 ; counter < 3 ; counter ++){
for (p = 0 ; p < 3 ; p ++){
for (q = 0 ; q < 3 ; q ++){
if( matrix[p][q] == 1){
xx = cordinates[p][0];
yy = cordinates[p][1];
xxx = cordinates[q][0];
yyy = cordinates[q][1];
glVertex2i(xx,yy);
glVertex2i(xxx,yyy);
}
}
}
}
glEnd();
systemtime();
time_chekcer_cnt = 0;
for(time_chekcer_cnt = 0 ; time_chekcer_cnt <10 ; time_chekcer_cnt ++){
if (system_time == trains[time_chekcer_cnt][0]){
switch (time_chekcer_cnt)
{
case 0: printf("Trian number %i have been started server time is %i \n",time_chekcer_cnt,system_time);
/*Initializing Train Data*/
train0 = time_chekcer_cnt;
speed0 = trains[time_chekcer_cnt][1];
start0 = trains[time_chekcer_cnt][2];
cout<<"\n >>>>>>>>>>>>>"<<start0<<endl;
tempx0 = cordinates[start0][0];
tempy0 = cordinates[start0][1];
next0 = trains[time_chekcer_cnt][3];
nextx0 = cordinates[next0][0];
nexty0 = cordinates[next0][1];
;
i=0;
while (trains[time_chekcer_cnt][i] != 999) {
i = i+1;
}
final0 = trains[time_chekcer_cnt][i-1];//999 signifies invalid
printf("\nfinal station is %i \n",final0);
//tempx01 = cordinates[start0][0]+10;
//tempy01 = cordinates[start0][1];
break;
case 1:
printf("Trian number %i have been started server time is %i \n",time_chekcer_cnt,system_time);
/*Initializing Train Data*/
train1 = time_chekcer_cnt;
speed1 = trains[time_chekcer_cnt][1];
start1 = trains[time_chekcer_cnt][2];
cout<<"\n >>>>>>>>>>>>>"<<start0<<endl;
tempx1 = cordinates[start0][0];
tempy1 = cordinates[start0][1];
next1 = trains[time_chekcer_cnt][3];
nextx1 = cordinates[next0][0];
nexty1 = cordinates[next0][1];
;
i=0;
while (trains[time_chekcer_cnt][i] != 999) {
i = i+1;
}
final1 = trains[time_chekcer_cnt][i-1];//999 signifies invalid
printf("\nfinal station is %i \n",final0);
break;
//default: // code to be executed if n doesn't match any cases
}
}
}
if (train0 != 999){
glColor3f(1.0, 1.0, 0.0);
draw_dda( &tempx0, &tempy0 ,nextx0, nexty0,speed0);
cout << "Draving from corinates ("<<tempx0<<","<<tempy0<<") To ("<<nextx0<<","<<nexty0<<")"<<endl;
}
if (train1 != 999){
glColor3f(1.0, 1.0, 0.0);
/// cout << "original x and y are "<<nextx0<<" & "<<nexty0;
draw_dda( &tempx1, &tempy1 ,nextx1, nexty1,speed1);
cout << "Draving from corinates ("<<tempx0<<","<<tempy0<<") To ("<<nextx0<<","<<nexty0<<")"<<endl;
// drawline( &tempx0, &tempy0 ,nextx0, nexty0);
//draw_dda( &tempx01, &tempy01 ,nextx0+10, nexty0);
// cout<<"After call by reference it is :"<<nextx0<<" & "<<nexty0;
}
/*bresenham_circle(100, 100, r);
while (flag != 1){
r--;
cout <<"\n r is "<<r<<endl;
if (r == 0){
flag = 1;
}
}*/
glFlush();
glGetError();
}
void timlycall (int unused) {
glutPostRedisplay();
glutTimerFunc(1000, timlycall, 0);
}
int main(int argc,char *argv[])
{
glutInit(&argc,argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (900, 900);
glutInitWindowPosition (0, 0);
glutCreateWindow ("points and lines");
init2D();
glutDisplayFunc(display_ndots);
//glutDisplayFunc(init2D);
glutTimerFunc(0, timlycall, 0);
glutMainLoop();
return 0;
}
Please not macos have library GLUT but windows have GL
Update 1.0
OK folks we have made some progress :
Using GLUT_RGB in glreadpixel() gives error code 1280 i.e. detected
by method BDL have provided. Which stands for incorrect enumeration ,
so use GL_RGB inside glreadpixel()
Now one more interesting thing we have to tackle, i.e now GlReadPixel
is giving r:255 g: 255 b: 255 as output , i.e background color
instead of color that must be yellow , because we are calling the
function on point which lies on the circle that too after its
painted.
You are passing a wrong enumeration to glReadPixels. GLUT_RGB is not the same as GL_RGB and may thus not be used for this function.
This would have been reported as a GL_INVALID_ENUM error by glGetError(), but the error code is never checked. You should use something like:
GLenum error = glGetError();
if (error != GL_NO_ERROR)
std::cout << "OpenGL error: " << error << std::endl;

How do I change the size of the polygon that is called from a text file?

I am having a problem with changing the size of a polygon that I am calling from a text file using vertices. Whenever I try and change the coordinates of the vertices in the text file and run the program the shape stays the same size and when I go back to the text file all the coordinates have changed back. How can I change the shapes size?
Here is the code I'm using for this:
void cal_vertices() {
// open a file for writing pentagon vertices
ofstream outfile("vertices1.txt");
float a = 2 * 3.1415926 / 5.0;
float x1 = 0.0, y1 = 1.0;
outfile << x1 << " " << y1 << endl;;
float x, y;
for (int i = 1; i < 5; i++) {
x = x1 * cos(a * i) - y1 * sin(a * i);
y = y1 * cos(a * i) + x1 * sin(a * i);
outfile << x << " " << y << endl;;
}
outfile.close();
}
void read_vertices() {
//reads verticies from the text file
ifstream infile("vertices1.txt");
for (int i = 0; i < 5; i++){
infile >> vertices[i][0];
infile >> vertices[i][1];
cout << vertices[i][0] << " " << vertices[i][1] << endl;
}
}
void init(){
cal_vertices();
read_vertices();
glNewList(listname, GL_COMPILE);
glColor4f(red, green, blue, 1.0);
glBegin(GL_LINE_LOOP);
for (int i = 0; i < 5; i++){
glVertex3f(vertices[i][0], vertices[i][1], 0.0);
}
glEnd();
glEndList();
Try this:
glPushMatrix ();
glScalef (2.0F, 2.0F, 2.0F);
glBegin(GL_LINE_LOOP);
...
glEnd();
glPopMatrix ();
That should double the size of your polygon in each dimension.

Wierd C++ Problems, OpenGL game

Aight so, I'm in the process of making a simple terrain program, not exactly a game, but hey maybe someday. I'll start with describing the basics of how my program works. I'm using an two-dimension array to store the coordinates of the vertexes which make up a grid of triangles. The x and z values are assigned in the follow code:
//Sets up the array for the vertexes
int e = 0;
int p = 0;
for (int r = 0; r < 10; r++) {
for (int x = 0; x < 5; x++) {
grid[p][0] = x * 2;
grid[p][2] = e;
p++;
}
e += 2;
}
Okay, so the grid array is the one I use for storing the values of all the vertexes in the program, the first argument (the value in the first set of []) is used to choose a point, the second set of [] is the x, y, and z values, the code snippet above only sets values for the x and z coordinates.
The y value, height, is randomised at the start of the program using the following code:
//Random heights for the terrain
if (fir == true) {
for (int h = 0; h < 64; h++) {
grid[h][1] = rand() % 3;
}
fir = false;
}
And the code for drawing the triangles:
for (int q = 0; q < 11; q++) {
a = q * 5;
b = a + 1;
c = a + 5;
glBegin(GL_TRIANGLE_STRIP);
for (int dw = 0; dw < 8; dw++) {
//a
glColor3f(grid[a][1], grid[a][1], grid[a][1]);
glVertex3f(grid[a][0], grid[a][1], grid[a][2]);
//b
glColor3f(grid[b][1], grid[b][1], grid[b][1]);
glVertex3f(grid[b][0], grid[b][1], grid[b][2]);
//c
glColor3f(1, 0, 0);
glVertex3f(grid[c][0], grid[c][1], grid[c][2]);
a = c;
t = b;
b = a + 1;
c = t;
}
glEnd();
}
glutSwapBuffers();
}
The problem I'm having is that I can't make the size of the grid bigger without the program breaking, I would like to be able to change the size of the grid of triangles to whatever I like. when I try to change the for loop which goes through the x values (first code snippet) the program breaks, my movement speed drastically increases, moving the mouse has no effect on the camera rotation. When I do manage to find a set of values to work the grid of triangles is messed up, any points after the 5th row are all set to 0, I'll post the whole program, I don't know if it will run for everyone, but I think the problem is something that requires the whole program to be looked at in order to solve.
I think the problem may be due to variables being shared by different parts of the program, I have looked and looked but can't seem to find any cause. This is my last resort to solving this nightmare of a problem...
main.cpp
/*
*/
#include <iostream>
#include <glut.h>
#include <gl\GL.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <cstdlib>
#include "vector3f.h"
using namespace std;
//Variables
const int WINDOW_WIDTH = 1280;
const int WINDOW_HEIGHT = 720;
const char* WINDOW_TITLE = "Terrain";
const float WALKING_SPEED = 5.0;
const float MOUSE_SENSITIVITY = 0.3;
const float MAX_TILT = 90.0;
float grid[200][3];
float LAST_TIME;
float CURRENT_TIME;
float DELTA_TIME;
bool KEY[256];
int a;
int b;
int c;
int t;
int MOUSE_LAST_X;
int MOUSE_LAST_Y;
int MOUSE_CURRENT_X;
int MOUSE_CURRENT_Y;
int MOUSE_DELTA_X;
int MOUSE_DELTA_Y;
float red;
float green;
float blue;
bool fir = true;
//Object
vector3f CAMERA_POSITION;
vector3f CAMERA_ROTATION;
//Functions
void initialize();
void display();
void reshape(int w, int h);
void keyboardDown(unsigned char key, int x, int y);
void keyboardUp(unsigned char key, int x, int y);
void mouseMove(int x, int y);
void movement();
double degreesToRadians(double degrees);
double dsin(double theta);
double dcos(double theta);
double dtan(double theta);
void display() {
//cout << KEY[' '] << endl;
movement();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
//Camera transformations
glRotatef(CAMERA_ROTATION.x, 1, 0, 0);
glRotatef(CAMERA_ROTATION.y, 0, 1, 0);
glRotatef(CAMERA_ROTATION.z, 0, 0, 1);
glTranslatef(-CAMERA_POSITION.x, -CAMERA_POSITION.y, CAMERA_POSITION.z);
//Draw the basic triangle
glBegin(GL_TRIANGLES);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(-1.0, -1.0, -3.0);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, -3.0);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(10.0, -1.0, -3.0);
glEnd();
/*
1 0,0,0
2 2,0,0
3 4,0,0
4 6,0,0
5 0,0,2
6 2,0,2
7 4,0,2
8 6,0,2
9 0,0,4
10 2,0,4
11 4,0,4
12 6,0,4
13 0,0,6
14 2,0,6
15 4,0,6
16 6,0,6
*/
/*//Option 1 (2 for loops, four if statements)
for (int p = 0; p < 16; p++) {
for (int x = 0; x < 7; x += 2) {
grid[p][0] = x;
}
grid[p][1] = 0;
if (p < 4) {
grid[p][2] = 0;
}
if (p < 8 && p >= 4) {
grid[p][2] = 2;
}
if (p < 12 && p >= 8) {
grid[p][2] = 4;
}
if (p < 16 && p >= 12) {
grid[p][2] = 6;
}
}
*/
//Option 2 (three for loops)
//Sets up the array for the vertexes
int e = 0;
int p = 0;
for (int r = 0; r < 10; r++) {
for (int x = 0; x < 5; x++) {
grid[p][0] = x * 2;
grid[p][2] = e;
p++;
}
e += 2;
}
//Random heights for the terrain
if (fir == true) {
for (int h = 0; h < 64; h++) {
grid[h][1] = rand() % 3;
}
fir = false;
}
//cout << "point 0: " << grid[0][0] << ", " << grid[0][1] << ", " << grid[0][2] << endl;
//cout << "point 1: " << grid[1][0] << ", " << grid[1][1] << ", " << grid[1][2] << endl;
//cout << "point 2: " << grid[2][0] << ", " << grid[2][1] << ", " << grid[2][2] << endl;
//cout << "point 3: " << grid[3][0] << ", " << grid[3][1] << ", " << grid[3][2] << endl;
//cout << "point 4: " << grid[4][0] << ", " << grid[4][1] << ", " << grid[4][2] << endl;
//cout << "point 5: " << grid[5][0] << ", " << grid[5][1] << ", " << grid[5][2] << endl;
//cout << "point 6: " << grid[6][0] << ", " << grid[6][1] << ", " << grid[6][2] << endl;
//cout << "point 7: " << grid[7][0] << ", " << grid[7][1] << ", " << grid[7][2] << endl;
//cout << "point 8: " << grid[8][0] << ", " << grid[8][1] << ", " << grid[8][2] << endl;
//cout << "point 9: " << grid[9][0] << ", " << grid[9][1] << ", " << grid[9][2] << endl;
//cout << "point 10: " << grid[10][0] << ", " << grid[10][1] << ", " << grid[10][2] << endl;
//cout << "point 11: " << grid[11][0] << ", " << grid[11][1] << ", " << grid[11][2] << endl;
//cout << "point 12: " << grid[12][0] << ", " << grid[12][1] << ", " << grid[12][2] << endl;
//cout << "point 13: " << grid[13][0] << ", " << grid[13][1] << ", " << grid[13][2] << endl;
//cout << "point 14: " << grid[14][0] << ", " << grid[14][1] << ", " << grid[14][2] << endl;
//cout << "point 15: " << grid[15][0] << ", " << grid[15][1] << ", " << grid[15][2] << endl;
for (int q = 0; q < 11; q++) {
a = q * 5;
b = a + 1;
c = a + 5;
glBegin(GL_TRIANGLE_STRIP);
for (int dw = 0; dw < 8; dw++) {
//a
glColor3f(grid[a][1], grid[a][1], grid[a][1]);
glVertex3f(grid[a][0], grid[a][1], grid[a][2]);
//b
glColor3f(grid[b][1], grid[b][1], grid[b][1]);
glVertex3f(grid[b][0], grid[b][1], grid[b][2]);
//c
glColor3f(1, 0, 0);
glVertex3f(grid[c][0], grid[c][1], grid[c][2]);
a = c;
t = b;
b = a + 1;
c = t;
}
glEnd();
}
glutSwapBuffers();
}
void keyboardDown(unsigned char key, int x, int y) {
KEY[key] = true;
}
void keyboardUp(unsigned char key, int x, int y) {
KEY[key] = false;
}
void movement() {
CURRENT_TIME = ((float)glutGet(GLUT_ELAPSED_TIME) / 1000);
DELTA_TIME = CURRENT_TIME - LAST_TIME;
LAST_TIME = CURRENT_TIME;
MOUSE_DELTA_X = MOUSE_CURRENT_X - MOUSE_LAST_X;
MOUSE_DELTA_Y = MOUSE_CURRENT_Y - MOUSE_LAST_Y;
MOUSE_LAST_X = MOUSE_CURRENT_X;
MOUSE_LAST_Y = MOUSE_CURRENT_Y;
CAMERA_ROTATION.y += (float)MOUSE_DELTA_X * MOUSE_SENSITIVITY;
CAMERA_ROTATION.x += (float)MOUSE_DELTA_Y * MOUSE_SENSITIVITY;
if (CAMERA_ROTATION.x > MAX_TILT) {
CAMERA_ROTATION.x = MAX_TILT;
}
if (CAMERA_ROTATION.x < -MAX_TILT) {
CAMERA_ROTATION.x = -MAX_TILT;
}
if (KEY['w'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y);
CAMERA_POSITION.y += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.x + 180);
}
if (KEY['s'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y + 180);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y + 180);
CAMERA_POSITION.y += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.x);
}
if (KEY['a'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y + 270);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y + 270);
}
if (KEY['d'] == true) {
CAMERA_POSITION.x += (WALKING_SPEED * DELTA_TIME) * dsin(CAMERA_ROTATION.y + 90);
CAMERA_POSITION.z += (WALKING_SPEED * DELTA_TIME) * dcos(CAMERA_ROTATION.y + 90);
}
if (KEY[' '] == true) {
CAMERA_POSITION.y += (WALKING_SPEED * DELTA_TIME);
}
if (KEY['e'] == true) {
exit(1);
}
}
void mouseMove(int x, int y) {
MOUSE_CURRENT_X = x;
MOUSE_CURRENT_Y = y;
}
double degreesToRadians(double degrees){
return degrees * M_PI / 180;
}
double dsin(double theta) {
return sin(degreesToRadians(theta));
}
double dcos(double theta) {
return cos(degreesToRadians(theta));
}
double dtan(double theta) {
return tan(degreesToRadians(theta));
}
void reshape(int w, int h) {
//Stops the ratio from dividing by 0
if (h == 0) {
h = 1;
}
float fRatio = (float)w / h;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
gluPerspective(60, fRatio, 0.1, 1000);
glMatrixMode(GL_MODELVIEW);
}
void initialize() {
glClearColor(0.0, 0.0, 102.0 / 255.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
}
int main(int iArgc, char** cArgv) {
//Initialise OpenGL and GLUT
glutInit(&iArgc, cArgv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
//Setup window
glutInitWindowPosition(0, 0);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow(WINDOW_TITLE);
//Setup GLUT callback functions
initialize();
glutReshapeFunc(reshape);
glutDisplayFunc(display);
glutIdleFunc(display);
glutKeyboardFunc(keyboardDown);
glutKeyboardUpFunc(keyboardUp);
glutMotionFunc(mouseMove);
glutPassiveMotionFunc(mouseMove);
glEnable(GL_DEPTH_TEST);
//Enter main loop
glutMainLoop();
return 0;
}
Some quick remarks:
your loops access different number of points!
1st loop (r, x) initialize 50 points
2nd loop (h) initialize 64 points
3rd loop (q, dw) access 59 points
glColor3f values should be between 0 and 1 but, using your grid y values, you get 0, 1 or 2
beware of the gimbal lock problem when trying to rotate your view!

No matching function for call to class

/*
* File: ShapeTwoD.h
* Author: Administrator
*
* Created on October 30, 2012, 12:05 AM
*/
#ifndef SHAPETWOD_H
#define SHAPETWOD_H
#include <string>
#include <math.h>
using namespace std;
struct Point {
int x, y;
};
class ShapeTwoD {
public:
ShapeTwoD(string shapename, bool containsWS);
string getName();
bool getContainsWarpSpace();
string toString();
virtual double computeArea();
virtual bool isPointInShape(Point P, Point* V, int n);
virtual bool isPointOnShape(Point A, Point B, Point C, int slope, int intercept, int left, int top, int right, int bottom, int dx, int dy);
void setName(string shapename);
void setContainsWarpSpace(bool containsWS);
private:
string name;
bool containsWarpSpace;
};
class Cross : public ShapeTwoD {
public:
Cross(string shapename = "Cross", bool containsWS, int vertices = 12, Point ordinates[]):ShapeTwoD(shapename, containsWS){}
int getVert();
void setVert(int vertices);
Point getOrd();
void setOrd(Point ordinates[]);
virtual double computeArea(Point A[], int vertices);
private:
int vert;
Point ord[];
};
class Rectangle : public ShapeTwoD {
public:
Rectangle(string shapename = "Rectangle", bool containsWS, int vertices = 4, Point ordinates[]):ShapeTwoD(shapename, containsWS){}
int getVert();
void setVert(int vertices);
Point getOrd();
void setOrd(Point ordinates[]);
virtual double computeArea(Point A, Point B);
private:
int vert;
Point ord[];
};
class Square : public ShapeTwoD {
public:
Square(string shapename = "Square", bool containsWS, int vertices = 4, Point ordinates[]):ShapeTwoD(shapename, containsWS){}
int getVert();
void setVert(int vertices);
Point getOrd();
void setOrd(Point ordinates[]);
virtual double computeArea(Point A, Point B);
private:
int vert;
Point ord[];
};
#endif /* SHAPETWOD_H */
/*
* File: ShapeTwoD.cpp
* Author: Administrator
*
* Created on October 30, 2012, 12:05 AM
*/
#include "ShapeTwoD.h"
#include <sstream>
ShapeTwoD::ShapeTwoD(string shapename, bool containsWS) {
name = shapename;
containsWarpSpace = containsWS;
}
string ShapeTwoD::getName() {
return name;
}
void ShapeTwoD::setName(string shapename) {
name = shapename;
};
bool ShapeTwoD::getContainsWarpSpace() {
return containsWarpSpace;
}
void ShapeTwoD::setContainsWarpSpace(bool containsWS) {
containsWarpSpace = containsWS;
}
string cvtBool(bool b) {
stringstream ss;
ss << b;
return ss.str();
}
string ShapeTwoD::toString() {
return "Name:\t" + name + "\nSpecial Type:\t" + cvtBool(containsWarpSpace) + "\n";
}
// Formulas gotten from http://www.mathopenref.com/coordpolygonarea.html
// http://softsurfer.com/Archive/algorithm_0103/algorithm_0103.htm
int pointsInShape;
int pointsOnShape;
double ShapeTwoD::computeArea() {
// Based on Pick's Thorem
double area = pointsInShape + (pointsOnShape / 2) - 1;
return area;
}
float isLeft(Point P0, Point P1, Point P2) {
return ((P1.x - P0.x) * (P2.y - P0.y) - (P2.x - P0.x) * (P1.y - P0.y));
}
bool ShapeTwoD::isPointInShape(Point P, Point* V, int n) {
// Input: P = a point,
// V[] = vertex points of a polygon V[n+1] with V[n]=V[0]
int wn = 0; // the winding number counter
// loop through all edges of the polygon
for (int i = 0; i < n; i++) { // edge from V[i] to V[i+1]
if (V[i].y <= P.y) { // start y <= P.y
if (V[i + 1].y > P.y) // an upward crossing
if (isLeft(V[i], V[i + 1], P) > 0) // P left of edge
++wn; // have a valid up intersect
} else { // start y > P.y (no test needed)
if (V[i + 1].y <= P.y) // a downward crossing
if (isLeft(V[i], V[i + 1], P) < 0) // P right of edge
--wn; // have a valid down intersect
}
}
pointsInShape += wn;
return true;
}
bool ShapeTwoD::isPointOnShape(Point A, Point B, Point C, int slope, int intercept, int left, int top, int right, int bottom, int dx, int dy) {
// Linear equation
dx = B.x - A.x;
dy = B.y - A.y;
slope = dy / dx;
intercept = y1 - slope * A.x;
if (A.x < B.x) {
left = A.x;
right = B.x;
} else {
left = B.x;
right = A.x;
}
if (A.y < B.y) {
top = A.y;
bottom = B.y;
} else {
top = B.y;
bottom = A.y;
}
if (slope * C.x + intercept > (C.y - 0.01) && slope * C.x + intercept < (C.y + 0.01)) {
if (C.x >= left && C.x <= right && C.y >= top && C.y <= bottom) {
pointsOnShape++;
return true;
}
}
}
Cross::Cross(string shapename, bool containsWS, int vertices = 12, Point ordinates[]):ShapeTwoD(shapename, containsWS) {
vert = vertices;
ord[] = ordinates[];
}
int Cross::getVert() {
return vert;
}
void Cross::setVert(int vertices) {
vert = vertices;
}
Point Cross::getOrd() {
return ord[];
}
void Cross::setOrd(Point ordinates[]) {
ord[] = ordinates[];
}
double Cross::computeArea(Point A[], int vertices) {
/* If you know the coordinates of the vertices of a polygon, this algorithm can be used to find the area.
* Parameters
* X, Y Arrays of the x and y coordinates of the vertices, traced in a clockwise direction, starting at any vertex. If you trace them counterclockwise, the result will be correct but have a negative sign.
* numPoints The number of vertices
* Returns the area of the polygon
*/
double area = 0;
int j = vertices - 1; // The last vertex is the 'previous' one to the first
for (int i = 0; i < vertices; i++) {
area = (area + (A[j].x + A[i].x) * (A[j].y - A[i].y))/2;
j = i;
}
return area;
}
Rectangle::Rectangle(string shapename, bool containsWS, int vertices = 4, Point ordinates[]):ShapeTwoD(shapename, containsWS) {
vert = vertices;
ord[] = ordinates[];
}
int Rectangle::getVert() {
return vert;
}
void Rectangle::setVert(int vertices) {
vert = vertices;
}
void Rectangle::getOrd() {
return ord[];
}
void Rectangle::setOrd(Point ordinates[]) {
ord[] = ordinates[];
}
double Rectangle::computeArea(Point A, Point B, Point C) {
double length = sqrt(pow((A.x - B.x), 2) + pow((A.y - B.y), 2));
double width = sqrt(pow((B.x - C.x), 2) + pow((B.y - C.y), 2));
double area = length * width;
return area;
}
Square::Square(string shapename, bool containsWS, int vertices, Point ordinates[]):ShapeTwoD(shapename, containsWS) {
vert = vertices;
ord[] = ordinates[];
}
int Square::getVert() {
return vert;
}
void Square::setVert(int vertices) {
vert = vertices;
}
void Square::getOrd() {
return ord[];
}
void Square::setOrd(Point ordinates[]) {
ord[] = ordinates[];
}
double Square::computeArea(Point A, Point B) {
double length = sqrt(pow((A.x - B.x), 2) + pow((A.y - B.y), 2));
double area = pow(length, 2);
return area;
}
/*
* File: Assn2.cpp
* Author: Administrator
*
* Created on October 29, 2012, 11:58 PM
*/
#include "ShapeTwoD.h"
#include <iostream>
#include <math.h>
#include <string>
#include <vector>
using namespace std;
// Global declarations
void menu(), option1(), option2(), option3(), option4();
int choice, vert;
string shape, special;
double area;
bool containsWS;
vector<ShapeTwoD> stdv;
int main() {
cout << "Welcome to Assn2 program!\n\n";
// When user enters 5 as input, the program quits
while (choice != 5) {
menu();
/* switch evaluates expression and checks if it is equivalent to constant1,
* if it is, it executes group of statements 1 until it finds the break statement.
* When it finds this break statement the program jumps to the end of the switch selective structure.
* If expression was not equal to constant1 it will be checked against constant2.
* If it is equal to this, it will execute group of statements 2 until a break keyword is found,
* and then will jump to the end of the switch selective structure.
*/
switch (choice) {
case 1:
option1();
break;
case 2:
option2();
break;
case 3:
option3();
break;
case 4:
option4();
break;
}
}
}
void menu() {
cout << "1) Input sensor data\n";
cout << "2) Compute area (for all records)\n";
cout << "3) Print shapes report\n";
cout << "4) Sort shape data\n";
cout << "5) Quit\n\n";
cout << "Please enter your choice: ";
cin >> choice;
cout << "\n";
}
void option1() {
cout << "[ Input sensor data ]\n";
cout << "Please enter name of Shape (Cross, Rectangle or Square): ";
cin >> shape;
cout << "Please enter Special type (NS or WS): ";
cin >> special;
if (special == "WS") {
containsWS = true;
}
else {
containsWS = false;
}
if (shape == "Cross") {
vert = 12;
for (int v = 0; v < vert; v++) {
Point ordinates[v];
cout << "Please enter x-ordinate of pt. " << (v+1) << ":";
cin >> ordinates[v].x;
cout << "Please enter y-ordinate of pt. " << (v+1) << ":";
cin >> ordinates[v].y;
Cross cross(shape, containsWS, vert, ordinates[v]);
stdv.push_back(cross);
}
}
if (shape == "Rectangle") {
vert = 4;
for (int v = 0; v < vert; v++) {
Point ordinates[v];
cout << "Please enter x-ordinate of pt. " << (v+1) << ":";
cin >> ordinates[v].x;
cout << "Please enter y-ordinate of pt. " << (v+1) << ":";
cin >> ordinates[v].y;
Rectangle rectangle(shape, containsWS, vert, ordinates[v]);
stdv.push_back(rectangle);
}
}
else {
shape = "Square";
vert = 4;
for (int v = 0; v < vert; v++) {
Point ordinates[v];
cout << "Please enter x-ordinate of pt. " << (v+1) << ":";
cin >> ordinates[v].x;
cout << "Please enter y-ordinate of pt. " << (v+1) << ":";
cin >> ordinates[v].y;
Square square(shape, containsWS, vert, ordinates[v]);
stdv.push_back(square);
}
}
cout << "Record successfully stored. Going back to main menu";
}
void option2() {
if (stdv.size() != 0) {
for (int count = 0; count < stdv.size(); count++) {
area = stdv.at(count).computeArea();
//Debugging purpose
cout << (count+1) << ")" << stdv.at(count).getName() << "\t" << area;
}
cout << "Computation completed! (" << stdv.size() << " records were updated)\n\n";
}
}
Here I'm trying to insert an array of the struct Point into my class constructors (Cross, Rectangle, Square). But it returned me some errors which I don't really get.
Assn2.cpp:113: error: no matching function for call to
`Cross::Cross(std::string&, bool&, int&, Point&)'
ShapeTwoD.h:41: note: candidates are: Cross::Cross(const Cross&)
ShapeTwoD.h:43: note: Cross::Cross(std::string, bool,
int, Point*)
Assn2.cpp:136: error: no matching function for call to
`Rectangle::Rectangle(std::string&, bool&, int&, Point&)
ShapeTwoD.h:56: note: candidates are: Rectangle::Rectangle(const
Rectangle&)
ShapeTwoD.h:58: note: Rectangle::Rectangle(std::string, bool, int,
Point*)
your function declaration won't even compile, the parameter with default value can't be in the front of argument without default value:
Cross(string shapename = "Cross", bool containsWS, int vertices = 12, Point ordinates[])
Rectangle(string shapename = "Rectangle", bool containsWS, int vertices = 4, Point ordinates[]):ShapeTwoD(shapename, containsWS){}
Square(string shapename = "Square", bool containsWS, int vertices = 4, Point ordinates[]):ShapeTwoD(shapename, containsWS){}
you either make all parameters having all default values or change the order, for example below is valid function declaration:
Cross(bool containsWS, Point ordinates[], string shapename = "Cross", int vertices = 12)