WebGL Drawing Sphere

←Back

Related Topics: OpenGL Sphere, VBO

Overview

parametric equation of sphere
Sectors and stacks of a sphere

The parametric equation of a sphere is;
formula to find a point on a sphere
where angle is the sector (longitude) angle and angle is the stack (latitude) angle. The range of the sector angle is from 0 to 360 degrees, and the stack angle is from -90 to 90 degrees.

Since we cannot draw all the points on a sphere, we only sample a limited amount of points by dividing the sphere by number of sectors and stacks. Then, simplify the sphere by connecting these sampled points together to form surfaces of the sphere.

Please see the details how to construct the vertices and triangles for a sphere.

Sphere Class

Sphere.js is a JavaScript class to construct a sphere geometry with the following parameters; radius, the number of sectorr and stacks and surface smoothing flag. If no parameters are specified, it creates a sphere with default values (r=1, sectorCount=36, steackCount=18, smooth=true). Other main methods and properties of Sphere class are;

Sphere
InterfaceDescription
set()Change all the parameters of the current instance at once
setRadius()Change the radius of this
setSectorCount()Change the number of sectors of this
(Min. sector count is 2.)
setStackCount()Change the number of stacks of this
(Min. stack count is 2)
setSmooth()Change the surface smoothness of this
getVertexCount()Return the number of vertices
getIndexCount()Return the number of indices
vboVertexVBO ID of the vertex attributes for WebGL
vboIndexVBO ID of the indices for WebGL

Sphere class creates VBOs for rendering when it is created, so no need to create VBO and to copy vertex data to VBO by yourself. A typical usage of this Sphere class follows;


let gl = {}; // global var

// create a sphere with default parameters
// radius=1, sectorCount=36, stackCount=18, smooth=true
gl.sphere = new Sphere(gl);

// can change params after creation
// radius=2, sectorCount=72, stackCount=36, smooth=false
gl.sphere.set(2, 72, 36, false);
...

// draw sphere with interleaved mode, V/N/T
gl.bindBuffer(gl.ARRAY_BUFFER, gl.sphere.vboVertex);
gl.vertexAttribPointer(gl.program.attribute.position, 3, gl.FLOAT, false, gl.sphere.stride, 0);
gl.vertexAttribPointer(gl.program.attribute.normal, 3, gl.FLOAT, false, gl.sphere.stride, 12);
gl.vertexAttribPointer(gl.program.attribute.texCoord0, 2, gl.FLOAT, false, gl.sphere.stride, 24);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.sphere.vboIndex);
gl.drawElements(gl.TRIANGLES, gl.sphere.getIndexCount(), gl.UNSIGNED_SHORT, 0);

Example: Drawing Sphere

This demo is drawing a sphere and it allows a user interact with its parameters.


decoration Fullscreen Demo: test_sphere.html
decoration GitHub Repo: test_sphere.html

←Back
 
Hide Comments
comments powered by Disqus