ascii_renderer 1.1.2

A wireframe rendering engine that renders into ascii text, written for fun entirely in Rust.
Documentation
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use super::char_buffer::CharBuffer;
use super::line::Line;
use std::collections::HashMap;

/// Slightly more concise way of declaring a Vector3
#[macro_export]
macro_rules! vec3 {
    ($x: expr, $y: expr, $z: expr) => {
        Vector3::new($x, $y, $z)
    };
    ($x: expr, $y: expr, $z: expr,) => {
        Vector3::new($x, $y, $z)
    };
}

/// Slightly more concise way of declaring a Vector2
#[macro_export]
macro_rules! vec2 {
    ($x: expr, $y: expr) => {
        Vector2::new($x, $y)
    };
    ($x: expr, $y: expr,) => {
        Vector2::new($x, $y)
    };
}

/// Used for rendering meshs to a CharBuffer.
#[derive(Debug, Clone)]
pub struct Renderer {
    pub meshs: Vec<Mesh>,
    pub camera: Camera,
}

impl Renderer {
    ///Draws all the meshs to the CharBuffer
    /// # Example
    /// ```
    /// let buf = CharBuffer::new(30, 30);  //Make sure to use a char buffer that has dimensions proportional to the camera's FOV, otherwise everything will be stretched oddly...
    /// let renderer = Renderer {
    ///     meshs: vec![create_cube()],
    ///     camera: Camera {
    ///         position: vec3!(0.0, 0.0, -10.0),
    ///         rotation: vec3!(0.0, 0.0, 0.0),
    ///         fov: vec2!(0.7, 0.7);   //FOV is in radians
    ///     },
    /// };
    /// renderer.draw(&mut buf);
    /// println!("{buf}");
    /// ```
    pub fn draw(&self, buffer: &mut CharBuffer) {
        for mesh in self.meshs.iter() {
            self.draw_mesh(mesh, buffer);
        }
    }
    /// Draws an individual mesh.
    pub fn draw_mesh(&self, mesh: &Mesh, buffer: &mut CharBuffer) {
        let point_map: HashMap<usize, (Vector2, bool)> = mesh
            .get_global_verticies()
            .iter()
            .map(|(&k, &v)| {
                let mut pnt = self.camera.map_point_uv(v);
                pnt.x *= buffer.dimensions.0 as f32;
                pnt.y *= buffer.dimensions.1 as f32;
                (k, (pnt, self.camera.is_pnt_on_screen(v)))
            })
            .fold(HashMap::new(), |mut accum, (k, v)| {
                accum.insert(k, v);
                accum
            });

        let lines: Vec<Line> = mesh
            .edges
            .iter()
            .filter_map(|&point_indexs| {
                let ((point1, is_on_screen1), (point2, is_on_screen2)) = (*point_map.get(&point_indexs.0).unwrap(), *point_map.get(&point_indexs.1).unwrap());

                if !is_on_screen1 && !is_on_screen2 {return None;}

                Some(Line {
                    char: mesh.char,
                    points: (
                        (point1).into(),
                        (point2).into(),
                    ),
                })
            })
            .collect();

        buffer.draw_lines(lines);
    }
}

#[derive(Debug, Clone)]
pub struct Camera {
    pub position: Vector3,
    pub rotation: Vector3,
    pub fov: Vector2,
}

impl Camera {
    /// Maps a global 3d point to the screen. The output is a UV point, meaning the top left of the screen is (0.0, 0.0) and the bottom right is (1.0, 1.0).
    pub fn map_point_uv(&self, point: Vector3) -> Vector2 {
        // Maps a three dimensional GLOBAL point to UV point dictating its location on screen
        //EX: (0.0, 0.0) is top left of screen and (1.0, 1.0) is bottom right of screen
        let relative = (point - self.position).rotate(self.rotation);

        let thetas = vec2!(
            vec2!(relative.z, relative.x).to_polar().y,
            vec2!(relative.z, relative.y).to_polar().y
        );

        vec2!(thetas.x / self.fov.x + 0.5, thetas.y / self.fov.y + 0.5)
    }

