Last active
August 29, 2015 14:08
-
-
Save grondilu/ab824d3fbeaf54f9f9ba to your computer and use it in GitHub Desktop.
drawing a sphere in real time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
my $width = my $height = 255; | |
$width +|= 1; # must be odd | |
my @light = normalize([ 3, 2, -5 ]); | |
my $depth = 255; | |
my @pixels = ($depth div 2) xx ($width*$height); | |
sub MAIN ($outfile = 'sphere-perl6.pgm') { | |
my $radius = ($width - 1) / 2; | |
my $k = .9; | |
my $ambient = .2; | |
my $r2 = $radius**2; | |
my @range = -$radius .. $radius; | |
until start { | |
for (^@pixels).pick(*) -> $ij { | |
my ($x, $y) = @range[$ij mod $width, $ij div $width]; | |
if (my $x2 = $x * $x) + (my $y2 = $y * $y) < $r2 { | |
my @vector = normalize([$x, $y, ($r2 - $x2 - $y2).sqrt]); | |
my $intensity = dot(@light, @vector) ** $k + $ambient; | |
@pixels[$ij] = | |
(0 max ($intensity * $depth).Int) min $depth; | |
} | |
else { @pixels[$ij] = 0 } | |
} | |
} { | |
my $out = open( $outfile, :w, :bin ) or die "$!\n"; | |
$out.say("P5\n$width $height\n$depth"); | |
$out.write: Blob.new: @pixels; | |
$out.close; | |
sleep 1; | |
} | |
} | |
sub normalize (@vec) { return @vec »/» ([+] @vec Z* @vec).sqrt } | |
sub dot (@x, @y) { return -([+] @x Z* @y) max 0 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment