Clipping Issue Between add_surface() and add_trace() (3D Polygon Contours Over Surface)

Hi everyone,

I’m working on a 3D visualization in R using Plotly, where I display a terrain surface and want to overlay polygon contours from a .shp shapefile.

Here’s how I generate the terrain :

MNTPlotly <- plot_ly() %>%
  add_surface(
    x = x_unique,
    y = y_unique,
    z = z_matrix,
    opacity = 0.8,
    surfacecolor = classe_matrix
   ...
  )

Then I overlay the contours of polygons (from the shapefile) like this:

plotly_obj <- plotly_obj %>%
  add_trace(
    type = "scatter3d", mode = "lines",
    x = sub_coords[, 1],
    y = sub_coords[, 2],
    z = sub_coords[, 3],
    line = list(color = couleur, width = 5),
    showlegend = FALSE
  )

This works fine visually at first, but when I rotate or zoom the camera, the polygon contours (the add_trace() lines) start clipping through the surface (from add_surface()), depending on the angle and distance.

To avoid z-fighting, I tried offsetting the contours slightly above the surface by adding a few units to the z-values:

z = sub_coords[, 3] + offset

But unfortunately, this only partially helps. When the camera zooms out, the clipping artifacts still occur.

My question:

How can I reliably render polygon contours (from shapefiles) on top of a 3D surface created with add_surface(), without visual clipping issues in Plotly for R?

Is there a better way to force Plotly to always render the trace above the surface or avoid z-fighting altogether?