我正在为计算机图形学建立一个Octree。尝试使用以下代码构建树:
void Accel::build() {
Octree *m_octree = new Octree(depth);
std::vector<uint32_t> indices(triangleCount);
for (uint32_t i = 0; i < triangleCount; ++i) {
indices[i] = i;
}
m_octree->root = m_octree->octreeBuild(m_bbox, indices, m_mesh);
}
树和树节点类如下:
Octree.h
class Octree {
public:
uint32_t totalNodes = 0;
uint32_t maxDepth = 0;
uint32_t totalDepth = 0;
std::vector<OctreeNode *> octreeVector;
OctreeNode *root;
Octree();
Octree(uint32_t d);
~Octree();
OctreeNode *octreeBuild(BoundingBox3f boundingBox, std::vector<uint32_t> indices, Mesh* mesh);
};
Octree.cpp
Octree::Octree(){}
Octree::Octree(uint32_t d): maxDepth(d) {}
Octree::~Octree(){
}
OctreeNode *Octree::octreeBuild(BoundingBox3f boundingBox, std::vector<uint32_t> indices, Mesh* mesh) {
if (indices.empty()) {
OctreeNode *node = nullptr;
octreeVector.push_back(node);
return node;
}
if (indices.size() <= 10 || totalDepth == maxDepth) {
OctreeNode *node = new OctreeNode(indices, boundingBox, true);
octreeVector.push_back(node);
totalNodes += 1;
return node;
}
if (totalDepth < maxDepth){
std::vector<uint32_t> nodeArray[8]; // Eight vector to store child node indices
BoundingBox3f boxArray[8] = {
boundingBox, boundingBox, boundingBox, boundingBox, boundingBox, boundingBox, boundingBox, boundingBox
}; // Eight bounding box, one for each child node
for (uint32_t i = 0; i < 8; ++i) { // Seperate bounding box
Point3f corner = boundingBox.getCorner(i);
Point3f center = boundingBox.getCenter();
Point3f minPoint = Point3f(std::min(corner.x(), center.x()), std::min(corner.y(), center.y()), std::min(corner.z(), center.z()));
Point3f maxPoint = Point3f(std::max(corner.x(), center.x()), std::max(corner.y(), center.y()), std::max(corner.z(), center.z()));
boxArray[i] = BoundingBox3f(minPoint, maxPoint);
}
for (uint32_t i = 0; i < static_cast<uint32_t>(indices.size()); i++) { // Check overlapping, store indices to cooresponding vector
BoundingBox3f triangleBox = mesh->getBoundingBox(i);
for (uint32_t j = 0; j < 8; ++j) {
if (boxArray[j].overlaps(triangleBox) && boxArray[j].contains(triangleBox.getCenter())) {
nodeArray[j].push_back(i);
break;
}
}
}
OctreeNode *node = new OctreeNode(indices, boundingBox, false); // Build the new node with children
octreeVector.push_back(node);
if (octreeVector.size() == 1) {
root = node;
}
totalDepth += 1;
for (uint32_t i = 0; i < 8; ++i) {
node->child[i] = octreeBuild(boxArray[i], nodeArray[i], mesh);
totalNodes += 1;
}
return node;
}
return nullptr;
};
我设法构建程序,并且Octree :: build顺利通过,没有错误消息。但是在尝试搜索树根之后,出现了EXC_BAD_ACCESS错误。看来我八叉树的根已经消失了。我是C ++的新手,不确定是否是因为算法或我用C ++编程的方式是错误的。感谢您的任何建议!