    /// Checks if a point is on screen
    pub fn is_pnt_on_screen(&self, point: Vector3) -> bool {
        let relative = (point - self.position).rotate(self.rotation);
        
        !(vec2!(relative.z, relative.x).to_polar().y.abs() > self.fov.x / 2.0) && !(vec2!(relative.z, relative.y).to_polar().y.abs() > self.fov.y / 2.0)
    }
}

/// A struct containing all the data for a mesh. Rotation, as with everything in this crate, is in radians, with each value determining the amount that the mesh should be rotated around the given axis.
/// Note that vertices are stored on a hashmap, not a vector.
#[derive(Debug, Clone)]
pub struct Mesh {
    vertices: HashMap<usize, Vector3>,
    edges: Vec<(usize, usize)>,
    pub rotation: Vector3,
    pub position: Vector3,
    pub scale: Vector3,
    pub char: char,
}

impl Mesh {
    pub fn insert_vertex(&mut self, index: usize, vertex: Vector3) -> Option<Vector3> {
        self.vertices.insert(index, vertex)
    }
    pub fn get_vertex(&mut self, index: usize) -> Option<Vector3> {
        self.vertices.get(&index).map(|&x| x)
    }
    pub fn insert_vertices(
        &mut self,
        vertices: Vec<(usize, Vector3)>,
    ) -> Vec<(usize, Option<Vector3>)> {
        vertices
            .iter()
            .map(|(index, vertex)| (*index, self.insert_vertex(*index, *vertex)))
            .collect()
    }
    pub fn remove_vertex(&mut self, index: usize) -> Option<Vector3> {
        self.vertices.remove(&index)
    }
    pub fn get_verticies(&self) -> &HashMap<usize, Vector3> {
        &self.vertices
    }
    pub fn get_verticies_mut(&mut self) -> &mut HashMap<usize, Vector3> {
        &mut self.vertices
    }
    pub fn add_edge(&mut self, edge: (usize, usize)) {
        self.edges.push(edge)
    }
    pub fn add_edges(&mut self, edges: Vec<(usize, usize)>) {
        for edge in edges {
            self.edges.push(edge);
        }
    }
    pub fn remove_edge(&mut self, edge: (usize, usize)) -> Option<(usize, usize)> {
        let i = self.edges.iter().enumerate().find(|(_, &x)| x == edge)?.0;
        Some(self.edges.remove(i))
    }
    pub fn get_edges(&self) -> &Vec<(usize, usize)> {
        &self.edges
    }
    pub fn get_edges_mut(&mut self) -> &mut Vec<(usize, usize)> {
        &mut self.edges
    }
    pub fn get_global_verticies(&self) -> HashMap<usize, Vector3> {
        let mut ret = self.vertices.clone();
        ret.iter_mut().for_each(|(_, item)| {
            item.x *= self.scale.x;
            item.y *= self.scale.y;
            item.z *= self.scale.z;

            *item = item.rotate(self.rotation);

            *item = *item + self.position;
        });
        ret
    }
    /// Gets the average position of all the vertices and centers the mesh to be centered around that point. Good for meshes you want to rotate.
    /// returns the global coords to where the mesh was previously centered. If the mesh's position is set to this, then the mesh will go back to it's previous position, only now it's center is appropriatly placed so rotation won't look broken.
    /// EX:
    /// ```
    /// let new_position = my_mesh.recenter();
    /// my_mesh.position = new_position;
    /// ```
    pub fn recenter(&mut self) -> Vector3 {
        let avg_pos = self
            .vertices
            .values()
            .fold(vec3!(0.0, 0.0, 0.0), |accum, vertex| accum + *vertex)
            / self.vertices.values().count() as f32;
        self.vertices
            .values_mut()
            .for_each(|vertex| *vertex -= avg_pos);
        avg_pos
    }
}

