/* Place a single pixel on the screen, and allow the user to move it around in 3D with the cursor keys and PgUp/PgDn. A simple demonstration of how to move points in 3D and reflect their position on a 2D computer screen. */ #include #include #include #include /* The 4 lines below set the screen_center variables */ int x_resolution = 640; int y_resolution = 480; int screen_center_x = x_resolution/2; int screen_center_y = y_resolution/2; /* --------------------- */ /* The vertex is the point in 3D. X, Y, and Z are its 3D coordinates */ double vertex_x = - 100, vertex_y = -100, vertex_z = 300; /* screen_x and screen_y will be the actual final pixel coordinates */ int screen_x, screen_y; /* "distance" is a theoretical variable indicating how far you, the viewer, are from the screen */ int distance = 256; /* keystroke will be used to read input from the keyboard */ int keystroke; void PrintNewCoords() { /* Print the new vertex's coordinates in the upper-left corner of the screen */ cleardevice(); /* cleardevice clears the previous pixel instance. Comment out the above line if you want to leave a trail instead of only having one pixel on-screen at a time. */ gotoxy(1,1); /* Move text cursor to upper-left corner of screen */ printf("X = %f\n", vertex_x); printf("Y = %f\n", vertex_y); printf("Z = %f", vertex_z); } void DrawNewPoint() { /* Draw the new pixel on the screen */ /* The two lines below are where all the real 3D work is done. These two lines convert the 3D coordinates of the vertex into 2D coordinates for a pixel on the screen. Once you know the algorithm, it's really that easy. */ screen_x = screen_center_x + distance * (vertex_x / vertex_z); screen_y = screen_center_y - distance * (vertex_y / vertex_z); /* And now, we just draw the pixel... */ putpixel (screen_x, screen_y, 9); } void GetKeyStroke() { /* Get a keystroke */ keystroke = _bios_keybrd(_NKEYBRD_READ); switch (keystroke) { case 19424: /* left arrow */ vertex_x = vertex_x - 1; break; case 19936: /* right arrow */ vertex_x = vertex_x + 1; break; case 20704: /* down arrow */ vertex_y = vertex_y - 1; break; case 18656: /* up arrow */ vertex_y = vertex_y + 1; break; case 18912: /* PgUp */ vertex_z = vertex_z + 1; break; case 20960: /* PgDn */ vertex_z = vertex_z - 1; break; } } main() { /* The two lines below just initialize the graphics mode. */ int gdriver=VGA, gmode=2; initgraph(&gdriver, &gmode, "C:\\TC\\BGI"); /* Quit if the user presses q. Otherwise, let the user use the cursor keys (to control 2D motion) and PgUp and PgDn (to control depth), and adjust the point on-screen accordingly. */ while (keystroke != 4209) { PrintNewCoords(); DrawNewPoint(); GetKeyStroke(); } return(0); }