I'm trying to play around with OpenGL and this is my very first code. How can I change to different view to 2 object drawn on the screen?
Is there anyway to do this manually, in stead of using function gluPerspective()?
I tried glRotatef(60, 0.0, 0.0, 5.0) but there is nothing happen. Cos I want to see other faces of the Pyramid and also different view of the rotating sphere.
Also I want to set different colours to different objects that I draw on the screen, how can I do that?
The code to set colour for each object, which is glColor3f, I put it in between glPushMatrix() and glPopMatrix(), also I always include the line glLoadIdentity() before starting draw objects on screen. As far as I know, this line will reset the settings of the previous objects and allows me to set new properties for new object.
Then why when I press button D, the sphere is blue when it supposes to be in white?
Here is my full code:
#include <windows.h>
#include <GL/glew.h>
#include <GL/gl.h>
#include <math.h>
#include <GLFW/glfw3.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define X .525731112119133606
#define Z .850650808352039932
#define Y 0.0
#define PI 3.1415926535898
#define CIRCLE_STEP 5000
using namespace std;
// Open an OpenGL window
GLFWwindow* window;
int keyboard = 0, itr;
bool big_Sphere = true, sphereWithNormalV = false, animation = false;
GLdouble angle = 0;
/****Step 1: define vertices in (x, y, z) form****/
// Coordinates to draw a Icosahedron
GLfloat icoVertices[12][3] = {
{-X, Y, Z}, {X, Y, Z}, {-X, Y, -Z}, {X, Y, -Z},
{Y, Z, X}, {Y, Z, -X}, {Y, -Z, X}, {Y, -Z, -X},
{Z, X, Y}, {-Z, X, Y}, {Z, -X, Y}, {-Z, -X, Y}
};
// Coordinates to draw a Pyramid
GLfloat pyVertices[4][3] = {
{0.0f, 1.0f, 0.0f},
{1.0f, 0.0f, 0.0f},
{-1.0f, 0.0f, 0.0f},
{0.0f, 0.0f, -1.0f}
};
static GLuint icoIndices[20][3] = {
{0,4,1}, {0,9,4}, {9,5,4}, {4,5,8}, {4,8,1},
{8,10,1}, {8,3,10}, {5,3,8}, {5,2,3}, {2,7,3},
{7,10,3}, {7,6,10}, {7,11,6}, {11,0,6}, {0,1,6},
{6,1,10}, {9,0,11}, {9,11,2}, {9,2,5}, {7,2,11} };
static GLuint pyIndices[4][3] = {
{0,1,2}, {0,1,3}, {0,2,3}, {1,2,3}
};
/************************/
void normalize3f(float v[3]) {
GLfloat d = sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
if (d == 0.0) {
fprintf(stderr, "zero length vector");
return;
}
v[0] /= d; v[1] /= d; v[2] /= d;
}
void sphereNormalV(GLfloat p1[3], GLfloat p2[3], GLfloat p3[3])
{
glBegin(GL_LINES);
glVertex3f(p1[0] *1.5,p1[1] *1.5, p1[2] *1.5);
glVertex3fv(p1);
glEnd();
glBegin(GL_LINES);
glVertex3f(p2[0] *1.1,p2[1] *1.1, p2[2] *1.1);
glVertex3fv(p2);
glEnd();
glBegin(GL_LINES);
glVertex3f(p3[0] *1.1,p3[1] *1.1, p3[2] *1.1);
glVertex3fv(p3);
glEnd();
}
void drawtriangle(float *v1, float *v2, float *v3)
{
glBegin(GL_LINE_LOOP);
//glNormal3fv(v1);
glVertex3fv(v1);
//glNormal3fv(v2);
glVertex3fv(v2);
//glNormal3fv(v3);
glVertex3fv(v3);
glEnd();
}
void subdivide(GLfloat *v1, GLfloat *v2, GLfloat *v3, long depth)
{
GLfloat v12[3], v23[3], v31[3];
GLint i;
if (depth == 0){
drawtriangle(v1, v2, v3);
if (sphereWithNormalV == true){
sphereNormalV(v1, v2, v3);
}
return;
}
for (i = 0; i < 3; i++) {
v12[i] = v1[i]+v2[i];
v23[i] = v2[i]+v3[i];
v31[i] = v3[i]+v1[i];
}
normalize3f(v12);
normalize3f(v23);
normalize3f(v31);
subdivide(v1, v12, v31, depth-1);
subdivide(v2, v23, v12, depth-1);
subdivide(v3, v31, v23, depth-1);
subdivide(v12, v23, v31, depth-1);
}
void drawSphere(GLfloat x, GLfloat y, GLfloat z){
glLoadIdentity();
glPushMatrix();
if (big_Sphere == true){
glScaled(0.4, 0.55, 0.4);
}else{
glScaled(0.13, 0.18, 0.13);
}
if (animation){
glTranslatef(x, y, z);
}
glBegin(GL_LINE_LOOP);
for (int i = 0; i < 20; i++) {
subdivide(&icoVertices[icoIndices[i][0]][0], &icoVertices[icoIndices[i][1]][0], &icoVertices[icoIndices[i][2]][0], 3);
}
glEnd();
glPopMatrix();
}
void drawPyramid(){//(GLfloat x, GLfloat y, GLfloat z){
glLoadIdentity();
glPushMatrix();
glScaled(0.13, 0.18, 0.13);
glBegin(GL_LINE_LOOP);
for (int i = 0; i < 4; i++){
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3fv(pyVertices[pyIndices[i][0]]);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3fv(pyVertices[pyIndices[i][1]]);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3fv(pyVertices[pyIndices[i][2]]);
}
glEnd();
glPopMatrix();
}
int getKeyPressed(){
if (glfwGetKey(window, GLFW_KEY_A)){
keyboard = GLFW_KEY_A;
}
if (glfwGetKey(window, GLFW_KEY_B)){
keyboard = GLFW_KEY_B;
}
if (glfwGetKey(window, GLFW_KEY_C)){
keyboard = GLFW_KEY_A;
}
if (glfwGetKey(window, GLFW_KEY_D)){
keyboard = GLFW_KEY_D;
}
if (glfwGetKey(window, GLFW_KEY_E)){
keyboard = GLFW_KEY_E;
}
return keyboard;
}
void controlSphere(bool _big_Sphere, bool _sphereNormalV, bool _animation){
big_Sphere = _big_Sphere;
sphereWithNormalV = _sphereNormalV;
animation = _animation;
}
void gluPerspective(double fovy,double aspect, double zNear, double zFar)
{
// Start in projection mode.
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double xmin, xmax, ymin, ymax;
ymax = zNear * tan(fovy * PI / 360.0);
ymin = -ymax;
xmin = ymin * aspect;
xmax = ymax * aspect;
glFrustum(xmin, xmax, ymin, ymax, zNear, zFar);
}
int main( void ) {
if (!glfwInit()){
fprintf(stderr, "Failed to initialize GLFW.\n");
return -1;
}
// Create a windowed mode window and its OpenGL context
window = glfwCreateWindow(1100, 800, "Hello World", NULL, NULL);
if (window == NULL) {
fprintf(stderr, "glfw failed to create window.\n");
//glfwTerminate();
return -1;
}
// Make the window's context current
glfwMakeContextCurrent(window);
glewInit();
if (glewInit() != GLEW_OK){
fprintf(stderr, "Failed to initialize GLEW: %s.\n", glewGetErrorString(glewInit()));
return -1;
}
// 4x anti aliasing
glfwWindowHint(GLFW_SAMPLES, 4);
/**Step 3: Main loop for OpenGL draw the shape**
/* Main loop */
int i = 0;
GLfloat pos_X, pos_Y;
glRotatef(60, 0.0f, 0.3f, 0.4f);
do{
//glMatrixMode(GL_MODELVIEW);
glClear(GL_COLOR_BUFFER_BIT);
switch(getKeyPressed()){
case 65:
controlSphere(true, false, false);
drawSphere(0, 0, 0);
break;
case 66:
controlSphere(true, true, false);
drawSphere(0, 0, 0);
break;
case 67:
// drawPyramid();
break;
case 68:
// drawing a Sphere moving in a circular path
controlSphere(false, false, true);
angle = 2*PI*i/CIRCLE_STEP;
pos_X = cos(angle) * 4.5;
pos_Y = sin(angle) * 4.5;
drawSphere(pos_X, pos_Y, 0);
i += 1;
angle += 1;
if (angle >= 360){
angle = 0;
}
// drawing a Pyramid rotate around its y axis
drawPyramid();
break;
default:
controlSphere(true, false, false);
drawSphere(0, 0, 0);
break;
}
Sleep(1);
// Swap front and back rendering buffers
glfwSwapBuffers(window);
//Poll for and process events
glfwPollEvents();
} // check if the ESC key was pressed or the window was closed
while(glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0);
/***********************************************/
// Close window and terminate GLFW
glfwDestroyWindow(window);
glfwTerminate();
// Exit program
exit( EXIT_SUCCESS );
}
Is there anyway to do this manually, in stead of using function gluPerspective()?
I don't really understand this question. But if you want to set multiples objects (that have the same parameters) with different transformations, scale, rotation and/or translation, you need to push this to the stack and then draw the desired object. A good starting point can be found here: http://www.songho.ca/opengl/gl_transform.html
Also I want to set different colours to different objects that I draw on the screen, how can I do that?
Your sphere is blue because the last call for glColor3f() was in drawPyramid().
You can change the color of your ball by just calling glColor3f (1.0f, 1.0f, 1.0f); in the beginning of its draw function:
void drawSphere (GLfloat x, GLfloat y, GLfloat z)
{
glColor3f (1.0f, 1.0f, 1.0f);
...
}
A really great site to learn OpenGL from the old pipeline (what you just implemented) to the new (GLSL) is http://www.lighthouse3d.com/tutorials/.
You are looking for Multiple viewports which allows the to split the screen. In your case two different viewports two different cameras(one for each) will be enough.
Check this post.
Related
I would like to be able to click on a point on the surface of a sphere in OpenGL. Here's what I have so far:
#include <iostream>
#include <stdlib.h>
#include "GL/freeglut.h"
#include "glm/glm.hpp"
#include "quaternion.h"
const GLsizei WINDOW_WIDTH = 640;
const GLsizei WINDOW_HEIGHT = 640;
int mouse_x = 0;
int mouse_y = 0;
float zoom = 1.0f;
float zoom_sensitivity = 0.1f;
const float zoom_max = 1.5f;
const float zoom_min = 0.1f;
bool clicked = false;
glm::vec3 pointClick;
glm::vec3 GetOGLPos(int x, int y);
void display(void) {
// Clear display port
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
// Reset camera
gluLookAt(
0.0, 0.0, 2.0,
0.0, 0.0, 0.0,
0.0, 1.0, 0.0
);
// Zoom
glScalef(zoom, zoom, zoom);
// Render sphere
glPushMatrix();
glTranslatef(0, 0, 0);
glColor3f(1, 0, 0);
glutSolidSphere(1, 64, 64);
glPopMatrix();
// Render point
if (clicked == true) {
glPushMatrix();
glColor3f(0, 1, 0);
glPointSize(0.5f);
glBegin(GL_POINTS);
glVertex3f(pointClick.x, pointClick.y, pointClick.z);
printf("%f, %f, %f\n", pointClick.x, pointClick.y, pointClick.z);
glEnd();
glPopMatrix();
}
// Swap buffers
glutSwapBuffers();
}
void reshape(GLsizei width, GLsizei height) {
if (height == 0) {
height = 1;
}
float ratio = 1.0 * width / height;
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, width, height);
gluPerspective(45, ratio, 1, 100);
glMatrixMode(GL_MODELVIEW);
}
// Handles mouse input for camera rotation.
void motion(int x, int y) {
pointClick = GetOGLPos(x, y);
clicked = true;
glutPostRedisplay();
}
// Handles scroll input for zoom.
void mouseWheel(int button, int state, int x, int y) {
if (state == 1) {
zoom = zoom + zoom_sensitivity >= zoom_max ? zoom_max : zoom + zoom_sensitivity;
}
else if (state == -1) {
zoom = zoom - zoom_sensitivity <= zoom_min ? zoom_min : zoom - zoom_sensitivity;
}
glutPostRedisplay();
}
int main(int argc, char** argv) {
// Initialize glut.
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DOUBLE);
glutInitWindowPosition(
(glutGet(GLUT_SCREEN_WIDTH) - WINDOW_WIDTH) / 2,
(glutGet(GLUT_SCREEN_HEIGHT) - WINDOW_HEIGHT) / 2
);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
glutCreateWindow("Window");
// Register callbacks.
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMotionFunc(motion);
glutMouseWheelFunc(mouseWheel);
// Start glut.
glutMainLoop();
return 0;
}
// Get position of click in 3-d space
glm::vec3 GetOGLPos(int x, int y)
{
GLint viewport[4];
GLdouble modelview[16];
GLdouble projection[16];
GLfloat winX, winY, winZ;
GLdouble posX, posY, posZ;
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);
winX = (float)x;
winY = (float)viewport[3] - (float)y;
glReadPixels(x, int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);
gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);
return glm::vec3(posX, posY, posZ);
}
This is the visual output:
This renders a point on the screen, but it's not "on" the sphere. I'm wondering how to put the point on the surface of the sphere so, if I were to rotate and zoom the camera, the point would stay in the same place. How do I "project" the point on the surface of the sphere?
You first want to convert the cursor to a ray in the world, and then perform a ray-sphere intersection test to figure out where the ray intersects the sphere. You can read this article regarding how to convert the cursor to a ray in the world: http://antongerdelan.net/opengl/raycasting.html.
I'm trying to make a color swatch tool, where you give it n colors and it makes a n-gon with those colors merging at the center.
So far it just makes an n-gon(without specifying colors, it randomly generates them for now).
However the colors don't merge at the center but rather a single vertex.
Is there any fix to this?
#include <GLFW/glfw3.h>
#include <iostream>
#include <cmath>
float randfloat(){
float r = ((float)(rand() % 10))/10;
return r;
}
int main() {
int side_count;
std::cout<<"Type the no. of sides: "<<std::endl;
std::cin>>side_count;
srand(time(NULL));
std::cout<<randfloat()<<std::endl;
std::cout<<randfloat()<<std::endl;
float rs[side_count];
float gs[side_count];
float bs[side_count];
for (int i=0;i<side_count;i++)
{
rs[i] = randfloat();
gs[i] = randfloat();
bs[i] = randfloat();
}
GLFWwindow* window;
if (!glfwInit())
return 1;
window = glfwCreateWindow(800, 800, "Window", NULL, NULL);
if (!window) {
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(window);
if(glewInit()!=GLEW_OK)
std::cout<<"Error"<<std::endl;
while(!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.11f,0.15f,0.17f,1.0f);
glBegin(GL_POLYGON);
//glColor3f(1.0f,0.0f,0.0f);glVertex3f(-0.5f,0.0f,0.0f);
for(int i=0; i<side_count;i++)
{
float r = rs[i];
float g = gs[i];
float b = bs[i];
float x = 0.5f * sin(2.0*M_PI*i/side_count);
float y = 0.5f * cos(2.0*M_PI*i/side_count);
glColor3f(r,g,b);glVertex2f(x,y);
}
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
All you've to do is to add a new point to the GL_POLYGON primitive, in the center of the circular shape:
glBegin(GL_TRIANGLE_FAN);
glColor3f(0.5f, 0.5f, 0.5f);
glVertex2f(0, 0);
for(int i=0; i <= side_count; i++)
{
float r = rs[i % side_count];
float g = gs[i % side_count];
float b = bs[i % side_count];
float x = 0.5f * sin(2.0*M_PI*i/side_count);
float y = 0.5f * cos(2.0*M_PI*i/side_count);
glColor3f(r, g, b);
glVertex2f(x, y);
}
glEnd();
Note, you've to define the color for the center point. In the code snippet, I've chosen (0.5, 0.5, 0.5).
Instead of GL_POLYGON, GL_TRIANGLE_FAN can be used, too.
I am building a virtual oscilloscope with OpenGL. I am able to plot the x and y axis and also create a grid. But I cannot get the grid lines to stipple using the code below... Any suggestions ?? glLineStipple is called in the DrawMainWindow function that is passed to glutDisplayFunction....
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
//procedures for shared memory access
#include <sys/shm.h>
#include <sys/stat.h>
#include "binary_sems.h"
///////////////////////////////////////
//debug - FIXME - Add Controls !!!
///////////////////////////////////////
////////////////////////////////////////
// So in debug turn this off to run
// the oscilloscope standalone
////////////////////////////////////////
//#define USE_COMMS
////////////////////////////////////////
// Define a constant for the value of PI
////////////////////////////////////////
#define GL_PI 3.1415f
// Rotation amounts
static GLfloat xRot = 0.0f;
static GLfloat yRot = 0.0f;
//range
GLfloat nRange = 1000.0f;
//gain control
float gain = 1.00;
//enable / disable grid
int grid_enable = 1;
//debug
int frame_id=0;
//////////////////////////////////////////
//Shared Memory Variables
//////////////////////////////////////////
/*variable for shared memory*/
int segment_id;
char *shared_memory;
/*variables for semaphore*/
int semid;
//variables
float BorderClr[3] = {1, 1, 1}; //Default colour for borders
float Ch1TrClr[3] = {1, 1, 0}; //Default colour for channel 1 traces
float GridClr[3] = {1, 1, 1}; //Default colour for grid
float TextClr[3] = {1, 0, 0}; //Default colour for text
float PauseClr[3] = {1, 0, 0}; //Colour for "Paused" text
//defines
#define DISP_BUFFER_LENGTH 1000
//structure defining data points
typedef struct voltage_samples{
float volts; //this is the raw voltage data
float volts_scaled; //this is the scaled voltage data for display (x)
float time_stamp; //this is the time stamp (y )
} DISPLAY_SAMPLES;
//declare a buffer of display samples
DISPLAY_SAMPLES sample_buffer[DISP_BUFFER_LENGTH];
int display_update = 0;
//Function Prototypes
void DrawMainWindow(void);
void IdleProcessing(void);
void SetupRC(void);
void ChangeSize(int w, int h);
void SpecialKeys(int key, int x, int y);
void WriteText(char *text, float height, float x, float y, float z);
////////////////////////////////////////////////////////
//Procedure Entry Point
////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
#ifdef USE_COMMS
//Verify that the shared memory data buffer
//has been specified
if(argc != 3){
printf("ERROR:Usage::APPLICATION <Shared Memory Segment ID> <Semaphore ID for this shared memory segment>\n");
return(-1);
}
//Initialize shared memory parameters
/*get the segment ID from the command line */
segment_id = strtol(argv[1],NULL,0);
/*get the semaphore ID from the comand line*/
semid = strtol(argv[2],NULL,0);
/*attach to the shared memory segment*/
shared_memory = (char *)shmat(segment_id, 0, 0);
#endif
//Initialization parameters for glut
glutInit(&argc, argv);
//Suggest to O/S where the window should
//be initialized at.
//glutInitWindowPosition(0,0);
//Initialize the window size
glutInitWindowSize(640,480);
//Argument for next opened window
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
//Create the window
glutCreateWindow("CUDA Oscilloscope");
//Register Special Keys and Change Size Functions
glutReshapeFunc(ChangeSize);
glutSpecialFunc(SpecialKeys);
//Register callback function for redrawing window
glutDisplayFunc(DrawMainWindow);
//Register callback function for idle processing
glutIdleFunc(IdleProcessing);
//Enable depth testing ???
glEnable(GL_DEPTH_TEST);
//Set up drawing environment
//SetupRC();
//Start the infinite loop - function will never return
//till controlled ^c
glutMainLoop();
return 0;
}
/////////////////////////////////////////////////////////
//Functions
/////////////////////////////////////////////////////////
void DrawMainWindow(void)
{
//GLfloat x, y, z;
float x,y,z;
//Clear buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//Save previous settings
glPushMatrix();
//Draw all samples
glColor3fv(Ch1TrClr);
//Get scaled / processed data from buffer;
//this was the data that was created during
//idle state
glBegin(GL_POINTS);
z = 0.00;
for(int ii=0; ii < DISP_BUFFER_LENGTH; ii++){
//plot point on the coordinate
x = -nRange + ii*2.00;
y = sample_buffer[ii].volts_scaled;
//plot the coordinate
glVertex3f(x,y,z);
}
glEnd();
if(grid_enable == 1){
//Grid Color and Line Widths
glColor3fv(GridClr);
//Draw X and Y axis
GLint factor = 10;
GLushort pattern = 0x5555;
glLineWidth(2);
//Draw X-Axis
glBegin(GL_LINES);
glLineStipple(factor, pattern);
glVertex3f(-nRange, 0.00, 0.00);
glVertex3f( nRange, 0.00, 0.00);
glEnd();
//Draw Y-Axis
glBegin(GL_LINES);
glLineStipple(factor, pattern);
glVertex3f(0.00, -nRange, 0.00);
glVertex3f(0.00, nRange, 0.00);
glEnd();
//Draw a 10x10 grid ( stipple lines )
factor = 10;
pattern = 0x5050;
glLineWidth(1);
// //Bottom to top - horizintal lines
for(float ii=-nRange; ii < nRange; ii += 100)
{
glLineStipple(factor, pattern);
glBegin(GL_LINES);
glVertex3f(-nRange, ii, 0.00);
glVertex3f( nRange, ii, 0.00);
glEnd();
}
// //Left to right - vertical lines
for(float ii=-nRange; ii < nRange+100; ii += 100)
{
glLineStipple(factor, pattern);
glBegin(GL_LINES);
glVertex3f(ii, -nRange, 0.00);
glVertex3f(ii, nRange, 0.00);
glEnd();
}
}
//Write Measurement parameters to the screen
glColor3fv(TextClr);
WriteText("(Y)::Vertical Scale=", 50.00, 300.00, 800.00, 0.00);
WriteText("(X)::Horizontal Scale=", 50.00, 300.00, 700.00, 0.00);
//FIXME - Display Time Settings
//FIXME - Display "Paused" if capture is paused
//FIXME - Display trigger settings
//FIXME - Display Ch1 Settings
//Restore previous settings
glPopMatrix();
//Puts rendered scene on front buffer
//glFlush is called by glutSwapBuffers implicitely
glutSwapBuffers();
}
//FIXME - Several functions are required for GUI
void IdleProcessing(void)
{
/*clear read buffer so new write data can be added*/
initSemAvailable(semid, 1);
/*try bump down semaphore to indicate completion of memory read*/
reserveSem(semid,0);
//Here we acquire and process the content of the
//data buffer
double *p = (double *)shared_memory;
for(int ii=0; ii < DISP_BUFFER_LENGTH; ii++){
#ifdef USE_COMMS
sample_buffer[ii].volts_scaled = gain*p[ii];
#else
sample_buffer[ii].volts_scaled = gain*cos((2.0f*GL_PI)*ii*4/DISP_BUFFER_LENGTH + rand()%2) + rand()%10;
#endif
}
#ifdef DEBUG
for(int ii=0; ii < DISP_BUFFER_LENGTH; ii++){
if(ii%10==0){
printf("\n");
}
printf("%f ",sample_buffer[ii].volts_scaled);
}
printf("\n");
#endif
printf("Frame Cntr = %d\r",frame_id);
frame_id++;
//FIXME - data processing during idle time
DrawMainWindow();
}
// This function does any needed initialization on the rendering
// context.
void SetupRC()
{
// Black background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f );
// Set drawing color to green
glColor3f(1.0f, 1.0f, 1.0f);
//enable line stippling
glEnable(GL_LINE_STIPPLE);
}
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP){
//xRot-= 5.0f;
if(gain < 10000.00)
gain = gain + 100.0;
}
if(key == GLUT_KEY_DOWN){
//xRot += 5.0f;
if(gain > 0.00)
gain = gain - 100.0;
}
if(key == GLUT_KEY_LEFT)
//yRot -= 5.0f;
grid_enable = 1;
if(key == GLUT_KEY_RIGHT)
//yRot += 5.0f;
grid_enable = 0;
if(key > 356.0f)
xRot = 0.0f;
if(key < -1.0f)
xRot = 355.0f;
if(key > 356.0f)
yRot = 0.0f;
if(key < -1.0f)
yRot = 355.0f;
// Refresh the Window
glutPostRedisplay();
}
void ChangeSize(int w, int h)
{
// Prevent a divide by zero
if(h == 0)
h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
// Reset projection matrix stack
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Establish clipping volume (left, right, bottom, top, near, far)
if (w <= h)
glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange);
else
glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange);
// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void WriteText(char *text, float height, float x, float y, float z)
{
const float charHeight = 119.05;
glPushMatrix();
glTranslatef(x,y,z);
glScalef(height/charHeight/1.5, height/charHeight, height/charHeight);
while(*text){
glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, (int)*text);
*text++;
}
glPopMatrix();
}
I never got the concept down on how to get an animation working in OpenGL. I was working on his project trying to get it to work but never got the skier to move. Trying to figure out how to get this fixed.
#include "../shared/gltools.h" // OpenGL toolkit
#define PI 3.14159265
float a = -5;//maybe
float b = 29;
float c = 27;
float d = 28.25;
float e = 28.5;
bool lookUp;
bool setback;
bool lookDown;
bool lookLeft;
bool lookRight;
bool walkForward;
bool walkBackward;
bool strafeLeft;
bool strafeRight;
float xTranslation;
float yTranslation;
float zTranslation;
float yRotationAngle;
float zRotationAngle;
float xRotationAngle;
int mouseLastx;
int mouseLasty;
float sunRotationAngle=0;
float sunRadius = 150.0;
float day=0;
float dusk=1;
// Light values and coordinates
GLfloat lightPos[] = { 0.0f, 30.0f, 0.0f, 1.0f };
GLfloat lightPos2[] = { 0.0f, 0.0f, 40.0f, 1.0f };
GLfloat specular[] = { 1.0f, 1.0f, 1.0f, 1.0f};
GLfloat specular2[] = { 0.0f, 1.0f, 0.0f, 1.0f};
GLfloat diffuse[] = { 1.0f, 1.0f, 1.0f, 1.0f};
GLfloat diffuse2[] = { 0.0f, 0.3f, 0.0f, 1.0f};
GLloat specref[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat ambientLight[] = { 0.5f, 0.5f, 0.5f, 1.0f};
GLfloat spotDir[] = { 0.0f, 0.0f, -1.0f };
void mouseMovement(int x, int y)
{
int mouseDiffx=x-mouseLastx;
int mouseDiffy=y-mouseLasty;
mouseLastx=x;
mouseLasty=y; //set lasty to the current y position
xRotationAngle += (GLfloat) mouseDiffy;
yRotationAngle += (GLfloat) mouseDiffx;
if (xRotationAngle>=90)
xRotationAngle=90;
if (xRotationAngle<=-90)
xRotationAngle=-90;
//cout << "x:" << x << "y:" << y << endl;
}
void drawcabin()
{
glColor3ub(0, 0, 0);
glBegin(GL_TRIANGLES);
//glTranslatef(0,-5,0); // move view left
//glNormal3f(-3,0.7,-1.7);
//glutSolidCube(5.0f);
glNormal3d(0,0.7,0.7);
glVertex3d(0,6,0);
glVertex3d(-3,3.5,-2);
glVertex3d(2,3.5,-2);
glNormal3d(2,-1,1);
glVertex3d(0,6,0);
glVertex3d(-3,3.5,-2);
glVertex3d(2,3.5,-2);
glTranslatef(0,-5,0); // move view left
glNormal3d(-3,0.7,-1.7);
glEnd();
glColor3ub(185, 0, 0);
glutSolidCube(5.0f);
}
void drawskislope()
{
glColor3ub(0, 0, 0);
glBegin(GL_QUADS);
glTranslatef(0,-5,90); // move view left
glColor3ub(185, 122, 87);
glNormal3d(0,5,1);
glVertex3d(10,0,5);
glVertex3d(10,.5,5);
glVertex3d(15,.5,5);
glVertex3d(15,0,5);//small square
glColor3ub(201, 192, 187);
glVertex3d(11.5,.5,5);
glVertex3d(13.5,.5,5);
glVertex3d(13.5,-10,5);
glVertex3d(11.5,-10,5);
//slope start
glTranslatef(0,-5,0); // move view left
// glNormal3d(-3,0.7,-1.7);
glEnd();
}
void drawskier()
{
float a = -5;//maybe
float b = 29;
float c = 27;
float d = 28.25;
float e = 28.5;
glBegin(GL_QUADS);
glTranslatef(0,-5,0); // move view
glColor3ub(185, 122, 87);
glNormal3d(0,5,1);
//Do While loop
// do
// {
// to move skier do a loop and update a in the translate
glTranslatef(0,a,0); // move view
glVertex3d(c,0,5);//10
glVertex3d(c,.1,5);//10
glVertex3d(b,.1,5);//15
glVertex3d(b,0,5);//skis on skier
glNormal3d(0,5,1);
glVertex3d(d,0,5);
glVertex3d(d,1.35,5);
glVertex3d(e,1.35,5);
glVertex3d(e,0,5);//body on skier
glutSwapBuffers;
// }while(b>15); //try to animate
glEnd();
glFlush();
b=b-1;
c=c-1;
d=d-1;
e=e-1;
glutPostRedisplay();
glTranslatef(30,3,0); // move view left
glColor3ub(168, 220, 109);
glutSolidSphere(.5,7,8); //sphere-head
glPushMatrix();
glTranslatef(3.5,-100,2);
glutSolidSphere(25,15,15); //sphere
glPopMatrix();
}
void updatescene()
{
}
///////////////////////////////////////////////////////////
// Called to draw scene
void RenderScene(void)
{
GLUquadricObj *pObj; // Quadric Object
pObj = gluNewQuadric();
gluQuadricNormals(pObj, GLU_SMOOTH);
GLfloat horizontalMovement=1;
GLfloat verticalMovement=0;
horizontalMovement=cos(xRotationAngle*PI/180);
verticalMovement=-sin(xRotationAngle*PI/180);
// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
horizontalMovement=cos(xRotationAngle*PI/180);
verticalMovement=-sin(xRotationAngle*PI/180);
if (lookDown)
{
xRotationAngle+=1;
if (xRotationAngle>=90)
xRotationAngle=90;
}
if (lookUp)
{
xRotationAngle-=1;
if (xRotationAngle<=-90)
xRotationAngle=-90;
}
if (lookRight)
{
yRotationAngle+=1;
if (yRotationAngle>=360)
yRotationAngle=0;
}
if (lookLeft)
{
yRotationAngle-=1;
if (yRotationAngle<=-360)
yRotationAngle=0;
}
if (walkForward)
{
zTranslation+=cos(yRotationAngle*PI/180)*horizontalMovement;
xTranslation-=sin(yRotationAngle*PI/180)*horizontalMovement;
yTranslation-=verticalMovement;
}
if (walkBackward)
{
zTranslation-=cos(yRotationAngle*PI/180)*horizontalMovement;
xTranslation+=sin(yRotationAngle*PI/180)*horizontalMovement;
yTranslation+=verticalMovement;
}
if (strafeRight)
{
zTranslation+=cos((yRotationAngle+90)*PI/180);
xTranslation-=sin((yRotationAngle+90)*PI/180);
}
if (strafeLeft)
{
zTranslation-=cos((yRotationAngle+90)*PI/180);
xTranslation+=sin((yRotationAngle+90)*PI/180);
}
if (setback)
{
zTranslation=0;
xTranslation=0;
yTranslation=0;
}
// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glRotatef(xRotationAngle,1,0,0);
glRotatef(zRotationAngle,0,0,1);
glRotatef(yRotationAngle,0,1,0);
glTranslatef(xTranslation,yTranslation,zTranslation);
//glRotatef(-15,1,0,0);
//glRotatef(90,0,1,0);
glTranslatef(0,-0.50,-10);
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
sunRotationAngle++;
// Clear the window with current clearing color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor3d(0,0,0);
glLineWidth(2);
//snow
glColor3ub(255, 255, 255);
glBegin(GL_QUADS);
glNormal3f(0,1,0);
for (int i=-100;i<=200;i+=10) //x
for (int j=-100;j<=200;j+=10)//z
{
float y1=(-j)*.25;
float y2=(-j+10)*.25;
glVertex3d(i+10,y2,-100);
glVertex3d(i,y2,-100);
glVertex3d(i,y1,-100);
glVertex3d(i+10,y1,-100);
}
glEnd();
glPushMatrix();
glTranslatef(-10,14,-50);
drawcabin();
drawskislope();
drawskier();
glPopMatrix();
// Flush drawing commands
glutSwapBuffers();
glutPostRedisplay();
//GLfloat horizontalMovement=1;
// GLfloat verticalMovement=0;
}
void TimerFunction(int value)
{
// Redraw the scene with new coordinates
glutPostRedisplay();
updatescene();
glutTimerFunc(16,TimerFunction, 1);
}
///////////////////////////////////////////////////////////
// Setup the rendering context
void SetupRC(void)
{
lookUp=false;
lookDown=false;
lookLeft=false;
lookRight=false;
walkForward=false;
walkBackward=false;
strafeLeft=false;
strafeRight=false;
yRotationAngle=0;
xRotationAngle=0;
zRotationAngle=0;
xTranslation=0;
yTranslation=0;
zTranslation=0;
// White background
glClearColor(0.5f,0.95f, 1.0f, 1.0f );
// Set drawing color to green
glColor3f(0.0f, 1.0f, 0.0f);
// Set color shading model to flat
glShadeModel(GL_SMOOTH);
// Clock wise wound polygons are front facing, this is reversed
// because we are using triangle fans
glFrontFace(GL_CCW);
glEnable (GL_DEPTH_TEST);
}
void ChangeSize(int w, int h)
{
//GLfloat nRange = 100.0f;
// Prevent a divide by zero
if(h == 0)
h = 1;
// Set Viewport to window dimensions
glViewport(0, 0, w, h);
// Reset projection matrix stack
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Establish clipping volume (left, right, bottom, top, near, far)
GLfloat fAspect;
fAspect = (GLfloat)w / (GLfloat)h;
//glOrtho(-10,10,-10,10,0,1000);
gluPerspective(45,fAspect,0.1,1000);
// Reset Model view matrix stack
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
// Respond to arrow keys by moving the camera frame of reference
void SpecialKeys(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
lookUp=true;
if(key == GLUT_KEY_DOWN)
lookDown=true;
if(key == GLUT_KEY_LEFT)
lookLeft=true;
if(key == GLUT_KEY_RIGHT)
lookRight=true;
// Refresh the Window
glutPostRedisplay();
}
void SpecialKeysUp(int key, int x, int y)
{
if(key == GLUT_KEY_UP)
lookUp=false;
if(key == GLUT_KEY_DOWN)
lookDown=false;
if(key == GLUT_KEY_LEFT)
lookLeft=false;
if(key == GLUT_KEY_RIGHT)
lookRight=false;
// Refresh the Window
glutPostRedisplay();
}
void keyboardFunc(unsigned char key, int x, int y)
{
switch(key)
{
case 'w':
walkForward=true;
break;
case 's':
walkBackward=true;
break;
case 'a':
strafeLeft=true;
break;
case 'd':
strafeRight=true;
break;
case 'r':
setback=true;
break;
default:
break;
}
}
void keyboardUpFunc(unsigned char key, int x, int y)
{
switch(key)
{
case 'w':
walkForward=false;
break;
case 's':
walkBackward=false;
break;
case 'a':
strafeLeft=false;
break;
case 'd':
strafeRight=false;
break;
default:
break;
}
}
///////////////////////////////////////////////////////////
// Main program entry point
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500,500);
glutCreateWindow("Assignment 2");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutSpecialFunc(SpecialKeys);
glutSpecialUpFunc(SpecialKeysUp);
glutKeyboardUpFunc(keyboardUpFunc);
glutKeyboardFunc(keyboardFunc);
glutPassiveMotionFunc(mouseMovement);
SetupRC();
glutMainLoop();
return 0;
}
My general approach is to use a glutTimerFunc() callback to post a redisplay event every 16 milliseconds or so (~60 FPS).
Then in the glutDisplayFunc() callback you can grab the new GLUT_ELAPSED_TIME to calculate a delta-time (dt) from the last frame.
With dt in hand you can update any number of variables such as angles or translation offsets. You'll want to use dt instead of fixed increment values to decouple your animation speed from your framerate.
Then back in the glutDisplayFunc() callback you draw a new frame using the updated state variables.
This is an example that uses the method above to rotate a square at about 30 degrees per second:
#include <GL/glut.h>
float angle = 0;
void update( const double dt )
{
// in degrees per second
const float SPEED = 30.0f;
// update angle
angle += ( SPEED * dt );
}
void display()
{
// GLUT_ELAPSED_TIME is in milliseconds
static int prvMs = glutGet( GLUT_ELAPSED_TIME );
const int curMs = glutGet( GLUT_ELAPSED_TIME );
// dt is in seconds
const double dt = ( curMs - prvMs ) / 1000.0;
prvMs = curMs;
// update world state
update( dt );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
// reset projection/modelview matrices each frame;
// this makes sure we have a known-good matrix
// stack each time through display()
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho( -2, 2, -2, 2, -1, 1 );
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
// draw rotated square
glRotatef( angle, 0, 0, 1 );
glBegin( GL_QUADS );
glColor3ub( 255, 0, 0 );
glVertex2i( -1, -1 );
glVertex2i( 1, -1 );
glVertex2i( 1, 1 );
glVertex2i( -1, 1 );
glEnd();
glutSwapBuffers();
}
void timer( int value )
{
glutPostRedisplay();
glutTimerFunc( 16, timer, 0 );
}
int main( int argc, char **argv )
{
glutInit( &argc, argv );
glutInitDisplayMode( GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE );
glutInitWindowSize( 600, 600 );
glutCreateWindow( "GLUT" );
glutDisplayFunc( display );
glutTimerFunc( 0, timer, 0 );
glutMainLoop();
return 0;
}
I have been trying to draw multiple balls for a game I am making, I have tried to get this working but there are problems in my init class and display method class, I have commented it where the errors are.
Ball.h:
#pragma once
#include "Vector2f.h"
#include "Vector3f.h"
class Ball
{
private:
Vector3f position;
Vector3f velocity;
public:
Ball(void);
~Ball(void);
void Draw();
void SetPos(Vector3f New_position);
void SetVel(Vector3f New_velocity);
Vector3f GetPos();
};
Ball.cpp
#include "Ball.h"
#include "Vector2f.h"
#include "Vector3f.h"
#include "Glut/glut.h"
#include "GL/gl.h"
#include "GL/glu.h"
Ball::Ball(void)
{
Vector3f Temp_position;
position = Temp_position;
Vector3f Temp_velocity;
velocity = Temp_velocity;
}
Ball::~Ball(void)
{
}
void Ball::SetPos(Vector3f New_position)
{
position = New_position;
}
void Ball::Draw()
{
glPushMatrix();
glTranslatef(position.X(), position.Y(), position.Z());
glColor3d(1, 0, 0);
glutSolidSphere(0.3, 50, 50);
glPopMatrix();
}
void Ball::SetVel(Vector3f New_velocity)
{
velocity = New_velocity;
}
Vector3f Ball::GetPos()
{
Vector3f temp;
temp = position;
return temp;
}
I want the be able to draw an array of the balls in Main.cpp
Main.cpp
#include "Display.h"
#include "Vector3f.h"
#include "Ball.h"
#include "Glut/glut.h"
#include "GL/gl.h"
#include "GL/glu.h"
#include <math.h>
static float TableWidth = 4; // Z axis normal = 4
float Display::eyeX = -7.5; //-7.5
float Display::eyeY = 3; //3
float Display::eyeZ = 5; //5
float Display::Position[4] = { 1.0f, 0.0f, -3.5, 1.0f };
float Display::translateZ = -3.5;
float Display::translateX = 0.0;
//Timer Display::m_Timer = Timer();
float Display::lightX = 5.0; //5 2.5
float Display::lightY = 5.0;
float Display::lightZ = 2.5;
float m_TableX = -5.0f;
float m_TableZ = -2.5f;
float m_TableWidth = 2.5f;
float m_TableLength = 5.0f;
float ballx = 0.7;
float bally = 0.1;
float ballz = -0.7;
Ball Redball;
float BALL_RED_START = 0;
float RADIUS_OF_BALL = 0.3;
float BALL_RED_END = 8;
float m_ball;
void Display::Init(int argc, char ** argv)
{
glutInit(&argc, argv); // initializes glut
// sets display mode. These parameter set RGB colour model
// and double buffering.
glutInitWindowSize(500,500);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutCreateWindow("Pool Version 1.0");
// Set glut callback functions
glutDisplayFunc(Display::DisplayScene);
glutIdleFunc(Display::Idle);
glutReshapeFunc(Display::Resize);
glutKeyboardFunc(Display::KeyboardInput);
//m_Timer.getSeconds();
glEnable(GL_DEPTH_TEST);
glPointSize(5);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHTING);
glClearColor(0,0,0,1);
glEnable(GL_COLOR_MATERIAL);
float white[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
glEnable(GL_LIGHT0);
Redball.SetPos(Vector3f(0.0,0.3,0.0));
for(int i = BALL_RED_START; i < BALL_RED_START; i++)
{
glColor3f(1,0,0);
Redball[i]->SetPos(Vector3f (i+128,RADIUS_OF_BALL,45)); //I tried this but it doesn't work Error C2227
}
// Begin glut main loop
glutMainLoop();
}
void BallMovement()
{
//Vector3f position(0.0,0.3,0.0);
/*Redball.SetPos(Vector3f(0.0,0.3,0.0));*/
Vector3f New_velocity(0.01,0,0);
Redball.SetVel(New_velocity);
Vector3f New_position;
Vector3f Old_position;
Old_position = Redball.GetPos();
//New_position = Old_position + New_velocity;
New_position.SetX(Old_position.X() + New_velocity.X());
New_position.SetY(Old_position.Y() + New_velocity.Y());
New_position.SetZ(Old_position.Z() + New_velocity.Z());
Redball.SetPos(New_position);
}
void Display::DisplayScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the back buffer
glPushMatrix();
glLoadIdentity();
glNormal3f(0,1,0);
Vector3f didums = Redball.GetPos();
gluLookAt(eyeX, eyeY, eyeZ, // eye position
0, 0, 0, // what I'm looking at
0.0, 1.0, 0); // Up direction
float Position[] = {lightX, lightY, lightZ, 1.0f};
glLightfv(GL_LIGHT0, GL_POSITION, Position);
DrawLight(0, Position);
/* Rendering code goes here */
for (int i = BALL_RED_START; i<BALL_RED_END;i++)
{
glColor3f(1,0,0);
Redball[i]->Draw(); //I tried this but it doesn't work Error C2227
}
drawTable();
drawTableLegFrontLeft();
drawTableLegFrontRight();
drawTableLegBackLeft();
drawTableLegBackRight();
drawCushions();
//drawCircle();
//drawHCircle();
Table(-2,-4.5,2,4.5); // Draws the table top in trianglestrip -4.5, 0.5, -0.5, 9.5
glPopMatrix();
glutSwapBuffers(); // Swap the front and back buffers
}
void Display::Resize(int w, int h)
{
/* Resize is called when window is resized */
glMatrixMode(GL_PROJECTION); // set matrix mode to profection
// this dictates how the 3d scene is "squashed" onto the 2d screen
glLoadIdentity();
glViewport(0, 0, w, h); // Set the part of the window to use.
gluPerspective(45, // field of view
(float)w/(float)h, // ration of window
1, // front clipping plane
1000 // back clipping plane
); // set the area in the 3d scene to draw
glMatrixMode(GL_MODELVIEW); // Setthe matrix mode to model view
// the matrix specifies how the 3d scene is viewed
/*glLoadIdentity();
gluLookAt(-3.5, 2, eyeZ, // eye position
1, 1, 0, // what I'm looking at
0.0, 1.0, 0); // Up direction*/
}
void Display::Idle()
{
/* When nothing else is happening, idle is called.
* Simulation should be done here and then
* the display method should be called
*/
BallMovement();
glutPostRedisplay();
}
I see you have declared Ball as Ball Redball; which will create a single Ball on the stack.
Then you attempt to treat it as a collection of Balls with Redball[i]->SetPos(...) and Redball[i]->Draw(). It appears you are attempting to work with 8 of them.
What you want to do is create an array of Balls, with a max size of 8 (according to BALL_RED_END). For simplicity, you could do
Ball RedBall[8];
for( //some conditions here )
{
RedBall[i].Draw();
}
as your declaration and usage.
Remember that anytime you use Redball.SetPos(...) will no longer be valid.