impl std::default::Default for Mesh {
    fn default() -> Self {
        Self {
            vertices: HashMap::new(),
            edges: vec![],
            rotation: vec3!(0.0, 0.0, 0.0),
            position: vec3!(0.0, 0.0, 0.0),
            scale: vec3!(1.0, 1.0, 1.0),
            char: '+',
        }
    }
}

/// A struct used for storing 3d points, rotation vectors, etc. It is easiest to create using vec3!(x, y, z)
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Vector3 {
    pub x: f32,
    pub y: f32,
    pub z: f32,
}

impl Vector3 {
    pub fn new(x: f32, y: f32, z: f32) -> Self {
        Self { x, y, z }
    }
    pub fn rotate(self, rotation_vec: Vector3) -> Self {
        //Rotate around x
        let mut ret = {
            let z_y = vec2!(self.z, self.y).rotate(rotation_vec.x);
            vec3!(self.x, z_y.y, z_y.x)
        };

        //Rotate around y
        ret = {
            let x_z = vec2!(ret.x, ret.z).rotate(rotation_vec.y);
            vec3!(x_z.x, ret.y, x_z.y)
        };

        //Rotate around z
        ret = {
            let x_y = vec2!(ret.x, ret.y).rotate(rotation_vec.z);
            vec3!(x_y.x, x_y.y, ret.z)
        };

        ret
    }
    pub fn len(self) -> f32 {
        (self.x * self.x + self.y * self.y + self.z * self.z).sqrt()
    }
    pub fn normalize(self) -> Self {
        let len = self.len();
        if len == 1.0 || len == 0.0 {
            return self;
        } else {
            vec3!(self.x / len, self.y / len, self.z / len)
        }
    }
}

impl std::ops::Add for Vector3 {
    type Output = Vector3;
    fn add(self, other: Self) -> Self::Output {
        Vector3 {
            x: self.x + other.x,
            y: self.y + other.y,
            z: self.z + other.z,
        }
    }
}

impl std::ops::Sub for Vector3 {
    type Output = Self;
    fn sub(self, other: Self) -> Self::Output {
        Vector3 {
            x: self.x - other.x,
            y: self.y - other.y,
            z: self.z - other.z,
        }
    }
}

impl std::convert::Into<(f32, f32, f32)> for Vector3 {
    fn into(self) -> (f32, f32, f32) {
        (self.x, self.y, self.z)
    }
}

impl std::ops::AddAssign for Vector3 {
    fn add_assign(&mut self, rhs: Self) {
        *self = vec3!(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z);
    }
}

impl std::ops::SubAssign for Vector3 {
    fn sub_assign(&mut self, rhs: Self) {
        *self = *self - rhs;
    }
}

impl std::ops::Mul<f32> for Vector3 {
    type Output = Vector3;
    fn mul(self, rhs: f32) -> Self::Output {
        vec3!(self.x * rhs, self.y * rhs, self.z * rhs,)
    }
}

impl std::ops::Div<f32> for Vector3 {
    type Output = Vector3;
    fn div(self, rhs: f32) -> Self::Output {
        vec3!(self.x / rhs, self.y / rhs, self.z / rhs,)
    }
}

impl std::ops::MulAssign<f32> for Vector3 {
    fn mul_assign(&mut self, rhs: f32) {
        *self = *self * rhs;
    }
}

impl std::ops::DivAssign<f32> for Vector3 {
    fn div_assign(&mut self, rhs: f32) {
        *self = *self / rhs;
    }
}

impl std::ops::Neg for Vector3 {
    type Output = Self;
    fn neg(self) -> Self::Output {
        vec3!(-self.x, -self.y, -self.z)
    }
}

impl std::ops::Add<Vector2> for Vector3 {
    type Output = Vector3;

    fn add(self, rhs: Vector2) -> Self::Output {
        vec3!(self.x + rhs.x, self.y + rhs.y, self.z)
    }
}

impl std::ops::Sub<Vector2> for Vector3 {
    type Output = Vector3;
    fn sub(self, rhs: Vector2) -> Self::Output {
        vec3!(self.x - rhs.x, self.y - rhs.y, self.z)
    }
}

impl std::ops::AddAssign<Vector2> for Vector3 {
    fn add_assign(&mut self, rhs: Vector2) {
        *self = *self + rhs;
    }
}

impl std::ops::SubAssign<Vector2> for Vector3 {
    fn sub_assign(&mut self, rhs: Vector2) {
        *self = *self - rhs;
    }
}

/// A struct used for storing 2d points, rotation vectors, etc. It is easiest to create using vec2!(x, y)
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Vector2 {
    pub x: f32,
    pub y: f32,
}

impl Vector2 {
    pub fn new(x: f32, y: f32) -> Self {
        Self { x, y }
    }
    pub fn to_polar(self) -> Self {
        //! x: radius, y: theta
        vec2!(
            (self.x * self.x + self.y * self.y).sqrt(),
            self.y.atan2(self.x)
        )
    }
    pub fn to_cartesian(self) -> Self {
        vec2!(self.x * self.y.cos(), self.x * self.y.sin())
    }
    pub fn rotate(self, delta_theta: f32) -> Self {
        let mut polar = self.to_polar();
        polar.y += delta_theta;
        polar.to_cartesian()
    }
    pub fn len(self) -> f32 {
        (self.x * self.x + self.y * self.y).sqrt()
    }
    pub fn normalize(self) -> Self {
        let len = self.len();
        if len == 1.0 || len == 0.0 {
            return self;
        } else {
            vec2!(self.x / len, self.y / len)
        }
    }
}

impl std::ops::Add for Vector2 {
    type Output = Self;
    fn add(self, other: Self) -> Self::Output {
        Self {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

impl std::ops::Sub for Vector2 {
    type Output = Self;
    fn sub(self, other: Self) -> Self::Output {
        Self {
            x: self.x - other.x,
            y: self.y - other.y,
        }
    }
}

impl std::convert::Into<(f32, f32)> for Vector2 {
    fn into(self) -> (f32, f32) {
        (self.x, self.y)
    }
}

impl std::ops::AddAssign for Vector2 {
    fn add_assign(&mut self, rhs: Self) {
        *self = *self - rhs;
    }
}

impl std::ops::SubAssign for Vector2 {
    fn sub_assign(&mut self, rhs: Self) {
        *self = *self - rhs;
    }
}

impl std::ops::Mul<f32> for Vector2 {
    type Output = Vector2;
    fn mul(self, rhs: f32) -> Self::Output {
        vec2!(self.x * rhs, self.y * rhs,)
    }
}

impl std::ops::Div<f32> for Vector2 {
    type Output = Vector2;
    fn div(self, rhs: f32) -> Self::Output {
        vec2!(self.x / rhs, self.y / rhs,)
    }
}

impl std::ops::MulAssign<f32> for Vector2 {
    fn mul_assign(&mut self, rhs: f32) {
        *self = *self * rhs;
    }
}

impl std::ops::DivAssign<f32> for Vector2 {
    fn div_assign(&mut self, rhs: f32) {
        *self = *self / rhs;
    }
}

impl std::ops::Neg for Vector2 {
    type Output = Self;
    fn neg(self) -> Self::Output {
        vec2!(-self.x, -self.y,)
    }
}

impl std::ops::Sub<Vector3> for Vector2 {
    type Output = Self;
    fn sub(self, rhs: Vector3) -> Self::Output {
        vec2!(self.x - rhs.x, self.y - rhs.y)
    }
}

impl std::ops::SubAssign<Vector3> for Vector2 {
    fn sub_assign(&mut self, rhs: Vector3) {
        *self = *self - rhs;
    }
}