Draw a sphere: Difference between revisions

Content added Content deleted
(→‎{{header|DWScript}}: add Emacs Lisp)
m (syntax highlighting fixup automation)
Line 21: Line 21:
{{trans|Python}}
{{trans|Python}}


<lang 11l>V shades = [‘.’, ‘:’, ‘!’, ‘*’, ‘o’, ‘e’, ‘&’, ‘#’, ‘%’, ‘@’]
<syntaxhighlight lang="11l">V shades = [‘.’, ‘:’, ‘!’, ‘*’, ‘o’, ‘e’, ‘&’, ‘#’, ‘%’, ‘@’]


F dotp(v1, v2)
F dotp(v1, v2)
Line 46: Line 46:
V light = normalize((30.0, 30.0, -50.0))
V light = normalize((30.0, 30.0, -50.0))
draw_sphere(20, 4, 0.1, light)
draw_sphere(20, 4, 0.1, light)
draw_sphere(10, 2, 0.4, light)</lang>
draw_sphere(10, 2, 0.4, light)</syntaxhighlight>


{{out}}
{{out}}
Line 115: Line 115:


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>INT ARRAY SinTab=[
<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
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
88 92 96 100 104 108 112 116 120 124 128 132 136 139 143
Line 176: Line 176:
DO UNTIL CH#$FF OD
DO UNTIL CH#$FF OD
CH=$FF
CH=$FF
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Draw_a_sphere.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Draw_a_sphere.png Screenshot from Atari 8-bit computer]
Line 185: Line 185:
Uses the Cairo component of GtkAda to create and save as png
Uses the Cairo component of GtkAda to create and save as png
[[File:SphereAda.png|thumb|right]]
[[File:SphereAda.png|thumb|right]]
<lang Ada>with Glib; use Glib;
<syntaxhighlight lang="ada">with Glib; use Glib;
with Cairo; use Cairo;
with Cairo; use Cairo;
with Cairo.Png; use Cairo.Png;
with Cairo.Png; use Cairo.Png;
Line 214: Line 214:
Status_Out := Write_To_Png (Surface, "SphereAda.png");
Status_Out := Write_To_Png (Surface, "SphereAda.png");
pragma Assert (Status_Out = Cairo_Status_Success);
pragma Assert (Status_Out = Cairo_Status_Success);
end Sphere;</lang>
end Sphere;</syntaxhighlight>


{{libheader|Display}}
{{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
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">
<lang Ada>
with Display; use Display;
with Display; use Display;
with Display.Basic; use Display.Basic;
with Display.Basic; use Display.Basic;
Line 232: Line 232:
null;
null;
end Main;
end Main;
</syntaxhighlight>
</lang>


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
{{Trans|AWK}} with some changes inspired by other samples.
{{Trans|AWK}} with some changes inspired by other samples.
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% draw a sphere %
% draw a sphere %
% returns the next integer larger than x or x if x is an integer %
% returns the next integer larger than x or x if x is an integer %
Line 319: Line 319:
drawSphere( 10, 2, 0.4, light, ".:!*oe#%&@" )
drawSphere( 10, 2, 0.4, light, ".:!*oe#%&@" )
end test
end test
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 397: Line 397:


=={{header|ATS}}==
=={{header|ATS}}==
<lang>
<syntaxhighlight lang="text">
(*
(*
** Solution to Draw_a_sphere.dats
** Solution to Draw_a_sphere.dats
Line 499: Line 499:


(* ****** ****** *)
(* ****** ****** *)
</syntaxhighlight>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{libheader|GDIP}}
{{libheader|GDIP}}
<lang ahk>#NoEnv
<syntaxhighlight lang="ahk">#NoEnv
SetBatchLines, -1
SetBatchLines, -1
#SingleInstance, Force
#SingleInstance, Force
Line 559: Line 559:
; gdi+ may now be shutdown on exiting the program
; gdi+ may now be shutdown on exiting the program
Gdip_Shutdown(pToken)
Gdip_Shutdown(pToken)
ExitApp</lang>
ExitApp</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f DRAW_A_SPHERE.AWK
# syntax: GAWK -f DRAW_A_SPHERE.AWK
# converted from VBSCRIPT
# converted from VBSCRIPT
Line 622: Line 622:
return(n)
return(n)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 694: Line 694:
This is based, but not exactly, on the [http://rosettacode.org/wiki/Draw_a_sphere#Tcl Tcl] implementation.
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.
Thus, the output is almost the same to the output of Tcl implementation below.
<lang basic256>clg
<syntaxhighlight lang="basic256">clg
color white
color white
rect 0,0,graphwidth, graphheight
rect 0,0,graphwidth, graphheight
Line 700: Line 700:
color rgb(2*n,2*n,2*n)
color rgb(2*n,2*n,2*n)
circle 150-2*n/3,150-n/2,150-n
circle 150-2*n/3,150-n/2,150-n
next n</lang>
next n</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
Using Direct3D.
Using Direct3D.
<lang bbcbasic> MODE 8
<syntaxhighlight lang="bbcbasic"> MODE 8
INSTALL @lib$+"D3DLIB"
INSTALL @lib$+"D3DLIB"
D3DTS_VIEW = 2
D3DTS_VIEW = 2
Line 822: Line 822:
SYS "FreeLibrary", d3dx%
SYS "FreeLibrary", d3dx%
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
[[File:Sphere_BBC.jpeg]]
[[File:Sphere_BBC.jpeg]]
Line 830: Line 830:
Some simple 3D objects are built into DarkBASIC. Creating a sphere only takes 1 line:
Some simple 3D objects are built into DarkBASIC. Creating a sphere only takes 1 line:


<lang darkbasic>MAKE OBJECT SPHERE 1,1</lang>
<syntaxhighlight lang="darkbasic">MAKE OBJECT SPHERE 1,1</syntaxhighlight>


==={{header|FreeBASIC}}===
==={{header|FreeBASIC}}===
<lang FreeBASIC>' "\" = a integer division (CPU)
<syntaxhighlight lang="freebasic">' "\" = a integer division (CPU)
' "/" = a floating point division (FPU)
' "/" = a floating point division (FPU)
' the compiler takes care of the conversion between floating point and integer
' the compiler takes care of the conversion between floating point and integer
Line 880: Line 880:
Print : Print "hit any key to end program"
Print : Print "hit any key to end program"
Sleep
Sleep
End</lang>
End</syntaxhighlight>
{{works with|FreeBASIC}}
{{works with|FreeBASIC}}
needs #Lang "fblite", #Lang "qb" or #Lang "deprecated" to compile.
needs #Lang "fblite", #Lang "qb" or #Lang "deprecated" to compile.
<lang FreeBASIC>'Sphere for FreeBASIC May 2015
<syntaxhighlight lang="freebasic">'Sphere for FreeBASIC May 2015
'spherefb4.bas
'spherefb4.bas
'Sphere using XPL0 code from rosetacode sphere page
'Sphere using XPL0 code from rosetacode sphere page
Line 918: Line 918:
Print "Enter any key to exit "
Print "Enter any key to exit "
sleep
sleep
END</lang>
END</syntaxhighlight>


==={{header|Liberty BASIC}}===
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">
<lang lb>
WindowWidth =420
WindowWidth =420
WindowHeight =460
WindowHeight =460
Line 948: Line 948:
close #w
close #w
end
end
</syntaxhighlight>
</lang>


==={{header|Locomotive Basic}}===
==={{header|Locomotive Basic}}===
Translated from ERRE version, this will print a 39x20 text sphere onscreen.
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).
The variables in line 80 can be used to adjust size (r), spotlight (k), reflective light (ambient).
<lang locobasic>
<syntaxhighlight lang="locobasic">
10 MODE 2:s$=".:!*oe&#%@"
10 MODE 2:s$=".:!*oe&#%@"
20 DIM v(2),vec(2)
20 DIM v(2),vec(2)
Line 990: Line 990:
3010 IF d<0 THEN d=-d ELSE d=0
3010 IF d<0 THEN d=-d ELSE d=0
3020 RETURN
3020 RETURN
</syntaxhighlight>
</lang>


==={{header|PureBasic}}===
==={{header|PureBasic}}===
3D Sphere animation.
3D Sphere animation.
<lang PureBasic>; Original by Comtois @ 28/03/06
<syntaxhighlight lang="purebasic">; Original by Comtois @ 28/03/06
;
;
; Updated/Formated by Fluid Byte @ March.24,2009
; Updated/Formated by Fluid Byte @ March.24,2009
Line 1,244: Line 1,244:
SetMeshData(0,#PB_Mesh_Face,*IBuffer,Length)
SetMeshData(0,#PB_Mesh_Face,*IBuffer,Length)
EndProcedure</lang>
EndProcedure</syntaxhighlight>
[[image:PB_Animated_sphere.png]]
[[image:PB_Animated_sphere.png]]


===[[QBasic]]===
===[[QBasic]]===


<lang QBASIC>SCREEN 13 ' enter high-color graphic mode
<syntaxhighlight lang="qbasic">SCREEN 13 ' enter high-color graphic mode


' sets palette colors B/N
' sets palette colors B/N
Line 1,267: Line 1,267:
' wait until keypress
' wait until keypress
DO: LOOP WHILE INKEY$ = ""
DO: LOOP WHILE INKEY$ = ""
END</lang>
END</syntaxhighlight>


==={{header|Run BASIC}}===
==={{header|Run BASIC}}===
<lang runbasic>'Run BASIC White Sphere, Black background
<syntaxhighlight lang="runbasic">'Run BASIC White Sphere, Black background
'runbasic.com
'runbasic.com
graphic #win, 300, 300
graphic #win, 300, 300
Line 1,287: Line 1,287:
next X
next X
next Y
next Y
render #win</lang>
render #win</syntaxhighlight>


<lang Runbasic>'This is a simple Circle
<syntaxhighlight lang="runbasic">'This is a simple Circle
graphic #g, 300, 300 'create a graphic object
graphic #g, 300, 300 'create a graphic object
#g place(100,100) 'place the drawing pen at 100,100
#g place(100,100) 'place the drawing pen at 100,100
#g circle(75) 'make a circle with radius 75
#g circle(75) 'make a circle with radius 75
render #g 'show it</lang>
render #g 'show it</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Works with 1k of RAM. A screenshot of the output is [http://www.edmundgriffiths.com/zx81sphere.jpg here].
Works with 1k of RAM. A screenshot of the output is [http://www.edmundgriffiths.com/zx81sphere.jpg here].
<lang basic>10 LET I=21
<syntaxhighlight lang="basic">10 LET I=21
20 LET J=2
20 LET J=2
30 FOR K=-PI TO PI STEP 0.07
30 FOR K=-PI TO PI STEP 0.07
Line 1,305: Line 1,305:
70 LET I=I-J
70 LET I=I-J
80 LET J=J+1
80 LET J=J+1
90 IF I>0 THEN GOTO 30</lang>
90 IF I>0 THEN GOTO 30</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
Line 1,311: Line 1,311:
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.
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.
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.
<lang dos>:: Draw a Sphere Task from Rosetta Code
<syntaxhighlight lang="dos">:: Draw a Sphere Task from Rosetta Code
:: Batch File Implementation
:: Batch File Implementation
Line 1,413: Line 1,413:
echo(!line!
echo(!line!
)
)
goto :EOF</lang>
goto :EOF</syntaxhighlight>
{{Out}}
{{Out}}
<pre> eeeeeeeeee&&&&&##
<pre> eeeeeeeeee&&&&&##
Line 1,464: Line 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.
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.


<lang befunge>45*65*65*"2"30p20p10p::00p2*40p4*5vv<
<syntaxhighlight lang="befunge">45*65*65*"2"30p20p10p::00p2*40p4*5vv<
>60p140g->:::*00g50g*60g40g-:*-\-v0>1
>60p140g->:::*00g50g*60g40g-:*-\-v0>1
^_@#`\g0<|`\g04:+1, <*84$$_v#`\0:<>p^
^_@#`\g0<|`\g04:+1, <*84$$_v#`\0:<>p^
Line 1,471: Line 1,471:
^>#0 *#12#<0g:^>+::"~~"90g*80g+*70gv|
^>#0 *#12#<0g:^>+::"~~"90g*80g+*70gv|
g-10g*+:9**00gv|!*`\2\`-20::/2-\/\+<>
g-10g*+:9**00gv|!*`\2\`-20::/2-\/\+<>
%#&eo*!:..^g05<>$030g-*9/\20g*+60g40^</lang>
%#&eo*!:..^g05<>$030g-*9/\20g*+60g40^</syntaxhighlight>


{{out}}
{{out}}
Line 1,517: Line 1,517:
=={{header|Brlcad}}==
=={{header|Brlcad}}==


<lang brlcad>opendb balls.g y # Create a database to hold our shapes
<syntaxhighlight lang="brlcad">opendb balls.g y # Create a database to hold our shapes
units cm # Set the unit of measure
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 </lang>
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 </syntaxhighlight>


=={{header|C}}==
=={{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.
The lighting calculation is somewhere between crude and bogus, but hey, I'm shading it with ASCII characters, don't expect too much.
<lang C>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <string.h>
#include <string.h>
Line 1,579: Line 1,579:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> #############%%%%
<pre> #############%%%%
Line 1,645: Line 1,645:
===Fun with 3D noise texture===
===Fun with 3D noise texture===
[[file:sphere-perlin.png]]
[[file:sphere-perlin.png]]
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdlib.h>
#include <math.h>
#include <math.h>
Line 1,806: Line 1,806:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{trans|C}}
{{trans|C}}
<lang java>using System;
<syntaxhighlight lang="java">using System;


namespace Sphere {
namespace Sphere {
Line 1,860: Line 1,860:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
{{libheader|Qt}}
{{libheader|Qt}}
<lang cpp>// Based on https://www.cairographics.org/samples/gradient/
<syntaxhighlight lang="cpp">// Based on https://www.cairographics.org/samples/gradient/


#include <QImage>
#include <QImage>
Line 1,900: Line 1,900:
image.save("sphere.png");
image.save("sphere.png");
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,907: Line 1,907:
=={{header|Clojure}}==
=={{header|Clojure}}==
{{libheader|quil}}
{{libheader|quil}}
<lang clojure>
<syntaxhighlight lang="clojure">
(use 'quil.core)
(use 'quil.core)


Line 1,928: Line 1,928:
:draw draw
:draw draw
:renderer :opengl)
:renderer :opengl)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,938: Line 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.
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.


<lang lisp>;; * Loading the cairo bindings
<syntaxhighlight lang="lisp">;; * Loading the cairo bindings
(eval-when (:compile-toplevel :load-toplevel)
(eval-when (:compile-toplevel :load-toplevel)
(ql:quickload '("cl-cairo2" "cl-cairo2-xlib")))
(ql:quickload '("cl-cairo2" "cl-cairo2-xlib")))
Line 1,982: Line 1,982:
(set-source pat)
(set-source pat)
(arc *middle* *middle* 180 0 (* 2 pi))
(arc *middle* *middle* 180 0 (* 2 pi))
(fill-path))))</lang>
(fill-path))))</syntaxhighlight>


=={{header|ContextFree}}==
=={{header|ContextFree}}==
<syntaxhighlight lang="contextfree">
<lang contextFree>
startshape SPHERE
startshape SPHERE


Line 1,992: Line 1,992:
SPHERE[x 0.1% y 0.1%s 0.99 0.99 b 0.05]
SPHERE[x 0.1% y 0.1%s 0.99 0.99 b 0.05]
}
}
</syntaxhighlight>
</lang>


=={{header|D}}==
=={{header|D}}==
{{trans|C}}
{{trans|C}}
<lang d>import std.stdio, std.math, std.algorithm, std.numeric;
<syntaxhighlight lang="d">import std.stdio, std.math, std.algorithm, std.numeric;


alias V3 = double[3];
alias V3 = double[3];
Line 2,035: Line 2,035:
drawSphere(20, 4, 0.1);
drawSphere(20, 4, 0.1);
drawSphere(10, 2, 0.4);
drawSphere(10, 2, 0.4);
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 2,044: Line 2,044:
'''Steps:''' Run the CMD Windows shell. Then follow this path to setup the new width: '''Main Menu-> Properties -> Layout -> Window Size -> Width'''.
'''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">
<lang Delphi>
program DrawASphere;
program DrawASphere;


Line 2,115: Line 2,115:
Readln;
Readln;
end.
end.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,183: Line 2,183:
[[image:DWScript-sphere.pbm.png|thumb|right|PBM output magnified 5 times]]
[[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
{{trans|C}} but adapted to spit out a [[wp:Netpbm_format|PGM]] image
<lang delphi>
<syntaxhighlight lang="delphi">
type
type
TFloat3 = array[0..2] of Float;
TFloat3 = array[0..2] of Float;
Line 2,239: Line 2,239:
normalize(light);
normalize(light);
drawSphere(19, 4, 0.1);
drawSphere(19, 4, 0.1);
</syntaxhighlight>
</lang>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
{{trans|Go}}
{{trans|Go}}
<lang lisp>; Draw a sphere
<syntaxhighlight lang="lisp">; Draw a sphere


(defun normalize (v)
(defun normalize (v)
Line 2,296: Line 2,296:
(pic-show arr size)))
(pic-show arr size)))


(sphere 200 1.5 0.2 '(-30 -30 50))</lang>
(sphere 200 1.5 0.2 '(-30 -30 50))</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
Using ASCII art: output is written to 'SPHERE.PRN' sequential file.
Using ASCII art: output is written to 'SPHERE.PRN' sequential file.
<lang ERRE>PROGRAM SPHERE
<syntaxhighlight lang="erre">PROGRAM SPHERE


CONST SHADES$=".:!*oe&#%@"
CONST SHADES$=".:!*oe&#%@"
Line 2,354: Line 2,354:
CLOSE(1)
CLOSE(1)
END PROGRAM
END PROGRAM
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre> !::::::!!!**o
<pre> !::::::!!!**o
Line 2,424: Line 2,424:
{{libheader|raylib}}
{{libheader|raylib}}
{{works with|Factor|0.99 2020-03-02}}
{{works with|Factor|0.99 2020-03-02}}
<lang factor>USING: classes.struct kernel raylib.ffi ;
<syntaxhighlight lang="factor">USING: classes.struct kernel raylib.ffi ;
640 480 "sphere" init-window
640 480 "sphere" init-window
Line 2,445: Line 2,445:
end-mode-3d
end-mode-3d
end-drawing
end-drawing
] until drop close-window</lang>
] until drop close-window</syntaxhighlight>
{{out}}
{{out}}
[https://i.imgur.com/FXHkZm6.png]
[https://i.imgur.com/FXHkZm6.png]
Line 2,456: Line 2,456:


===ASCII output===
===ASCII output===
<lang forth>: 3dup 2 pick 2 pick 2 pick ;
<syntaxhighlight lang="forth">: 3dup 2 pick 2 pick 2 pick ;


: sqrt ( u -- sqrt ) ( Babylonian method )
: sqrt ( u -- sqrt ) ( Babylonian method )
Line 2,497: Line 2,497:


20 draw
20 draw
10 draw</lang>
10 draw</syntaxhighlight>


{{out}}
{{out}}
Line 2,563: Line 2,563:
===PGM output===
===PGM output===
The same program as the ASCII one is translated to produce a PGM portable pixmap image file.
The same program as the ASCII one is translated to produce a PGM portable pixmap image file.
<lang forth>: 3dup 2 pick 2 pick 2 pick ;
<syntaxhighlight lang="forth">: 3dup 2 pick 2 pick 2 pick ;


: sqrt ( u -- sqrt ) ( Babylonian method )
: sqrt ( u -- sqrt ) ( Babylonian method )
Line 2,610: Line 2,610:
1000 +loop drop image-close ;
1000 +loop drop image-close ;


200 draw</lang>
200 draw</syntaxhighlight>


=={{header|Frink}}==
=={{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!
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!
<lang frink>res = 254 / in
<syntaxhighlight lang="frink">res = 254 / in
v = callJava["frink.graphics.VoxelArray", "makeSphere", [1/2 inch res]]
v = callJava["frink.graphics.VoxelArray", "makeSphere", [1/2 inch res]]


Line 2,626: Line 2,626:
w.println[v.toSTLFormat["sphere", 1/(res mm)]]
w.println[v.toSTLFormat["sphere", 1/(res mm)]]
w.close[]
w.close[]
println["done."]</lang>
println["done."]</syntaxhighlight>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>
<syntaxhighlight lang="futurebasic">
include "Tlbx agl.incl"
include "Tlbx agl.incl"
include "Tlbx glut.incl"
include "Tlbx glut.incl"
Line 2,704: Line 2,704:
HandleEvents
HandleEvents
until gFBquit
until gFBquit
</syntaxhighlight>
</lang>


=={{header|Go}}==
=={{header|Go}}==
Line 2,710: Line 2,710:
{{trans|C}}
{{trans|C}}
Using image library rather than ASCII art.
Using image library rather than ASCII art.
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 2,777: Line 2,777:
fmt.Println(err)
fmt.Println(err)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
[[File:Sphere_Haskell.png|thumb|right]]
[[File:Sphere_Haskell.png|thumb|right]]
<lang haskell>import Graphics.Rendering.OpenGL.GL
<syntaxhighlight lang="haskell">import Graphics.Rendering.OpenGL.GL
import Graphics.UI.GLUT.Objects
import Graphics.UI.GLUT.Objects
import Graphics.UI.GLUT
import Graphics.UI.GLUT
Line 2,828: Line 2,828:
setMaterial
setMaterial
displayCallback $= display
displayCallback $= display
mainLoop</lang>
mainLoop</syntaxhighlight>


=== ASCII art ===
=== ASCII art ===
{{trans|Python}}
{{trans|Python}}


<lang haskell>import Data.List (genericLength)
<syntaxhighlight lang="haskell">import Data.List (genericLength)


shades = ".:!*oe%#&@"
shades = ".:!*oe%#&@"
Line 2,848: Line 2,848:
else ' '
else ' '
| y <- map (/2.12) [- 2*r - 0.5 .. 2*r + 0.5] ]
| y <- map (/2.12) [- 2*r - 0.5 .. 2*r + 0.5] ]
| x <- [ - r - 0.5 .. r + 0.5] ]</lang>
| x <- [ - r - 0.5 .. r + 0.5] ]</syntaxhighlight>


<pre>λ> putStrLn $ sphere 10 4 0.1 (normalize [30,30,-50])
<pre>λ> putStrLn $ sphere 10 4 0.1 (normalize [30,30,-50])
Line 2,879: Line 2,879:
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]]
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]]


<lang Unicon>procedure main()
<syntaxhighlight lang="unicon">procedure main()
W := open("Demo", "gl", "size=400,400", "bg=black") | stop("can't open window!")
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" )
WAttrib(W, "slices=40", "rings=40", "light0=on, ambient white; diffuse gold; specular gold; position 5, 0, 0" )
Line 2,885: Line 2,885:
DrawSphere(W, 0, 0, -5, 1)
DrawSphere(W, 0, 0, -5, 1)
Event(W)
Event(W)
end</lang>
end</syntaxhighlight>
<div style="border: 1px solid #000000; overflow: auto; width: 100%"></div>
<div style="border: 1px solid #000000; overflow: auto; width: 100%"></div>


Line 2,903: Line 2,903:
But bringing up the example with a line of code is trivial enough:
But bringing up the example with a line of code is trivial enough:


<lang j>load '~system/examples/graphics/opengl/simple/sphere.ijs'</lang>
<syntaxhighlight lang="j">load '~system/examples/graphics/opengl/simple/sphere.ijs'</syntaxhighlight>


(Note that this example has been removed from recent versions of J, but still works for J version 5 and version 6.)
(Note that this example has been removed from recent versions of J, but still works for J version 5 and version 6.)
Line 2,912: Line 2,912:
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.
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.


<lang j>'R k ambient' =. 10 2 0.4
<syntaxhighlight lang="j">'R k ambient' =. 10 2 0.4
light =. (% +/&.:*:) 30 30 _50
light =. (% +/&.:*:) 30 30 _50
pts =. (0&*^:(0={:))@:(,,(0>.(*:R)-+)&.*:)"0/~ i:15j200
pts =. (0&*^:(0={:))@:(,,(0>.(*:R)-+)&.*:)"0/~ i:15j200
Line 2,919: Line 2,919:
load 'viewmat'
load 'viewmat'
torgb =. 256 #. [: <. 255 255 255 *"1 0 ]
torgb =. 256 #. [: <. 255 255 255 *"1 0 ]
'rgb' viewmat torgb luminosity</lang>
'rgb' viewmat torgb luminosity</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
{{trans|C}}
{{trans|C}}
<lang java>public class Sphere{
<syntaxhighlight lang="java">public class Sphere{
static char[] shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'};
static char[] shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'};


Line 2,965: Line 2,965:
drawSphere(10, 2, .4);
drawSphere(10, 2, .4);
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> &&&&&&&&&&#######
<pre> &&&&&&&&&&#######
Line 3,036: Line 3,036:
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.
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.


<lang javascript><!DOCTYPE html>
<syntaxhighlight lang="javascript"><!DOCTYPE html>
<html>
<html>
<head>
<head>
Line 3,097: Line 3,097:
<canvas id="c">Unsupportive browser...</canvas><br>
<canvas id="c">Unsupportive browser...</canvas><br>
</body>
</body>
</html></lang>
</html></syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
{{works with|jq|1.4}}
{{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.
The approach adopted here is to generate an SVG file, which may then be viewed, for example, in a web browser.
<lang jq>def svg:
<syntaxhighlight lang="jq">def svg:
"<svg width='100%' height='100%' version='1.1'
"<svg width='100%' height='100%' version='1.1'
xmlns='http://www.w3.org/2000/svg'
xmlns='http://www.w3.org/2000/svg'
Line 3,120: Line 3,120:


def sphere(cx; cy; r; gradientId):
def sphere(cx; cy; r; gradientId):
"<circle fill='url(#\(gradientId))' cx='\(cx)' cy='\(cy)' r='\(r)' />" ;</lang>
"<circle fill='url(#\(gradientId))' cx='\(cx)' cy='\(cy)' r='\(r)' />" ;</syntaxhighlight>


'''Example:'''
'''Example:'''
<lang jq>def draw_sphere:
<syntaxhighlight lang="jq">def draw_sphere:
svg,
svg,
"<title>Teal sphere</title>",
"<title>Teal sphere</title>",
Line 3,131: Line 3,131:
"</svg>" ;
"</svg>" ;
draw_sphere</lang>
draw_sphere</syntaxhighlight>
{{out}}
{{out}}
<lang sh>$ jq -r -n -f spheres.jq > spheres.svg</lang>
<syntaxhighlight lang="sh">$ jq -r -n -f spheres.jq > spheres.svg</syntaxhighlight>


One way to view the output as an image is to point your browser to the generated SVG.
One way to view the output as an image is to point your browser to the generated SVG.
Line 3,140: Line 3,140:
===ASCII Text===
===ASCII Text===
{{trans|C}}
{{trans|C}}
<lang julia>function draw_sphere(r, k, ambient, light)
<syntaxhighlight lang="julia">function draw_sphere(r, k, ambient, light)
shades = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@')
shades = ('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@')
for i in floor(Int, -r):ceil(Int, r)
for i in floor(Int, -r):ceil(Int, r)
Line 3,167: Line 3,167:
draw_sphere(20, 4, 0.1, light)
draw_sphere(20, 4, 0.1, light)
draw_sphere(10, 2, 0.4, light)
draw_sphere(10, 2, 0.4, light)
</syntaxhighlight>
</lang>
===Graphical===
===Graphical===
<lang julia># run from REPL
<syntaxhighlight lang="julia"># run from REPL


using Makie
using Makie
Line 3,182: Line 3,182:


surface(x, y, z, backgroundcolor = :black, show_axis = false)
surface(x, y, z, backgroundcolor = :black, show_axis = false)
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|C}}
{{trans|C}}
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


const val shades = ".:!*oe&#%@"
const val shades = ".:!*oe&#%@"
Line 3,232: Line 3,232:
drawSphere(20.0, 4.0, 0.1)
drawSphere(20.0, 4.0, 0.1)
drawSphere(10.0, 2.0, 0.4)
drawSphere(10.0, 2.0, 0.4)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 3,300: Line 3,300:


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>----------------------------------------
<syntaxhighlight lang="lingo">----------------------------------------
-- Draw a circle
-- Draw a circle
-- @param {image} img
-- @param {image} img
Line 3,315: Line 3,315:
props[#color] = drawColor
props[#color] = drawColor
img.draw(x-r, y-r, x+r, y+r, props)
img.draw(x-r, y-r, x+r, y+r, props)
end</lang>
end</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
Line 3,322: Line 3,322:
{{works with|MSWlogo}}
{{works with|MSWlogo}}


<lang logo>to sphere :r
<syntaxhighlight lang="logo">to sphere :r
cs perspective ht ;making the room ready to use
cs perspective ht ;making the room ready to use
repeat 180 [polystart circle :r polyend down 1]
repeat 180 [polystart circle :r polyend down 1]
polyview
polyview
end</lang>
end</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
{{trans|C}}
{{trans|C}}
{{works with|Lua|5.1.4}}
{{works with|Lua|5.1.4}}
<lang Lua>require ("math")
<syntaxhighlight lang="lua">require ("math")


shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'}
shades = {'.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'}
Line 3,367: Line 3,367:


draw_sphere (20, 4, 0.1)
draw_sphere (20, 4, 0.1)
draw_sphere (10, 2, 0.4)</lang>
draw_sphere (10, 2, 0.4)</syntaxhighlight>
{{out}}
{{out}}
<pre> &&&&&&&&&&&&#####
<pre> &&&&&&&&&&&&#####
Line 3,433: Line 3,433:


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
Er$="Pset is a new statement"
Er$="Pset is a new statement"
Line 3,493: Line 3,493:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


[[https://2.bp.blogspot.com/-ZWy2xDxXbzg/W98lAuNSY9I/AAAAAAAAHZ0/DFYluvWtz_cwwAUKfblujnW6mTC5XVs1QCLcBGAs/s1600/sphere.png]image]
[[https://2.bp.blogspot.com/-ZWy2xDxXbzg/W98lAuNSY9I/AAAAAAAAHZ0/DFYluvWtz_cwwAUKfblujnW6mTC5XVs1QCLcBGAs/s1600/sphere.png]image]
Line 3,499: Line 3,499:
=={{header|Maple}}==
=={{header|Maple}}==
[[File:Sphere_Maple.png|thumb]]
[[File:Sphere_Maple.png|thumb]]
<lang maple>plots[display](plottools[sphere](), axes = none, style = surface);</lang>
<syntaxhighlight lang="maple">plots[display](plottools[sphere](), axes = none, style = surface);</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica has many 3D drawing capabilities. To create a sphere with radius one centered at (0,0,0):
Mathematica has many 3D drawing capabilities. To create a sphere with radius one centered at (0,0,0):
<lang Mathematica>Graphics3D[Sphere[{0,0,0},1]]</lang>
<syntaxhighlight lang="mathematica">Graphics3D[Sphere[{0,0,0},1]]</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
To create the unit sphere:
To create the unit sphere:
<lang MATLAB>figure; sphere</lang>
<syntaxhighlight lang="matlab">figure; sphere</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>/* Two solutions */
<syntaxhighlight lang="maxima">/* Two solutions */
plot3d(1, [theta, 0, %pi], [phi, 0, 2 * %pi],
plot3d(1, [theta, 0, %pi], [phi, 0, 2 * %pi],
[transform_xy, spherical_to_xyz], [grid, 30, 60],
[transform_xy, spherical_to_xyz], [grid, 30, 60],
Line 3,520: Line 3,520:
sin(phi)*sin(theta),
sin(phi)*sin(theta),
cos(theta),
cos(theta),
theta, 0, %pi, phi, 0, 2 * %pi))$</lang>
theta, 0, %pi, phi, 0, 2 * %pi))$</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
{{trans|C}}
{{trans|C}}
<lang nim>import math
<syntaxhighlight lang="nim">import math


type Point = tuple[x,y,z: float]
type Point = tuple[x,y,z: float]
Line 3,554: Line 3,554:


drawSphere 20, 4.0, 0.1
drawSphere 20, 4.0, 0.1
drawSphere 10, 2.0, 0.4</lang>
drawSphere 10, 2.0, 0.4</syntaxhighlight>
{{out}}
{{out}}
<pre> &&&&&&&&&&#######
<pre> &&&&&&&&&&#######
Line 3,620: Line 3,620:
=={{header|Ol}}==
=={{header|Ol}}==
{{libheader|OpenGL}}
{{libheader|OpenGL}}
<lang scheme>
<syntaxhighlight lang="scheme">
(import (lib gl))
(import (lib gl))
(import (OpenGL version-1-0))
(import (OpenGL version-1-0))
Line 3,637: Line 3,637:
(gluSphere quadric 0.4 32 10)
(gluSphere quadric 0.4 32 10)
))
))
</syntaxhighlight>
</lang>


=={{header|Openscad}}==
=={{header|Openscad}}==
Drawing a sphere is easy in openscad:
Drawing a sphere is easy in openscad:


<lang openscad>// This will produce a sphere of radius 5
<syntaxhighlight lang="openscad">// This will produce a sphere of radius 5
sphere(5);</lang>
sphere(5);</syntaxhighlight>


[[Category:Geometric Primitives]]
[[Category:Geometric Primitives]]
Line 3,649: Line 3,649:
=={{header|OxygenBasic}}==
=={{header|OxygenBasic}}==
Using an OpenGl-based console
Using an OpenGl-based console
<lang>
<syntaxhighlight lang="text">
% Title "Sphere"
% Title "Sphere"
'% Animated
'% Animated
Line 3,667: Line 3,667:


EndScript
EndScript
</syntaxhighlight>
</lang>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 3,678: Line 3,678:
This produces a PGM image which can't be uploaded on rosettacode at the moment. It looks similar as the Raku solution, though.
This produces a PGM image which can't be uploaded on rosettacode at the moment. It looks similar as the Raku solution, though.


<lang perl>use strict;
<syntaxhighlight lang="perl">use strict;
use warnings;
use warnings;


Line 3,728: Line 3,728:
},
},
q{""} => sub { sprintf "Vector:[%s]", join ' ', @{shift()} };
q{""} => sub { sprintf "Vector:[%s]", join ' ', @{shift()} };
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Line 3,736: Line 3,736:
Sphere will resize to match the window.
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.
You can run this online [http://phix.x10.mx/p2js/drawsphere.htm here]. Note fullscreen redraw can be quite slow.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Draw_a_sphere.exw
-- demo\rosetta\Draw_a_sphere.exw
Line 3,823: Line 3,823:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</lang>-->
<!--</syntaxhighlight>-->


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
{{libheader|GLUT}}
{{libheader|GLUT}}
This is for the 64-bit version.
This is for the 64-bit version.
<lang PicoLisp>(load "@lib/openGl.l")
<syntaxhighlight lang="picolisp">(load "@lib/openGl.l")


(glutInit)
(glutInit)
Line 3,853: Line 3,853:
# Exit upon mouse click
# Exit upon mouse click
(mouseFunc '((Btn State X Y) (bye)))
(mouseFunc '((Btn State X Y) (bye)))
(glutMainLoop)</lang>
(glutMainLoop)</syntaxhighlight>


{{trans|C}}
{{trans|C}}


<lang PicoLisp>(scl 24)
<syntaxhighlight lang="picolisp">(scl 24)


(setq *Shades
(setq *Shades
Line 3,916: Line 3,916:
(setq *Light (normalize *Light))
(setq *Light (normalize *Light))
(drawSphere 20.0 4 0.1)
(drawSphere 20.0 4 0.1)
(drawSphere 10.0 2 0.4)</lang>
(drawSphere 10.0 2 0.4)</syntaxhighlight>
{{out}}
{{out}}
<pre> ##############%%%
<pre> ##############%%%
Line 3,986: Line 3,986:
=={{header|PostScript}}==
=={{header|PostScript}}==
Gradient filled circle:
Gradient filled circle:
<lang PostScript>%!PS-Adobe-3.0
<syntaxhighlight lang="postscript">%!PS-Adobe-3.0
%%BoundingBox 0 0 300 300
%%BoundingBox 0 0 300 300


Line 4,009: Line 4,009:
showpage
showpage
%%EOF
%%EOF
</syntaxhighlight>
</lang>


=={{header|POV-Ray}}==
=={{header|POV-Ray}}==
Line 4,015: Line 4,015:
This is what POVray was made for. An example with a sky, surface and transparency:
This is what POVray was made for. An example with a sky, surface and transparency:


<syntaxhighlight lang="povray">
<lang POVray>
camera { location <0.0 , .8 ,-3.0> look_at 0}
camera { location <0.0 , .8 ,-3.0> look_at 0}
Line 4,031: Line 4,031:
interior { ior 1.5}
interior { ior 1.5}
}
}
</syntaxhighlight>
</lang>


Yields this:
Yields this:
Line 4,040: Line 4,040:
3D rendering is built into Processing.
3D rendering is built into Processing.


<lang java>void setup() {
<syntaxhighlight lang="java">void setup() {
size(500, 500, P3D);
size(500, 500, P3D);
}
}
Line 4,052: Line 4,052:
// draw sphere
// draw sphere
sphere(200);
sphere(200);
}</lang>
}</syntaxhighlight>
A sphere build from triangles (to for instance allow distortion)
A sphere build from triangles (to for instance allow distortion)
<lang java>float rotX, rotY;
<syntaxhighlight lang="java">float rotX, rotY;


PVector[][] sphere;
PVector[][] sphere;
Line 4,098: Line 4,098:
rotY -= (mouseX - pmouseX) * 0.01;
rotY -= (mouseX - pmouseX) * 0.01;
rotX -= (mouseY - pmouseY) * 0.01;
rotX -= (mouseY - pmouseY) * 0.01;
}</lang>
}</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
===Ascii-Art===
===Ascii-Art===
{{trans|C}}
{{trans|C}}
<lang python>import math
<syntaxhighlight lang="python">import math


shades = ('.',':','!','*','o','e','&','#','%','@')
shades = ('.',':','!','*','o','e','&','#','%','@')
Line 4,134: Line 4,134:
light = normalize((30,30,-50))
light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)</lang>
draw_sphere(10,2,0.4, light)</syntaxhighlight>
{{out}}
{{out}}
<pre> &&&&&&&&&&######
<pre> &&&&&&&&&&######
Line 4,204: Line 4,204:
This code contains unnecessary functions which are part of a 3D graphics library I wrote. <br>
This code contains unnecessary functions which are part of a 3D graphics library I wrote. <br>
Uses Pygame and Python 3.2.2
Uses Pygame and Python 3.2.2
<lang python>
<syntaxhighlight lang="python">
import pygame
import pygame
from pygame.locals import *
from pygame.locals import *
Line 4,211: Line 4,211:
import random
import random
import math
import math
</syntaxhighlight>
</lang>
<lang python>
<syntaxhighlight lang="python">
class Tricubic:
class Tricubic:
def __init__(self,pts):
def __init__(self,pts):
Line 4,984: Line 4,984:
if event.type == KEYDOWN:
if event.type == KEYDOWN:
pass
pass
</syntaxhighlight>
</lang>


==={{libheader|VPython}}===
==={{libheader|VPython}}===
{{works with|Python|2.7.5}}
{{works with|Python|2.7.5}}
'''Short version''':
'''Short version''':
<lang python>from visual import *
<syntaxhighlight lang="python">from visual import *
scene.title = "VPython: Draw a sphere"
scene.title = "VPython: Draw a sphere"
sphere() # using defaults, see http://www.vpython.org/contents/docs/defaults.html </lang>
sphere() # using defaults, see http://www.vpython.org/contents/docs/defaults.html </syntaxhighlight>


'''Regular version''', with some window-dressing:
'''Regular version''', with some window-dressing:
<lang python>
<syntaxhighlight lang="python">
from __future__ import print_function, division
from __future__ import print_function, division
from visual import *
from visual import *
Line 5,017: Line 5,017:
rate(100)
rate(100)
pass # no animation in this demo
pass # no animation in this demo
</syntaxhighlight>
</lang>


=={{header|Racket}}==
=={{header|Racket}}==
Line 5,025: Line 5,025:
Using the Typed Racket language with the plot library:
Using the Typed Racket language with the plot library:


<lang racket>
<syntaxhighlight lang="racket">
#lang typed/racket
#lang typed/racket


(require plot/typed)
(require plot/typed)
(plot3d (polar3d (λ (θ ρ) 1)) #:altitude 25)
(plot3d (polar3d (λ (θ ρ) 1)) #:altitude 25)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 5,042: Line 5,042:


[[File:Sphere-perl6.png|thumb]]
[[File:Sphere-perl6.png|thumb]]
<lang perl6>my $width = my $height = 255; # must be odd
<syntaxhighlight lang="raku" line>my $width = my $height = 255; # must be odd


my @light = normalize([ 3, 2, -5 ]);
my @light = normalize([ 3, 2, -5 ]);
Line 5,079: Line 5,079:
}
}
flat |@pixels.map: *.list;
flat |@pixels.map: *.list;
}</lang>
}</syntaxhighlight>


===Cairo graphics library===
===Cairo graphics library===
<lang perl6>use Cairo;
<syntaxhighlight lang="raku" line>use Cairo;


given Cairo::Image.create(Cairo::FORMAT_ARGB32, 256, 256) {
given Cairo::Image.create(Cairo::FORMAT_ARGB32, 256, 256) {
Line 5,112: Line 5,112:
};
};
.write_png('sphere2-perl6.png');
.write_png('sphere2-perl6.png');
}</lang>
}</syntaxhighlight>
See [https://github.com/thundergnat/rc/blob/master/img/sphere2-perl6.png sphere2-perl6.png] (offsite .png image)
See [https://github.com/thundergnat/rc/blob/master/img/sphere2-perl6.png sphere2-perl6.png] (offsite .png image)


Line 5,122: Line 5,122:


Programming note: &nbsp; the output will appear slightly different when executed on an EBCDIC machine &nbsp; (due to different dithering characters).
Programming note: &nbsp; the output will appear slightly different when executed on an EBCDIC machine &nbsp; (due to different dithering characters).
<lang rexx>/*REXX program expresses a lighted sphere with simple characters used for shading. */
<syntaxhighlight lang="rexx">/*REXX program expresses a lighted sphere with simple characters used for shading. */
call drawSphere 19, 4, 2/10, '30 30 -50' /*draw a sphere with a radius of 19. */
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. */
call drawSphere 10, 2, 4/10, '30 30 -50' /* " " " " " " " ten. */
Line 5,156: Line 5,156:
numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g= g*.5'e'_%2
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 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</lang>
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g</syntaxhighlight>
{{out|output|text=&nbsp; when using the default input and executed on an '''ASCII''' machine:}}
{{out|output|text=&nbsp; when using the default input and executed on an '''ASCII''' machine:}}
(Shown at &nbsp; <big>'''<sup>1</sup>/<sub>2</sub>'''</big> &nbsp; size.)
(Shown at &nbsp; <big>'''<sup>1</sup>/<sub>2</sub>'''</big> &nbsp; size.)
Line 5,226: Line 5,226:
Shoes comes with this sample program.
Shoes comes with this sample program.
[[File:sphere.shoes.png|thumb|right]]
[[File:sphere.shoes.png|thumb|right]]
<lang ruby>Shoes.app :width => 500, :height => 500, :resizable => false do
<syntaxhighlight lang="ruby">Shoes.app :width => 500, :height => 500, :resizable => false do
image 400, 470, :top => 30, :left => 50 do
image 400, 470, :top => 30, :left => 50 do
nostroke
nostroke
Line 5,253: Line 5,253:
end
end
end
end
end</lang>
end</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
{{trans|Go}}
{{trans|Go}}
<lang rust>// [dependencies]
<syntaxhighlight lang="rust">// [dependencies]
// image = "0.23"
// image = "0.23"


Line 5,318: Line 5,318:
Err(error) => eprintln!("{}", error),
Err(error) => eprintln!("{}", error),
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 5,324: Line 5,324:


=={{header|Scala}}==
=={{header|Scala}}==
<lang Scala>object Sphere extends App {
<syntaxhighlight lang="scala">object Sphere extends App {
private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d))
private val (shades, light) = (Seq('.', ':', '!', '*', 'o', 'e', '&', '#', '%', '@'), Array(30d, 30d, -50d))


Line 5,357: Line 5,357:
drawSphere(10, 2, .4)
drawSphere(10, 2, .4)


}</lang>
}</syntaxhighlight>
{{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)].
{{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 5,363: Line 5,363:
{{trans|Raku}}
{{trans|Raku}}
Produces a PGM image.
Produces a PGM image.
<lang ruby>func normalize (vec) { vec »/» (vec »*« vec -> sum.sqrt) }
<syntaxhighlight lang="ruby">func normalize (vec) { vec »/» (vec »*« vec -> sum.sqrt) }
func dot (x, y) { -(x »*« y -> sum) `max` 0 }
func dot (x, y) { -(x »*« y -> sum) `max` 0 }
 
 
Line 5,395: Line 5,395:
out.say("P5\n#{x} #{y}\n#{depth}") # .pgm header
out.say("P5\n#{x} #{y}\n#{depth}") # .pgm header
out.print(draw_sphere((x-1)/2, .9, .2).map{.chr}.join)
out.print(draw_sphere((x-1)/2, .9, .2).map{.chr}.join)
out.close</lang>
out.close</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
Line 5,403: Line 5,403:
{{works with|Smalltalk/X}}
{{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.
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">
<lang Smalltalk>
Point3D :=
Point3D :=
Point subclass:#Point3D
Point subclass:#Point3D
Line 5,467: Line 5,467:


main value.
main value.
</syntaxhighlight>
</lang>
[[file:sphere-smalltalk.png]]
[[file:sphere-smalltalk.png]]


Line 5,476: Line 5,476:
=={{header|Swift}}==
=={{header|Swift}}==
In Playground for example:
In Playground for example:
<syntaxhighlight lang="swift">
<lang Swift>
class Sphere: UIView{
class Sphere: UIView{
Line 5,508: Line 5,508:


var s = Sphere(frame: CGRectMake(0, 0, 200, 200))
var s = Sphere(frame: CGRectMake(0, 0, 200, 200))
</syntaxhighlight>
</lang>


In SwiftUI:
In SwiftUI:
<syntaxhighlight lang="swift">
<lang Swift>
struct ContentView: View {
struct ContentView: View {


Line 5,525: Line 5,525:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 5,531: Line 5,531:
Assuming the task is to draw a <i>likeness</i> of a sphere, this would usually do:
Assuming the task is to draw a <i>likeness</i> of a sphere, this would usually do:


<lang Tcl>proc grey {n} {format "#%2.2x%2.2x%2.2x" $n $n $n}
<syntaxhighlight lang="tcl">proc grey {n} {format "#%2.2x%2.2x%2.2x" $n $n $n}


pack [canvas .c -height 400 -width 640 -background white]
pack [canvas .c -height 400 -width 640 -background white]
Line 5,539: Line 5,539:
.c create arc [expr {100+$i/5}] [expr {50+$i/5}] [expr {400-$i/1.5}] [expr {350-$i/1.5}] \
.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
-start 0 -extent 359 -fill $h -outline $h
}</lang>
}</syntaxhighlight>
Results in this image:
Results in this image:


Line 5,549: Line 5,549:
The PGF <code>shadings</code> library includes a "ball" for a 3-D style highlight.
The PGF <code>shadings</code> library includes a "ball" for a 3-D style highlight.


<lang LaTeX>\documentclass{minimal}
<syntaxhighlight lang="latex">\documentclass{minimal}
\usepackage{tikz}
\usepackage{tikz}
\usetikzlibrary{shadings}
\usetikzlibrary{shadings}
Line 5,556: Line 5,556:
\shade[ball color=black] (0,0) circle (4);
\shade[ball color=black] (0,0) circle (4);
\end{tikzpicture}
\end{tikzpicture}
\end{document}</lang>
\end{document}</syntaxhighlight>


=={{header|Turing}}==
=={{header|Turing}}==
Translated and optimized from the Algol W solution and others posted here.
Translated and optimized from the Algol W solution and others posted here.


<lang Turing>% Draw a sphere in ASCII art in Turing
<syntaxhighlight lang="turing">% Draw a sphere in ASCII art in Turing
% Light intensity to character map
% Light intensity to character map
Line 5,618: Line 5,618:
% Draw some spheres
% Draw some spheres
drawSphere (20, 4, lightsource, brightness)
drawSphere (20, 4, lightsource, brightness)
drawSphere (15, 10, lightsource, brightness)</lang>
drawSphere (15, 10, lightsource, brightness)</syntaxhighlight>


{{Out}}
{{Out}}
Line 5,697: Line 5,697:
=={{header|VBScript}}==
=={{header|VBScript}}==
{{trans|C}}
{{trans|C}}
<lang vb>shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
<syntaxhighlight lang="vb">shades = Array(".", ":", "!", "*", "o", "e", "&", "#", "%", "@")
light = Array(30, 30, -50)
light = Array(30, 30, -50)


Line 5,747: Line 5,747:
Normalize light
Normalize light
DrawSphere 20, 4, 0.1
DrawSphere 20, 4, 0.1
DrawSphere 10,2,0.4</lang>
DrawSphere 10,2,0.4</syntaxhighlight>
{{Out}}
{{Out}}
<pre> &&&&&&&&&&#######
<pre> &&&&&&&&&&#######
Line 5,813: Line 5,813:
=={{header|Wren}}==
=={{header|Wren}}==
{{trans|C}}
{{trans|C}}
<lang ecmascript>var shades = ".:!*oe&#\%@"
<syntaxhighlight lang="ecmascript">var shades = ".:!*oe&#\%@"
var light = [30, 30, -50]
var light = [30, 30, -50]


Line 5,850: Line 5,850:
normalize.call(light)
normalize.call(light)
drawSphere.call(20, 4, 0.1)
drawSphere.call(20, 4, 0.1)
drawSphere.call(10, 2, 0.4)</lang>
drawSphere.call(10, 2, 0.4)</syntaxhighlight>


{{out}}
{{out}}
Line 5,919: Line 5,919:
=={{header|XPL0}}==
=={{header|XPL0}}==
[[File:SphereXPL0.png|right]]
[[File:SphereXPL0.png|right]]
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
def R=100, R2=R*R; \radius, in pixels; radius squared
def R=100, R2=R*R; \radius, in pixels; radius squared
def X0=640/2, Y0=480/2; \coordinates of center of screen
def X0=640/2, Y0=480/2; \coordinates of center of screen
Line 5,936: Line 5,936:
repeat until KeyHit; \wait for keystroke
repeat until KeyHit; \wait for keystroke
SetVid($03); \restore normal text mode
SetVid($03); \restore normal text mode
]</lang>
]</syntaxhighlight>


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>ancho = 640 : alto = 480
<syntaxhighlight lang="yabasic">ancho = 640 : alto = 480
open window 640,480
open window 640,480
backcolor 16,16,16
backcolor 16,16,16
Line 5,952: Line 5,952:
fill circle ancho/2-2*n/3, alto/2-n/2, 150-n
fill circle ancho/2-2*n/3, alto/2-n/2, 150-n
next n
next n
end sub</lang>
end sub</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
Line 5,958: Line 5,958:
{{trans|XPL0}}
{{trans|XPL0}}
[[File:Sphere.zkl.jpg|200px|thumb|right]]
[[File:Sphere.zkl.jpg|200px|thumb|right]]
<lang zkl>img:=PPM(640,480);
<syntaxhighlight lang="zkl">img:=PPM(640,480);
R:=100; R2:=R*R; //radius, in pixels; radius squared
R:=100; R2:=R*R; //radius, in pixels; radius squared
X0:=640/2; Y0:=480/2; //coordinates of center of screen
X0:=640/2; Y0:=480/2; //coordinates of center of screen
Line 5,972: Line 5,972:
}
}
}
}
img.write(File("foo.ppm","wb"));</lang>
img.write(File("foo.ppm","wb"));</syntaxhighlight>
The radius of 100 is the max before the color calculation overflows 24 bits so for a radius (R) of, say 200, use
The radius of 100 is the max before the color calculation overflows 24 bits so for a radius (R) of, say 200, use
<lang zkl>img[X+X0,Y+Y0]=C*140+C;</lang>
<syntaxhighlight lang="zkl">img[X+X0,Y+Y0]=C*140+C;</syntaxhighlight>
Perhaps a more useful solution is to use GnuPlot (I grabbed the code from http://ayapin-film.sakura.ne.jp/Gnuplot/):
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]]
[[File:GnuplotSphere.zkl.png|250px|thumb|right]]
<lang zkl>#<<<
<syntaxhighlight lang="zkl">#<<<
cmd:=0'|
cmd:=0'|
set term wxt
set term wxt
Line 5,999: Line 5,999:
gnuplot:=System.popen("gnuplot","w");
gnuplot:=System.popen("gnuplot","w");
gnuplot.write(cmd); gnuplot.flush();
gnuplot.write(cmd); gnuplot.flush();
ask("Hit return to finish"); gnuplot.close();</lang>
ask("Hit return to finish"); gnuplot.close();</syntaxhighlight>
Where "term wxt" is X11 on my Linux box. A window pops up and stays until the pipe is closed.
Where "term wxt" is X11 on my Linux box. A window pops up and stays until the pipe is closed.


=={{header|ZX Spectrum Basic}}==
=={{header|ZX Spectrum Basic}}==
<lang zxbasic>1 REM fast
<syntaxhighlight lang="zxbasic">1 REM fast
50 REM spheer with hidden lines and rotation
50 REM spheer with hidden lines and rotation
100 CLS
100 CLS
Line 6,054: Line 6,054:
1050 LET yy=bx*x+by*y+bz*z
1050 LET yy=bx*x+by*y+bz*z
1060 LET zz=cx*x+cy*y+cz*z
1060 LET zz=cx*x+cy*y+cz*z
1070 RETURN</lang>
1070 RETURN</syntaxhighlight>


[[Category:Geometry]]
[[Category:Geometry]]