Full Code of brandonpelfrey/SimpleOctree for AI

master f334cf2c9116 cached
8 files
11.3 KB
3.5k tokens
19 symbols
1 requests
Download .txt
Repository: brandonpelfrey/SimpleOctree
Branch: master
Commit: f334cf2c9116
Files: 8
Total size: 11.3 KB

Directory structure:
gitextract_u777gmx3/

├── LICENSE
├── Makefile
├── Octree.h
├── OctreePoint.h
├── README.md
├── Stopwatch.h
├── Vec3.h
└── main.cpp

================================================
FILE CONTENTS
================================================

================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2017 Brandon Pelfrey

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: Makefile
================================================
default:
	g++ main.cpp -O3 -o octree
clean:
	@rm -f octree 


================================================
FILE: Octree.h
================================================
#ifndef Octree_H
#define Octree_H

#include <cstddef>
#include <vector>
#include "OctreePoint.h"

namespace brandonpelfrey {

	/**!
	 *
	 */
	class Octree {
		// Physical position/size. This implicitly defines the bounding 
		// box of this node
		Vec3 origin;         //! The physical center of this node
		Vec3 halfDimension;  //! Half the width/height/depth of this node

		// The tree has up to eight children and can additionally store
		// a point, though in many applications only, the leaves will store data.
		Octree *children[8]; //! Pointers to child octants
		OctreePoint *data;   //! Data point to be stored at a node

		/*
				Children follow a predictable pattern to make accesses simple.
				Here, - means less than 'origin' in that dimension, + means greater than.
				child:	0 1 2 3 4 5 6 7
				x:      - - - - + + + +
				y:      - - + + - - + +
				z:      - + - + - + - +
		 */

		public:
		Octree(const Vec3& origin, const Vec3& halfDimension) 
			: origin(origin), halfDimension(halfDimension), data(NULL) {
				// Initially, there are no children
				for(int i=0; i<8; ++i) 
					children[i] = NULL;
			}

		Octree(const Octree& copy)
			: origin(copy.origin), halfDimension(copy.halfDimension), data(copy.data) {

			}

		~Octree() {
			// Recursively destroy octants
			for(int i=0; i<8; ++i) 
				delete children[i];
		}

		// Determine which octant of the tree would contain 'point'
		int getOctantContainingPoint(const Vec3& point) const {
			int oct = 0;
			if(point.x >= origin.x) oct |= 4;
			if(point.y >= origin.y) oct |= 2;
			if(point.z >= origin.z) oct |= 1;
			return oct;
		}

		bool isLeafNode() const {
			// This is correct, but overkill. See below.
			/*
				 for(int i=0; i<8; ++i)
				 if(children[i] != NULL) 
				 return false;
				 return true;
			 */

			// We are a leaf iff we have no children. Since we either have none, or 
			// all eight, it is sufficient to just check the first.
			return children[0] == NULL;
		}

		void insert(OctreePoint* point) {
			// If this node doesn't have a data point yet assigned 
			// and it is a leaf, then we're done!
			if(isLeafNode()) {
				if(data==NULL) {
					data = point;
					return;
				} else {
					// We're at a leaf, but there's already something here
					// We will split this node so that it has 8 child octants
					// and then insert the old data that was here, along with 
					// this new data point

					// Save this data point that was here for a later re-insert
					OctreePoint *oldPoint = data;
					data = NULL;

					// Split the current node and create new empty trees for each
					// child octant.
					for(int i=0; i<8; ++i) {
						// Compute new bounding box for this child
						Vec3 newOrigin = origin;
						newOrigin.x += halfDimension.x * (i&4 ? .5f : -.5f);
						newOrigin.y += halfDimension.y * (i&2 ? .5f : -.5f);
						newOrigin.z += halfDimension.z * (i&1 ? .5f : -.5f);
						children[i] = new Octree(newOrigin, halfDimension*.5f);
					}

					// Re-insert the old point, and insert this new point
					// (We wouldn't need to insert from the root, because we already
					// know it's guaranteed to be in this section of the tree)
					children[getOctantContainingPoint(oldPoint->getPosition())]->insert(oldPoint);
					children[getOctantContainingPoint(point->getPosition())]->insert(point);
				}
			} else {
				// We are at an interior node. Insert recursively into the 
				// appropriate child octant
				int octant = getOctantContainingPoint(point->getPosition());
				children[octant]->insert(point);
			}
		}

