Mujoco C++ code to inject a ground plane into a scene

Here’s some pretty crude code which uses string operations to inject a ground plane into a Mujoco XML scene description:

This plane is positioned slightly above the ground to avoid Z-fighting artifacts. It is a collision plane as well as a visual plane

Mujoco Plane

std::string inject_ground_plane(const std::string& xml) {
    // Only attempt if it looks like MJCF
    if (xml.find("<mujoco") == std::string::npos) return {};

    // Slightly lift the visual plane above z=0 to avoid Z-fighting with the
    // viewer's debug grid (which is rendered at z=0). Physics is unchanged
    // except for a negligible 1mm offset.
    std::string planeGeom =
        "\n    <geom name=\"ground\" type=\"plane\" pos=\"0 0 0.001\" size=\"0 0 1\" "
        "rgba=\"0.2 0.2 0.8 0.5\" contype=\"1\" conaffinity=\"1\"/\>\n";

    std::string out = xml;

    // Try to insert into existing worldbody (right before its closing tag)
    size_t closeWorld = out.rfind("</worldbody>");
    if (closeWorld != std::string::npos) {
        out.insert(closeWorld, planeGeom);
        return out;
    }

    // No worldbody found: create one before </mujoco>
    size_t closeMujoco = out.rfind("</mujoco>");
    if (closeMujoco != std::string::npos) {
        std::string block = std::string("\n  <worldbody>\n") + planeGeom + "  </worldbody>\n";
        out.insert(closeMujoco, block);
        return out;
    }

    // As a last resort, append a minimal wrapper (shouldn't happen for valid MJCF)
    return out + "\n<worldbody>" + planeGeom + "</worldbody>\n";
}