Posted By

gyunjgf2 on 05/16/12

Who likes this?

1 person have marked this snippet as a favorite

Voxel Raycaster

/ Published in: C++

Traverses unit cubes given a starting position and direction vector.

`//Raycaster.h #ifndef RAYCASTER_H#define RAYCASTER_H #include <glm\glm.hpp> class Raycaster{public:	Raycaster(glm::vec3 p, glm::vec3 p_dir);	glm::ivec3 getNextVoxel();private:	glm::vec3 pos;	glm::vec3 dir;	bool xplus;	bool yplus;	bool zplus;}; #endif  //Raycaster.cpp#include "Raycaster.h" Raycaster::Raycaster(glm::vec3 p, glm::vec3 p_dir){	pos = p;	dir = p_dir;	xplus = true;	yplus = true;	zplus = true;	if (dir.x < 0)		xplus = false;	if (dir.y < 0)		yplus = false;	if (dir.z < 0)		zplus = false;} glm::ivec3 Raycaster::getNextVoxel(){	int nextX = (int) pos.x;	int nextY = (int) pos.y;	int nextZ = (int) pos.z;	if (xplus)		nextX++;	if (yplus)		nextY++;	if (zplus)		nextZ++;	float distanceX = nextX - pos.x;	float distanceY = nextY - pos.y;	float distanceZ = nextZ - pos.z;	float qx = distanceX / dir.x;	float qy = distanceY / dir.y;	float qz = distanceZ / dir.z; 	//The qx/y/z+=0.000001; is a quick and dirty solution 	//to enable the continuation of the raycast.	if (qx <= qy && qx <= qz)	{		qx+=0.000001;		pos += qx * dir;	}	else if (qy <= qx && qy <= qz)	{		qy+=0.000001;		pos += qy * dir;	}	else if (qz <= qx && qz <= qy)	{		qz+=0.000001;		pos += qz * dir;	} 	return glm::ivec3( (int) pos.x, (int) pos.y, (int) pos.z); }`