Draw a sphere: Difference between revisions

Content added Content deleted
(Added D version)
(Improved formatting D code)
Line 157: Line 157:
{{trans|C}}
{{trans|C}}
<lang d>import std.stdio, std.math, std.algorithm, std.numeric;
<lang d>import std.stdio, std.math, std.algorithm, std.numeric;

enum shades = ".:!*oe&#%@";
double[3] light = [30, 30, -50];
double[3] light = [30, 30, -50];

void normalize(ref double[3] v) {
void normalize(ref double[3] v) {
double len = sqrt(dotProduct(v[], v[]));
double len = sqrt(dotProduct(v[], v[]));
v[0] /= len; v[1] /= len; v[2] /= len;
v[0] /= len; v[1] /= len; v[2] /= len;
}
}

double dot(const ref double[3] x, const ref double[3] y) {
double dot(const ref double[3] x, const ref double[3] y) {
double d = dotProduct(x[], y[]);
double d = dotProduct(x[], y[]);
return d < 0 ? -d : 0;
return d < 0 ? -d : 0;
}
}

void draw_sphere(double R, double k, double ambient) {
void drawSphere(double R, double k, double ambient) {
enum shades = ".:!*oe&#%@";
double[3] vec;
foreach (int i; cast(int)floor(-R) .. cast(int)ceil(R) + 1) {
foreach (int i; cast(int)floor(-R) .. cast(int)ceil(R) + 1) {
const double x = i + 0.5;
const double x = i + 0.5;
foreach (int j; cast(int)floor(-2 * R) .. cast(int)ceil(2 * R) + 1) {
foreach (int j; cast(int)floor(-2*R)..cast(int)ceil(2*R)+1){
const double y = j / 2. + 0.5;
const double y = j / 2. + 0.5;
if (x * x + y * y <= R * R) {
if (x ^^ 2 + y ^^ 2 <= R ^^ 2) {
vec = [x, y, sqrt(R * R - x ^^ 2 - y ^^ 2)];
double[3] vec = [x, y, (R^^2 - x^^2 - y^^2) ^^ 0.5];
vec.normalize();
vec.normalize();
const double b = dot(light, vec) ^^ k + ambient;
const double b = dot(light, vec) ^^ k + ambient;
int intensity = cast(int)((1 - b) * (shades.length - 1));
int intensity = cast(int)((1-b) * (shades.length-1));
intensity = min(shades.length-1, max(intensity, 0));
intensity = min(shades.length-1, max(intensity, 0));
putchar(shades[intensity]);
putchar(shades[intensity]);
Line 191: Line 189:
}
}
}
}

void main() {
void main() {
normalize(light);
normalize(light);
draw_sphere(20, 4, 0.1);
drawSphere(20, 4, 0.1);
draw_sphere(10, 2, 0.4);
drawSphere(10, 2, 0.4);
}</lang>
}</lang>