PDA

View Full Version : OpenGL not rendering figure



AdarshJain
03-02-2018, 05:46 AM
The code below is expected to draw a snowman and then camera is controlled using keyboard keys. But it's only drawing some dots.

I tried to increase the radius of sphere but it was still not working properly. what's the problem in the code ? If it is about dimensions, then what should be the correct dimension ?

Output should look like this image -2678



from __future__ import division
import time
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import sys, math

# angle of rotation for the camera direction
angle=0.0;
# actual vector representing the camera's direction
lx=0.0
lz=-1.0;
# XZ position of the camera
x=0.0
z=5.0;

def drawSnowMan():
glColor3f(1.0, 1.0, 1.0);

# Draw Body
glTranslatef(0.0 ,0.75, 0.0);
glutSolidSphere(0.75,20,20);

# Draw Head
glTranslatef(0.0, 1.0, 0.0);
glutSolidSphere(0.25,20,20);

# Draw Eyes
glPushMatrix();
glColor3f(0.0,0.0,0.0);
glTranslatef(0.05, 0.10, 0.18);
glutSolidSphere(0.05,10,10);
glTranslatef(-0.1, 0.0, 0.0);
glutSolidSphere(0.05,10,10);
glPopMatrix();

# Draw Nose
glColor3f(1.0, 0.5 , 0.5);
glutSolidCone(0.08,0.5,10,2);


def renderScene():
global angle, lx, lz, x, z

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()

refresh2d(width, height)

# Set the camera
gluLookAt( x, 1.0, z, x+lx, 1.0, z+lz, 0.0, 1.0, 0.0);

# Draw ground
glColor3f(0.9, 0.9, 0.9);
glBegin(GL_QUADS);
glVertex3f(-100.0, 0.0, -100.0);
glVertex3f(-100.0, 0.0, 100.0);
glVertex3f( 100.0, 0.0, 100.0);
glVertex3f( 100.0, 0.0, -100.0);
glEnd();

# Draw 36 SnowMen
for i in range(-3,3):
for j in range(-3, 3):
glPushMatrix();
glTranslatef(i*10.0,0,j * 10.0);
drawSnowMan();
glPopMatrix();

glutSwapBuffers();


def processSpecialKeys(key, xx, yy):
global angle, lx, lz, x, z

fraction = 0.1

if(key == GLUT_KEY_LEFT):
angle -= 0.01
lx = math.sin(angle);
lz = -math.cos(angle);

elif(key == GLUT_KEY_RIGHT):
angle += 0.01
lx = math.sin(angle);
lz = -math.cos(angle);

elif(key == GLUT_KEY_UP):
x += lx * fraction;
z += lz * fraction;

elif(key == GLUT_KEY_DOWN):
x -= lx * fraction;
z -= lz * fraction;


def refresh2d(width, height):
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-300.0, 300, -300, 300, 0.0, 10.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()


# init GLUT and create window
width = 600
height = 600

glutInit();
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)
glutInitWindowPosition(100,100);
glutInitWindowSize(width, height);
glutCreateWindow("Lighthouse3D - GLUT Tutorial");

# register callbacks
glutDisplayFunc(renderScene);
glutIdleFunc(renderScene);
glutSpecialFunc(processSpecialKeys);

# OpenGL init
glEnable(GL_DEPTH_TEST);

# enter GLUT event processing cycle
glutMainLoop();