Draw a sphere: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
Simple9371 (talk | contribs) m (→{{header|Batch File}}: make the code slightly clearer) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(43 intermediate revisions by 24 users not shown) | |||
Line 9:
Either static or rotational projection is acceptable for this task.
;Related tasks:
* [[Draw_a_cuboid|draw a cuboid]]
* [[Draw_a_rotating_cube|draw a rotating cube]]
* [[Write_language_name_in_3D_ASCII|write language name in 3D ASCII]]
* [[Death_Star|draw a Deathstar]]
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">V shades = [‘.’, ‘:’, ‘!’, ‘*’, ‘o’, ‘e’, ‘&’, ‘#’, ‘%’, ‘@’]
F dotp(v1, v2)
V d = dot(v1, v2)
R I d < 0 {-d} E 0.0
F draw_sphere(r, k, ambient, light)
L(i) Int(floor(-r)) .< Int(ceil(r) + 1)
V x = i + 0.5
V line = ‘’
L(j) Int(floor(-2 * r)) .< Int(ceil(2 * r) + 1)
V y = j / 2 + 0.5
I x * x + y * y <= r * r
V vec = normalize((x, y, sqrt(r * r - x * x - y * y)))
V b = dotp(light, vec) ^ k + ambient
V intensity = Int((1 - b) * (:shades.len - 1))
line ‘’= I intensity C 0 .< :shades.len {:shades[intensity]} E :shades[0]
E
line ‘’= ‘ ’
print(line)
V light = normalize((30.0, 30.0, -50.0))
draw_sphere(20, 4, 0.1, light)
draw_sphere(10, 2, 0.4, light)</syntaxhighlight>
{{out}}
<pre>
&&&&&&&&&&#######
&eeeeeeeeeeeeeeee&&&&&&#######%
&eoooo*******oooooooeeeee&&&&&########%
eoo****!!!!!!!!******oooooeeee&&&&&########%%
eoo**!!!!::::::::!!!!!*****ooooeeee&&&&&########%%%
eo**!!::::::...:::::::!!!!!***ooooeeee&&&&&########%%%%
eo*!!:::.............:::::!!!!***ooooeeee&&&&&########%%%%%
eo*!!:::.................::::!!!!***ooooeeee&&&&#########%%%%%%
eo*!!::....................::::!!!****oooeeee&&&&&#########%%%%%%
&o**!::......................::::!!!****oooeeee&&&&&##########%%%%%%%
&o**!::.......................::::!!!****oooeeee&&&&&##########%%%%%%%%
&oo*!!::.......................:::!!!!***ooooeeee&&&&&##########%%%%%%%%%
&eo*!!::.......................::::!!!****ooooeeee&&&&&##########%%%%%%%%%%
eo**!!::......................::::!!!!***ooooeeeee&&&&&##########%%%%%%%%%%
&eo**!!:::...................:::::!!!!****ooooeeee&&&&&###########%%%%%%%%%%%
eeo**!!::::................:::::!!!!!****ooooeeee&&&&&&###########%%%%%%%%%%%
&eeo***!!:::::...........::::::!!!!!****oooooeeee&&&&&&###########%%%%%%%%%%%%%
&eeoo**!!!!::::::::::::::::::!!!!!*****ooooeeeee&&&&&&############%%%%%%%%%%%%%
&eeooo***!!!!::::::::::::!!!!!!!*****oooooeeeee&&&&&&############%%%%%%%%%%%%%%
&&eeooo***!!!!!!!!!!!!!!!!!!!******oooooeeeeee&&&&&&############%%%%%%%%%%%%%%%
&&eeeooo******!!!!!!!!!!********ooooooeeeeee&&&&&&&############%%%%%%%%%%%%%%%%
#&&eeeooooo******************oooooooeeeeee&&&&&&&#############%%%%%%%%%%%%%%%%%
#&&&eeeeoooooooo******oooooooooooeeeeeee&&&&&&&&#############%%%%%%%%%%%%%%%%%%
##&&&&eeeeeooooooooooooooooooeeeeeeee&&&&&&&&&##############%%%%%%%%%%%%%%%%%%%
##&&&&&eeeeeeeeeeeeeeeeeeeeeeeeee&&&&&&&&&################%%%%%%%%%%%%%%%%%%%
####&&&&&&eeeeeeeeeeeeeeeeeee&&&&&&&&&&&################%%%%%%%%%%%%%%%%%%%%%
#####&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#################%%%%%%%%%%%%%%%%%%%%%%
%#######&&&&&&&&&&&&&&&&&&&&&&&&###################%%%%%%%%%%%%%%%%%%%%%%%%
%###########&&&&&&&&&&&&&#######################%%%%%%%%%%%%%%%%%%%%%%%%%
%############################################%%%%%%%%%%%%%%%%%%%%%%%%%%
%%#######################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%#################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%#########################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%#############%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%
::...:::!!!*o
..............::!!*oo
..................::!!**ooe
.....................::!!**ooee
.......................::!!**ooee
........................::!!**oooee
.........................::!!**oooeee
:........................::!!!**oooeeee
........................::!!!**ooooeeee
:......................::!!!***oooeeeee
:....................:::!!!***oooeeeeee
!:.................:::!!!****oooeeeeeee
*!:::...........::::!!!!***ooooeeeeeeee
*!!!:::::::::::!!!!!****oooooeeeeeeee
o**!!!!!!!!!!!!!*****oooooeeeeeeeee
oo**************ooooooeeeeeeeeeee
eoooooooooooooooooeeeeeeeeeeeee
eeeooooooooeeeeeeeeeeeeeeee
eeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeee
</pre>
=={{header|Action!}}==
<syntaxhighlight lang="action!">INT ARRAY SinTab=[
0 4 9 13 18 22 27 31 36 40 44 49 53 58 62 66 71 75 79 83
88 92 96 100 104 108 112 116 120 124 128 132 136 139 143
147 150 154 158 161 165 168 171 175 178 181 184 187 190
193 196 199 202 204 207 210 212 215 217 219 222 224 226
228 230 232 234 236 237 239 241 242 243 245 246 247 248
249 250 251 252 253 254 254 255 255 255 256 256 256 256]
INT FUNC Sin(INT a)
WHILE a<0 DO a==+360 OD
WHILE a>360 DO a==-360 OD
IF a<=90 THEN
RETURN (SinTab(a))
ELSEIF a<=180 THEN
RETURN (SinTab(180-a))
ELSEIF a<=270 THEN
RETURN (-SinTab(a-180))
ELSE
RETURN (-SinTab(360-a))
FI
RETURN (0)
INT FUNC Cos(INT a)
RETURN (Sin(a-90))
PROC Ellipse(INT x0,y0,rx,ry)
INT i
CARD x
BYTE y
x=x0+rx*Sin(0)/256
y=y0+ry*Cos(0)/256
Plot(x,y)
FOR i=5 TO 360 STEP 5
DO
x=x0+rx*Sin(i)/256
y=y0+ry*Cos(i)/256
DrawTo(x,y)
OD
RETURN
PROC Main()
BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6
INT cx=[160],cy=[96],r=[90],r2
BYTE i
Graphics(8+16)
COLOR1=$0C
COLOR2=$02
Color=1
Ellipse(cx,cy,r,r)
FOR i=10 TO 90 STEP 10
DO
r2=r*Cos(i)/256
Ellipse(cx,cy,r,r2)
Ellipse(cx,cy,r2,r)
OD
DO UNTIL CH#$FF OD
CH=$FF
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Draw_a_sphere.png Screenshot from Atari 8-bit computer]
=={{header|Ada}}==
Line 16 ⟶ 185:
Uses the Cairo component of GtkAda to create and save as png
[[File:SphereAda.png|thumb|right]]
<
with Cairo; use Cairo;
with Cairo.Png; use Cairo.Png;
Line 45 ⟶ 214:
Status_Out := Write_To_Png (Surface, "SphereAda.png");
pragma Assert (Status_Out = Cairo_Status_Success);
end Sphere;</
{{libheader|Display}}
This uses a very loose binding to SDL as found in any GPS installation. For it to work, you must choose New Project From Templte|Empty Game
<syntaxhighlight lang="ada">
with Display; use Display;
with Display.Basic; use Display.Basic;
Line 63 ⟶ 232:
null;
end Main;
</syntaxhighlight>
=={{header|ALGOL W}}==
{{Trans|AWK}} with some changes inspired by other samples.
<
% draw a sphere %
% returns the next integer larger than x or x if x is an integer %
Line 147 ⟶ 316:
light( 3 ) := -59;
normalize( light );
drawSphere( 20, 4, 0.1, light, ".:!*oe
drawSphere( 10, 2, 0.4, light, ".:!*oe
end test
end.</
{{out}}
<pre>
%%%%%%%%%%%%%&&&&
#
#
%#
%#
%#
%%##
%%##
&%%##
&%%%####eeeeeooooooooooooooooooeeeeeeee#######%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&
&%%%%####eeeeeeeeeeeeeeeeeeeeeeeeee########%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&
&&%%%%####
&&%%%%%%####
&&&&%%%%%%%#####################%%%%%%%%%%%%%&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
Line 216 ⟶ 384:
eeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeee
</pre>
Line 230 ⟶ 397:
=={{header|ATS}}==
<syntaxhighlight lang="text">
(*
** Solution to Draw_a_sphere.dats
Line 332 ⟶ 499:
(* ****** ****** *)
</syntaxhighlight>
=={{header|AutoHotkey}}==
{{libheader|GDIP}}
<
SetBatchLines, -1
#SingleInstance, Force
Line 392 ⟶ 559:
; gdi+ may now be shutdown on exiting the program
Gdip_Shutdown(pToken)
ExitApp</
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f DRAW_A_SPHERE.AWK
# converted from VBSCRIPT
Line 455 ⟶ 622:
return(n)
}
</syntaxhighlight>
{{out}}
<pre>
Line 527 ⟶ 694:
This is based, but not exactly, on the [http://rosettacode.org/wiki/Draw_a_sphere#Tcl Tcl] implementation.
Thus, the output is almost the same to the output of Tcl implementation below.
<
color white
rect 0,0,graphwidth, graphheight
Line 533 ⟶ 700:
color rgb(2*n,2*n,2*n)
circle 150-2*n/3,150-n/2,150-n
next n</
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
Using Direct3D.
<
INSTALL @lib$+"D3DLIB"
D3DTS_VIEW = 2
Line 655 ⟶ 822:
SYS "FreeLibrary", d3dx%
END
</syntaxhighlight>
{{out}}
[[File:Sphere_BBC.jpeg]]
Line 663 ⟶ 830:
Some simple 3D objects are built into DarkBASIC. Creating a sphere only takes 1 line:
<syntaxhighlight lang
==={{header|FreeBASIC}}===
<
' "/" = a floating point division (FPU)
' the compiler takes care of the conversion between floating point and integer
Line 713 ⟶ 880:
Print : Print "hit any key to end program"
Sleep
End</
{{works with|FreeBASIC}}
needs #Lang "fblite", #Lang "qb" or #Lang "deprecated" to compile.
<
'spherefb4.bas
'Sphere using XPL0 code from rosetacode sphere page
Line 751 ⟶ 918:
Print "Enter any key to exit "
sleep
END</
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">
WindowWidth =420
WindowHeight =460
Line 781 ⟶ 948:
close #w
end
</syntaxhighlight>
==={{header|Locomotive Basic}}===
Translated from ERRE version, this will print a 39x20 text sphere onscreen.
The variables in line 80 can be used to adjust size (r), spotlight (k), reflective light (ambient).
<
10 MODE 2:s$=".:!*oe&#%@"
20 DIM v(2),vec(2)
Line 823 ⟶ 990:
3010 IF d<0 THEN d=-d ELSE d=0
3020 RETURN
</syntaxhighlight>
==={{header|PureBasic}}===
3D Sphere animation.
<
;
; Updated/Formated by Fluid Byte @ March.24,2009
Line 1,077 ⟶ 1,244:
SetMeshData(0,#PB_Mesh_Face,*IBuffer,Length)
EndProcedure</
[[image:PB_Animated_sphere.png]]
===[[QBasic]]===
<
' sets palette colors B/N
Line 1,100 ⟶ 1,267:
' wait until keypress
DO: LOOP WHILE INKEY$ = ""
END</
==={{header|Run BASIC}}===
<
'runbasic.com
graphic #win, 300, 300
Line 1,120 ⟶ 1,287:
next X
next Y
render #win</
<
graphic #g, 300, 300 'create a graphic object
#g place(100,100) 'place the drawing pen at 100,100
#g circle(75) 'make a circle with radius 75
render #g 'show it</
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM. A screenshot of the output is [http://www.edmundgriffiths.com/zx81sphere.jpg here].
<
20 LET J=2
30 FOR K=-PI TO PI STEP 0.07
Line 1,138 ⟶ 1,305:
70 LET I=I-J
80 LET J=J+1
90 IF I>0 THEN GOTO 30</
=={{header|Batch File}}==
{{trans|C}}
Since Batch Files do not support floating point, the input parameters for drawing the sphere are limited to integers only. The ''k'' parameter has been hardcoded to 2. The <code>ambient</code> variable for this code is scaled up 10 times of its value in C implementation. For example, <code>ambient = 0.1</code> in C code corresponds to <code>ambient = 1</code> here.
Lastly, the variables used in calculations are scaled up 100 times of the actual values in C implementation, and then scaled down 100 times back for determination of shades.
<
:: Batch File Implementation
Line 1,151 ⟶ 1,318:
rem more info: https://www.dostips.com/forum/viewtopic.php?f=3&t=6744
rem integer sqrt arithmetic function by Aacini, penpen and
rem source: https://www.dostips.com/forum/viewtopic.php?f=3&t=5819&start=30#p44016
set "sqrt(N)=( M=(N),j=M/(11*1024)+40, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j=(M/j+j)>>1, j+=(M-j*j)>>31 )"
Line 1,211 ⟶ 1,378:
set /a "R=%1", "negR=-R", "twiceR=R*2", "twiceNegR=negR*2"
set /a "sqrdR=R*R*100*100" %== R*R is mult. by 100*100 ==%
set "k=2"
set "ambient=%
rem start draw line-by-line
for /l %%i in (%negR%, 1, %R%) do (
Line 1,246 ⟶ 1,413:
echo(!line!
)
goto :EOF</
{{Out}}
<pre> eeeeeeeeee&&&&&##
Line 1,297 ⟶ 1,464:
Also note that the z-coordinate of the light vector is negated at runtime to more closely match the C defaults. This is preferable to making the initial constant negative since negative data values aren't supported across all Befunge implementations.
<
>60p140g->:::*00g50g*60g40g-:*-\-v0>1
^_@#`\g0<|`\g04:+1, <*84$$_v#`\0:<>p^
Line 1,304 ⟶ 1,471:
^>#0 *#12#<0g:^>+::"~~"90g*80g+*70gv|
g-10g*+:9**00gv|!*`\2\`-20::/2-\/\+<>
%#&eo*!:..^g05<>$030g-*9/\20g*+60g40^</
{{out}}
Line 1,350 ⟶ 1,517:
=={{header|Brlcad}}==
<
units cm # Set the unit of measure
in ball.s sph 0 0 0 3 # Create a sphere of radius 3 cm named ball.s with its centre at 0,0,0 </
=={{header|C}}==
The lighting calculation is somewhere between crude and bogus, but hey, I'm shading it with ASCII characters, don't expect too much.
<
#include <stdlib.h>
#include <string.h>
Line 1,412 ⟶ 1,579:
return 0;
}</
{{out}}
<pre> #############%%%%
Line 1,478 ⟶ 1,645:
===Fun with 3D noise texture===
[[file:sphere-perlin.png]]
<
#include <stdlib.h>
#include <math.h>
Line 1,639 ⟶ 1,806:
return 0;
}</
=={{header|C sharp|C#}}==
{{trans|C}}
<
namespace Sphere {
Line 1,693 ⟶ 1,860:
}
}
}</
=={{header|C++}}==
{{libheader|Qt}}
<
#include <QImage>
Line 1,733 ⟶ 1,900:
image.save("sphere.png");
return 0;
}</
{{out}}
[[Media:Draw a sphere cpp.png]]
=={{header|Clojure}}==
{{libheader|quil}}
<
(use 'quil.core)
Line 1,761 ⟶ 1,928:
:draw draw
:renderer :opengl)
</syntaxhighlight>
{{out}}
Line 1,771 ⟶ 1,938:
Saved as a png file and rendered in a X-Window. Unfortunately the file upload isn't working anymore for like four years so I cannot show my results directly.
<
(eval-when (:compile-toplevel :load-toplevel)
(ql:quickload '("cl-cairo2" "cl-cairo2-xlib")))
Line 1,815 ⟶ 1,982:
(set-source pat)
(arc *middle* *middle* 180 0 (* 2 pi))
(fill-path))))</
=={{header|ContextFree}}==
<syntaxhighlight lang="contextfree">
startshape SPHERE
Line 1,825 ⟶ 1,992:
SPHERE[x 0.1% y 0.1%s 0.99 0.99 b 0.05]
}
</syntaxhighlight>
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">let j = 2
for i = 221 to 0 step j * -1
for k = -3.14 to 3.14 step .01
dot 221 + i * sin(k), 222 + 221 * cos(k)
dot 221 + 221 * sin(k), 222 + (i - 1) * cos(k)
wait
next k
let j = j + 1
next i</syntaxhighlight>
=={{header|D}}==
{{trans|C}}
<
alias V3 = double[3];
Line 1,868 ⟶ 2,053:
drawSphere(20, 4, 0.1);
drawSphere(10, 2, 0.4);
}</
=={{header|Delphi}}==
Line 1,877 ⟶ 2,062:
'''Steps:''' Run the CMD Windows shell. Then follow this path to setup the new width: '''Main Menu-> Properties -> Layout -> Window Size -> Width'''.
<syntaxhighlight lang="delphi">
program DrawASphere;
Line 1,948 ⟶ 2,133:
Readln;
end.
</syntaxhighlight>
{{out}}
Line 2,016 ⟶ 2,201:
[[image:DWScript-sphere.pbm.png|thumb|right|PBM output magnified 5 times]]
{{trans|C}} but adapted to spit out a [[wp:Netpbm_format|PGM]] image
<
type
TFloat3 = array[0..2] of Float;
Line 2,072 ⟶ 2,257:
normalize(light);
drawSphere(19, 4, 0.1);
</syntaxhighlight>
=={{header|Emacs Lisp}}==
{{trans|Go}}
<syntaxhighlight lang="lisp">; Draw a sphere
(defun normalize (v)
"Normalize a vector."
(setq invlen (/ 1.0 (sqrt (dot v v))))
(mapcar (lambda (x) (* invlen x)) v))
(defun dot (v1 v2)
"Dot product of two vectors."
(+ (* (car v1) (car v2))
(* (cadr v1) (cadr v2))
(* (caddr v1) (caddr v2))))
(defun make-array (size)
"Create an empty array with size*size elements."
(setq m-array (make-vector size nil))
(dotimes (i size)
(setf (aref m-array i) (make-vector size 0)))
m-array)
(defun pic-lines (arr size)
"Turn array into a string."
(setq all "")
(dotimes (y size)
(setq line "")
(dotimes (x size)
(setq line (concat line (format "%i \n" (elt (elt arr y) x)))))
(setq all (concat all line "\n")))
all)
(defun pic-show (arr size)
"Convert size*size array to grayscale PBM image and show it."
(insert-image (create-image (concat (format "P2
%i %i 255\n" size size) (pic-lines arr size)) 'pbm t)))
(defun sphere (size k amb dir)
"Draw a sphere."
(let ((arr (make-array size))
(ndir (normalize dir))
(r (/ size 2)))
(dotimes (yp size)
(dotimes (xp size)
(setq x (- xp r))
(setq y (- yp r))
(setq z (- (* r r) (* x x) (* y y)))
(if (>= z 0)
(let* ((vec (normalize (list x y (sqrt z))))
(s (max 0 (dot vec ndir)))
(lum (max 0 (min 255 (* 255 (+ amb (expt s k))
(/ (1+ amb)))))))
(setf (elt (elt arr yp) xp) lum)))))
(pic-show arr size)))
(sphere 200 1.5 0.2 '(-30 -30 50))</syntaxhighlight>
=={{header|ERRE}}==
Using ASCII art: output is written to 'SPHERE.PRN' sequential file.
<
CONST SHADES$=".:!*oe&#%@"
Line 2,130 ⟶ 2,372:
CLOSE(1)
END PROGRAM
</syntaxhighlight>
{{out}}
<pre> !::::::!!!**o
Line 2,196 ⟶ 2,438:
</pre>
=={{header|Evaldraw}}==
Draw a sphere. We dont need to wrap the main () function with braces if we have no functions.
[[File:Evaldraw draw sphere.png|thumb|alt=A red sphere on a black background.|A red sphere, 5 units in front of camera.]]
<syntaxhighlight lang="C">
()
cls(0);
clz(1e32);
setcam(0,0,-5,0,0);
setcol(128,64,64);
drawsph(0,0,0,1);
</syntaxhighlight>
=={{header|Factor}}==
{{libheader|raylib}}
{{works with|Factor|0.99 2020-03-02}}
<
640 480 "sphere" init-window
Line 2,221 ⟶ 2,478:
end-mode-3d
end-drawing
] until drop close-window</
{{out}}
[https://i.imgur.com/FXHkZm6.png]
=={{header|
{{works with|gforth|0.7.3}}
Inspired by C version but simplified.
Traditionaly, Forth use Fixed-Point Arithmetic (here with a 1000 scale). Integer square root function is hand coded.
===ASCII output===
<syntaxhighlight lang="forth">: 3dup 2 pick 2 pick 2 pick ;
: sqrt ( u -- sqrt ) ( Babylonian method )
dup 2/ ( first square root guess is half )
dup 0= if drop exit then ( sqrt[0]=0, sqrt[1]=1 )
begin dup >r 2dup / r> + 2/ ( stack: square old-guess new-guess )
2dup > while ( as long as guess is decreasing )
nip repeat ( forget old-guess and repeat )
drop nip ;
: normalize ( x1 y1 z1 -- x1' y1' z1' ) ( normalise down to 1000 )
3dup dup * rot dup * rot dup * + + sqrt 1000 / >r ( length )
r@ / rot r@ / rot r> / rot ;
: r2-y2-x2 ( x y r -- z2 ) dup * swap dup * - swap dup * - ;
: shade ( u -- c ) C" @#&eo%*!:. " + c@ ;
: map-to-shade ( u -- u ) 0 shade * 1000 / 1 max 0 shade min ;
: dot-light ( x y z -- i ) ( hard coded light vector z, y, x )
-770 * rot 461 * rot 461 * + +
0 min 1000 / ;
: intensity ( x y z -- u ) dot-light dup * 1000 / map-to-shade ;
: pixel ( x y r -- c )
3dup r2-y2-x2 dup 0> if ( if in disk )
sqrt nip normalize intensity shade ( z=sqrt[r2-x2-y2] )
else 2drop 2drop bl ( else blank )
then ;
: draw ( r -- ) ( r x1000 )
1000 * dup dup negate do
cr
dup dup negate do
dup I 500 + J 500 + rot pixel emit
500 +loop
1000 +loop drop ;
20 draw
10 draw</syntaxhighlight>
{{out}}
<pre> eeooooeeeeee&&&##
o%%%%******%%%%%%ooooeee&&&##@@
o%**!!!!!!!!!!!!*****%%%%oooeee&&&##@@@
%*!!!:::::::::::::!!!!!****%%%oooeee&&&##@@@@
%*!!:::............:::::!!!!****%%%oooeee&&###@@@@@
%*!::...... ........::::!!!!***%%%oooeee&&&##@@@@@@
%!!::... .....::::!!!!***%%%oooeee&&&##@@@@@@@
%*!::... .....::::!!!****%%%oooee&&&###@@@@@@@@
*!::... .....:::!!!!***%%%oooeee&&&###@@@@@@@@
o*!::.. .....::::!!!***%%%oooeee&&&###@@@@@@@@@@
o*!::.. .....::::!!!***%%%oooeee&&&####@@@@@@@@@@
o*!::... ....::::!!!!***%%%oooeee&&&&###@@@@@@@@@@@
o*!!::.. .....::::!!!****%%%oooeee&&&####@@@@@@@@@@@@
%*!::... .....::::!!!!***%%%%oooeee&&&####@@@@@@@@@@@@
o%*!::.... .....::::!!!!****%%%oooeeee&&&###@@@@@@@@@@@@@@
%**!:::.... ......::::!!!!****%%%ooooeee&&&####@@@@@@@@@@@@@@
e%**!!::..... .......:::::!!!!****%%%ooooeee&&&&####@@@@@@@@@@@@@@@
o%**!!::::.....................:::::!!!!*****%%%ooooeee&&&&####@@@@@@@@@@@@@@@@
o%%**!!:::::...............:::::::!!!!!****%%%%ooooeeee&&&####@@@@@@@@@@@@@@@@@
eo%***!!!:::::::......:::::::::!!!!!!****%%%%%ooooeee&&&&####@@@@@@@@@@@@@@@@@@
eo%%***!!!!:::::::::::::::::!!!!!!******%%%%ooooeeee&&&&####@@@@@@@@@@@@@@@@@@@
eeo%%****!!!!!!!!::::!!!!!!!!!!******%%%%%oooooeeee&&&&####@@@@@@@@@@@@@@@@@@@@
&eoo%%%*****!!!!!!!!!!!!!!!********%%%%%oooooeeee&&&&&####@@@@@@@@@@@@@@@@@@@@@
#&eooo%%%%*********************%%%%%%ooooooeeee&&&&&#####@@@@@@@@@@@@@@@@@@@@@@
&&eeooo%%%%%%************%%%%%%%%ooooooeeeee&&&&&#####@@@@@@@@@@@@@@@@@@@@@@@
#&&eeeoooo%%%%%%%%%%%%%%%%%%%oooooooeeeeee&&&&&#####@@@@@@@@@@@@@@@@@@@@@@@@@
##&&eeeeoooooooooooooooooooooooeeeeeee&&&&&&#####@@@@@@@@@@@@@@@@@@@@@@@@@@
@##&&&eeeeeeooooooooooooooeeeeeeeee&&&&&&######@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@##&&&&&eeeeeeeeeeeeeeeeeeee&&&&&&&&#######@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@###&&&&&&&&&&&&&&&&&&&&&&&&&&########@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@######&&&&&&&&&&&&&&&##########@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@#######################@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@########@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@
o%%%%%%ooe&#@
*!::...:::!!*%%oe&&#@
*:. ..::!!*%ooe&#@@@
*: ..:!!*%ooe&#@@@@
!. ..::!*%%oe&&#@@@@
!. ..::!*%%oee&#@@@@@
!: ..:!!*%%oe&&#@@@@@@
%!. ..:!!**%ooe&&#@@@@@@@
%!:. ..::!!**%ooe&&##@@@@@@@
%!::.. ...:::!!*%%ooee&##@@@@@@@@
o*!!::.......:::!!!**%%oee&&##@@@@@@@@@
eo%*!!!!:::!!!!!**%%%ooee&&##@@@@@@@@@@
#eo%%**********%%%ooeee&&##@@@@@@@@@@@@
#&eooo%%%%%%ooooeee&&&###@@@@@@@@@@@@
##&&eeeeeeeeee&&&&###@@@@@@@@@@@@@@
@@##&&&&&&&&#####@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@ ok</pre>
===PGM output===
The same program as the ASCII one is translated to produce a PGM portable pixmap image file.
<syntaxhighlight lang="forth">: 3dup 2 pick 2 pick 2 pick ;
: sqrt ( u -- sqrt ) ( Babylonian method )
dup 2/ ( first square root guess is half )
dup 0= if drop exit then ( sqrt[0]=0, sqrt[1]=1 )
begin dup >r 2dup / r> + 2/ ( stack: square old-guess new-guess )
2dup > while ( as long as guess is decreasing )
nip repeat ( forget old-guess and repeat )
drop nip ;
: normalize ( x1 y1 z1 -- x1' y1' z1' ) ( normalise down to 1000 )
3dup dup * rot dup * rot dup * + + sqrt 1000 / >r ( length )
r@ / rot r@ / rot r> / rot ;
: r2-y2-x2 ( x y r -- z2 ) dup * swap dup * - swap dup * - ;
0 value fileidstore
: image-open ( r -- )
outfile-id to fileidstore
s" sphere.pgm" w/o create-file throw to outfile-id
s\" P2\n" type 2* dup . .
s\" \n255" type ;
: image-close outfile-id close-file throw fileidstore to outfile-id ;
: map-to-shade 255 * 1000 / 1 max 255 min ;
: dot-light ( x y z -- i ) ( hard coded light vector z, y, x )
-770 * rot 461 * rot 461 * + +
0 min 1000 / ;
: intensity ( x y z -- u ) dot-light dup * 1000 / map-to-shade ;
: pixel ( x y r -- c )
3dup r2-y2-x2 dup 0> if ( if in disk )
sqrt nip normalize intensity ( z=sqrt[r2-x2-y2] )
else 2drop 2drop 255 ( else blank )
then ;
: draw ( r -- ) ( r x1000 )
dup image-open
1000 * dup dup negate do
cr
dup dup negate do
dup I 500 + J 500 + rot pixel .
1000 +loop
1000 +loop drop image-close ;
200 draw</syntaxhighlight>
=={{header|Frink}}==
This program not only draws a sphere and renders it onscreen projected on the x,y, and z axes but also outputs a <CODE>.stl</CODE> file for 3-D printing or display in a 3-D modeling package like MeshLab! Frink has [https://frinklang.org/3d/frink/graphics/package-summary.html built-in routines for 3-D modeling] and can emit STL files or Wavefront OBJ files natively! Frink will let you print a sphere that you can hold in your hand!
<syntaxhighlight lang="frink">res = 254 / in
v = callJava["frink.graphics.VoxelArray", "makeSphere", [1/2 inch res]]
v.projectX[undef].show["X"]
v.projectY[undef].show["Y"]
v.projectZ[undef].show["Z"]
filename = "sphere.stl"
print["Writing $filename..."]
w = new Writer[filename]
w.println[v.toSTLFormat["sphere", 1/(res mm)]]
w.close[]
println["done."]</syntaxhighlight>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
_window = 1
begin enum output 1
_sphereImageView
end enum
void local fn BuildWindow
CGRect r = fn CGRectMake( 0, 0, 400, 400 )
window _window, @"Rosetta Code Sphere", r, NSWindowStyleMaskTitled + NSWindowStyleMaskClosable
r = fn CGRectMake( 20, 20, 360, 360 )
imageview _sphereImageView, YES, , r, NSImageScaleAxesIndependently, NSImageAlignCenter, NSImageFrameNone, _window
end fn
local fn SphereImageWithCIFilter( imageDimension as NSUInteger, sphereColor as ColorRef, backgroundColor as ColorRef, radiusBlur as float, radiusSphere as float ) as ImageRef
CIVectorRef civ = fn CIVectorWithXY( imageDimension/2, imageDimension/2 )
CIFilterRef filter = fn CIFilterWithName( @"CIRadialGradient" )
CIFilterSetDefaults( filter )
ObjectSetValueForKey( filter, civ, @"inputCenter" )
ObjectSetValueForKey( filter, fn NumberWithFloat( radiusBlur ), @"inputRadius0" )
ObjectSetValueForKey( filter, fn NumberWithFloat( radiusSphere ), @"inputRadius1" )
ObjectSetValueForKey( filter, fn CIColorWithCGColor( fn ColorCGColor( sphereColor ) ), @"inputColor0" )
ObjectSetValueForKey( filter, fn CIColorWithCGColor( fn ColorCGColor( backgroundColor ) ), @"inputColor1" )
ImageRef resultImage = fn ImageWithSize( fn CGSizeMake( imageDimension, imageDimension ) )
ImageLockFocus( resultImage )
CIImageDrawAtPoint( fn CIFilterOutputImage( filter ), CGPointZero, fn CGRectMake( 0, 0, imageDimension, imageDimension ), NSCompositeDestinationAtop, 1.0 )
ImageUnlockFocus( resultImage )
end fn = resultImage
local fn BuildSphere
ImageRef sphereImage = fn SphereImageWithCIFilter( 340, fn ColorWithRGB( 0.988, 0.335, 0.176, 1.0 ), fn ColorBlack, 0.0, 125.0 )
ImageViewSetImage( _sphereImageView, sphereImage )
end fn
fn BuildWindow
fn BuildSphere
HandleEvents
</syntaxhighlight>
{{output}}
[[File:Rosetta Code Sphere.png]]
=={{header|Go}}==
Line 2,307 ⟶ 2,709:
{{trans|C}}
Using image library rather than ASCII art.
<
import (
Line 2,374 ⟶ 2,776:
fmt.Println(err)
}
}</
=={{header|Haskell}}==
[[File:Sphere_Haskell.png|thumb|right]]
<
import Graphics.UI.GLUT.Objects
import Graphics.UI.GLUT
Line 2,425 ⟶ 2,827:
setMaterial
displayCallback $= display
mainLoop</
=== ASCII art ===
{{trans|Python}}
<syntaxhighlight lang="haskell">import Data.List (genericLength)
shades = ".:!*oe%#&@"
n = genericLength shades
dot a b = sum $ zipWith (*) a b
normalize x = (/ sqrt (x `dot` x)) <$> x
sphere r k amb light = unlines $
[ [ if x*x + y*y <= r*r
then let vec = normalize [x, y, sqrt (r*r-x*x-y*y)]
b = (light `dot` vec) ** k + amb
intensity = (1 - b)*(n - 1)
in shades !! round ((0 `max` intensity) `min` n)
else ' '
| y <- map (/2.12) [- 2*r - 0.5 .. 2*r + 0.5] ]
| x <- [ - r - 0.5 .. r + 0.5] ]</syntaxhighlight>
<pre>λ> putStrLn $ sphere 10 4 0.1 (normalize [30,30,-50])
#%%%%%%%####&&
eoo*****oooee%%%###&&&
eo*!!::::!!!**ooee%%%###&&&&
e*!::......::!!**ooee%%####&&&&&
%o!::.........::!!**ooee%%###&&&&&&&
eo!::..........::!!**ooee%%###&&&&&&&&
%o*!:..........::!!**ooee%%%###&&&&&&&&&
#eo*!::.......:::!!**ooeee%%####&&&&&&&&&&
%eo*!!:::::::::!!***ooeee%%####&&&&&&&&&&&
%eeo**!!!!!!!!****ooeee%%%####&&&&&&&&&&&&
#%eeooo*******ooooeee%%%%####&&&&&&&&&&&&&
##%%eeeoooooooeeeee%%%%####&&&&&&&&&&&&&&&
&###%%%%eeeeee%%%%%%######&&&&&&&&&&&&&&&#
&&####%%%%%%%%########&&&&&&&&&&&&&&&&&&
&&&##############&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&#
</pre>
==Icon and {{header|Unicon}}==
Unicon provides a built-in interface to openGL including some higher level abstractions (for more information see [[Icon%2BUnicon/Intro#Graphics.2C_Network_Messaging.2C_etc.|Unicon Technical References, 3D Graphics]]). The example below draws a blue sphere on a black background and waits for input to quit.[[File:Sphere_unicon.PNG|thumb|Unicon Sphere]]
<
W := open("Demo", "gl", "size=400,400", "bg=black") | stop("can't open window!")
WAttrib(W, "slices=40", "rings=40", "light0=on, ambient white; diffuse gold; specular gold; position 5, 0, 0" )
Line 2,436 ⟶ 2,884:
DrawSphere(W, 0, 0, -5, 1)
Event(W)
end</
<div style="border: 1px solid #000000; overflow: auto; width: 100%"></div>
=={{header|J}}==
===Demo Solution===
[[File:J-sphere.png|thumb|J Sphere]]
Line 2,459 ⟶ 2,902:
But bringing up the example with a line of code is trivial enough:
<
(Note that this example has been removed from recent versions of J, but still works for J version 5 and version 6.)
<div style="border: 1px solid #000000; overflow: auto; width: 100%"></div>
Line 2,466 ⟶ 2,911:
Here's a version using raytracing computed in J. luminosity is an array of luminosity values with theoretical maximum 1 and minimum 0, and viewmat is used to display this.
<
light =. (% +/&.:*:) 30 30 _50
pts =. (0&*^:(0={:))@:(,,(0>.(*:R)-+)&.*:)"0/~ i:15j200
Line 2,473 ⟶ 2,918:
load 'viewmat'
torgb =. 256 #. [: <. 255 255 255 *"1 0 ]
'rgb' viewmat torgb luminosity</
=={{header|Java}}==
{{trans|C}}
<
static char[] shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'};
Line 2,519 ⟶ 2,964:
drawSphere(10, 2, .4);
}
}</
{{out}}
<pre> &&&&&&&&&&#######
Line 2,590 ⟶ 3,035:
This Javascript entry uses an HTML wrapper to offer easy running and some interactivity. It is made as such, though, that the entire HTML wrapper can be removed (except for a canvas with id <code>c</code>) and still work. If you remove the HTML, call the <code>draw_sphere</code> function to draw the thing.
<
<html>
<head>
Line 2,651 ⟶ 3,096:
<canvas id="c">Unsupportive browser...</canvas><br>
</body>
</html></
=={{header|jq}}==
{{works with|jq|1.4}}
The approach adopted here is to generate an SVG file, which may then be viewed, for example, in a web browser.
<
"<svg width='100%' height='100%' version='1.1'
xmlns='http://www.w3.org/2000/svg'
Line 2,674 ⟶ 3,119:
def sphere(cx; cy; r; gradientId):
"<circle fill='url(#\(gradientId))' cx='\(cx)' cy='\(cy)' r='\(r)' />" ;</
'''Example:'''
<
svg,
"<title>Teal sphere</title>",
Line 2,685 ⟶ 3,130:
"</svg>" ;
draw_sphere</
{{out}}
<
One way to view the output as an image is to point your browser to the generated SVG.
Line 2,694 ⟶ 3,139:
===ASCII Text===
{{trans|C}}
<
shades = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@')
for i in floor(Int, -r):ceil(Int, r)
Line 2,721 ⟶ 3,166:
draw_sphere(20, 4, 0.1, light)
draw_sphere(10, 2, 0.4, light)
</syntaxhighlight>
===Graphical===
<
using Makie
Line 2,736 ⟶ 3,181:
surface(x, y, z, backgroundcolor = :black, show_axis = false)
</syntaxhighlight>
=={{header|Kotlin}}==
{{trans|C}}
<
const val shades = ".:!*oe&#%@"
Line 2,786 ⟶ 3,231:
drawSphere(20.0, 4.0, 0.1)
drawSphere(10.0, 2.0, 0.4)
}</
{{out}}
Line 2,854 ⟶ 3,299:
=={{header|Lingo}}==
<
-- Draw a circle
-- @param {image} img
Line 2,869 ⟶ 3,314:
props[#color] = drawColor
img.draw(x-r, y-r, x+r, y+r, props)
end</
=={{header|Logo}}==
Line 2,876 ⟶ 3,321:
{{works with|MSWlogo}}
<
cs perspective ht ;making the room ready to use
repeat 180 [polystart circle :r polyend down 1]
polyview
end</
=={{header|Lua}}==
{{trans|C}}
{{works with|Lua|5.1.4}}
<
shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'}
Line 2,921 ⟶ 3,366:
draw_sphere (20, 4, 0.1)
draw_sphere (10, 2, 0.4)</
{{out}}
<pre> &&&&&&&&&&&&#####
Line 2,987 ⟶ 3,432:
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Er$="Pset is a new statement"
Line 3,047 ⟶ 3,492:
}
Checkit
</syntaxhighlight>
[[https://2.bp.blogspot.com/-ZWy2xDxXbzg/W98lAuNSY9I/AAAAAAAAHZ0/DFYluvWtz_cwwAUKfblujnW6mTC5XVs1QCLcBGAs/s1600/sphere.png]image]
Line 3,053 ⟶ 3,498:
=={{header|Maple}}==
[[File:Sphere_Maple.png|thumb]]
<
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica has many 3D drawing capabilities. To create a sphere with radius one centered at (0,0,0):
<
=={{header|MATLAB}}==
To create the unit sphere:
<syntaxhighlight lang
=={{header|Maxima}}==
<
plot3d(1, [theta, 0, %pi], [phi, 0, 2 * %pi],
[transform_xy, spherical_to_xyz], [grid, 30, 60],
Line 3,074 ⟶ 3,519:
sin(phi)*sin(theta),
cos(theta),
theta, 0, %pi, phi, 0, 2 * %pi))$</
=={{header|Nim}}==
{{trans|C}}
<
type Point = tuple[x,y,z: float]
Line 3,093 ⟶ 3,538:
let light = normalize(30.0, 30.0, -50.0)
proc drawSphere(r
for i in -r .. r:
let x = i.float + 0.5
Line 3,108 ⟶ 3,553:
drawSphere 20, 4.0, 0.1
drawSphere 10, 2.0, 0.4</
{{out}}
<pre> &&&&&&&&&&#######
Line 3,174 ⟶ 3,619:
=={{header|Ol}}==
{{libheader|OpenGL}}
<
(import (lib gl))
(import (OpenGL version-1-0))
Line 3,191 ⟶ 3,636:
(gluSphere quadric 0.4 32 10)
))
</syntaxhighlight>
=={{header|Openscad}}==
Drawing a sphere is easy in openscad:
<
sphere(5);</
[[Category:Geometric Primitives]]
=={{header|OxygenBasic}}==
Using an OpenGl-based console
<syntaxhighlight lang="text">
% Title "Sphere"
'% Animated
% PlaceCentral
uses ConsoleG
sub main
========
cls 0.0, 0.2, 0.7
shading
scale 10
pushstate
GoldMaterial.act
go sphere
popstate
end sub
EndScript
</syntaxhighlight>
=={{header|Pascal}}==
Line 3,210 ⟶ 3,677:
This produces a PGM image which can't be uploaded on rosettacode at the moment. It looks similar as the Raku solution, though.
<
use warnings;
Line 3,260 ⟶ 3,727:
},
q{""} => sub { sprintf "Vector:[%s]", join ' ', @{shift()} };
}</
=={{header|Phix}}==
{{libheader|Phix/pGUI}}
{{libheader|Phix/online}}
{{trans|Go}} (Go gets credit for the dot/normalize/drawSphere routines, but this draws on screen rather than to png file)
Sphere will resize to match the window.
You can run this online [http://phix.x10.mx/p2js/drawsphere.htm here]. Note fullscreen redraw can be quite slow.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Draw_a_sphere.exw
-- ==============================
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">include</span> <span style="color: #000000;">pGUI</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">title</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Draw a sphere"</span>
<span style="color: #004080;">Ihandle</span> <span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">canvas</span>
<span style="color: #004080;">cdCanvas</span> <span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">dot</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">normalize</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">len</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dot</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">return</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">len</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?{</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">}:</span><span style="color: #7060A8;">sq_mul</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">/</span><span style="color: #000000;">len</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">drawSphere</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">width</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">amb</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">direction</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">t0</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">lmul</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">255</span><span style="color: #0000FF;">/(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">amb</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #7060A8;">min</span><span style="color: #0000FF;">(</span><span style="color: #000000;">width</span><span style="color: #0000FF;">,</span><span style="color: #000000;">height</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">20</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">cx</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">width</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">cy</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">height</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">r</span> <span style="color: #008080;">to</span> <span style="color: #000000;">r</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()></span><span style="color: #000000;">t1</span> <span style="color: #008080;">then</span>
<span style="color: #000080;font-style:italic;">-- Let the user know we aren't completely dead just yet</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s - drawing (%d%%)"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">title</span><span style="color: #0000FF;">,</span><span style="color: #000000;">100</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)/(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)})</span>
<span style="color: #000000;">t1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()+</span><span style="color: #000000;">1</span>
<span style="color: #000080;font-style:italic;">-- (as per DeathStar.exw, prevent "(Not Responding)" nonsense)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">IupLoopStep</span><span style="color: #0000FF;">()=</span><span style="color: #004600;">IUP_CLOSE</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupExitLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">exit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">r</span> <span style="color: #008080;">to</span> <span style="color: #000000;">r</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">z</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">*</span><span style="color: #000000;">r</span><span style="color: #0000FF;">-(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">*</span><span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">y</span><span style="color: #0000FF;">*</span><span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">z</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dot</span><span style="color: #0000FF;">(</span><span style="color: #000000;">direction</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">normalize</span><span style="color: #0000FF;">({</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">z</span><span style="color: #0000FF;">)})),</span>
<span style="color: #000000;">l</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #000000;">0</span><span style="color: #0000FF;">:</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">k</span><span style="color: #0000FF;">))</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">lum</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">#FF</span><span style="color: #0000FF;">,</span><span style="color: #000000;">lmul</span><span style="color: #0000FF;">*(</span><span style="color: #000000;">l</span><span style="color: #0000FF;">+</span><span style="color: #000000;">amb</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">cdCanvasPixel</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">+</span><span style="color: #000000;">cx</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">y</span><span style="color: #0000FF;">+</span><span style="color: #000000;">cy</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">lum</span><span style="color: #0000FF;">*</span><span style="color: #000000;">#10101</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">t1</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">t0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupSetStrAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"TITLE"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">title</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">redraw_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000080;font-style:italic;">/*posx*/</span><span style="color: #0000FF;">,</span> <span style="color: #000080;font-style:italic;">/*posy*/</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">width</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">height</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupGetIntInt</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"DRAWSIZE"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasActivate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasClear</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">drawSphere</span><span style="color: #0000FF;">(</span><span style="color: #000000;">width</span><span style="color: #0000FF;">,</span><span style="color: #000000;">height</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1.5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0.2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">normalize</span><span style="color: #0000FF;">({-</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">30</span><span style="color: #0000FF;">,</span><span style="color: #000000;">50</span><span style="color: #0000FF;">}))</span>
<span style="color: #7060A8;">cdCanvasFlush</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">map_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cdcanvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_IUP</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ih</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">cddbuffer</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">cdCreateCanvas</span><span style="color: #0000FF;">(</span><span style="color: #004600;">CD_DBUFFER</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">cdcanvas</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">cdCanvasSetBackground</span><span style="color: #0000FF;">(</span><span style="color: #000000;">cddbuffer</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">CD_BLACK</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_DEFAULT</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupOpen</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">canvas</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupCanvas</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"RASTERSIZE=340x340"</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetCallbacks</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"MAP_CB"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"map_cb"</span><span style="color: #0000FF;">),</span>
<span style="color: #008000;">"ACTION"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"redraw_cb"</span><span style="color: #0000FF;">)})</span>
<span style="color: #000000;">dlg</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">IupDialog</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span><span style="color: #008000;">`TITLE="%s"`</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">title</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">IupShow</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">IupSetAttribute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">canvas</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"RASTERSIZE"</span><span style="color: #0000FF;">,</span> <span style="color: #004600;">NULL</span><span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- release the minimum limitation</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">platform</span><span style="color: #0000FF;">()!=</span><span style="color: #004600;">JS</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">IupMainLoop</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">IupClose</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
=={{header|PicoLisp}}==
{{libheader|GLUT}}
This is for the 64-bit version.
<
(glutInit)
Line 3,365 ⟶ 3,852:
# Exit upon mouse click
(mouseFunc '((Btn State X Y) (bye)))
(glutMainLoop)</
{{trans|C}}
<
(setq *Shades
Line 3,428 ⟶ 3,915:
(setq *Light (normalize *Light))
(drawSphere 20.0 4 0.1)
(drawSphere 10.0 2 0.4)</
{{out}}
<pre> ##############%%%
Line 3,498 ⟶ 3,985:
=={{header|PostScript}}==
Gradient filled circle:
<
%%BoundingBox 0 0 300 300
Line 3,521 ⟶ 4,008:
showpage
%%EOF
</syntaxhighlight>
=={{header|POV-Ray}}==
Line 3,527 ⟶ 4,014:
This is what POVray was made for. An example with a sky, surface and transparency:
<syntaxhighlight lang="povray">
camera { location <0.0 , .8 ,-3.0> look_at 0}
Line 3,543 ⟶ 4,030:
interior { ior 1.5}
}
</syntaxhighlight>
Yields this:
Line 3,552 ⟶ 4,039:
3D rendering is built into Processing.
<
size(500, 500, P3D);
}
Line 3,564 ⟶ 4,051:
// draw sphere
sphere(200);
}</
A sphere build from triangles (to for instance allow distortion)
<
PVector[][] sphere;
Line 3,610 ⟶ 4,097:
rotY -= (mouseX - pmouseX) * 0.01;
rotX -= (mouseY - pmouseY) * 0.01;
}</
=={{header|Python}}==
===Ascii-Art===
{{trans|C}}
<
shades = ('.',':','!','*','o','e','&','#','%','@')
Line 3,646 ⟶ 4,133:
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)</
{{out}}
<pre> &&&&&&&&&&######
Line 3,716 ⟶ 4,203:
This code contains unnecessary functions which are part of a 3D graphics library I wrote. <br>
Uses Pygame and Python 3.2.2
<
import pygame
from pygame.locals import *
Line 3,723 ⟶ 4,210:
import random
import math
</syntaxhighlight>
<
class Tricubic:
def __init__(self,pts):
Line 4,496 ⟶ 4,983:
if event.type == KEYDOWN:
pass
</syntaxhighlight>
==={{libheader|VPython}}===
{{works with|Python|2.7.5}}
'''Short version''':
<
scene.title = "VPython: Draw a sphere"
sphere() # using defaults, see http://www.vpython.org/contents/docs/defaults.html </
'''Regular version''', with some window-dressing:
<
from __future__ import print_function, division
from visual import *
Line 4,529 ⟶ 5,016:
rate(100)
pass # no animation in this demo
</syntaxhighlight>
=={{header|Racket}}==
Line 4,537 ⟶ 5,024:
Using the Typed Racket language with the plot library:
<
#lang typed/racket
(require plot/typed)
(plot3d (polar3d (λ (θ ρ) 1)) #:altitude 25)
</syntaxhighlight>
=={{header|Raku}}==
Line 4,554 ⟶ 5,041:
[[File:Sphere-perl6.png|thumb]]
<syntaxhighlight lang="raku"
my @light = normalize([ 3, 2, -5 ]);
Line 4,591 ⟶ 5,078:
}
flat |@pixels.map: *.list;
}</
===Cairo graphics library===
<syntaxhighlight lang="raku"
given Cairo::Image.create(Cairo::FORMAT_ARGB32, 256, 256) {
Line 4,624 ⟶ 5,111:
};
.write_png('sphere2-perl6.png');
}</
See [https://github.com/thundergnat/rc/blob/master/img/sphere2-perl6.png sphere2-perl6.png] (offsite .png image)
Line 4,634 ⟶ 5,121:
Programming note: the output will appear slightly different when executed on an EBCDIC machine (due to different dithering characters).
<
call drawSphere 19, 4, 2/10, '30 30 -50' /*draw a sphere with a radius of 19. */
call drawSphere 10, 2, 4/10, '30 30 -50' /* " " " " " " " ten. */
Line 4,668 ⟶ 5,155:
numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g= g*.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g</
{{out|output|text= when using the default input and executed on an '''ASCII''' machine:}}
(Shown at <big>'''<sup>1</sup>/<sub>2</sub>'''</big> size.)
Line 4,738 ⟶ 5,225:
Shoes comes with this sample program.
[[File:sphere.shoes.png|thumb|right]]
<
image 400, 470, :top => 30, :left => 50 do
nostroke
Line 4,765 ⟶ 5,252:
end
end
end</
=={{header|Rust}}==
{{trans|Go}}
<
// image = "0.23"
Line 4,830 ⟶ 5,317:
Err(error) => eprintln!("{}", error),
}
}</
{{out}}
[[Media:Draw a sphere rust.png]]
=={{header|Scala}}==
<
private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d))
Line 4,869 ⟶ 5,356:
drawSphere(10, 2, .4)
}</
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/uSm8bJ9/0 ScalaFiddle (JavaScript)] or by [https://scastie.scala-lang.org/TtVHUp3aS0eDEB6YCW4gKg Scastie (JVM)].
Line 4,875 ⟶ 5,362:
{{trans|Raku}}
Produces a PGM image.
<
func dot (x, y) { -(x »*« y -> sum) `max` 0 }
Line 4,907 ⟶ 5,394:
out.say("P5\n#{x} #{y}\n#{depth}") # .pgm header
out.print(draw_sphere((x-1)/2, .9, .2).map{.chr}.join)
out.close</
=={{header|Smalltalk}}==
Line 4,915 ⟶ 5,402:
{{works with|Smalltalk/X}}
although there is a Point3 class in some loadable library, here is some self contained code, defining a local anon Point3D class.
<syntaxhighlight lang="smalltalk">
Point3D :=
Point subclass:#Point3D
Line 4,979 ⟶ 5,466:
main value.
</syntaxhighlight>
[[file:sphere-smalltalk.png]]
Line 4,988 ⟶ 5,475:
=={{header|Swift}}==
In Playground for example:
<syntaxhighlight lang="swift">
class Sphere: UIView{
Line 5,020 ⟶ 5,507:
var s = Sphere(frame: CGRectMake(0, 0, 200, 200))
</syntaxhighlight>
In SwiftUI:
<syntaxhighlight lang="swift">
struct ContentView: View {
Line 5,037 ⟶ 5,524:
}
}
</syntaxhighlight>
=={{header|Tcl}}==
Line 5,043 ⟶ 5,530:
Assuming the task is to draw a <i>likeness</i> of a sphere, this would usually do:
<
pack [canvas .c -height 400 -width 640 -background white]
Line 5,051 ⟶ 5,538:
.c create arc [expr {100+$i/5}] [expr {50+$i/5}] [expr {400-$i/1.5}] [expr {350-$i/1.5}] \
-start 0 -extent 359 -fill $h -outline $h
}</
Results in this image:
[[image:Tcl-spheroid.gif]]
=={{header|
{{libheader|PGF}}
The PGF <code>shadings</code> library includes a "ball" for a 3-D style highlight.
<
\usepackage{tikz}
\usetikzlibrary{shadings}
\begin{document}
\begin{tikzpicture}
\shade[ball color=black] (0,0) circle (4);
\end{tikzpicture}
\end{document}</
=={{header|Turing}}==
Translated and optimized from the Algol W solution and others posted here.
<syntaxhighlight lang="turing">% 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)</syntaxhighlight>
{{Out}}
<pre>
###############%%
#&&&eeeeeeeeee&&&&&&#######%%%%
&&eeeoooooooooooooeeeee&&&&&######%%%%%
&eeooo**************oooooeeee&&&&&#####%%%%%%
&eoo***!!!!!!!!!!!!!!!*****ooooeee&&&&&#####%%%%%%%
&eo**!!!:::::::::::::::!!!!****oooeeee&&&&######%%%%%%%
&eo**!!:::.............::::!!!!***ooooeee&&&&######%%%%%%%%
&eo**!!::..................::::!!!***ooooeee&&&&######%%%%%%%%%
&oo*!!::.....................::::!!!***oooeeee&&&&#####%%%%%%%%%%
#eo**!::........................:::!!!!***oooeee&&&&######%%%%%%%%%%%
&eo**!::.........................::::!!!***oooeeee&&&&#####%%%%%%%%%%%%
&eoo*!!::.........................::::!!!***oooeeee&&&&######%%%%%%%%%%%%
#&eo*!!::..........................:::!!!!***oooeeee&&&&######%%%%%%%%%%%%%
&eo**!!::.........................::::!!!***ooooeee&&&&&######%%%%%%%%%%%%%
&eeo**!!::.........................:::!!!****oooeeee&&&&#######%%%%%%%%%%%%%%
&eeo**!!::.......................::::!!!!***ooooeee&&&&&######%%%%%%%%%%%%%%%
#&eeo**!!:::.....................::::!!!****ooooeeee&&&&#######%%%%%%%%%%%%%%%%
#&eeoo**!!::::................:::::!!!!****ooooeeee&&&&&######%%%%%%%%%%%%%%%%%
#&eeoo***!!!:::::.........:::::::!!!!****oooooeeee&&&&&#######%%%%%%%%%%%%%%%%%
#&&eeoo***!!!!::::::::::::::::!!!!!*****ooooeeeee&&&&&#######%%%%%%%%%%%%%%%%%%
#&&eeeoo****!!!!!!!:::::!!!!!!!!******ooooeeeee&&&&&&#######%%%%%%%%%%%%%%%%%%%
##&&eeeooo*****!!!!!!!!!!!!!*******oooooeeeeee&&&&&########%%%%%%%%%%%%%%%%%%%%
###&&eeeooooo*******************ooooooeeeeee&&&&&&########%%%%%%%%%%%%%%%%%%%%%
%##&&&&eeeeooooooo********oooooooooeeeeee&&&&&&&#########%%%%%%%%%%%%%%%%%%%%%%
####&&&&eeeeeoooooooooooooooooeeeeeeee&&&&&&&#########%%%%%%%%%%%%%%%%%%%%%%%
%####&&&&&eeeeeeeeeeeeeeeeeeeeeeee&&&&&&&&##########%%%%%%%%%%%%%%%%%%%%%%%%%
%#####&&&&&&&&eeeeeeeeeeeeee&&&&&&&&&&&##########%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%######&&&&&&&&&&&&&&&&&&&&&&&&&&############%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%########&&&&&&&&&&&&&&&&&###############%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%##################################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%############################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%%%%#################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%
%%%%########%%%%%%%%%%%%%%%
%####&&&&&&&&#######%%%%%%%%%%%%%
%###&&eeeeooeeeee&&&#####%%%%%%%%%%%%%%
%##&eeoo********oooee&&&####%%%%%%%%%%%%%%%
%##&eo**!!::::::!!!**ooee&&#####%%%%%%%%%%%%%%%
%#&eo**!:.........::!**ooee&&####%%%%%%%%%%%%%%%%
##&eo*!:............:!!*ooee&&&####%%%%%%%%%%%%%%%%
%%#&eo*!:.............:!!**oee&&&####%%%%%%%%%%%%%%%%%%
%#&&eo*!:............::!!*ooee&&#####%%%%%%%%%%%%%%%%%%
%##&eoo*!:...........::!!**oee&&&####%%%%%%%%%%%%%%%%%%%%
%%##&eeo*!!:........:::!!*ooeee&&#####%%%%%%%%%%%%%%%%%%%%%
%%##&&eoo*!!::::::::!!!**ooee&&&#####%%%%%%%%%%%%%%%%%%%%%%
%%###&eeoo***!!!!!!***oooeee&&&#####%%%%%%%%%%%%%%%%%%%%%%%
%%%##&&&eeooooo**oooooeeee&&&######%%%%%%%%%%%%%%%%%%%%%%%%
%%%####&&&eeeeeeeeeeeee&&&&######%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%#####&&&&&&&&&&&&&&&#######%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%########&&&&###########%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%#####%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%
</pre>
=={{header|VBScript}}==
{{trans|C}}
<
light = Array(30, 30, -50)
Line 5,122 ⟶ 5,746:
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4</
{{Out}}
<pre> &&&&&&&&&&#######
Line 5,185 ⟶ 5,809:
eeeeeeeeeeeeeeeeeeeee
eeeeeeeeeeeee</pre>
=={{header|V (Vlang)}}==
Graphical
<syntaxhighlight lang="Zig">
import gg
import gx
const (
win_width = 600
win_height = 600
)
struct App {
mut:
gg &gg.Context = unsafe {nil}
}
fn main() {
mut app := &App{
gg: 0
}
app.gg = gg.new_context(
bg_color: gx.white
width: win_width
height: win_height
create_window: true
window_title: 'Circle'
frame_fn: frame
user_data: app
)
app.gg.run()
}
fn frame(app &App) {
app.gg.begin()
app.draw()
app.gg.end()
}
fn (app &App) draw() {
app.gg.draw_circle_filled(300, 300, 150, gx.red)
}
</syntaxhighlight>
=={{header|Wren}}==
{{trans|C}}
<
var light = [30, 30, -50]
Line 5,225 ⟶ 5,892:
normalize.call(light)
drawSphere.call(20, 4, 0.1)
drawSphere.call(10, 2, 0.4)</
{{out}}
Line 5,294 ⟶ 5,961:
=={{header|XPL0}}==
[[File:SphereXPL0.png|right]]
<
def R=100, R2=R*R; \radius, in pixels; radius squared
def X0=640/2, Y0=480/2; \coordinates of center of screen
Line 5,311 ⟶ 5,978:
repeat until KeyHit; \wait for keystroke
SetVid($03); \restore normal text mode
]</
=={{header|Yabasic}}==
<
open window 640,480
backcolor 16,16,16
Line 5,327 ⟶ 5,994:
fill circle ancho/2-2*n/3, alto/2-n/2, 150-n
next n
end sub</
=={{header|Zig}}==
{{trans|Factor}}
{{libheader|raylib}}
<syntaxhighlight lang="zig">
const std = @import("std");
const c = @cImport({
@cInclude("raylib.h");
});
pub fn main() !void {
c.SetConfigFlags(c.FLAG_WINDOW_RESIZABLE | c.FLAG_VSYNC_HINT);
c.InitWindow(600, 480, "Draw a Sphere");
defer c.CloseWindow();
const camera = c.Camera3D{
.position = .{ .x = 4.5, .y = 4.5, .z = 4.5 },
.target = .{ .x = 0, .y = 0, .z = 0 },
.up = .{ .x = 0, .y = 1, .z = 0 },
.fovy = 45.0,
.projection = c.CAMERA_PERSPECTIVE,
};
c.SetTargetFPS(60);
while (!c.WindowShouldClose()) {
c.BeginDrawing();
defer c.EndDrawing();
c.ClearBackground(c.BLACK);
{
c.BeginMode3D(camera);
defer c.EndMode3D();
c.DrawSphereWires(.{ .x = 0, .y = 0, .z = 0 }, 2, 20, 20, c.LIME);
}
}
}
</syntaxhighlight>
=={{header|zkl}}==
Line 5,333 ⟶ 6,040:
{{trans|XPL0}}
[[File:Sphere.zkl.jpg|200px|thumb|right]]
<
R:=100; R2:=R*R; //radius, in pixels; radius squared
X0:=640/2; Y0:=480/2; //coordinates of center of screen
Line 5,347 ⟶ 6,054:
}
}
img.write(File("foo.ppm","wb"));</
The radius of 100 is the max before the color calculation overflows 24 bits so for a radius (R) of, say 200, use
<
Perhaps a more useful solution is to use GnuPlot (I grabbed the code from http://ayapin-film.sakura.ne.jp/Gnuplot/):
[[File:GnuplotSphere.zkl.png|250px|thumb|right]]
<
cmd:=0'|
set term wxt
Line 5,374 ⟶ 6,081:
gnuplot:=System.popen("gnuplot","w");
gnuplot.write(cmd); gnuplot.flush();
ask("Hit return to finish"); gnuplot.close();</
Where "term wxt" is X11 on my Linux box. A window pops up and stays until the pipe is closed.
=={{header|ZX Spectrum Basic}}==
<
50 REM spheer with hidden lines and rotation
100 CLS
Line 5,429 ⟶ 6,136:
1050 LET yy=bx*x+by*y+bz*z
1060 LET zz=cx*x+cy*y+cz*z
1070 RETURN</
[[Category:Geometry]]
|