Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -1 +1,8 @@
The task is to draw a cuboid with relative dimensions of 2x3x4. The cuboid can be represented graphically, or in ascii art, depending on the language capabilities. To fulfil the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task.
The task is to draw a [http://en.wikipedia.org/wiki/Cuboid cuboid]
with relative dimensions of 2x3x4.
The cuboid can be represented graphically, or in ascii art,
depending on the language capabilities.
To fulfil the criteria of being a cuboid, three faces must be visible. <br>
Either static or rotational projection is acceptable for this task.

View file

@ -1,4 +1,6 @@
---
category:
- 3D
note: Geometric Primitives
requires:
- Graphics

View file

@ -0,0 +1,136 @@
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
const char *shades = ".:!*oe&#%@";
void vsub(double *v1, double *v2, double *s) {
s[0] = v1[0] - v2[0];
s[1] = v1[1] - v2[1];
s[2] = v1[2] - v2[2];
}
double normalize(double * v) {
double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
v[0] /= len; v[1] /= len; v[2] /= len;
return len;
}
double dot(double *x, double *y) {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
}
double * cross(double x[3], double y[3], double s[3]) {
s[0] = x[1] * y[2] - x[2] * y[1];
s[1] = x[2] * y[0] - x[0] * y[2];
s[2] = x[0] * y[1] - x[1] * y[0];
return s;
}
double* madd(double *x, double *y, double d, double *r) {
r[0] = x[0] + y[0] * d;
r[1] = x[1] + y[1] * d;
r[2] = x[2] + y[2] * d;
return r;
}
double v000[] = { -4, -3, -2 };
double v100[] = { 4, -3, -2 };
double v010[] = { -4, 3, -2 };
double v110[] = { 4, 3, -2 };
double v001[] = { -4, -3, 2 };
double v101[] = { 4, -3, 2 };
double v011[] = { -4, 3, 2 };
double v111[] = { 4, 3, 2 };
typedef struct {
double * v[4];
double norm[3];
} face_t;
face_t f[] = {
{ { v000, v010, v110, v100 }, { 0, 0, -1 } },
{ { v001, v011, v111, v101 }, { 0, 0, 1 } },
{ { v000, v010, v011, v001 }, { -1, 0, 0 } },
{ { v100, v110, v111, v101 }, { 1, 0, 0 } },
{ { v000, v100, v101, v001 }, { 0, -1, 0 } },
{ { v010, v110, v111, v011 }, { 0, 1, 0 } },
};
int in_range(double x, double x0, double x1) {
return (x - x0) * (x - x1) <= 0;
}
int face_hit(face_t *face, double src[3], double dir[3], double hit[3], double *d)
{
int i;
double dist;
for (i = 0; i < 3; i++)
if (face->norm[i])
dist = (face->v[0][i] - src[i]) / dir[i];
madd(src, dir, dist, hit);
*d = fabs(dot(dir, face->norm) * dist);
if (face->norm[0]) {
return in_range(hit[1], face->v[0][1], face->v[2][1]) &&
in_range(hit[2], face->v[0][2], face->v[2][2]);
}
else if (face->norm[1]) {
return in_range(hit[0], face->v[0][0], face->v[2][0]) &&
in_range(hit[2], face->v[0][2], face->v[2][2]);
}
else if (face->norm[2]) {
return in_range(hit[0], face->v[0][0], face->v[2][0]) &&
in_range(hit[1], face->v[0][1], face->v[2][1]);
}
return 0;
}
int main()
{
int i, j, k;
double eye[3] = { 7, 7, 6 };
double dir[3] = { -1, -1, -1 }, orig[3] = {0, 0, 0};
double hit[3], dx[3], dy[3] = {0, 0, 1}, proj[3];
double d, *norm, dbest, b;
double light[3] = { 6, 8, 6 }, ldist[3], decay, strength = 10;
normalize(cross(eye, dy, dx));
normalize(cross(eye, dx, dy));
for (i = -10; i <= 17; i++) {
for (j = -35; j < 35; j++) {
vsub(orig, orig, proj);
madd(madd(proj, dx, j / 6., proj), dy, i/3., proj);
vsub(proj, eye, dir);
dbest = 1e100;
norm = 0;
for (k = 0; k < 6; k++) {
if (!face_hit(f + k, eye, dir, hit, &d)) continue;
if (dbest > d) {
dbest = d;
norm = f[k].norm;
}
}
if (!norm) {
putchar(' ');
continue;
}
vsub(light, hit, ldist);
decay = normalize(ldist);
b = dot(norm, ldist) / decay * strength;
if (b < 0) b = 0;
else if (b > 1) b = 1;
b += .2;
if (b > 1) b = 0;
else b = 1 - b;
putchar(shades[(int)(b * (sizeof(shades) - 2))]);
}
putchar('\n');
}
return 0;
}

View file

@ -0,0 +1,22 @@
(use 'quil.core)
(def w 500)
(def h 400)
(defn setup []
(background 0))
(defn draw []
(push-matrix)
(translate (/ w 2) (/ h 2) 0)
(rotate-x 0.7)
(rotate-z 0.5)
(box 100 150 200) ; 2x3x4 relative dimensions
(pop-matrix))
(defsketch main
:title "cuboid"
:setup setup
:size [w h]
:draw draw
:renderer :opengl)

View file

@ -0,0 +1,46 @@
import java.awt.*;
import javax.swing.*;
public class Cuboid extends JFrame {
public static void main(String[] args) {
JFrame f = new Cuboid();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public Cuboid() {
Container content = getContentPane();
content.setLayout(new BorderLayout());
content.add(new CuboidPanel(), BorderLayout.CENTER);
setTitle("Cuboid");
setResizable(false);
pack();
setLocationRelativeTo(null);
}
}
class CuboidPanel extends JPanel {
public CuboidPanel() {
setPreferredSize(new Dimension(600, 500));
setBackground(Color.white);
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.translate(165, -80);
g.drawRect(50, 275, 100, 100);
g.drawLine(50, 275, 130, 240);
g.drawLine(150, 275, 210, 240);
g.drawLine(130, 240, 210, 240);
g.drawLine(210, 240, 210, 340);
g.drawLine(150, 375, 210, 340);
}
}

View file

@ -0,0 +1,3 @@
from visual import *
mybox = box(pos=(0,0,0), length=4, height=2, width=3, axis=(-0.1,-0.1,0.1) )
scene.title = "VPython: cuboid"

View file

@ -0,0 +1,261 @@
from __future__ import print_function, division
from visual import *
import itertools
title = "VPython: Draw a cuboid"
scene.title = title
print( "%s\n" % title )
msg = """
Drag with right mousebutton to rotate view.
Drag up+down with middle mousebutton to zoom.
Left mouseclick to show info.
Press x,X, y,Y, z,Z to rotate the box in single steps.
Press b, c,o,m to change background, color, opacity, material.
Press r,R to rotate, d,a for demo, automatic, space to stop.
Press h to show this help, ESC or q to quit.
"""
#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+...
## Rotate one step per keypress:
def rotX(obj, a) :
obj.rotate( angle=a, axis=(1,0,0) )
def rotY(obj, a) :
obj.rotate( angle=a, axis=(0,1,0) )
def rotZ(obj, a) :
obj.rotate( angle=a, axis=(0,0,1) )
## Selection of background-colors:
bg_list = [color.gray(0.2), color.gray(0.4), color.gray(0.7), color.gray(0.9)]
bg = itertools.cycle(bg_list)
def backgr() :
b = next(bg)
print("BackgroundColor=",b)
scene.background = b
## Selection of colors:
col_list = [color.white, color.red, color.orange, color.yellow,
color.green, color.blue, color.cyan, color.magenta,
color.black]
col = itertools.cycle(col_list)
#c = col.next()
#c = next(col)
def paint(obj) :
c = next(col)
print("Color=",c)
obj.color = c
## Selection of opacity / transparancy :
opa_list = [1.0, 0.7, 0.5, 0.2]
opa = itertools.cycle(opa_list)
def solid(obj) :
o = next(opa)
print("opacity =",o)
obj.opacity = o
## Selection of materials:
mName_list = ["None",
"wood",
"rough",
"bricks",
"glass",
"earth",
"plastic",
"ice",
"diffuse",
"marble" ]
mat_list = [ None,
materials.wood,
materials.rough,
materials.bricks,
materials.glass,
materials.earth,
materials.plastic,
materials.ice,
materials.diffuse,
materials.marble ]
mName = itertools.cycle(mName_list)
mat = itertools.cycle(mat_list)
def surface(obj) :
mM = next(mat)
mN = next(mName)
print("Material:", mN)
obj.material = mM
obj.mat = mN
## Selection for rotation-angle & axis :
rotAng_list = [ 0.0, 0.005, 0.0, -0.005 ]
rotDir_list = [ (1,0,0), (0,1,0), (0,0,1) ]
rotAng = itertools.cycle(rotAng_list)
rotDir = itertools.cycle(rotDir_list)
rotAn = next(rotAng) # rotAn = 0.005
rotAx = next(rotDir) # rotAx = (1,0,0)
def rotAngle() :
global rotAn
rotAn = next(rotAng)
print("RotateAngle=",rotAn)
def rotAxis() :
global rotAx
rotAx = next(rotDir)
print("RotateAxis=",rotAx)
## List of keypresses for demo:
#demoC_list = [ "h", "c", "a", "o", "m", "b" ]
demoCmd_list = "rcbr"+"robr"+"rmR_r?"
demoCmd = itertools.cycle(demoCmd_list)
def demoStep() :
k = next(demoCmd)
print("Demo:",k)
cmd(k)
#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+...
def objCount():
n=0
for obj in scene.objects:
n=n+1
return n
def objInfo(obj) :
print( "\nObject:", obj )
print( "Pos:", obj.pos, "Size:", obj.size )
print( "Axis:", obj.axis, "Up:", obj.up )
print( "Color", obj.color, obj.opacity )
print( "Mat:", obj.mat, obj.material )
def sceneInfo(sc) :
print( "\nScene:", sc )
print( ".width x height:", sc.width, "x", sc.height )
print( ".range:", sc.range, ".scale:", sc.scale )
print( ".center:", sc.center ) # Camera
print( ".forward:", sc.forward, ".fov:", sc.fov )
print( "Mouse:", sc.mouse.camera, "ray:", sc.mouse.ray )
print( ".ambient:", sc.ambient )
print( "Lights:", sc.lights ) # distant_light
print( "objects:", objCount(), scene.objects )
#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+...
scene.width = 600
scene.height = 400
scene.range = 4
#scene.autocenter = True
#scene.background = color.gray(0.2)
scene.background = next(bg)
autoDemo = -1
print( msg )
## Create cuboid (aka "box") :
# c = box() # using default-values --> cube
# c = box(pos=(0,0,0), length=4, height=2, width=3, axis=(-0.1,-0.1,0.1) )
##c = box(pos =( 0.0, 0.0, 0.0 ),
## size=( 4, 2, 3 ), # L,H,W
## axis=( 1.0, 0.0, 0.0 ),
## up =( 0.0, 1.0, 0.0 ),
## color = color.orange,
## opacity = 1.0,
## material= materials.marble
## )
c = box(pos =( 0.0, 0.0, 0.0 ),
size=( 4, 2, 3 ), # L,H,W
axis=( 1.0, 0.0, 0.0 ),
up =( 0.0, 1.0, 0.0 )
)
print("Box:", c)
paint(c) # c.color = color.red
solid(c) # c.opacity = 1.0
surface(c) # c.material = materials.marble
rotX(c,0.4) # rotate box, to bring three faces into view
rotY(c,0.6)
#sceneInfo(scene)
#objInfo(c)
print("\nPress 'a' to start auto-running demo.")
#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+...
## Processing of input:
cCount = 0
def click():
global cCount
cCount=cCount+1
sceneInfo(scene)
objInfo(c)
scene.bind( 'click', click )
def keyInput():
key = scene.kb.getkey()
print( 'Key: "%s"' % key )
if ( (key == 'esc') or (key == 'q') ) :
print( "Bye!" )
exit(0)
else :
cmd(key)
scene.bind('keydown', keyInput)
def cmd(key):
global autoDemo
if (key == 'h') : print( msg )
if (key == '?') : print( msg )
if (key == 's') : sceneInfo(scene)
if (key == 'i') : objInfo(c)
if (key == 'x') : rotX(c, 0.1)
if (key == 'X') : rotX(c,-0.1)
if (key == 'y') : rotY(c, 0.1)
if (key == 'Y') : rotY(c,-0.1)
if (key == 'z') : rotZ(c, 0.1)
if (key == 'Z') : rotZ(c,-0.1)
if (key == 'c') : paint(c)
if (key == 'o') : solid(c)
if (key == 'm') : surface(c)
if (key == 'b') : backgr()
if (key == 'r') : rotAngle()
if (key == 'R') : rotAxis()
if (key == 'd') : demoStep()
if (key == 'a') : autoDemo = -autoDemo
if (key == 'A') : autoDemo = -autoDemo
if (key == ' ') : stop()
def stop() :
global autoDemo, rotAn
autoDemo = -1
while rotAn <> 0 :
rotAngle()
print("**Stop**")
r=100
t=0
while True: # Animation-loop
rate(50)
t = t+1
if rotAn != 0 :
c.rotate( angle=rotAn, axis=rotAx )
if t>=r :
t=0
if autoDemo>0 :
demoStep()

View file

@ -11,9 +11,9 @@ x=p(x 1); y=p(y x); z=p(z y); indent=p(indent 0)
call sayer , , "+-"
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────P subroutjne────────────────────────*/
/*──────────────────────────────────P subroutine────────────────────────*/
p: return word(arg(1),1) /*pick the first word in the list*/
/*──────────────────────────────────SAYER subroutjne────────────────────*/
/*──────────────────────────────────SAYER subroutine────────────────────*/
sayer: parse arg times,a,_ /*get the arguments specified. */
say left('',indent)right(left(_,1),pick1(times 1)) || ,
copies(substr(_,2,1),4*x)left(_,1)right(substr(_,3,1),pick1(a 0)+1)

View file

@ -0,0 +1,19 @@
3 elements d h w
: spaces ( n- ) &space times ;
: --- ( - ) '+ putc @w 2 * [ '- putc ] times '+ putc ;
: ? ( n- ) @h <> [ '| ] [ '+ ] if ;
: slice ( n- ) '/ putc @w 2 * spaces '/ putc @d swap - dup spaces ? putc cr ;
: |...|/ ( - ) @h [ '| putc @w 2 * spaces '| putc 1- spaces '/ putc cr ] iterd ;
: face ( - )
--- @w 1+ spaces '/ putc cr
|...|/
--- cr ;
: cuboid ( whd- )
!d !h !w cr
@d 1+ spaces --- cr
@d [ dup spaces slice ] iterd
face ;
2 3 4 cuboid

View file

@ -0,0 +1,26 @@
DIR = {"-" => [1,0], "|" => [0,1], "/" => [1,1]}
def cuboid(nx, ny, nz)
puts "cuboid %d %d %d:" % [nx, ny, nz]
x, y, z = 8*nx, 2*ny, 4*nz
area = Array.new(y+z+1){" " * (x+y+1)}
line = lambda do |n, sx, sy, c|
dx, dy = DIR[c]
(n+1).times do |i|
xi, yi = sx+i*dx, sy+i*dy
area[yi][xi] = (area[yi][xi]==" " ? c : "+")
end
end
nz .times {|i| line[x, 0, 4*i, "-"]}
(ny+1).times {|i| line[x, 2*i, z+2*i, "-"]}
nx .times {|i| line[z, 8*i, 0, "|"]}
(ny+1).times {|i| line[z, x+2*i, 2*i, "|"]}
nz .times {|i| line[y, x, 4*i, "/"]}
(nx+1).times {|i| line[y, 8*i, z, "/"]}
puts area.reverse
end
cuboid(2, 3, 4)
cuboid(1, 1, 1)
cuboid(6, 2, 1)
cuboid(2, 4, 1)