Draw a rotating cube: Difference between revisions

m
→‎Zig: Update "works with". Simplify two lines involving casting and math.
(J: bugfix (version dependency -- case sensitive name))
m (→‎Zig: Update "works with". Simplify two lines involving casting and math.)
 
(28 intermediate revisions by 13 users not shown)
Line 15:
{{libheader|SDLAda}}
{{trans|Go}}
<langsyntaxhighlight Adalang="ada">with Ada.Numerics.Elementary_Functions;
 
with SDL.Video.Windows.Makers;
Line 119:
Window.Finalize;
SDL.Finalise;
end Rotating_Cube;</langsyntaxhighlight>
 
=={{header|Amazing Hopper}}==
{{Trans|BASIC256}}
{{Trans|FreeBASIC}}
<p>El programa requiere de la ejecución con "rxvt" de Linux:
 
rxvt -g 500x250 -fn "xft:FantasqueSansMono-Regular:pixelsize=1" -e ./bin/cubo
</p>
[[File:Captura_de_pantalla_de_2022-10-11_12-38-33.png|200px|thumb|rigth|Caption]]
<syntaxhighlight lang="txt">
#context-free Draw a cube
Loop for (i=1, #(i<=3), ++i)
Draw a line (size_2, {size_2} Minus(scale_zoff), [i] Get 'x',\
{size_2} Minus(scale x zoff) )
Draw a line (size_2, {size_2} Plus(scale_zoff), [{7}Minus(i)] Get 'x' ,\
{size_2} Plus(scale x zoff) )
Draw a line ([i] Get 'x', {size_2} Minus(scale x zoff),\
[Minusone(i) Module(3) Plus(4)] Get 'x', {size_2} Plus(scale x zoff) )
Draw a line ([i] Get 'x', {size_2} Minus(scale x zoff), \
[{i} Module(3) Plus(4)] Get 'x', {size_2} Plus(scale x zoff) )
Next
Return\\
 
#context-free Delete old cube
Color back '0', Draw a cube
Return\\
 
#context-free Setting values of program
Set( Div(M_PI,6), Mul(5,Div(M_PI,6)), Mul(3,M_PI_2), Mul(11,Div(M_PI,6)),\
M_PI_2, Mul(7,Div(M_PI,6)) )
Append to list 'cylphi'
/* pre-cálculos */
Let ( dt := Div(1,30 ))
Let (size_2 := Div( SIZE, 2))
Let (scale_zoff := Div( SCALE,zoff))
Let (scale x zoff := Mul (SCALE, zoff))
Return \\
 
#include <jambo.h>
 
/*
Execute with:
$ rxvt -g 250x250 -fn "xft:FantasqueSansMono-Regular:pixelsize=1" -e hopper jm/cubo.jambo
*/
 
#define SCALE 50
#define SIZE 200
#define zoff 0.5773502691896257645091487805019574556
#define cylr 1.6329931618554520654648560498039275946
 
Main
Set break
theta=0, dtheta=1.5, lasttime=0, dt=0 , timer=0
size_2=0, scale_zoff=0, scale x zoff=0, cylphi = {}
 
Dim (6) as zeros (x)
Setting values of program
Cls
/* Draw a cube */
Loop while ( Not (Keypressed))
Tic(lasttime)
Loop for( i=1, #(i<=6), ++i )
Add( size_2, Mul( Mul(SCALE,cylr), Cos( [i] Get 'cylphi' Plus 'theta')) )
Put 'x'
Next
Color back '15', Draw a cube
Loop
Timecpu(timer)
While ( This 'timer' Compared to 'Add(lasttime, dt)' Is less )
Let ( theta := Add( theta, Mul( dtheta, Sub(timer, lasttime))))
Sleep (0.01)
Delete old cube
Back
End
 
Subrutines
 
</syntaxhighlight>
 
=={{header|AutoHotkey}}==
Requires [https://www.autohotkey.com/boards/viewtopic.php?f=6&t=6517&start=320 Gdip Library]
<langsyntaxhighlight AutoHotkeylang="autohotkey">; ---------------------------------------------------------------
cubeSize := 200
deltaX := A_ScreenWidth/2
Line 436 ⟶ 519:
ExitApp
Return
; ---------------------------------------------------------------</langsyntaxhighlight>
 
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">global escala
global tam
global zoff
global cylr
 
escala = 50
tam = 320
zoff = 0.5773502691896257645091487805019574556
cylr = 1.6329931618554520654648560498039275946
 
clg
graphsize tam, tam
 
dim x(6)
theta = 0.0
dtheta = 1.5
dt = 1.0 / 30
dim cylphi = {PI/6, 5*PI/6, 3*PI/2, 11*PI/6, PI/2, 7*PI/6}
 
while key = ""
lasttime = msec
for i = 0 to 5
x[i] = tam/2 + escala *cylr * cos(cylphi[i] + theta)
next i
clg
call drawcube(x)
 
while msec < lasttime + dt
end while
theta += dtheta*(msec-lasttime)
pause .4
call drawcube(x)
end while
 
subroutine drawcube(x)
for i = 0 to 2
color rgb(0,0,0) #black
line tam/2, tam/2 - escala / zoff, x[i], tam/2 - escala * zoff
line tam/2, tam/2 + escala / zoff, x[5-i], tam/2 + escala * zoff
line x[i], tam/2 - escala * zoff, x[(i % 3) + 3], tam/2 + escala * zoff
line x[i], tam/2 - escala * zoff, x[((i+1)%3) + 3], tam/2 + escala * zoff
next i
end subroutine</syntaxhighlight>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="qbasic">100 cls
110 graphics 0
120 graphics color 0,0,0
130 while true
140 graphics cls
150 x = cos(t)*20
160 y = sin(t)*18
170 r = sin(t+t)
180 moveto (x+40),(y+40-r)
190 lineto (-y+40),(x+40-r)
200 moveto (-y+40),(x+40-r)
210 lineto (-x+40),(-y+40-r)
220 moveto (-x+40),(-y+40-r)
230 lineto (y+40),(-x+40-r)
240 moveto (y+40),(-x+40-r)
250 lineto (x+40),(y+40-r)
260 moveto (x+40),(y+20+r)
270 lineto (-y+40),(x+20+r)
280 moveto (-y+40),(x+20+r)
290 lineto (-x+40),(-y+20+r)
300 moveto (-x+40),(-y+20+r)
310 lineto (y+40),(-x+20+r)
320 moveto (y+40),(-x+20+r)
330 lineto (x+40),(y+20+r)
340 moveto (x+40),(y+40-r)
350 lineto (x+40),(y+20+r)
360 moveto (-y+40),(x+40-r)
370 lineto (-y+40),(x+20+r)
380 moveto (-x+40),(-y+40-r)
390 lineto (-x+40),(-y+20+r)
400 moveto (y+40),(-x+40-r)
410 lineto (y+40),(-x+20+r)
420 for i = 1 to 1000 : next i
430 t = t+0.15
440 wend</syntaxhighlight>
 
==={{header|GW-BASIC}}===
{{works with|PC-BASIC|any}}
<syntaxhighlight lang="qbasic">100 SCREEN 2
110 WHILE 1
120 CLS
130 X = COS(T)*20
140 Y = SIN(T)*18
150 R = SIN(T+T)
160 LINE (( X+40),( Y+40-R))-((-Y+40),( X+40-R))
170 LINE ((-Y+40),( X+40-R))-((-X+40),(-Y+40-R))
180 LINE ((-X+40),(-Y+40-R))-(( Y+40),(-X+40-R))
190 LINE (( Y+40),(-X+40-R))-(( X+40),( Y+40-R))
200 LINE (( X+40),( Y+20+R))-((-Y+40),( X+20+R))
210 LINE ((-Y+40),( X+20+R))-((-X+40),(-Y+20+R))
220 LINE ((-X+40),(-Y+20+R))-(( Y+40),(-X+20+R))
230 LINE (( Y+40),(-X+20+R))-(( X+40),( Y+20+R))
240 LINE (( X+40),( Y+40-R))-(( X+40),( Y+20+R))
250 LINE ((-Y+40),( X+40-R))-((-Y+40),( X+20+R))
260 LINE ((-X+40),(-Y+40-R))-((-X+40),(-Y+20+R))
270 LINE (( Y+40),(-X+40-R))-(( Y+40),(-X+20+R))
280 T = T+.15
290 WEND</syntaxhighlight>
 
==={{header|MSX Basic}}===
{{works with|MSX BASIC|any}}
<syntaxhighlight lang="qbasic">100 SCREEN 2
110 COLOR 15
120 CLS
130 X = COS(T)*20
140 Y = SIN(T)*18
150 R = SIN(T+T)
160 LINE (( X+40),( Y+40-R))-((-Y+40),( X+40-R))
170 LINE ((-Y+40),( X+40-R))-((-X+40),(-Y+40-R))
180 LINE ((-X+40),(-Y+40-R))-(( Y+40),(-X+40-R))
190 LINE (( Y+40),(-X+40-R))-(( X+40),( Y+40-R))
200 LINE (( X+40),( Y+20+R))-((-Y+40),( X+20+R))
210 LINE ((-Y+40),( X+20+R))-((-X+40),(-Y+20+R))
220 LINE ((-X+40),(-Y+20+R))-(( Y+40),(-X+20+R))
230 LINE (( Y+40),(-X+20+R))-(( X+40),( Y+20+R))
240 LINE (( X+40),( Y+40-R))-(( X+40),( Y+20+R))
250 LINE ((-Y+40),( X+40-R))-((-Y+40),( X+20+R))
260 LINE ((-X+40),(-Y+40-R))-((-X+40),(-Y+20+R))
270 LINE (( Y+40),(-X+40-R))-(( Y+40),(-X+20+R))
280 FOR I = 1 TO 40 : NEXT I
290 T = T+0.15
300 GOTO 120</syntaxhighlight>
 
=={{header|C}}==
Rotating wireframe cube in [https://www.opengl.org/ OpenGL], windowing implementation via [http://freeglut.sourceforge.net/ freeglut]
<syntaxhighlight lang="c">
<lang C>
#include<gl/freeglut.h>
 
Line 504 ⟶ 719:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
using System.Drawing;
using System.Drawing.Drawing2D;
Line 604 ⟶ 819:
}
}
}</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| Winapi.Windows}}
Line 614 ⟶ 829:
{{libheader| System.Classes}}
{{Trans|Javascript}}
<syntaxhighlight lang="delphi">
<lang Delphi>
unit main;
 
