Skip to content

Instantly share code, notes, and snippets.

@eriksk
Last active December 17, 2015 15:39
Show Gist options
  • Save eriksk/5633399 to your computer and use it in GitHub Desktop.
Save eriksk/5633399 to your computer and use it in GitHub Desktop.
OpenGL render a spinning colored cube in Ruby
require 'opengl'
include Gl, Glu, Glut
WIDTH = 512
HEIGHT = 512
NEAR = 0.1
FAR = 1000
class Vec3
attr_accessor :x, :y, :z
def initialize x = 0.0, y = 0.0, z = 0.0
@x, @y, @z = x, y, z
end
end
class Color
attr_accessor :r, :g, :b, :a
def initialize r = 0.0, g = 0.0, b = 0.0, a = 1.0
@r, @g, @b, @a = r, g, b, a
end
def set
glColor3f(@r, @g, @b, @a)
end
end
@cam = Vec3.new
@cam.x = 3
@cam.y = 2
@cam.z = 3
@rotation = Vec3.new
def init
glutInit
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(WIDTH, HEIGHT)
glutInitWindowPosition(300, 200)
glutCreateWindow("Ruby 3D!")
glEnable(GL_DEPTH_TEST)
render_proc = method("render").to_proc
glutDisplayFunc(render_proc)
glutIdleFunc(render_proc)
glutMainLoop()
end
def set_projection
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(50.0, WIDTH / HEIGHT, NEAR,FAR)
end
def update
@rotation.y += 0.01
@rotation.x += 0.005
end
def render
update()
glClearColor(0.0, 0.0, 0.0, 1.0)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
set_projection
gluLookAt(@cam.x, @cam.y, @cam.z, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
glRotatef(@rotation.x, 1.0, 0, 0)
glRotatef(@rotation.y, 0, 1.0, 0)
glRotatef(@rotation.z, 0, 0, 1.0)
cube()
glFlush()
glutSwapBuffers()
end
def cube
# White side - BACK
glBegin(GL_POLYGON);
glColor3f( 1.0, 1.0, 1.0 )
glVertex3f( 0.5, -0.5, 0.5 )
glVertex3f( 0.5, 0.5, 0.5 )
glVertex3f( -0.5, 0.5, 0.5 )
glVertex3f( -0.5, -0.5, 0.5 )
glEnd();
# Purple side - RIGHT
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 1.0 )
glVertex3f( 0.5, -0.5, -0.5 )
glVertex3f( 0.5, 0.5, -0.5 )
glVertex3f( 0.5, 0.5, 0.5 )
glVertex3f( 0.5, -0.5, 0.5 )
glEnd();
# Green side - LEFT
glBegin(GL_POLYGON)
glColor3f( 0.0, 1.0, 0.0)
glVertex3f( -0.5, -0.5, 0.5)
glVertex3f( -0.5, 0.5, 0.5)
glVertex3f( -0.5, 0.5, -0.5)
glVertex3f( -0.5, -0.5, -0.5)
glEnd();
# Blue side - TOP
glBegin(GL_POLYGON)
glColor3f( 0.0, 0.0, 1.0)
glVertex3f( 0.5, 0.5, 0.5)
glVertex3f( 0.5, 0.5, -0.5)
glVertex3f( -0.5, 0.5, -0.5)
glVertex3f( -0.5, 0.5, 0.5)
glEnd();
# Red side - BOTTOM
glBegin(GL_POLYGON)
glColor3f( 1.0, 0.0, 0.0)
glVertex3f( 0.5, -0.5, -0.5)
glVertex3f( 0.5, -0.5, 0.5)
glVertex3f( -0.5, -0.5, 0.5)
glVertex3f( -0.5, -0.5, -0.5)
glEnd();
end
init
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment