I’m trying render a point cloud in augmented reality, for that I started with this example:
https://threejs.org/examples/?q=point#webgl_buffergeometry_points
And modify it to run in AR. This is my resulting code:
<script type="module">
import * as THREE from 'three';
import Stats from 'three/examples/jsm/libs/stats.module.js';
import { ARButton } from 'three/examples/jsm/webxr/ARButton.js';
let container, stats;
let camera, scene, renderer;
let points;
init();
animate();
function init() {
const container = document.getElementById('container');
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 20);
camera.position.set(0, 1.6, 0);
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.xr.enabled = true;
container.appendChild(renderer.domElement);
document.body.appendChild(ARButton.createButton(renderer));
const particles = 5000; // Reduced particle count for performance
const geometry = new THREE.BufferGeometry();
const positions = [];
const colors = [];
const color = new THREE.Color();
const n = 1000, n2 = n / 2; // particles spread in the cube
for (let i = 0; i < particles; i++) {
// positions
const x = Math.random() * n - n2;
const y = Math.random() * n - n2;
const z = Math.random() * n - n2;
positions.push(x, y, z);
// colors
const vx = (x / n) + 0.5;
const vy = (y / n) + 0.5;
const vz = (z / n) + 0.5;
color.setRGB(vx, vy, vz);
colors.push(color.r, color.g, color.b);
}
geometry.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3));
geometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
geometry.computeBoundingSphere();
const material = new THREE.PointsMaterial({ size: 1, vertexColors: true });
points = new THREE.Points(geometry, material);
scene.add(points);
window.addEventListener('resize', onWindowResize);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
renderer.setAnimationLoop( render );
}
function render() {
renderer.render( scene, camera );
}
</script>
But when I run it nothing renders, not in the preview before I hit the AR button, not in AR mode. I looked at the dev console and it doesn’t give me any errors, the script seems to be running just fine. Any help would be appreciated! Thanks!
Best,
Adrian.