		// This is a really simple routine for querying the tree for points
		// within a bounding box defined by min/max points (bmin, bmax)
		// All results are pushed into 'results'
		void getPointsInsideBox(const Vec3& bmin, const Vec3& bmax, std::vector<OctreePoint*>& results) {
			// If we're at a leaf node, just see if the current data point is inside
			// the query bounding box
			if(isLeafNode()) {
				if(data!=NULL) {
					const Vec3& p = data->getPosition();
					if(p.x>bmax.x || p.y>bmax.y || p.z>bmax.z) return;
					if(p.x<bmin.x || p.y<bmin.y || p.z<bmin.z) return;
					results.push_back(data);
				}
			} else {
				// We're at an interior node of the tree. We will check to see if
				// the query bounding box lies outside the octants of this node.
				for(int i=0; i<8; ++i) {
					// Compute the min/max corners of this child octant
					Vec3 cmax = children[i]->origin + children[i]->halfDimension;
					Vec3 cmin = children[i]->origin - children[i]->halfDimension;

					// If the query rectangle is outside the child's bounding box, 
					// then continue
					if(cmax.x<bmin.x || cmax.y<bmin.y || cmax.z<bmin.z) continue;
					if(cmin.x>bmax.x || cmin.y>bmax.y || cmin.z>bmax.z) continue;

					// At this point, we've determined that this child is intersecting 
					// the query bounding box
					children[i]->getPointsInsideBox(bmin,bmax,results);
				} 
			}
		}

	};

}
#endif


================================================
FILE: OctreePoint.h
================================================
#ifndef OctreePoint_H
#define OctreePoint_H

#include "Vec3.h"

// Simple point data type to insert into the tree.
// Have something with more interesting behavior inherit
// from this in order to store other attributes in the tree.
class OctreePoint {
	Vec3 position; 
public:
	OctreePoint() { }
	OctreePoint(const Vec3& position) : position(position) { }
	inline const Vec3& getPosition() const { return position; }
	inline void setPosition(const Vec3& p) { position = p; }
};

#endif


================================================
FILE: README.md
================================================
SimpleOctree
============

A simple octree with good commenting for learning how octrees work. Blog post incoming with description, or read comments in Octree.h

Usage
============
make && ./octree


================================================
FILE: Stopwatch.h
================================================
#ifndef _WIN32
#include <sys/time.h>

double stopwatch()
{
	struct timeval time;
	gettimeofday(&time, 0 );
	return 1.0 * time.tv_sec + time.tv_usec / (double)1e6;
}

#else

#include <windows.h>
double stopwatch() 
{
	unsigned long long ticks;
	unsigned long long ticks_per_sec;
	QueryPerformanceFrequency( (LARGE_INTEGER *)&ticks_per_sec);
	QueryPerformanceCounter((LARGE_INTEGER *)&ticks);
	return ((float)ticks) / (float)ticks_per_sec;
}

#endif


================================================
FILE: Vec3.h
================================================
#ifndef Vec3_h_
#define Vec3_h_

#include <cmath>

struct Vec3;
Vec3 operator*(float r, const Vec3& v);

struct Vec3 {
	union {
		struct {
			float x,y,z;
		};
		float D[3];
	};

	Vec3() { }
	Vec3(float _x, float _y, float _z)
		:x(_x), y(_y), z(_z)
	{ }

	float& operator[](unsigned int i) {
		return D[i];
	}

	const float& operator[](unsigned int i) const {
		return D[i];
	}

	float maxComponent() const {
		float r = x;
		if(y>r) r = y;
		if(z>r) r = z;
		return r;
	}

	float minComponent() const {
		float r = x;
		if(y<r) r = y;
		if(z<r) r = z;
		return r;
	}

	Vec3 operator+(const Vec3& r) const {
		return Vec3(x+r.x, y+r.y, z+r.z); 
	}

	Vec3 operator-(const Vec3& r) const {
		return Vec3(x-r.x, y-r.y, z-r.z); 
	}

