Task

Draw a sphere.

The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.

Either static or rotational projection is acceptable for this task.



Related tasks

 draw a cuboid
 draw a rotating cube
 write language name in 3D ASCII
 draw a Deathstar


% Draw a sphere in ASCII art in Turing                                                                         
 
% Light intensity to character map
const shades := '.:!*oe&#%@'
const maxShades := length (shades)
 
% Absolute dot product of x and y 
function dot (x, y : array 1 .. 3 of real) : real
     result abs (x(1) * y(1) + x(2) * y(2) + x(3) * y(3))
end dot
 
% Vector normalization
procedure normalize (var v : array 1 .. 3 of real)
    const norm := sqrt (v(1)**2 + v(2)**2 + v(3)**2)
    for i : 1 .. 3
        v(i) := v(i) / norm
    end for
end normalize
 
% Draws a sphere using ASCII art                                                        
procedure drawSphere (radius : real, k : int, lightsource : array 1 .. 3 of real, brightness : real)
    const diameter := 2.0 * radius
    for i : floor (-radius) .. ceil (radius)
        var x := i + 0.5
        for j : floor (-diameter) .. ceil (diameter)
            var y  := j / 2 + 0.5
 
            if x**2 + y**2 <= radius**2 then
                var vec : array 1 .. 3 of real
                vec(1) := x; vec(2) := y; vec(3) := sqrt (radius**2 - x**2 - y**2)
                normalize (vec)
 
                const b := dot (lightsource, vec) ** k + brightness
                var intensity := round ((1 - b) * maxShades)
 
                if intensity < 1 then
                    intensity := 1
                elsif intensity > maxShades then
                    intensity := maxShades
                end if
 
                put shades (intensity) ..
            else
                put ' ' ..
            end if
        end for
        put ""
    end for
end drawSphere
 
% Light source
var lightsource : array 1 .. 3 of real := init (30, 30, -59)
normalize (lightsource)
const brightness := 0.1
 
% Draw some spheres
drawSphere (20, 4, lightsource, brightness)
drawSphere (15, 10, lightsource, brightness)