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$ Jun 24, 2018 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$ Jun 24, 2018 at 10:06


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.