GroundedSkybox.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { Mesh, MeshBasicMaterial, SphereGeometry, Vector3 } from 'three';
  2. /**
  3. * A ground-projected skybox. The height is how far the camera that took the photo was above the ground -
  4. * a larger value will magnify the downward part of the image. By default the object is centered at the camera,
  5. * so it is often helpful to set skybox.position.y = height to put the ground at the origin. Set the radius
  6. * large enough to ensure your user's camera stays inside.
  7. */
  8. class GroundedSkybox extends Mesh {
  9. constructor( map, height, radius, resolution = 128 ) {
  10. if ( height <= 0 || radius <= 0 || resolution <= 0 ) {
  11. throw new Error( 'GroundedSkybox height, radius, and resolution must be positive.' );
  12. }
  13. const geometry = new SphereGeometry( radius, 2 * resolution, resolution );
  14. geometry.scale( 1, 1, -1 );
  15. const pos = geometry.getAttribute( 'position' );
  16. const tmp = new Vector3();
  17. for ( let i = 0; i < pos.count; ++ i ) {
  18. tmp.fromBufferAttribute( pos, i );
  19. if ( tmp.y < 0 ) {
  20. // Smooth out the transition from flat floor to sphere:
  21. const y1 = - height * 3 / 2;
  22. const f =
  23. tmp.y < y1 ? - height / tmp.y : ( 1 - tmp.y * tmp.y / ( 3 * y1 * y1 ) );
  24. tmp.multiplyScalar( f );
  25. tmp.toArray( pos.array, 3 * i );
  26. }
  27. }
  28. pos.needsUpdate = true;
  29. super( geometry, new MeshBasicMaterial( { map, depthWrite: false } ) );
  30. }
  31. }
  32. export { GroundedSkybox };