Line 722 ⟶ 937:
end;
 
end.</langsyntaxhighlight>
Resource Form
<syntaxhighlight lang="delphi">
<lang Delphi>
object Form1: TForm1
OnCreate = FormCreate
Line 732 ⟶ 947:
end
end
</syntaxhighlight>
</lang>
 
 
Line 739 ⟶ 954:
Draws only the visible edges
 
[https://easylang.dev/show/#cod=jZTbboMwDIbv8xSWdteqaITSg7Q9ScUFKmkVCcJG0Ub29LNN0gTGtqZVTe3Pvx0TMG2lTsWpgFc44WeTum9x/3O/jv3eHeMRHcGeLYSqrnGpFCQDErZst5CxzZxGDju2OziwPcCe7R4jo3Du8ncub+90DlzuCcRb157hdi5rBRdIIBEAcGk70NhCCn0LtTJg3AQo6OKVj2fOiYsxXZyqAlavcHEBlkxEMpbq2r7sFZTmOtCP9TVv2gwoiYZj5Dq3N3KhubswbANlHWUDZR/pn1R9r6l3fkXOzDsDhdEBVmNPG4RX3LHDbJQrY8Evn7Lm7Cgl4IjZEbNB2c6wrAhqFtVshNFseZcVHpxsHHPVlZ9+tOdalR1dNKhxPB75kuazSR+Zlr7EXbxAE254szQzr66n95+UaPDLNf3BDzXZ40ff6CCO29QDOT0ho8pYYu1q4FJ1JCT/FUp/FQp7oM7NdFzV5MH4a1vwc2eYbXQBmDjpc3SHNFxD6qcdBKY947KLkJwpyTkkF5QWoZlS034oamwN+TPVJjsBam0U1RsBOQOS6XgTMb6IZC7ca2KbQ9mXBm7vXQ9S0KkWLT37usEwZTkwBZZlIBHf Run it]
[https://easylang.online/apps/_rotating-cube.html Run it]
 
<syntaxhighlight lang="text">
<lang>node[][] &= [ -1 -1 -1 ]
node[][] &= [ [ -1 -1 -1 ] [ -1 -1 1 ] [ -1 1 -1 ] [ -1 1 1 ] [ 1 -1 -1 ] [ 1 -1 1 ] [ 1 1 -1 ] [ 1 1 1 ] ]
edge[][] = [ [ 1 2 ] [ 2 4 ] [ 4 3 ] [ 3 1 ] [ 5 6 ] [ 6 8 ] [ 8 7 ] [ 7 5 ] [ 1 5 ] [ 2 6 ] [ 3 7 ] [ 4 8 ] ]
node[][] &= [ -1 1 -1 ]
node[][] &= [ -1 1 1 ]
node[][] &= [ 1 -1 -1 ]
node[][] &= [ 1 -1 1 ]
node[][] &= [ 1 1 -1 ]
node[][] &= [ 1 1 1 ]
#
proc scale f . .
edge[][] &= [ 0 1 ]
for i = 1 to len node[][]
edge[][] &= [ 1 3 ]
for d = 1 to 3
edge[][] &= [ 3 2 ]
edge node[i][d] &*= [ 2 0 ]f
edge[][] &= [ 4 5 ] .
.
edge[][] &= [ 5 7 ]
edge[][] &= [ 7 6 ]
edge[][] &= [ 6 4 ]
edge[][] &= [ 0 4 ]
edge[][] &= [ 1 5 ]
edge[][] &= [ 2 6 ]
edge[][] &= [ 3 7 ]
#
func scale f . .
for i range len node[][]
swap n[] node[i][]
n[0] *= f
n[1] *= f
n[2] *= f
swap n[] node[i][]
.
.
funcproc rotate angx angy . .
sinx = sin angx
cosx = cos angx
siny = sin angy
cosy = cos angy
for i range= 1 to len node[][]
swap n[] x = node[i][1]
x z = nnode[i][03]
y = nnode[i][1] = x * cosx - z * sinx
z y = nnode[i][2]
n[0] z = xz * cosx -+ zx * sinx
n node[i][2] = zy * cosxcosy +- xz * sinxsiny
node[i][3] = z * cosy + y * siny
z = n[2]
.
n[1] = y * cosy - z * siny
n[2] = z * cosy + y * siny
swap n[] node[i][]
.
.
len nd[] 3
funcproc draw . .
clear
clear_screen
m = 999
mi = -1
for i range= 1 to len node[][]
if node[i][23] < m
m = node[i][23]
mi = i
.
.
ix = 0
for i range len edge[][]
if edge[i][0] = mi
nd[ix] = edge[i][1]
ix += 1
elif edge[i][1] = mi
nd[ix] = edge[i][0]
ix += 1
.
.
for ni range len nd[]
for i range len edge[][]
if edge[i][0] = nd[ni] or edge[i][1] = nd[ni]
x1 = node[edge[i][0]][0]
y1 = node[edge[i][0]][1]
x2 = node[edge[i][1]][0]
y2 = node[edge[i][1]][1]
move_pen x1 + 50 y1 + 50
draw_line x2 + 50 y2 + 50
.
.
. ix = 1
for i = 1 to len edge[][]
if edge[i][1] = mi
nd[ix] = edge[i][2]
ix += 1
elif edge[i][2] = mi
nd[ix] = edge[i][1]
ix += 1
.
.
for ni = 1 to len nd[]
for i = 1 to len edge[][]
if edge[i][1] = nd[ni] or edge[i][2] = nd[ni]
x1 = node[edge[i][1]][1]
y1 = node[edge[i][1]][2]
x2 = node[edge[i][2]][1]
y2 = node[edge[i][2]][2]
move x1 + 50 y1 + 50
line x2 + 50 y2 + 50
.
.
.
.
call scale 25
call rotate 45 atan sqrt 2
call draw
on animate
call rotate 1 0
call draw
.
.</lang>
</syntaxhighlight>
 
=={{header|Evaldraw}}==
 
Based on the solution in draw cuboid.
Draws a filled cube with a texture on each face.
 
[[File:Evaldraw cube rotate.gif|thumb|alt=Rotating 3D cube|Rotating cube with texture. Makes use of rudimentary glBegin(GL_QUADS) function]]
 
<syntaxhighlight lang="C">
// We can define our own vec3 struct
struct vec3{x,y,z;}
static modelMatrix[9];
() {
cls(0x828282); // clear screen
clz(1e32); // clear depth buffer
setcam(0,0,-3,0,0); // set camera some units back
// create two local arrays to hold rotation matrices
double roty[9], rotz[9];
static otim;
tim=klock(0); dt=tim-otim; otim=tim;
static degrees = 0;
degrees+=200*dt;
rads = degrees/180*pi;
rotateZ( rotz, rads );
rotateY( roty, rads );
// evaldraw does support some GL-like drawing
// modes, but any transformations must be done by hand
// Here we use a global model matrix that
// transforms vertices created by the myVertex function
mult(modelMatrix, roty, rotz);
glSetTex("cloud.png");
drawcuboid(0,0,0,1,1,1);
}
 
drawcuboid(x,y,z,sx,sy,sz) {
glBegin(GL_QUADS);
setcol(192,32,32);
glTexCoord(0,0); myVertex(x-sx,y-sy,z-sz);
glTexCoord(1,0); myVertex(x+sx,y-sy,z-sz);
glTexCoord(1,1); myVertex(x+sx,y+sy,z-sz);
glTexCoord(0,1); myVertex(x-sx,y+sy,z-sz);
setcol(32,192,32);
glTexCoord(0,0); myVertex(x-sx,y-sy,z+sz);
glTexCoord(1,0); myVertex(x-sx,y-sy,z-sz);
glTexCoord(1,1); myVertex(x-sx,y+sy,z-sz);
glTexCoord(0,1); myVertex(x-sx,y+sy,z+sz);
setcol(32,32,192);
glTexCoord(0,0); myVertex(x+sx,y-sy,z+sz);
glTexCoord(1,0); myVertex(x-sx,y-sy,z+sz);
glTexCoord(1,1); myVertex(x-sx,y+sy,z+sz);
glTexCoord(0,1); myVertex(x+sx,y+sy,z+sz);
setcol(192,192,32);
glTexCoord(0,0); myVertex(x+sx,y-sy,z-sz);
glTexCoord(1,0); myVertex(x+sx,y-sy,z+sz);
glTexCoord(1,1); myVertex(x+sx,y+sy,z+sz);
glTexCoord(0,1); myVertex(x+sx,y+sy,z-sz);
 
setcol(192,32,192);
glTexCoord(0,0); myVertex(x-sx,y-sy,z+sz);
glTexCoord(1,0); myVertex(x+sx,y-sy,z+sz);
glTexCoord(1,1); myVertex(x+sx,y-sy,z-sz);
glTexCoord(0,1); myVertex(x-sx,y-sy,z-sz);
 
setcol(32,192,192);
glTexCoord(0,0); myVertex(x-sx,y+sy,z-sz);
glTexCoord(1,0); myVertex(x+sx,y+sy,z-sz);
glTexCoord(1,1); myVertex(x+sx,y+sy,z+sz);
glTexCoord(0,1); myVertex(x-sx,y+sy,z+sz);
glEnd();
}
myVertex(x,y,z) {
// Initialize a struct value
vec3 v = {x,y,z};
// Apply global model matrix transformation
transformPoint(v, modelMatrix);
// Submit the vertex to draw list
glVertex(v.x, v.y, v.z);
}
rotateY(m[9], r) {
c = cos(r); s=sin(r);
m[0] = c; m[1] = 0; m[2] = s;
m[3] = 0; m[4] = 1; m[5] = 0;
m[6] = -s; m[7] = 0; m[8] = c;
}
 
rotateZ(m[9], r) {
c = cos(r); s=sin(r);
m[0] = c; m[1] = -s; m[2] = 0;
m[3] = s; m[4] = c; m[5] = 0;
m[6] = 0; m[7] = 0; m[8] = 1;
}
transformPoint(vec3 v, m[9]) {
x2 = v.x * m[0] + v.y * m[1] + v.z * m[2];
y2 = v.x * m[3] + v.y * m[4] + v.z * m[5];
z2 = v.x * m[6] + v.y * m[7] + v.z * m[8];
// Mutate the struct v with new values
v.x=x2; v.y=y2; v.z=z2;
}
mult(c[9],a[9],b[9]) { // C = AB
// multiply a row in A with a column in B
for(i=0; i<3; i++)
for(j=0; j<3; j++) {
sum = 0.0;
for(k=0; k<3; k++) {
sum += A[k*3+i] * B[k*3+j];
}
C[i*3+j] = sum;
}
}
</syntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#define PI 3.14159265358979323
#define SCALE 50
#define SIZE 320
Line 865 ⟶ 1,176:
drawcube x(),0
wend
end</langsyntaxhighlight>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
[[File:rotating_cube.jpg|200px|thumb|right]]
include "Tlbx SceneKit.incl"
Among the capabilities of FutureBasic (or FB as it's called by its developers) is the ability to compile Open GL code as demonstrated here.
 
_window = 1
<lang futurebasic>
begin enum output 1
include "Tlbx agl.incl"
_sceneView
include "Tlbx glut.incl"
end enum
 
local fn RotatingCubeScene as SCNSceneRef
output file "Rotating Cube"
SCNSceneRef scene = fn SCNSceneInit
SCNNodeRef rootNode = fn SCNSceneRootNode( scene )
SCNCameraRef camera = fn SCNCameraInit
SCNNodeRef cameraNode = fn SCNNodeInit
SCNNodeSetCamera( cameraNode, camera )
SCNNodeAddChildNode( rootNode, cameraNode )
SCNVector3 cameraPos = {0.0, 0.0, 10.0}
SCNNodeSetPosition( cameraNode, cameraPos )
SCNNodeRef lightNode = fn SCNNodeInit
SCNLightRef light = fn SCNLightInit
SCNLightSetType( light, SCNLightTypeOmni )
SCNNodeSetPosition( lightNode, fn SCNVector3Make( 0.0, 10.0, 10.0 ) )
SCNNodeAddChildNode( rootNode, lightNode )
SCNNodeRef ambientLightNode = fn SCNNodeInit
SCNLightRef ambientLight = fn SCNLightInit
SCNLightSetType( ambientLight, SCNLightTypeAmbient )
SCNLightSetColor( ambientLight, fn ColorGray )
SCNNodeSetLight( ambientLightNode, ambientLight )
SCNNodeAddChildNode( rootNode, ambientLightNode )
SCNBoxRef boxGeometry = fn SCNBoxInit( 4.0, 4.0, 4.0, 0.0 )
SCNNodeRef boxNode = fn SCNNodeWithGeometry( boxGeometry )
SCNMaterialRef side1 = fn SCNMaterialInit
SCNMaterialRef side2 = fn SCNMaterialInit
SCNMaterialRef side3 = fn SCNMaterialInit
SCNMaterialRef side4 = fn SCNMaterialInit
SCNMaterialRef side5 = fn SCNMaterialInit
SCNMaterialRef side6 = fn SCNMaterialInit
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side1 ), fn ColorBlue )
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side2 ), fn ColorOrange )
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side3 ), fn ColorRed )
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side4 ), fn ColorGreen )
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side5 ), fn ColorYellow )
SCNMaterialPropertySetContents( fn SCNMaterialMultiply( side6 ), fn ColorCyan )
SCNGeometrySetMaterials( boxGeometry, @[side1,side2,side3,side4,side5,side6] )
SCNNodeAddChildNode( rootNode, boxNode )
SCNActionableRunAction( boxNode, fn SCNActionRepeatActionForever( fn SCNActionRotateByAngle( M_PI, fn SCNVector3Make( 0.0, 25.0, 5.0 ), 5.0 ) ) )
end fn = scene
 
