I'm using Unity3D based on the Mono framework and C#. The function below throw Stack Overflows. I cannot figure out where these come from; normally nowadays this tends to happen only with infinite loops, which mine isn't. It works fine with 8x8x16 voxels, but crashes at 16x16x32 voxels. I put a lock in because I figure it might happen that the function is fired for a second time before the first finished.
int FloatingVoxelsFlood(int x, int y, int z, ref bool[] voxelsAttached) {
if (GetPixel(x, y, z).a > 0.5f) return 0;
int id = GetPixelId(x, y, z);
if (voxelsAttached[id]) return 0;
voxelsAttached[id] = true;
int count = 1;
int minx = x-1;
int maxx = x+1;
if (minx >= 0)
count += FloatingVoxelsFlood(minx, y, z, ref voxelsAttached);
if (maxx < volumeWidth)
count += FloatingVoxelsFlood(maxx, y, z, ref voxelsAttached);
int miny = y-1;
int maxy = y+1;
if (miny >= 0)
count += FloatingVoxelsFlood(x, miny, z, ref voxelsAttached);
if (maxy < volumeHeight)
count += FloatingVoxelsFlood(x, maxy, z, ref voxelsAttached);
int minz = z-1;
int maxz = z+1;
if (minz >= 0)
count += FloatingVoxelsFlood(x, y, minz, ref voxelsAttached);
if (maxz < volumeDepth)
count += FloatingVoxelsFlood(x, y, maxz, ref voxelsAttached);
return count;
}
voxelsAttached is set to all false at start. GetPixel().a returns if a voxel needs to be used.
How can I solve this stack overflow?
The one below does not overflow the stack.
int FloatingVoxelsFlood(int x, int y, int z, ref bool[] voxelsAttached) {
if (GetPixel(x, y, z).a > 0.5f) return 0;
Queue<Pixel> queue = new Queue<Pixel>();
queue.Enqueue(new Pixel(x, y, z));
int count = 0;
while(queue.Count > 0) {
Pixel p = queue.Dequeue();
int id = GetPixelId(p.x, p.y, p.z);
if (!voxelsAttached[id] && GetPixel(p.x, p.y, p.z).a < 0.5f) {
count++;
voxelsAttached[id] = true;
int minx = p.x-1;
int maxx = p.x+1;
if (minx >= 0)
queue.Enqueue(new Pixel(minx, p.y, p.z));
if (maxx < volumeWidth)
queue.Enqueue(new Pixel(maxx, p.y, p.z));
int miny = p.y-1;
int maxy = p.y+1;
if (miny >= 0)
queue.Enqueue(new Pixel(p.x, miny, p.z));
if (maxy < volumeHeight)
queue.Enqueue(new Pixel(p.x, maxy, p.z));
int minz = p.z-1;
int maxz = p.z+1;
if (minz >= 0)
queue.Enqueue(new Pixel(p.x, p.y, minz));
if (maxz < volumeDepth)
queue.Enqueue(new Pixel(p.x, p.y, maxz));
}
}
return count;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.