Death Star: Difference between revisions

Content added Content deleted
(Maple Version)
(→‎{{header|Sidef}}: simplified the code to use the Vector class and added link to the output image)
Line 1,600: Line 1,600:
{{trans|Perl}}
{{trans|Perl}}
Writes a PGM to stdout.
Writes a PGM to stdout.
<lang ruby>func sq(*nums) {
<lang ruby>func hitf(sph, x, y) {
nums »**» 2 «+»;
x -= sph[0]
y -= sph[1]
}


func hitf(sph, x, y) {
var z = (sph[3]**2 - (x**2 + y**2))
x -= sph[0];
y -= sph[1];


var z = (sq(sph[3]) - sq(x, y));
z < 0 && return nil
z < 0 && return nil;


z.sqrt!;
z.sqrt!
[sph[2] - z, sph[2] + z];
[sph[2] - z, sph[2] + z]
}
}


func normalize(v) {
func normalize(v) {
var n = sq(v...).sqrt;
v / v.abs
v »/» n;
}
}


func dot(x, y) {
func dot(x, y) {
var s = (x[0]*y[0] + x[1]*y[1] + x[2]*y[2]);
max(0, x*y)
s > 0 ? s : 0;
}
}


var pos = [120, 120, 0, 120];
var pos = [120, 120, 0, 120]
var neg = [-77, -33, -100, 190];
var neg = [-77, -33, -100, 190]
var light = normalize([-12, 13, -10]);
var light = normalize(Vector(-12, 13, -10))


func draw(k, amb) {
func draw(k, amb) {
STDOUT.binmode(':raw');
STDOUT.binmode(':raw')
print ("P5\n", pos[0]*2 + 3, " ", pos[1]*2 + 3, "\n255\n");
print ("P5\n", pos[0]*2 + 3, " ", pos[1]*2 + 3, "\n255\n")


for y in ((pos[1] - pos[3] - 1) .. (pos[1] + pos[3] + 1)) {
for y in ((pos[1] - pos[3] - 1) .. (pos[1] + pos[3] + 1)) {
var row = [];
var row = []
for x in ((pos[0] - pos[3] - 1) .. (pos[0] + pos[3] + 1)) {
for x in ((pos[0] - pos[3] - 1) .. (pos[0] + pos[3] + 1)) {

var hit = 0;
var hs = [];
var hit = 0
var h = hitf(pos, x, y);
var hs = []
var h = hitf(pos, x, y)


if (!h) { hit = 0; h = [0, 0] }
if (!h) { hit = 0; h = [0, 0] }
Line 1,644: Line 1,640:
elsif (hs[0] > h[0]) { hit = 1 }
elsif (hs[0] > h[0]) { hit = 1 }
elsif (hs[1] > h[0]) { hit = (hs[1] > h[1] ? 0 : 2) }
elsif (hs[1] > h[0]) { hit = (hs[1] > h[1] ? 0 : 2) }
else { hit = 1 };
else { hit = 1 }

var (val, v)


var (val, v);
given(hit) {
given(hit) {
when (0) { val = 0}
when (0) { val = 0}
when (1) { v = [x-pos[0], y-pos[1], h[0]-pos[2]] }
when (1) { v = Vector(x-pos[0], y-pos[1], h[0]-pos[2]) }
default { v = [neg[0]-x, neg[1]-y, neg[2]-hs[1]] }
default { v = Vector(neg[0]-x, neg[1]-y, neg[2]-hs[1]) }
}
}


if (v) {
if (defined(v)) {
v = normalize(v);
v = normalize(v)
val = int((dot(v, light)**k + amb) * 255);
val = int((dot(v, light)**k + amb) * 255)
val = (val > 255 ? 255 : (val < 0 ? 0 : val));
val = (val > 255 ? 255 : (val < 0 ? 0 : val))
};
}
row.append(val);
row.append(val)
}
}
print 'C*'.pack(row...);
print 'C*'.pack(row...)
}
}
}
}


draw(2, 0.2);</lang>
draw(2, 0.2)</lang>
Output image: [https://github.com/trizen/rc/blob/master/img/death_star_sidef.png here].


=={{header|Tcl}}==
=={{header|Tcl}}==