I made this program as an excercise as I'm a bit rusty at C++, and I'm not sure if my implementation is "good"...
Basically I'm not sure if I need to delete anything in a Destructor, as I believe VECTOR handles this automatically and I'm not using any dynamic memory...
stars.h
#ifndef __DEMO_STAR_H
#define __DEMO_STAR_H
#include <vector>
// The STAR class.
class DEMO_Star
{
public:
// Constructors
DEMO_Star();
DEMO_Star(float X, float Y, float Z);
// Position of this star
float x, y, z;
};
class DEMO_Starfield
{
public:
DEMO_Starfield();
DEMO_Starfield(int numStars, int width, int height, int depth);
void addStar(float X, float Y, float Z);
void update(float distance);
void draw();
private:
std::vector<DEMO_Star> mStar;
int mNumStars;
int mWidth, mHeight, mDepth;
};
#endif // __DEMO_STARS_H
stars.cpp
#include "DarkGDK.h"
#include "stars.h"
DEMO_Star::DEMO_Star()
: x(0.0f), y(0.0f), z(0.0f)
{}
DEMO_Star::DEMO_Star(float X, float Y, float Z)
: x(X), y(Y), z(Z)
{}
DEMO_Starfield::DEMO_Starfield()
: mNumStars(0), mWidth(0), mHeight(0), mDepth(0)
{}
DEMO_Starfield::DEMO_Starfield(int numStars, int width, int height, int depth)
: mNumStars(numStars), mWidth(width), mHeight(height), mDepth(depth)
{
for(int i=0; i<mNumStars; i++)
{
DEMO_Star newStar;
newStar.x = (float)(dbRND(mWidth) - mWidth / 2);
newStar.y = (float)(dbRND(mHeight) - mHeight / 2);
newStar.z = (float)(dbRND(mDepth - 1) + 1);
mStar.push_back(newStar);
}
}
void DEMO_Starfield::addStar(float X, float Y, float Z)
{
DEMO_Star newStar;
newStar.x = (float)(dbRND(mWidth) - mWidth / 2);
newStar.y = (float)(dbRND(mHeight) - mHeight / 2);
newStar.z = (float)(dbRND(mDepth - 1) + 1);
mStar.push_back(newStar);
mNumStars++;
}
void DEMO_Starfield::update(float distance)
{
if( mNumStars > 0 )
{
for(int i=0; i<mNumStars; i++)
{
mStar[i].z -= distance;
if( mStar[i].z < 1.0f ) mStar[i].z += 1000.0f;
}
}
}
void DEMO_Starfield::draw()
{
if( mNumStars > 0 )
{
int bm = dbCurrentBitmap();
int sw = dbBitmapWidth(bm);
int sh = dbBitmapHeight(bm);
int hsw = sw >> 1;
int hsh = sh >> 1;
dbLockPixels();
for(int i=0; i<mNumStars; i++)
{
// 2D Projection
float px = (mStar[i].x / (mStar[i].z / (float)(sw / sh)));
float py = (mStar[i].y / mStar[i].z);
// Screen Space Mapping
int sx = (int)(((int)(px * sw) >> 1) + hsw);
int sy = (int)(((int)(py * sh) >> 1) + hsh);
// Color the star based on distance
int col = (int)(255.0 - 255.0f / 1000.0f * mStar[i].z);
// and finally Draw the star.
dbInk((255 << 24)|(col<<16)|(col<<8)|col, 0);
dbDot(sx, sy);
}
dbUnlockPixels();
}
}
Am I doing anything wrong here? Are there any bad coding practices here? Any optimizations? Other suggestions?
I have also attached the full project to this message incase you wanna have a closer look...
EDIT: Btw... Is there any "lang=dbp" type tags i can add to the codeblock to highlight C++ code and/or DarkGDK code?