void local fn AnimateCubeBuildWindow
window _window, @"Rosetta Code Rotating Cube", ( 0, 0, 600, 600 )
'~'1
scnview _sceneView, fn RotatingCubeScene, ( 0, 0, 600, 600 )
begin globals
SCNViewSetBackgroundColor( _sceneView, fn ColorBlack )
dim as double  sRotation
SCNViewSetAllowsCameraControl( _sceneView, YES )
end globals
end fn
 
void local fn DoDialog( ev as long, tag as long, wnd as long )
// Speed of rotation
select (ev)
sRotation += 2.9
case _windowWillClose : end
glMatrixMode( _GLMODELVIEW )
end select
 
glLoadIdentity()
glTranslated( 0.0, 0.0, 0.0 )
glRotated( sRotation, -0.45, -0.8, -0.6 )
glColor3d( 1.0, 0.0, 0.3 )
glLineWidth( 1.5 )
glutWireCube( 1.0 )
end fn
 
on dialog fn DoDialog
// Main program
dim as GLint           attrib(2)
dim as CGrafPtr        port
dim as AGLPixelFormat  fmt
dim as AGLContext      glContext
dim as EventRecord     ev
dim as GLboolean       yesOK
 
fn BuildWindow
window 1, @"Rotating Cube", (0,0) - (500,500)
 
