import * as THREE from 'three/webgpu'; /** * Pointer stirring for a spherical body of water. The ocean has no horizontal * plane to raycast, so the pointer is projected onto the ocean sphere itself; * when the ray misses the planet the nearest point on the ray is used instead, * which keeps a swipe past the limb pushing the water it grazes rather than * snapping the force to the last hit. */ export function createPlanetPointerInteraction( { renderer, camera, domainSize, oceanRadius, interactionPosition, interactionStrength, } ) { const pointer = new THREE.Vector2(); const raycaster = new THREE.Raycaster(); const oceanSphere = new THREE.Sphere( new THREE.Vector3( 0, 0, 0 ), oceanRadius ); const hit = new THREE.Vector3(); let moved = false; const updatePointer = event => { const bounds = renderer.domElement.getBoundingClientRect(); pointer.set( ( ( event.clientX - bounds.left ) / bounds.width ) * 2 - 1, - ( ( event.clientY - bounds.top ) / bounds.height ) * 2 + 1 ); raycaster.setFromCamera( pointer, camera ); if ( raycaster.ray.intersectSphere( oceanSphere, hit ) === null ) { raycaster.ray.closestPointToPoint( oceanSphere.center, hit ); const distance = hit.length(); if ( distance < 1e-4 ) return; hit.multiplyScalar( oceanRadius / distance ); } // The solver compares against normalized domain coordinates, and the // domain cube is centred on the planet. interactionPosition.value.set( THREE.MathUtils.clamp( hit.x / domainSize.x + 0.5, 0, 1 ), THREE.MathUtils.clamp( hit.y / domainSize.y + 0.5, 0, 1 ), THREE.MathUtils.clamp( hit.z / domainSize.z + 0.5, 0, 1 ) ); }; const onPointerMove = event => { if ( event.isPrimary === false ) return; updatePointer( event ); moved = true; }; const onPointerLeave = () => { moved = false; interactionStrength.value = 0; }; renderer.domElement.addEventListener( 'pointermove', onPointerMove ); renderer.domElement.addEventListener( 'pointercancel', onPointerLeave ); renderer.domElement.addEventListener( 'pointerleave', onPointerLeave ); return { onPointerMove, onPointerLeave, consumeMove: () => { const pending = moved; moved = false; return pending; }, }; }