three.js dev template - module
by atulmourya
HTML
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three/build/three.module.js",
"three/addons/": "https://unpkg.com/three/examples/jsm/"
}
}
</script>
CSS
body {
margin: 0px;
}
JavaScript
import * as THREE from 'three';
// Create a new Scene object
const scene = new THREE.Scene();
// Create a new Camera object
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
// Create a new Mesh object and add it to the scene
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({color: 0x00ff00});
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// Define the pathtracing shader using GLSL code
const pathTracingShader = {
uniforms: {
// Number of samples per pixel
numSamples: { value: 10 },
// Number of bounces per ray
maxBounces: { value: 4 }
},
vertexShader: `
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
// Ray tracing function
vec3 traceRay(vec3 origin, vec3 direction, int bounces) {
// Calculate intersection with objects in the scene
// ...
// Return the color of the intersection point
return vec3(1.0, 1.0, 1.0);
}
void main() {
// Initialize color to black
vec3 color = vec3(0.0, 0.0, 0.0);
// Loop over the number of samples per pixel
for (int i = 0; i < numSamples; i++) {
// Trace a ray from the camera through the current pixel
// ...
// Accumulate the color of the traced ray
color += traceRay(origin, direction, maxBounces);
}
// Average the accumulated color
color /= numSamples;
gl_FragColor = vec4(color, 1.0);
}
`
};
// Set the Mesh object's material to use the pathtracing shader
const pathTracingMaterial = new THREE.ShaderMaterial(pathTracingShader);
cube.material = pathTracingMaterial;
// Use three.js' rendering loop to render the scene using the pathtracing shader
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth,...