attrib(0) = _AGLRGBA
attrib(1) = _AGLDOUBLEBUFFER
attrib(2) = _AGLNONE
 
fmt = fn aglChoosePixelFormat( 0, 0, attrib(0) )
glContext = fn aglCreateContext( fmt, 0 )
aglDestroyPixelFormat( fmt )
 
port = window( _wndPort )
yesOK = fn aglSetDrawable( glContext, port )
yesOK = fn aglSetCurrentContext( glContext )
 
glClearColor( 0.0, 0.0, 0.0, 0.0 )
 
poke long event - 8, 1
do
glClear( _GLCOLORBUFFERBIT )
fn AnimateCube
aglSwapBuffers( glContext )
HandleEvents
</syntaxhighlight>
until gFBQuit
{{output}}
</lang>
[[File:FutureBasic Rotating Cube.png]]
 
=={{header|Go}}==
As of Go 1.9, it looks as if the only standard library supporting animated graphics is image/gif - so we create an animated GIF...
<langsyntaxhighlight Golang="go">package main
 
import (
Line 1,034 ⟶ 1,362:
}
return x
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
This implementation compiles to JavaScript that runs in a browser using the [https://github.com/ghcjs/ghcjs ghcjs compiler ] . The [https://github.com/reflex-frp/reflex-dom reflex-dom ] library is used to help with svg rendering and animation.
 
<langsyntaxhighlight Haskelllang="haskell">{-# LANGUAGE RecursiveDo #-}
import Reflex.Dom
import Data.Map as DM (Map, lookup, insert, empty, fromList)
Line 1,218 ⟶ 1,546:
elDynAttrSVG a2 a3 a4 = do
elDynAttrNS' (Just "http://www.w3.org/2000/svg") a2 a3 a4
return ()</langsyntaxhighlight>
 
Link to live demo: https://dc25.github.io/drawRotatingCubeHaskell/
Line 1,226 ⟶ 1,554:
Derived from J's [https://github.com/jsoftware/demos_qtdemo/blob/master/shader.ijs qt shader demo]:
 
<langsyntaxhighlight Jlang="j">require'gl2 gles ide/qt/opengl'
coinsert'jgl2 jgles qtopengl'
 
Line 1,363 ⟶ 1,691:
colorData=: unitCube NB. corresponding colors
 
rotcube''</langsyntaxhighlight>
 
A variation which did not use opengl would probably be much more concise.
Line 1,369 ⟶ 1,697:
=={{header|Java}}==
[[File:rotating_cube_java.png|200px|thumb|right]]
<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.event.ActionEvent;
import static java.lang.Math.*;
Line 1,460 ⟶ 1,788:
});
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{trans|Java}}
<langsyntaxhighlight lang="javascript"><!DOCTYPE html>
<html lang="en">
<head>
Line 1,552 ⟶ 1,880:
 
