Let's create a Marimo widget for 3D rendering with PBR (Physically Based Rendering) materials using Three.js. This implementation will include a basic scene with a 3D model, PBR materials, lighting, and orbit controls.
Here's a complete implementation:
python
import marimo as mo
import json
from pathlib import Path
def create_3d_viewer():
# HTML template for the 3D viewer
html_content = """
<!DOCTYPE html>
<html>
<head>
<style>
body { margin: 0; padding: 0; overflow: hidden; }
#container { width: 100%; height: 100%; }
</style>
</head>
<body>
<div id="container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r134/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.134.0/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.134.0/examples/js/loaders/GLTFLoader.js"></script>
<script>
class ThreeDViewer {
constructor(containerId) {
this.container = document.getElementById(containerId);
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, this.container.clientWidth / this.container.clientHeight, 0.1, 1000);
this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
this.init();
}
init() {
// Setup renderer
this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.physicallyCorrectLights = true;
this.renderer.outputEncoding = THREE.sRGBEncoding;
this.container.appendChild(this.renderer.domElement);
// Setup camera
this.camera.position.set(0, 1, 3);
// Setup controls
this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.05;
// Add lights
this.addLights();
// Add environment map
this.addEnvironment();
// Add sample object
this.addSampleObject();
// Handle resize
window.addEventListener('resize', () => this.onResize());
// Start animation
this.animate();
}
addLights() {
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
this.scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 5, 5);
this.scene.add(directionalLight);
}
addEnvironment() {
// Simple environment map (you can replace with HDR for better results)
const envGeometry = new THREE.SphereGeometry(500, 60, 40);
envGeometry.scale(-1, 1, 1);
const envMaterial = new THREE.MeshBasicMaterial({
color: 0x87ceeb,
side: THREE.BackSide
});
const envMesh = new THREE.Mesh(envGeometry, envMaterial);
this.scene.add(envMesh);
}
addSampleObject() {
// Create a sample sphere with PBR materials
const geometry = new THREE.SphereGeometry(1, 32, 32);
const material = new THREE.MeshStandardMaterial({
color: 0xaaaaaa,
metalness: 0.7,
roughness: 0.3,
envMapIntensity: 1.0
});
const sphere = new THREE.Mesh(geometry, material);
this.scene.add(sphere);
}
onResize() {
this.camera.aspect = this.container.clientWidth / this.container.clientHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(this.container.clientWidth, this.container.clientHeight);
}
animate() {
requestAnimationFrame(() => this.animate());
this.controls.update();
this.renderer.render(this.scene, this.camera);
}
}
// Initialize the viewer
const viewer = new ThreeDViewer('container');
// Expose the viewer to window for potential external control
window.threeDViewer = viewer;
</script>
</body>
</html>
"""
# Create a temporary HTML file
html_file = Path("temp_3d_viewer.html")
html_file.write_text(html_content)
# Create an iframe to display the 3D content
return mo.ui.html(f"""
<iframe
srcdoc="{html_content.replace('"', '"')}"
style="width: 100%; height: 400px; border: none;"
></iframe>
""")
# Create the Marimo app
app = mo.App(width="full")
@app.cell
def __():
import marimo as mo
return mo,
@app.cell
def __():
viewer = create_3d_viewer()
return viewer,
@app.cell
def __():
return mo.ui.vstack([
mo.md("# 3D PBR Viewer"),
viewer,
mo.md("""
Controls:
- Left click + drag: Rotate
- Right click + drag: Pan
- Mouse wheel: Zoom
""")
]),
if __name__ == "__main__":
app.run()
This implementation provides:
A complete 3D viewer with PBR materials using Three.js
Orbit controls for camera manipulation
Basic PBR lighting setup (ambient + directional)
A sample sphere with PBR materials
Responsive design that handles window resizing
Basic environment mapping
To use this in Marimo:
Save the code in a .py file
Run it using marimo run your_file.py
The 3D viewer will appear in your Marimo notebook
To enhance this implementation, you could:
Add HDR environment mapping for more realistic PBR:
javascript
// In the addEnvironment method, replace the simple environment with:
const pmremGenerator = new THREE.PMREMGenerator(this.renderer);
new THREE.RGBELoader()
.load('path/to/hdr/environment.hdr', (texture) => {
const envMap = pmremGenerator.fromEquirectangular(texture).texture;
this.scene.environment = envMap;
texture.dispose();
pmremGenerator.dispose();
});
Add model loading capabilities:
javascript
// Add this method to the ThreeDViewer class
loadModel(url) {
const loader = new THREE.GLTFLoader();
loader.load(url, (gltf) => {
this.scene.add(gltf.scene);
});
}
@app.cell
def __():
return mo.ui.vstack([
mo.md("# 3D PBR Viewer"),
mo.ui.spinner() if not viewer else viewer,
mo.md("Loading 3D viewer...") if not viewer else None
]),
Remember to:
Ensure you have an internet connection (for loading Three.js CDNs)
Consider local Three.js files for offline use
Add appropriate error handling for production use
Consider performance optimizations for complex scenes
Add documentation for users
This implementation provides a solid foundation for 3D visualization in Marimo notebooks with PBR materials. You can extend it based on your specific needs, such as adding custom models, more complex materials, or additional controls.