Copyright Tristan Aubrey-Jones January 2008.
This is an example OpenGL SDL application which creates an animated 3D underwater world (screenshot), with "Thunderbird 4" with headlights moving on a spline path, a randomly generated sand terrain, sunken ship/submarine/treasure chest models, and swaying fish and seaweed. It is designed to demonstrate basic OpenGL features, and the structure is as follows:
#include "worldobjects.h"
#include "vectors.h"
#define MIN_X 0.0
#define MIN_Y 0
#define MIN_Z 0.0
#define MAX_X 100.0
#define MAX_Y 0
#define MAX_Z 100.0
#define BLADE_COUNT 500
#define MAX_HEIGHT 10
// calculate a random float between
// 0.0 and ran.
inline GLfloat randf(GLfloat min, GLfloat max) {
// calculate between 0 and 1
int ir = rand() % 1000;
GLfloat v = ((float)(ir) / 1000.0f);
// change to range
return (v * (max - min)) + min;
}
// constructor
GrassObject::GrassObject()
{
// center position
pos.x = randf(MIN_X, MAX_X);
pos.y = randf(MIN_Y, MAX_Y);
pos.z = randf(MIN_Z, MAX_Z);
// height
h = randf(4, MAX_HEIGHT);
// grass amount
count = rand() % BLADE_COUNT;
// create blades
loc = new Vec3[count];
now = new Vec3[count];
shades = new float[count];
Mat4 m;
for (int i = 0; i < count; i++) {
// work out random pos
Vec3 top(0, randf(h/2,h), 0);
m.setI();
m.rotate(randf(-50,50), 1, 0, 0);
m.rotate(randf(-50,50), 0, 0, 1);
m.transform(&top);
// remember pos
loc[i].set(&top);
now[i].set(&top);
// random shade
shades[i] = randf(0.5, 1);
}
}
GrassObject::~GrassObject()
{
delete loc;
delete shades;
delete now;
}
// draw
void GrassObject::drawInternal()
{
glBegin(GL_LINES);
for (int i = 0; i < count; i++) {
// shade
glColor3f(0, shades[i], 0);
// start at bottom
glVertex3f(0, 0, 0);
// to top coordinate
glVertex3f(now[i].x, now[i].y, now[i].z);
}
glEnd();
}
// simulate
void GrassObject::simulate(GLfloat dT)
{
time += dT;
// make blades wave
for (int i = 0; i < count; i++) {
now[i].x = loc[i].x + sin(time);
}
}