	Vec3 cmul(const Vec3& r) const {
		return Vec3(x*r.x, y*r.y, z*r.z);
	}

	Vec3 cdiv(const Vec3& r) const {
		return Vec3(x/r.x, y/r.y, z/r.z);
	}

	Vec3 operator*(float r) const {
		return Vec3(x*r,y*r,z*r);
	}


	Vec3 operator/(float r) const {
		return Vec3(x/r, y/r, z/r);
	}

	Vec3& operator+=(const Vec3& r) {
		x+=r.x;
		y+=r.y;
		z+=r.z;
		return *this;
	}

	Vec3& operator-=(const Vec3& r) {
		x-=r.x;
		y-=r.y;
		z-=r.z;
		return *this;
	}

	Vec3& operator*=(float r) {
		x*=r; y*=r; z*=r;
		return *this;
	}

	// Inner/dot product
	float operator*(const Vec3& r) const {
		return x*r.x + y*r.y + z*r.z;
	}

	float norm() const {
		return sqrtf(x*x+y*y+z*z);
	}

	float normSquared() const {
		return x*x + y*y + z*z;
	}

	// Cross product
	Vec3 operator^(const Vec3& r) const {
		return Vec3(
				y * r.z - z * r.y, 
				z * r.x - x * r.z, 
				x * r.y - y * r.x
				);
	}

	Vec3 normalized() const {
		return *this / norm();
	}
};

inline Vec3 operator*(float r, const Vec3& v) {
	return Vec3(v.x*r, v.y*r, v.z*r);
}

#endif


================================================
FILE: main.cpp
================================================
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <algorithm>

#include "Octree.h"
#include "Stopwatch.h"

using namespace brandonpelfrey;

// Used for testing
std::vector<Vec3> points;
Octree *octree;
OctreePoint *octreePoints;
Vec3 qmin, qmax;

float rand11() // Random number between [-1,1]
{ return -1.f + (2.f*rand()) * (1.f / RAND_MAX); }

Vec3 randVec3() // Random vector with components in the range [-1,1]
{ return Vec3(rand11(), rand11(), rand11()); }

// Determine if 'point' is within the bounding box [bmin, bmax]
bool naivePointInBox(const Vec3& point, const Vec3& bmin, const Vec3& bmax) {
	return 
		point.x >= bmin.x &&
		point.y >= bmin.y &&
		point.z >= bmin.z &&
		point.x <= bmax.x &&
		point.y <= bmax.y &&
		point.z <= bmax.z;
}

void init() {
	// Create a new Octree centered at the origin
	// with physical dimension 2x2x2
	octree = new Octree(Vec3(0,0,0), Vec3(1,1,1));

	// Create a bunch of random points
	const int nPoints = 1 * 1000 * 1000;
	for(int i=0; i<nPoints; ++i) {
		points.push_back(randVec3());
	}
	printf("Created %ld points\n", points.size()); fflush(stdout);

	// Insert the points into the octree
	octreePoints = new OctreePoint[nPoints];
	for(int i=0; i<nPoints; ++i) {
		octreePoints[i].setPosition(points[i]);
		octree->insert(octreePoints + i);
	}
	printf("Inserted points to octree\n"); fflush(stdout);

	// Create a very small query box. The smaller this box is
	// the less work the octree will need to do. This may seem
	// like it is exagerating the benefits, but often, we only
	// need to know very nearby objects.
	qmin = Vec3(-.05,-.05,-.05);
	qmax = Vec3(.05,.05,.05);

	// Remember: In the case where the query is relatively close
	// to the size of the whole octree space, the octree will
	// actually be a good bit slower than brute forcing every point!
}

// Query using brute-force
void testNaive() {
	double start = stopwatch();

	std::vector<int> results;
	for(int i=0; i<points.size(); ++i) {
		if(naivePointInBox(points[i], qmin, qmax)) {
			results.push_back(i);
		}
	}

	double T = stopwatch() - start;
	printf("testNaive found %ld points in %.5f sec.\n", results.size(), T);
}

// Query using Octree
void testOctree() {
	double start = stopwatch();

	std::vector<OctreePoint*> results;
	octree->getPointsInsideBox(qmin, qmax, results);

	double T = stopwatch() - start;
	printf("testOctree found %ld points in %.5f sec.\n", results.size(), T);
}


