I am writing a raytracer in F# using montecarlo sampling I would like to make my recursive calls tail recursive but I am not sure of this is possible with MC raytracing as one has to evaluate sampled hemisphere before returning.

The accululator variables are there to facilitate the tail recursion and works for naiive raytracers which just trace along a single ray until it terminates. At the moment the problem is the for loop.

Any help / pointers / references I can read would be appreciated

Currently my code looks as follows:

        if surfaceGeometry.IntersectionAcceptable realSolution t 1.0f (PointForRay ray t)
            let emittedShading = surface.Emitted
            let e = accEmitted + accScatter*emittedShading 
            let mcSamples = surface.SampleCount

            //TODO rewrite this to make it tail recursive
            let mutable totalShading = e/surface.MCNormalization
            for _ in 0..mcSamples-1 do
                let (doesRayContribute,outRay,cosOfIncidence) = surface.Scatter ray t ((int)newTraceDepth)
                let shading = surface.BRDF*cosOfIncidence / (surface.PDF*surface.MCNormalization)
                let s = accScatter*shading
                totalShading <- totalShading + (rayTrace newTraceDepth (outRay , e , s))
           accEmitted + backgroundColor*accScatter
  • 1
    $\begingroup$ Are you familiar with path tracing? It lends itself well to a tail-recursive design, as you can accumulate the total radiance and "throughput" (product of reflectances) along the path. You would not have a for-loop here, since the path does not branch into multiple child rays—only a top-level for-loop to fire many paths per pixel. $\endgroup$ – Nathan Reed Jun 24 '18 at 3:48
  • $\begingroup$ Yes, I have a path tracer which uses tail recusion. But Its not the same as montecarlo sampling imho. Any indication that it is (mathematically) equivalent is most welcome $\endgroup$ – Marc HPunkt Jun 24 '18 at 10:06

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.