[UPDATE: Refer to this jsfiddle for a live demo along with the relevant code]
I am using three.js to create visualizations of celestial bodies with distinct characteristics.
While there are no specific examples available on implementing spherical heightmaps with threejs, there is an example showing how to apply a heightmap to a plane.
I adapted this example by utilizing a SphereGeometry();
instead of a PlaneGeometry();
Given that the geometry of a sphere differs significantly from that of a plane, I encountered difficulty as the rendered sphere appeared as a flat texture.
The heightmap code for planes:
var plane = new THREE.PlaneGeometry( 2000, 2000, quality - 1, quality - 1 );
plane.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
for ( var i = 0, l = plane.vertices.length; i < l; i ++ ) {
var x = i % quality, y = ~~ ( i / quality );
plane.vertices[ i ].y = data[ ( x * step ) + ( y * step ) * 1024 ] * 2 - 128;
}
I believe the solution lies in altering the mapping within the for loop to calculate the surface coordinates of the sphere in 3D space rather than the 2D coordinates of a plane. However, my limited knowledge of 3D mathematics has left me stuck at this juncture.
An illustration applying the heightmap to a sphere alongside all related code can be found in this jsfiddle. An updated version is available in this revised jsfiddle, displaying an altered sphere with randomized data instead of actual height map information.
I am aware that it is possible to distort the 3D points of a sphere to generate surface details, but my goal is to achieve this using a heightmap. The current JSFiddle demonstrates my progress so far – it distorts points randomly to simulate a rocky texture on the sphere, albeit appearing unnatural.
UPDATE: Here is the targeted logic required to implement mapping heightmap data onto a sphere.
To map the data onto a sphere, we must convert coordinates from a basic spherical coordinate system (longitude φ, latitude θ, radius r) to Cartesian coordinates (x, y, z). Similar to traditional height-mapping where the value at (x, y) corresponds to z, here we map the value at (φ, θ) to r. This transformation involves:
x = r × cos φ × sin θ
y = r × sin φ × sin θ
z = r × cos θ
r = Rdefault + Rscale × d(φ, θ)
The parameters Rdefault and Rscale can be adjusted to control the size of the sphere and the resulting height map applied to it.