</body>
</html></langsyntaxhighlight>
 
=={{header|Julia}}==
Run at the Julia REPL command line.
<langsyntaxhighlight Julialang="julia">using Makie, LinearAlgebra
 
N = 40
Line 1,568 ⟶ 1,896:
Makie.rotate!(rect, Quaternionf0(arr[1], arr[2], arr[3], arr[4]))
sleep(interval)
end</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// version 1.1
 
import java.awt.*
Line 1,672 ⟶ 2,000:
f.isVisible = true
}
}</langsyntaxhighlight>
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">local abs,atan,cos,floor,pi,sin,sqrt = math.abs,math.atan,math.cos,math.floor,math.pi,math.sin,math.sqrt
local bitmap = {
init = function(self, w, h, value)
Line 1,766 ⟶ 2,094:
screen:clear()
bitmap:render()
end</langsyntaxhighlight>
{{out}}
<pre style="font-size:50%">Frame 1:
Line 1,850 ⟶ 2,178:
················································································
················································································</pre>
 
=={{header|M2000 Interpreter}}==
[[File:Cube.png|thumb|Cube Example]]
Draw on M2000 console. Using of GDI+ for smooth lines. Using Every {} structure and Refresh 100 to immediate refresh double buffer, and set 100ms for the next auto refresh. So we erase the screen without refresh and draw again after dt time. Cube has 6 more lines for fancy drawing. Also time displayed. We can move the cube (and accelarate the rotation as we press a mouse button).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
<syntaxhighlight lang="m2000 interpreter">
Module Cube3D {
form 80, 32
smooth on // enable GDI+ smooth lines
zoff=0.5773502691896257645091487805019574556@
cylr=1.6329931618554520654648560498039275946@
oX=scale.x div 2 : oY=scale.y div 2
SCALE=min.data(oX, oY)/2*.6
gradient 0
theta = 0.0 : dtheta = 1.5 : dt = 1000/60
ScZof=SCALE/zoff
ScZofM=SCALE*zoff
dim cylphi(), x()
c =(PI/6, 5*PI/6, 3*PI/2, 11*PI/6, PI/2, 7*PI/6) : c*=180/Pi : cylphi()=c // cos() take Degree
every DT {
if mouse then (oX, oY)=(mouse.x,mouse.y) : dtheta*=1.05 else dtheta = 1.5
dim x(6)=oX : for i=0 to 5: x(i) += SCALE*cylr*cos(cylphi(i)+theta):next
drawcube() : refresh 100 : IF keypress(32) then exit
theta += dtheta : gradient 0, 5: cursor 0,0
Print "Press space to exit",,"Press any mouse button to move cube",,Time$(Now)
}
sub drawcube()
for i= 0 to 2
move x(i), oY-ScZofM:draw to oX,oY-ScZof, 11
move oX,ScZof+oY:draw to x(i),oY-ScZofM, 9
move oX,oY+ ScZof:draw to x(5-i),ScZofM+oY
move x(i),oY-ScZofM:draw to x(i mod 3 + 3),oY+ScZofM, 15
move oX,oY-ScZof:draw to x(i mod 3 + 3), oY+ScZofM, 7
move x(i),oY-ScZofM:draw to x((i+1) mod 3 + 3),oY+ScZofM, 13
next
end sub
}
Cube3D
</syntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">plots:-display(
seq(
plots:-display(
Line 1,858 ⟶ 2,241:
axes=none, scaling=constrained, orientation=[0,45,i] ),
i = 0..360, 20 ),
insequence=true );</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Dynamic[
Graphics3D[
GeometricTransformation[
Line 1,867 ⟶ 2,250:
RotationTransform[Clock[2 Pi], {0, 0, 1}]
],
Boxed -> False]]</langsyntaxhighlight>
 
