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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use super::generators::{IndexedPolygon, SharedVertex};
use super::Polygon::{PolyQuad, PolyTri};
use super::{Polygon, Quad, Triangle};
use std::f32::consts::PI;
use Vertex;
#[derive(Clone, Copy)]
pub struct SphereUv {
u: usize,
v: usize,
sub_u: usize,
sub_v: usize,
}
impl SphereUv {
pub fn new(u: usize, v: usize) -> Self {
assert!(u > 1 && v > 1);
SphereUv {
u: 0,
v: 0,
sub_u: u,
sub_v: v,
}
}
fn vert(&self, u: usize, v: usize) -> Vertex {
let u = (u as f32 / self.sub_u as f32) * PI * 2.;
let v = (v as f32 / self.sub_v as f32) * PI;
let p = [u.cos() * v.sin(), u.sin() * v.sin(), v.cos()];
Vertex {
pos: p.into(),
normal: p.into(),
}
}
}
impl Iterator for SphereUv {
type Item = Polygon<Vertex>;
fn next(&mut self) -> Option<Self::Item> {
if self.u == self.sub_u {
self.u = 0;
self.v += 1;
if self.v == self.sub_v {
return None;
}
}
let u1 = (self.u + 1) % self.sub_u;
let x = self.vert(self.u, self.v);
let y = self.vert(self.u, self.v + 1);
let z = self.vert(u1, self.v + 1);
let w = self.vert(u1, self.v);
let v = self.v;
self.u += 1;
Some(if v == 0 {
PolyTri(Triangle::new(x, y, z))
} else if v == self.sub_v - 1 {
let z = self.vert(0, self.sub_v);
PolyTri(Triangle::new(z, w, x))
} else {
PolyQuad(Quad::new(x, y, z, w))
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
let n = (self.sub_v - self.v) * self.sub_u + (self.sub_u - self.u);
(n, Some(n))
}
}
impl SharedVertex<Vertex> for SphereUv {
fn shared_vertex(&self, idx: usize) -> Vertex {
if idx == 0 {
self.vert(0, 0)
} else if idx == self.shared_vertex_count() - 1 {
self.vert(0, self.sub_v)
} else {
let idx = idx - 1;
let u = idx % self.sub_u;
let v = idx / self.sub_u;
self.vert(u, v + 1)
}
}
fn shared_vertex_count(&self) -> usize {
(self.sub_v - 1) * (self.sub_u) + 2
}
}
impl IndexedPolygon<Polygon<usize>> for SphereUv {
fn indexed_polygon(&self, idx: usize) -> Polygon<usize> {
let f = |u: usize, v: usize| {
if v == 0 {
0
} else if self.sub_v == v {
(self.sub_v - 1) * (self.sub_u) + 1
} else {
(v - 1) * self.sub_u + (u % self.sub_u) + 1
}
};
let u = idx % self.sub_u;
let v = idx / self.sub_u;
if v == 0 {
PolyTri(Triangle::new(f(u, v), f(u, v + 1), f(u + 1, v + 1)))
} else if self.sub_v - 1 == v {
PolyTri(Triangle::new(f(u + 1, v + 1), f(u + 1, v), f(u, v)))
} else {
PolyQuad(Quad::new(
f(u, v),
f(u, v + 1),
f(u + 1, v + 1),
f(u + 1, v),
))
}
}
fn indexed_polygon_count(&self) -> usize {
self.sub_v * self.sub_u
}
}