Matlab绘制视锥体/截锥

DrawFrustum.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
% 1.输入六个面的表达式
% 每个面由4个参数决定: ax + by + cx + d = 0
% left, right, bottom, top, far, near
as = [ -0.138808 0.997943 0.336104 0.234905 0.666782 -0.666782 ];
bs = [ -0.053909 -0.053909 0.864693 -0.936352 -0.0836785 0.0836785 ];
cs = [ 0.988851 -0.0346808 0.373283 0.26089 0.74054 -0.74054 ];
ds = [ 2.78514 3.55528 0.726959 3.48709 -5.07915 95.0791 ];

% 2.求交点
% 每3个面交于一点,共8个顶点
ids = [ % 面的索引
1, 4, 6;
2, 4, 6;
1, 4, 5;
2, 4, 5;
1, 3, 6;
2, 3, 6;
1, 3, 5;
2, 3, 5;
];
corners = zeros(8, 3); % 保存8个交点的x、y、z
for i = (1:8)
% 取3个面
ps = [ids(i, 1), ids(i, 2), ids(i, 3)];
% 3个面的a、b、c、d
a = [as(ps(1)), as(ps(2)), as(ps(3))];
b = [bs(ps(1)), bs(ps(2)), bs(ps(3))];
c = [cs(ps(1)), cs(ps(2)), cs(ps(3))];
d = [ds(ps(1)), ds(ps(2)), ds(ps(3))];

% 解三元一次方程组
A1 = a(2)*b(1)-a(1)*b(2);
B1 = a(2)*c(1)-a(1)*c(2);
C1 = a(2)*d(1)-a(1)*d(2);
A2 = a(2)*b(3)-a(3)*b(2);
B2 = a(2)*c(3)-a(3)*c(2);
C2 = a(2)*d(3)-a(3)*d(2);
z = (-C1*A2+C2*A1)/(B1*A2-B2*A1);
y = (-C1-B1*z)/A1;
x = (-d(1)-b(1)*y-c(1)*z)/a(1);

corners(i, 1) = x;
corners(i, 2) = y;
corners(i, 3) = z;
end
%corners

% 3.由交点绘制平面
% 每4个点组成一个面,共6个面
ids = [ % 点的索引
1, 5, 7, 3; % left
2, 6, 8, 4; % right
5, 6, 8, 7; % bottom
1, 2, 4, 3; % top
3, 4, 8, 7; % far
1, 2, 6, 5; % near
];
colors = ['r', 'g', 'b', 'y', 'w', 'k']; % 6个面的颜色
for i = (1:6)
% 取4个点
ps = [ids(i, 1), ids(i, 2), ids(i, 3), ids(i, 4)];
% 4个点的x、y、z
xs = [corners(ps(1), 1), corners(ps(2), 1), corners(ps(3), 1), corners(ps(4), 1)];
ys = [corners(ps(1), 2), corners(ps(2), 2), corners(ps(3), 2), corners(ps(4), 2)];
zs = [corners(ps(1), 3), corners(ps(2), 3), corners(ps(3), 3), corners(ps(4), 3)];

fill3(xs, ys, zs, colors(i));
hold on
end

% 设置坐标轴
xlabel("X");
ylabel("Y");
zlabel("Z");
axis equal;

因为使用的是右手系中的数据,所以颜色顺序不太对