Example code for CSG in OptiX


can anybody provide some example code for CSG in OptiX?!

Let’s say:

2 GeometryInstances (e.g. 1 box,glass and 1 sphere,phong)
Rendering the intersection of both instances.


You should write some sample code and post it :)

I haven’t thought about this too much, but for a limited number of closed shapes, you could use per ray data (PRD) to store a hit counter, or really just a flag, for each shape. Use the closest hit program to either terminate the ray and shade, or toggle the hit flag in PRD for the current shape and continue the ray using rtTrace. Terminate when all hit flags are toggled on at once, meaning that the current point is inside all the shapes.

For some shapes, you could use the geometric normals to determine whether the ray is entering or exiting, and then you might not need hit flags.

It may also be possible to do this with an any-hit program for a very small number of shapes, by storing all intersections for the ray and sorting/shading them in the ray gen program. That would be slow if there were too many shapes.

Anybody have other ideas?

Thank you dlacewell!

To be clear… You suggest to strategies:

closed-hit-program or any-hit-program → both are implemented in the material-shader…

So i should create a geometry instance,
with a geometry → bounding-box of CSG object
and a material → implementing the CSG operations ?

And the material has 2 variables for the geometry-instances of the child-nodes?
So I can use them to traverse the tree with rtTrace?

Sounds partly right. This part I’m not sure is correct:

If you haven’t written an OptiX sample before, I would start with something similar but easier involving transparency. You could take optixSpherePP in the SDK and make some changes:

  • add another sphere to the scene, that uses the same material
  • add a geometry id variable to the sphere, and expose it as an attribute for the closest hit program
  • change the closest hit program to make one of the spheres completely transparent based on id, and continue the ray with rtTrace.
  • Make the spheres semi-transparent. You still shoot a new ray with rtTrace, but composite the result with the current sphere color and opacity using per ray data.

Once you get that all working, then it’s probably not a big jump to CSG.