/* Threaded is a very simple way to multithread the node generation
* Be careful though, as the number of tasks generated is 8^threaded
* Anything more than 1 generally is slower than 1
* To be safe, either keep it at 0 or 1
*/
public bool ConstructNodes(List<VertexPositionColorNormal> vertices, int grid_size, int threaded = 0)
{
if (size == 1)
{
return ConstructLeaf(vertices, grid_size);
}
int child_size = size / 2;
bool has_children = false;
Task[] threads = new Task[8];
bool[] return_values = new bool[8];
for (int i = 0; i < 8; i++)
{
Vector3 offset = new Vector3(i / 4, i % 4 / 2, i % 2);
OctreeNode child = new OctreeNode();
child.size = child_size;
child.position = position + offset * (float)child_size;
child.type = OctreeNodeType.Internal;
int index = i;
if (threaded > 0 && size > 2)
{
threads[index] = Task.Factory.StartNew(
() =>
{
return_values[index] = child.ConstructNodes(vertices, grid_size, threaded - 1);
if (return_values[index])
children[index] = child;
else
children[index] = null;
}, TaskCreationOptions.AttachedToParent);
//threads[index].Start();
}
else
{
if (child.ConstructNodes(vertices, grid_size, 0))
has_children = true;
else
child = null;
children[i] = child;
}
}
if (threaded > 0 && size > 2)
{
for (int i = 0; i < 8; i++)
{
threads[i].Wait();
if (return_values[i])
has_children = true;
}
}
if (!has_children)
return false;
return true;
}