=={{header|MiniScript}}==
{{works with|Mini Micro}}
 
<syntaxhighlight lang="MiniScript">import "mathUtil"
scale = 250
radius = sqrt(scale^2)
 
Face = new Sprite
Face.image = file.loadImage("/sys/pics/shapes/SquareThin.png")
 
clear; gfx.clear color.gray
sprites = display(4).sprites
 
// build a sprite for each side
for i in range(0, 3)
sp = new Face
sp.x = 480; sp.y = 320
yBot = -sin(pi/4)
yTop = sin(pi/4)
cosAngL = cos(i*pi/2); sinAngL = sin(i*pi/2)
cosAngR = cos((i+1)*pi/2); sinAngR = sin((i+1)*pi/2)
sp.corners3d = [
[cosAngL, yBot, sinAngL], [cosAngR, yBot, sinAngR],
[cosAngR, yTop, sinAngR], [cosAngL, yTop, sinAngL] ]
sp.color = [color.yellow, color.aqua, color.pink, color.lime][i]
sprites.push sp
end for
// ...and one for the top
top = new Face
top.x = 480; top.y = 320
top.corners3d = []
for i in range(0, 3)
top.corners3d.push [cos(i*pi/2), sin(pi/4), sin(i*pi/2)]
end for
sprites.push top
 
