As for building the whole thing. I will just add photons to my photon map class as I trace them, and they will be stored in an std::vector<SPhoton>; object. Once the tracing is done, a CPhotonMap::BuildMap() function will be called. I will find the median in the main vector of photons along the axis that spans the greatest distance. This will be the root of the kd-tree. I will then have to split all other photons in the array into two subarrays, one on each side of the splitting plane, and recursively find their own root. I am still wondering how to efficiently structure the algorithm.
I am thinking of something of the form:
Balance(std::vector<SPhoton>& PhotonArray, std::vector<SPhoton>& HeapArray, unsigned int HeapIndex){ // Find the axis along which the photons in photonarray span the greatest distance // And equivalently we find the splitting plane Axis = FindAxis(PhotonArray); // linear-scanning O(n) // Find the median photon of PhotonArray along the desired axis MedianPhoton = FindMedian(PhotonArray, Axis); // recursive, O(n) // Place the median photon in the heap array HeapArray[HeapIndex] = MedianPhoton; // Split the photon array into two subarrays, for each side of the median // std::vector<SPhoton> LeftArray = Photons < Median // std::vector<SPhoton> RightArray = Photons >= Median // Recursively process each half Balance(LeftArray, HeapArray, 2 * HeapIndex); Balance(RightArray, HeapArray, 2 * HeapIndex + 1);}
Of course there are going to be a good bit of memory allocations, but it seems like it won't use more than 3 times the memory of the original photon array in total. I can also make sure to reserve enough space in the arrays before recursively passing them along. As for the FindMedian(), it can be done in-place. My intuition tells me this algorithm should run in O(n log n) time.
I specified the photon array as a non-const reference because the function to find the median will need to partition it recursively, and it would seem wasteful to make a copy every time.
I guess that part of the algorithm should be allright. I'm still not sure how to find the nearest photons in the kd-tree efficiently, however.