int main(int argc, char **argv) {
	init();
	testNaive();
	testOctree();

	return 0;
}
Download .txt
gitextract_u777gmx3/

├── LICENSE
├── Makefile
├── Octree.h
├── OctreePoint.h
├── README.md
├── Stopwatch.h
├── Vec3.h
└── main.cpp
Download .txt
SYMBOL INDEX (19 symbols across 5 files)

FILE: Octree.h
  function namespace (line 8) | namespace brandonpelfrey {

FILE: OctreePoint.h
  function class (line 9) | class OctreePoint {

FILE: Stopwatch.h
  function stopwatch (line 4) | double stopwatch()
  function stopwatch (line 14) | double stopwatch()

FILE: Vec3.h
  type Vec3 (line 6) | struct Vec3
  function const (line 9) | struct Vec3 {
  function maxComponent (line 30) | float maxComponent() const {
  function Vec3 (line 52) | Vec3 cmul(const Vec3& r) const {
  function Vec3 (line 56) | Vec3 cdiv(const Vec3& r) const {
  function Vec3 (line 60) | Vec3 operator*(float r) const {
  function Vec3 (line 65) | Vec3 operator/(float r) const {
  function Vec3 (line 102) | Vec3 operator^(const Vec3& r) const {

FILE: main.cpp
  function rand11 (line 17) | float rand11() // Random number between [-1,1]
  function Vec3 (line 20) | Vec3 randVec3() // Random vector with components in the range [-1,1]
  function naivePointInBox (line 24) | bool naivePointInBox(const Vec3& point, const Vec3& bmin, const Vec3& bm...
  function init (line 34) | void init() {
  function testNaive (line 67) | void testNaive() {
  function testOctree (line 82) | void testOctree() {
  function main (line 93) | int main(int argc, char **argv) {
Condensed preview — 8 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (13K chars).
[
  {
    "path": "LICENSE",
    "chars": 1072,
    "preview": "MIT License\n\nCopyright (c) 2017 Brandon Pelfrey\n\nPermission is hereby granted, free of charge, to any person obtaining a"
  },
  {
    "path": "Makefile",
    "chars": 60,
    "preview": "default:\n\tg++ main.cpp -O3 -o octree\nclean:\n\t@rm -f octree \n"
  },
  {
    "path": "Octree.h",
    "chars": 4965,
    "preview": "#ifndef Octree_H\n#define Octree_H\n\n#include <cstddef>\n#include <vector>\n#include \"OctreePoint.h\"\n\nnamespace brandonpelfr"
  },
  {
    "path": "OctreePoint.h",
    "chars": 487,
    "preview": "#ifndef OctreePoint_H\n#define OctreePoint_H\n\n#include \"Vec3.h\"\n\n// Simple point data type to insert into the tree.\n// Ha"
  },
  {
    "path": "README.md",
    "chars": 198,
    "preview": "SimpleOctree\n============\n\nA simple octree with good commenting for learning how octrees work. Blog post incoming with d"
  },
  {
    "path": "Stopwatch.h",
    "chars": 471,
    "preview": "#ifndef _WIN32\r\n#include <sys/time.h>\r\n\r\ndouble stopwatch()\r\n{\r\n\tstruct timeval time;\r\n\tgettimeofday(&time, 0 );\r\n\tretur"
  },
  {
    "path": "Vec3.h",
    "chars": 1767,
    "preview": "#ifndef Vec3_h_\n#define Vec3_h_\n\n#include <cmath>\n\nstruct Vec3;\nVec3 operator*(float r, const Vec3& v);\n\nstruct Vec3 {\n\t"
  },
  {
    "path": "main.cpp",
    "chars": 2518,
    "preview": "#include <cstdlib>\n#include <cstdio>\n#include <vector>\n#include <algorithm>\n\n#include \"Octree.h\"\n#include \"Stopwatch.h\"\n"
  }
]

About this extraction

This page contains the full source code of the brandonpelfrey/SimpleOctree GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 8 files (11.3 KB), approximately 3.5k tokens, and a symbol index with 19 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!