// Rotate the given [x,y,z] point by some number of degrees
// around the Y axis, then project to the screen.
rotateAndProject = function(point3d, rotDegrees)
radians = rotDegrees * pi/180
cosAng = cos(radians); sinAng = sin(radians)
// First, rotate around the Y axis in 3D space
x = point3d[0] * cosAng - point3d[2] * sinAng
y = point3d[1]
z = point3d[0] * sinAng + point3d[2] * cosAng
// Then, project this to the screen
result = [480 + x * scale, 320 + y * scale + z*0]
p = (8 - z) / 8 // (perspective factor)
return mathUtil.lerp2d(result, [480,800], 1-p)
end function
 
// Position all the sprites where they should be on screen for the given rotation.
positionSprites = function(rotDegrees)
for sp in sprites
corners = []
for i in range(0,3)
corners.push rotateAndProject(sp.corners3d[i], rotDegrees)
end for
sp.setCorners corners
if sp == top then continue
if corners[1][0] > corners[0][0] then
sp.tint = sp.color
else
sp.tint = color.clear
end if
end for
end function
 
// Main program
rot = 0
while not key.pressed("escape") and not key.pressed("q")
yield
positionSprites rot
rot = rot + 1
end while
key.clear</syntaxhighlight>
 
{{output}}
[[File:MiniScript-spnning-cube.gif|alt=MiniScript spinning cube solution|MiniScript spinning cube solution]]
 
=={{header|Nim}}==
{{trans|Ada}}
{{libheader|SDL2}}
<langsyntaxhighlight Nimlang="nim">import math
import sdl2
 
Line 1,952 ⟶ 2,415:
while not endSimulation:
endSimulation = drawCube()
window.destroy()</langsyntaxhighlight>
 
=={{header|Objeck}}==
{{libheader|SDL2}}
{{trans|Ada}}
<langsyntaxhighlight lang="objeck">#~
Rotating Cube
~#
Line 2,078 ⟶ 2,541:
SCREEN_HEIGHT := 600,
DRAW_OFFSET := 300
}</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
Using An OpenGl-based console
<syntaxhighlight lang="text">
% Title "Rotating Cube"
% Animated
% PlaceCentral
uses ConsoleG
 
sub main
========
cls 0.0, 0.5, 0.7
shading
scale 7
pushstate
GoldMaterial.act
static float ang
rotateX ang
rotateY ang
go cube
popstate
ang+=.5 : if ang>=360 then ang-=360
end sub
 
EndScript
</syntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict; # http://www.rosettacode.org/wiki/Draw_a_rotating_cube
Line 2,111 ⟶ 2,600:
$c->createLine( $mid, $height, @points[10, 11], -width => 5,);
$mw->after($wait, \&draw);
}</langsyntaxhighlight>
 
=={{header|Phix}}==
Line 2,117 ⟶ 2,606:
{{libheader|Phix/online}}
You can run this online [http://phix.x10.mx/p2js/drawrotatingcube.htm here].
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\DrawRotatingCube.exw
Line 2,321 ⟶ 2,810:
<span style="color: #000000;">main</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PostScript}}==
'''Don't send this to your printer!'''
<langsyntaxhighlight lang="postscript">%!PS-Adobe-3.0
%%BoundingBox: 0 0 400 400
 
Line 2,361 ⟶ 2,850:
 
0 {3.2 add dup page } loop
%%EOF</langsyntaxhighlight>
 
=={{header|Processing}}==
Create a cube in Processing with box(), rotate the scene with rotate(), and drive the rotation with either the built-in millis() or frameCount timers.
 
<langsyntaxhighlight Processinglang="processing">void setup() {
size(500, 500, P3D);
}
Line 2,382 ⟶ 2,871:
// draw box
box(300, 300, 300);
}</langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,391 ⟶ 2,880:
 
====Short version====
<langsyntaxhighlight lang="python">from visual import *
scene.title = "VPython: Draw a rotating cube"
 
Line 2,409 ⟶ 2,898:
rate(50)
cube.rotate( angle=0.005, axis=(0,1,0) )
</syntaxhighlight>
</lang>
 
<!--
Line 2,416 ⟶ 2,905:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket/gui
(require math/matrix math/array)
 
Line 2,485 ⟶ 2,974:
(send c refresh))
 
