static BVHTree2() { PREALLOC = new BVHBuildEntry[128]; for (int i = 0; i < 128; ++i) { PREALLOC[i] = new BVHBuildEntry(); } }
public void Build() { mNumNodes = mNumLeafs = 0; int stackptr = 0; uint Untouched = 0xffffffff; uint TouchedTwice = 0xfffffffd; PREALLOC[stackptr].mStart = 0; PREALLOC[stackptr].mEnd = (uint)mBuildPrims.Count; PREALLOC[stackptr].mParent = 0xfffffffc; stackptr++; List <BVHFlatNode2> buildnodes = new List <BVHFlatNode2>(mBuildPrims.Count * 2); while (stackptr > 0) { BVHBuildEntry bnode = PREALLOC[--stackptr]; uint start = bnode.mStart; uint end = bnode.mEnd; uint nPrims = end - start; mNumNodes++; BVHFlatNode2 node = new BVHFlatNode2(); node.mStartIndex = start; node.mLeafCount = nPrims; node.mRightOffset = Untouched; BVHAABB2 bb = new BVHAABB2(mBuildPrims[(int)start].GetAABB().mMin, mBuildPrims[(int)start].GetAABB().mMax); BVHAABB2 bc = new BVHAABB2(mBuildPrims[(int)start].GetCenter(), mBuildPrims[(int)start].GetCenter()); for (uint p = start + 1; p < end; ++p) { bb.ExpandToInclude(mBuildPrims[(int)p].GetAABB()); bc.ExpandToInclude(mBuildPrims[(int)p].GetCenter()); } node.mBox = bb; if (nPrims <= mNodeMaxLeafSize) { node.mRightOffset = 0; mNumLeafs++; } buildnodes.Add(node); // 记录父节点关于右孩子结点相对父结点的偏移值mRightOffset // 第一次为左孩子,相对父结点的偏移值为1 // 每个父节点最多被两次 hit if (bnode.mParent != 0xfffffffc) { buildnodes[(int)bnode.mParent].mRightOffset--; if (buildnodes[(int)bnode.mParent].mRightOffset == TouchedTwice) { buildnodes[(int)bnode.mParent].mRightOffset = (uint)mNumNodes - 1 - bnode.mParent; } } if (node.mRightOffset == 0) { continue; } // 选择合适的分割维度 uint split_dim = (uint)bc.MaxDimension(); float split_coord = 0.5f * (bc.mMin[(int)split_dim] + bc.mMax[(int)split_dim]); uint mid = start; // 交换 start 和 end 之间 的数据 for (uint i = start; i < end; ++i) { if (mBuildPrims[(int)i].GetCenter()[(int)split_dim] < split_coord) { if (i != mid) { BVHObject2 temp = mBuildPrims[(int)i]; mBuildPrims[(int)i] = mBuildPrims[(int)mid]; mBuildPrims[(int)mid] = temp; } ++mid; } } if (mid == start || mid == end) { mid = start + (end - start) / 2; } // 右孩子 PREALLOC[stackptr].mStart = mid; PREALLOC[stackptr].mEnd = end; PREALLOC[stackptr].mParent = (uint)mNumNodes - 1; stackptr++; // 左孩子 PREALLOC[stackptr].mStart = start; PREALLOC[stackptr].mEnd = mid; PREALLOC[stackptr].mParent = (uint)mNumNodes - 1; stackptr++; } if (mFlatTreeList != null) { mFlatTreeList.Clear(); } mFlatTreeList = new List <BVHFlatNode2>(mNumNodes); for (uint n = 0; n < mNumNodes; ++n) { mFlatTreeList.Add(buildnodes[(int)n]); } }