Custom shapes in Python

You can extend Mitsuba with your own shapes defined in Python and efficiently render them on the GPU or CPU. In this tutorial, we will subclass mi.Shape to implement the Mandelbulb, a 3D fractal inspired by the Mandelbrot set, with detail at ever smaller scales. This involves sphere tracing to advance rays by an estimated distance to the surface until they are close enough to count as hits. See Inigo Quilez’s Mandelbulb article for the construction and distance estimate.

[1]:
import drjit as dr
import mitsuba as mi

mi.set_variant('cuda_ad_rgb', 'metal_ad_rgb', 'llvm_ad_rgb')  # Prefer a GPU-accelerated backend

The class below implements the bounding box, intersection, and shading methods of mi.Shape. Shapes can consist of multiple primitive shapes (e.g., individual triangles within a larger mesh). Here, there is only one primitive.

[2]:
class Mandelbulb(mi.Shape):
    """Power-8 Mandelbulb implemented by sphere tracing its distance estimate"""

    def primitive_count(self) -> int:
        """Return the number of primitives."""
        return 1

    def bbox(self, prim_index: int | None = None) -> mi.ScalarBoundingBox3f:
        """
        Return an axis-aligned bounding box covering the whole shape
        (`prim_index=None`) or the primitive selected by `prim_index`.

        This implementation returns the same box in both cases because
        there is only one primitive.
        """
        return mi.ScalarBoundingBox3f(-1.25, 1.25)

    @dr.syntax
    def distance_estimate(self, p: mi.Point3f) -> mi.Float:
        """
        Estimate the distance from `p` to the fractal using power-8 iteration.

        Each step raises the radius to the eighth power and multiplies both
        angles by eight. `dz` tracks the derivative.
        `max_iterations` bounds the loop for reverse-mode autodiff.
        """
        z, dz, i = mi.Point3f(p), mi.Float(1), mi.UInt32(0)
        r = dr.maximum(dr.norm(z), 1e-8)
        while dr.hint((r < 2) & (i < 8), max_iterations=8):
            theta, phi = 8 * dr.safe_acos(z.z / r), 8 * dr.atan2(z.y, z.x)
            z = r**8 * dr.sphdir(theta, phi) + p
            dz = 8 * r**7 * dz + 1
            r = dr.maximum(dr.norm(z), 1e-8)
            i += 1
        return 0.5 * dr.log(r) * r / dz

    @dr.syntax
    def ray_intersect_preliminary(self, ray: mi.Ray3f, prim_index: mi.UInt32, active: mi.Bool) -> mi.PreliminaryIntersection3f:
        """
        Find an intersection along `ray` within `[0, ray.maxt]`.

        Mitsuba splits intersection into two steps: this method returns a
        preliminary record with the hit distance and validity, then
        `compute_surface_interaction()` expands it into detailed shading data.

        `prim_index` selects the primitive. We ignore it for our single primitive.
        `active` selects which rays to test.
        """
        t, d, i = mi.Float(0), mi.Float(dr.inf), mi.UInt32(0)
        while active & (d > 1e-4) & (t <= ray.maxt) & (i < 256):
            d = self.distance_estimate(ray(t))
            t += dr.select(d > 1e-4, d / dr.norm(ray.d), 0)
            i += 1
        pi = dr.zeros(mi.PreliminaryIntersection3f)
        pi.valid = active & (d <= 1e-4) & (t <= ray.maxt)
        pi.t = dr.select(pi.valid, t, dr.inf)
        return pi

    def compute_surface_interaction(self, ray: mi.Ray3f, pi: mi.PreliminaryIntersection3f, ray_flags: int, active: mi.Bool) -> mi.SurfaceInteraction3f:
        """
        Compute shading data from `ray` and its preliminary intersection `pi`.

        `active` selects enabled lanes. `ray_flags` requests specific fields.
        Here we always compute the position and normal needed for shading.
        """
        si = dr.zeros(mi.SurfaceInteraction3f)
        si.t = dr.select(active, pi.t, dr.inf)
        si.p = ray(si.t)
        with dr.resume_grad():  # The distance gradient gives the surface normal
            p = mi.Point3f(si.p)
            dr.enable_grad(p)
            dr.backward(self.distance_estimate(p))
            si.n = si.sh_frame.n = dr.normalize(p.grad)
        si.p_err = 5e-3  # Offset outgoing rays past unresolved fractal detail
        si.shape = pi.shape
        return si

mi.register_shape('mandelbulb', Mandelbulb)

mi.register_shape() makes the class available by name in scene descriptions. We render it below with a diffuse material and procedural lighting.

[3]:
scene = mi.load_dict({
    'type': 'scene',
    'integrator': {'type': 'path' },
    'sensor': {
        'type': 'perspective', 'fov': 38,
        'to_world': mi.ScalarTransform4f().look_at(origin=[2.9, -3.5, 1.15], target=[0, 0, -0.1], up=[0, 0, 1]),
        'film': {'type': 'hdrfilm', 'width': 512, 'height': 512 },
    },
    'sky': {'type': 'sunsky', 'sun_direction': [-1, -0.8, 0.9], 'sun_scale': 2.5, 'sky_scale': 2.5},
    'floor': {'type': 'rectangle', 'bsdf': {'type': 'diffuse', 'reflectance': 0.5},
              'to_world': mi.ScalarTransform4f().translate([0, 0, -1.25]).scale(5000)},
    'shape': {'type': 'mandelbulb', 'bsdf': {'type': 'diffuse',
              'reflectance': {'type': 'rgb', 'value': [0.8, 0.5, 0.3]}}},
})

mi.Bitmap(mi.render(scene, spp=64))
[3]: