C++#include <bits/stdc++.h>
#include <windows.h>
using namespace std;
const int SW = 100, SH = 100;
bool screen[SH][SW];
// ----- 3D 向量 -----
struct Vec3 { double x, y, z; };
// ----- 投影结果 -----
struct Point2D { int x, y; };
Vec3 rotateX(Vec3 v, double a) {
double c = cos(a), s = sin(a);
Vec3 r;
r.x = v.x;
r.y = v.y * c - v.z * s;
r.z = v.y * s + v.z * c;
return r;
}
Vec3 rotateY(Vec3 v, double a) {
double c = cos(a), s = sin(a);
Vec3 r;
r.x = v.x * c + v.z * s;
r.y = v.y;
r.z = -v.x * s + v.z * c;
return r;
}
// ----- 透视投影 -----
Point2D project(Vec3 p, double focal) {
Point2D pt;
pt.x = -1;
pt.y = -1;
if (p.y <= 0.001) return pt;
double px = p.x * focal / p.y;
double py = p.z * focal / p.y;
int sx = int(px + SW / 2.0);
int sy = int(SH / 2.0 - py);
if (sx < 0 || sx >= SW || sy < 0 || sy >= SH) return pt;
pt.x = sx;
pt.y = sy;
return pt;
}
// ----- Bresenham 画线 -----
void drawLine(int x0, int y0, int x1, int y1) {
int dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
int dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
int err = dx + dy;
for (;;) {
if (x0 >= 0 && x0 < SW && y0 >= 0 && y0 < SH)
screen[y0][x0] = true;
if (x0 == x1 && y0 == y1) break;
int e2 = 2 * err;
if (e2 >= dy) { err += dy; x0 += sx; }
if (e2 <= dx) { err += dx; y0 += sy; }
}
}
// ----- 控制台工具 -----
void hideCursor() {
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO ci;
ci.dwSize = 1;
ci.bVisible = 0;
SetConsoleCursorInfo(h, &ci);
}
void resetCursor() {
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), (COORD){0, 0});
}
// ----- 主程序 -----
int main() {
double focal = (SW / 2.0) / tan(30.0 * M_PI / 180.0);
// 正方体 8 个顶点
Vec3 local[8] = {
{-1, -1, -1}, { 1, -1, -1}, {-1, 1, -1}, { 1, 1, -1},
{-1, -1, 1}, { 1, -1, 1}, {-1, 1, 1}, { 1, 1, 1}
};
// 12 条边
int edges[12][2] = {
{0,1},{1,3},{3,2},{2,0},
{4,5},{5,7},{7,6},{6,4},
{0,4},{1,5},{2,6},{3,7}
};
double angleX = 0.0, angleY = 0.0;
hideCursor();
for (;;) {
if (GetAsyncKeyState(VK_ESCAPE) & 0x8000) break;
// 清空帧缓冲
for (int i = 0; i < SH; i++)
for (int j = 0; j < SW; j++)
screen[i][j] = false;
// 旋转 + 平移 + 投影 + 画线
for (int k = 0; k < 12; k++) {
Vec3 a = local[edges[k][0]];
Vec3 b = local[edges[k][1]];
a = rotateX(a, angleX);
a = rotateY(a, angleY);
b = rotateX(b, angleX);
b = rotateY(b, angleY);
a.y += 5.0;
b.y += 5.0;
Point2D pa = project(a, focal);
Point2D pb = project(b, focal);
if (pa.x >= 0 && pa.y >= 0 && pb.x >= 0 && pb.y >= 0)
drawLine(pa.x, pa.y, pb.x, pb.y);
}
// 输出到控制台
resetCursor();
for(int i = 0; i < SH; i++) {
for (int j = 0; j < SW; j++)
{
if(screen[i][j]) printf("边");
else printf(" ");
}
printf("|\n");
}
for(int j = 0; j < SW; j++) printf("--");
printf("ESC to quit\n");
angleY += 0.04;
angleX += 0.025;
Sleep(30);
}
return 0;
}