instanced-mesh + three.js r182 - FIXED (backward compatible)
by Scott Divelbiss
HTML
<div id="info">Loading three.js r182...</div>
CSS
body { margin: 0; background: #1a1a2e; }
canvas { display: block; }
#info {
position: absolute; top: 10px; left: 10px; color: #4488ff;
font-family: monospace; font-size: 14px;
background: rgba(0,0,0,0.8); padding: 12px 16px; border-radius: 6px;
border: 1px solid #4488ff; max-width: 500px;
}
JavaScript
import * as THREE from 'https://unpkg.com/[email protected]/build/three.module.js';
// ---- FIX (same patch as r183 fix) ----
// Always use vec4 + USE_COLOR_ALPHA — works on r182 too because
// USE_COLOR_ALPHA makes r182 declare vColor as vec4
THREE.ShaderChunk['instanced_color_vertex'] = [
'#ifdef USE_INSTANCING_COLOR_INDIRECT',
' #ifdef USE_VERTEX_COLOR',
' vColor = vec4(color, 1.0);',
' #else',
' vColor = vec4( 1.0 );',
' #endif',
'#endif'
].join('\n');
var info = document.getElementById('info');
var scene = new THREE.Scene();
scene.background = new THREE.Color(0x1a1a2e);
var camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 2, 6);
camera.lookAt(0, 0, 0);
var renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(devicePixelRatio);
document.body.appendChild(renderer.domElement);
var geometry = new THREE.SphereGeometry(0.8, 32, 32);
var colors = [0x4488ff, 0xff4488, 0x44ff88];
var positions = [[-2, 0, 0], [0, 0, 0], [2, 0, 0]];
for (var i = 0; i < 3; i++) {
var material = new THREE.MeshStandardMaterial({ color: colors[i], roughness: 0.4, metalness: 0.3 });
material.onBeforeCompile = function(shader) {
shader.defines['USE_INSTANCING_COLOR_INDIRECT'] = '';
shader.defines['USE_COLOR_ALPHA'] = '';
shader.vertexShader = shader.vertexShader.replace(
'#include <color_vertex>',
THREE.ShaderChunk['instanced_color_vertex']
);
};
var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(positions[i][0], positions[i][1], positions[i][2]);
scene.add(mesh);
}
var floor = new THREE.Mesh(
new THREE.PlaneGeometry(10, 10),
new THREE.MeshStandardMaterial({ color: 0x333355, roughness: 0.9 })
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -1;
scene.add(floor);
scene.add(new THREE.AmbientLight(0xffffff, 0.4));
var dirLight...