(define t (new timer% [notify-callback refresh] [interval 35] [just-once? #f]))</langsyntaxhighlight>
 
=={{header|Raku}}==
Line 2,492 ⟶ 2,981:
Raku has no native graphics libraries built in, but makes it fairly easy to bind to third party libraries. Here we'll use bindings to [[wp:Libcaca|Libcaca]], the '''C'''olor '''A'''S'''C'''II '''A'''rt library to generate a rotating cube in an ASCII terminal.
 
<syntaxhighlight lang="raku" perl6line>use Terminal::Caca;
given my $canvas = Terminal::Caca.new {
.title('Rosetta Code - Rotating cube - Press any key to exit');
Line 2,584 ⟶ 3,073:
.cleanup;
}
}</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
#===================================================================#
# Based on Original Sample from RayLib (https://www.raylib.com/)
Line 2,665 ⟶ 3,154:
 
CloseWindow()
</syntaxhighlight>
</lang>
[https://www.mediafire.com/view/xjimb82x8lvfwd9/RotatingCube.jpg/file Rotating a Cube]
 
Line 2,673 ⟶ 3,162:
{{libheader|Scala GUI Animation}}
{{works with|Scala|2.13}}
<langsyntaxhighlight Scalalang="scala">import java.awt.event.ActionEvent
import java.awt._
 
Line 2,760 ⟶ 3,249:
}
 
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 2,771 ⟶ 3,260:
See [http://wiki.tcl.tk/14283 this wiki page] (and others linked from it) for many similar examples.
 
<langsyntaxhighlight Tcllang="tcl"># matrix operation support:
package require math::linearalgebra
namespace import ::math::linearalgebra::matmul
Line 2,903 ⟶ 3,392:
}
set ::world [make_cube 100]
tick</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
<langsyntaxhighlight lang="ti83b">:-1→Xmin:1→Xmax
:-1→Ymin:1→Ymax
:AxesOff
Line 2,928 ⟶ 3,417:
:Line(.3,FV,-.3,-PV
:End
:End</langsyntaxhighlight>
 
I%, PV, and FV are all finance variables that can be found in the finance menu (inside the APPS menu on TI-83+ and up).
Line 2,936 ⟶ 3,425:
{{trans|Kotlin}}
{{libheader|DOME}}
<langsyntaxhighlight ecmascriptlang="wren">import "graphics" for Canvas, Color
import "dome" for Window
import "math" for Math
Line 3,030 ⟶ 3,519:
}
 
var Game = RotatingCube.new(640, 640)</langsyntaxhighlight>
 
=={{header|XPL0}}==
The main challenge was figuring out the initial coordinates of the cube.
Zometool came to the rescue. The program runs much smoother than the animated gif.
<langsyntaxhighlight XPL0lang="xpl0">def Size=100., Speed=0.05; \drawing size and rotation speed
real X, Y, Z, Farthest; \arrays: 3D coordinates of vertices
int I, J, K, ZI, Edge;
Line 3,063 ⟶ 3,552:
until KeyHit; \run until a key is struck
SetVid(3); \restore normal text mode
]</langsyntaxhighlight>
 
{{out}}
http://www.xpl0.org/rotcube2.gif
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Draw_a_rotating_cube
// adapted to Yabasic by Galileo, 05/2022
 
// GFA Punch (code from tigen.ti-fr.com/)
// Carré 3D en rotation
 
open window 50, 70
backcolor 0,0,0
clear window
color 255,255,255
 
do
clear window
x = COS(T) * 20
y = SIN(T) * 18
r = SIN(T + T)
line (x + 40), (y + 40 - r), (-y + 40), (x + 40 - r)
line (-y + 40), (x + 40 - r), (-x + 40), (-y + 40 - r)
line (-x + 40), (-y + 40 - r), (y + 40), (-x + 40 - r)
line (y + 40), (-x + 40 - r), (x + 40), (y + 40 - r)
line (x + 40), (y + 20 + r), (-y + 40), (x + 20 + r)
line (-y + 40), (x + 20 + r), (-x + 40), (-y + 20 + r)
line (-x + 40), (-y + 20 + r), (y + 40), (-x + 20 + r)
line (y + 40), (-x + 20 + r), (x + 40), (y + 20 + r)
line (x + 40), (y + 40 - r), (x + 40), (y + 20 + r)
line (-y + 40), (x + 40 - r), (-y + 40), (x + 20 + r)
line (-x + 40), (-y + 40 - r), (-x + 40), (-y + 20 + r)
line (y + 40), (-x + 40 - r), (y + 40), (-x + 20 + r)
 
pause 0.02
T = T + 0.15
loop</syntaxhighlight>
 
=={{header|Zig}}==
{{libheader|Raylib}}
{{works with|Zig|0.11.0}} {{works with|Raylib|4.6}}
<syntaxhighlight lang="zig">const std = @import("std");
const c = @cImport({
@cInclude("raylib.h");
@cInclude("rlgl.h");
});
 
const dark_mode = true;
const show_grid = false;
 
pub fn main() !void {
const screen_width = 640;
const screen_height = 360;
 
const cube_side = 1;
const size = c.Vector3{ .x = cube_side, .y = cube_side, .z = cube_side };
const position = c.Vector3{ .x = 0, .y = 0, .z = 0 };
const x_rot = 45;
const y_center: f32 = std.math.sqrt(3.0) * cube_side / 2.0;
const z_rot = std.math.radiansToDegrees(f32, std.math.atan(@as(f32, std.math.sqrt1_2)));
 
c.SetConfigFlags(c.FLAG_WINDOW_RESIZABLE | c.FLAG_VSYNC_HINT);
c.InitWindow(screen_width, screen_height, "Draw a Rotating Cube");
defer c.CloseWindow();
 
var camera = c.Camera{
.position = .{ .x = 3, .y = 3, .z = 3 },
.target = .{ .x = 0, .y = y_center, .z = 0 }, // Center of cube
.up = .{ .x = 0, .y = 1, .z = 0 },
.fovy = 45, // Camera field-of-view Y
.projection = c.CAMERA_PERSPECTIVE,
};
 
c.SetTargetFPS(60);
 
while (!c.WindowShouldClose()) // Detect window close button or ESC key
{
c.UpdateCamera(&camera, c.CAMERA_ORBITAL);
 
c.BeginDrawing();
defer c.EndDrawing();
 
c.ClearBackground(if (dark_mode) c.BLACK else c.RAYWHITE);
{
c.BeginMode3D(camera);
defer c.EndMode3D();
{
c.rlPushMatrix();
defer c.rlPopMatrix();
c.rlTranslatef(0, y_center, 0);
c.rlRotatef(z_rot, 0, 0, 1);
c.rlRotatef(x_rot, 1, 0, 0);
c.DrawCubeWiresV(position, size, if (dark_mode) c.LIME else c.BLACK);
}
if (show_grid) c.DrawGrid(12, 0.75);
}
}
}</syntaxhighlight>
 
[[Category:Geometry]]
59

edits