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
// #![doc(html_logo_url = "https://rin.rs/logo.svg")]
// #![doc(html_favicon_url = "https://rin.rs/favicon.ico")]

#[cfg(feature="dds")]
pub extern crate dds;

#[doc(inline)]
pub use self::mesh::Mesh;
#[doc(inline)]
pub use self::mesh_slice::MeshSlice;
#[doc(inline)]
pub use self::mesh::IndexT;
#[doc(inline)]
pub use self::mesh::PrimitiveType;
#[doc(inline)]
pub use self::mesh::mesh;
#[doc(inline)]
pub use self::mesh_slice::mesh_slice;
#[doc(inline)]
pub use self::mesh::load_ply;
#[doc(inline)]
pub use self::primitives::*;
#[doc(inline)]
pub use self::path::Path2D;
#[doc(inline)]
pub use self::node::Node;
#[cfg(feature="ecs")]
#[doc(inline)]
pub use self::node::NodeParts;
#[doc(inline)]
pub use self::node::{NodeRef, NodeMut};
#[doc(inline)]
pub use self::projection::{Projection,CoordinateOrigin};
#[doc(inline)]
pub use self::mvp::{Mvp, Model, CameraMatrices, ModelMatrices};
#[doc(inline)]
pub use self::gradient::{Gradient, LinearGradientDirection};
#[doc(inline)]
#[cfg(feature="dds")]
pub use self::dds::Dds;
#[doc(inline)]
pub use self::camera::{
    Camera, CameraExt, CameraPerspective, CameraOrthographic,
    arcball_camera::{self, ArcballCamera},
    ortho_camera::{self, OrthoCamera},
};
#[cfg(feature="ttf")]
#[doc(inline)]
pub use self::ttf::Ttf;

#[cfg(feature="ttf_rusttype")]
pub use self::ttf_rusttype as ttf;
#[cfg(feature="ttf_rusttype")]
#[doc(inline)]
pub use self::ttf::Ttf;

#[cfg(not(any(feature="ttf", feature="ttf_rusttype")))]
pub type Ttf = ();

pub use self::vertex::*;

#[cfg(feature = "freeimage")]
pub mod freeimage;

#[cfg(feature = "freeimage")]
pub use self::freeimage as image;

#[doc(no_inline)]
#[cfg(feature = "freeimage")]
pub use self::freeimage::Image;

#[cfg(feature = "image")]
pub mod image;

#[doc(no_inline)]
#[cfg(feature = "image")]
pub use self::image::Image;
pub use self::polyline::Polyline;
pub use self::polyline_slice::PolylineSlice;

#[cfg(feature = "libhdr")]
pub use libhdr::Hdr;


mod mesh;
mod mesh_slice;
mod primitives;
pub mod node;
pub mod path;
mod gradient;
pub mod vertex;
pub mod projection;
pub mod mvp;
pub mod camera;
#[cfg(feature="ttf")]
pub mod ttf;
#[cfg(all(feature="ttf_rusttype", feature="image"))]
pub mod ttf_rusttype;
mod polyline;
mod polyline_slice;

use std::f32;
use rin_math::{
    pnt4, Rect, Pnt2, convert, pnt2, zero, BaseNum, Mat4, vec4, vec2, Pnt3, Vec2,
    NumCast, RealField, ToVec, ToPnt, cast
};
#[cfg(feature="serialize")]
use serde_derive::{Serialize, Deserialize};

pub type Mesh2D = Mesh<Vertex2D>;
pub type Mesh2DColor = Mesh<Vertex2DColor>;
pub type Mesh2DTex = Mesh<Vertex2DTex>;
pub type Mesh2DTexColor = Mesh<Vertex2DTexColor>;
pub type Mesh2DTex3D = Mesh<Vertex2DTex3D>;
pub type Mesh3D = Mesh<Vertex3D>;
pub type Mesh3DColor = Mesh<Vertex3DColor>;
pub type Mesh3DColorNormal = Mesh<Vertex3DColorNormal>;
pub type Mesh3DNormal = Mesh<Vertex3DNormal>;
pub type Mesh3DTexColor = Mesh<Vertex3DTexColor>;
pub type Mesh3DTexNormal = Mesh<Vertex3DTexNormal>;
pub type Mesh3DTex = Mesh<Vertex3DTex>;

/// Z value for screen <-> world conversions
#[derive(Clone, Copy, PartialEq, Debug)]
#[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
pub enum ScreenZ{
    /// The z value is in world coordinates
    World(f32),
    /// The z value is in normalized depth
    Depth(f32),
}

impl ScreenZ{
    pub fn to_world(self, projection_view: &Mat4) -> ScreenZ{
        match self{
            ScreenZ::World(_) => self,
            ScreenZ::Depth(z) => {
                let w = projection_view.try_inverse().unwrap() * vec4(0., 0., z, 1.);
                let w = w.xyz() / w.w;
                ScreenZ::World(w.z)
            }
        }
    }

    pub fn to_depth(self, projection_view: &Mat4) -> ScreenZ{
        match self{
            ScreenZ::Depth(_) => self,
            ScreenZ::World(z) => {
                let w = projection_view * vec4(0., 0., z, 1.);
                let w = w.xyz() / w.w;
                ScreenZ::Depth(w.z)
            }
        }
    }

    pub fn value(self) -> f32{
        match self{
            ScreenZ::Depth(z) => z,
            ScreenZ::World(z) => z,
        }
    }
}

/// Converts a 3d point to a projection in the screen in 2D + normalized coordinates of it's depth
pub fn world_to_screen(p: &Pnt3, viewport: &Rect<i32>, projection_view: &Mat4) -> (Pnt2, ScreenZ){
    let c = *projection_view * pnt4!(*p, 1.0);
    let c = c.xyz() / c.w;
    let mut p = pnt2(((c.x + 1.0f32) / 2.0f32 * viewport.width as f32).round(),
         ((1.0f32 - c.y) / 2.0f32 * viewport.height as f32).round());
    let viewport_pos: Pnt2 = convert(viewport.pos);
    p += viewport_pos.to_vec();
    (p, ScreenZ::Depth(c.z))
}

/// Converts a screen position + a z value in either world coordinates
/// or normalized depth into a world 3d position
pub fn screen_to_world(screen: &Pnt2, depth: ScreenZ, projection_view: &Mat4, viewport: &Rect<i32>) -> Pnt3 {
	//convert from screen to camera
	let x = 2.0f32 * (screen.x - viewport.pos.x as f32) / viewport.width as f32 - 1.0f32;
	let y = 1.0f32 - 2.0f32 * (screen.y - viewport.pos.y as f32) / viewport.height as f32;
    let z = depth.to_depth(projection_view).value();
    let camera_xyz = vec4(x, y, z, 1.);

	//convert camera to world
	let v4 = projection_view.try_inverse().unwrap() * camera_xyz;
    (v4.xyz() / v4.w).to_pnt()

}

fn num_partial_min<T:PartialOrd>(a: T, b: T) -> T{
    if a<b {a} else {b}
}

fn num_partial_max<T:PartialOrd>(a: T, b: T) -> T{
    if a>b {a} else {b}
}

/// Bounding box of a set of 2d points
pub fn bounding_box<T: BaseNum>(mesh: &[Vec2<T>]) -> Rect<T>{
    if mesh.is_empty(){
        return Rect{pos: pnt2(zero(), zero()), width: zero(), height: zero()}
    }else{
        let mut iter = mesh.iter();
        let (max, min) = iter.next()
            .map(|head| iter.fold((head.clone(), head.clone()), |(max, min), v| {
                let max_x = num_partial_max(max.x.inlined_clone(), v.x.inlined_clone());
                let max_y = num_partial_max(max.y.inlined_clone(), v.y.inlined_clone());
                let min_x = num_partial_min(min.x.inlined_clone(), v.x.inlined_clone());
                let min_y = num_partial_min(min.y.inlined_clone(), v.y.inlined_clone());
                (vec2(max_x, max_y), vec2(min_x, min_y))
            }))
            .unwrap();
        Rect{
            pos: pnt2(min.x.inlined_clone(), min.y.inlined_clone()),
            width: max.x.inlined_clone() - min.x.inlined_clone(),
            height: max.y.inlined_clone() - min.y.inlined_clone()
        }
    }
}
/// Trait to check if a point is inside a polygon
pub trait InsidePolygon<T: RealField>{
    fn inside_polygon(&self, polygon: &Polyline<T>, bound: bool) -> bool;
}

impl<T: RealField + NumCast> InsidePolygon<T> for Pnt2<T>{
    fn inside_polygon(&self, polygon: &Polyline<T>, bound: bool) -> bool{
        //cross points count of x
        let mut count = 0;

        //left vertex
        let mut p1 = polygon[0];

        //check all rays
        for i in 0 .. polygon.len()+1
        {
            //point is an vertex
            if *self == p1 { return bound; }

            //right vertex
            let p2 = polygon[i % polygon.len()];

            //ray is outside of our interests
            if self.y < p1.y.min(p2.y) || self.y > p1.y.max(p2.y){
                //next ray left point
                p1 = p2; continue;
            }

            //ray is crossing over by the algorithm (common part of)
            if self.y > p1.y.min(p2.y) && self.y < p1.y.max(p2.y){
                //x is before of ray
                if self.x <= p1.x.max(p2.x){
                    //overlies on a horizontal ray
                    if p1.y == p2.y && self.x >= p1.x.min(p2.x) { return bound; }

                    //ray is vertical
                    if p1.x == p2.x {
                        //overlies on a ray
                        if p1.x == self.x { return bound; }
                        //before ray
                        else { count += 1; }
                    }else{
                        //cross point on the left side
                        //cross point of x
                        let xinters = (self.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x;

                        //overlies on a ray
                        if self.x == xinters { return bound; }

                        //before ray
                        if self.x < xinters { count += 1; }
                    }
                }
            }else{
                //special case when ray is crossing through the vertex
                //p crossing over p2
                if self.y == p2.y && self.x <= p2.x {
                    //next vertex
                    let p3 = polygon[(i+1) % polygon.len()];

                    //p.y lies between p1.y & p3.y
                    if self.y >= p1.y.min(p3.y) && self.y <= p1.y.max(p3.y){
                        count += 1;
                    }else{
                        count += 2;
                    }
                }
            }
            //next ray left point
            p1 = p2;
        }

        //EVEN
        if count % 2 == 0{
            false
        }else{
        //ODD
            true
        }
    }
}

pub trait GeometryIterator {
    type Point;
    type Field;
    fn signed_area(self) -> Self::Field;
    fn centroid(self) -> Option<Self::Point>;
}

impl<T, I: Iterator<Item = Pnt2<T>>> GeometryIterator for I
where
    T: RealField + NumCast
{
    type Point = Pnt2<T>;
    type Field = T;

    fn signed_area(mut self) -> T {
        let mut area = zero();
        let first = self.next();
        let mut next = first.clone();
        loop {
            let p0 = next.take();
            let p1 = self.next();
            if let (Some(p0), Some(p1)) = (p0, p1) {
                area = area + (p0.x * p1.y - p1.x * p0.y);
                next = Some(p1);
            }else {
                if p0.is_some() {
                    next = p0;
                }
                break;
            }
        }
        if let (Some(p0), Some(p1)) = (next, first) {
            area = area + (p0.x * p1.y - p1.x * p0.y);
        }
        area = area * cast(0.5).unwrap();
        area
    }

    fn centroid(self) -> Option<Pnt2<T>> {
        let (num, acc) = self
            .fold((0, Pnt2::origin()), |(i, acc), p|
                (i + 1, acc + p.to_vec())
            );
        if num > 0 {
            Some(acc / cast(num).unwrap())
        }else{
            None
        }
    }
}

#[cfg(feature="gl")]
use glin::gl;

#[cfg(feature="gl")]
pub trait PrimitiveTypeToGl{
    fn to_gl(self) -> gl::types::GLenum;
}

/// Mesh primitive type to gl primitive type
#[cfg(all(feature="gl", not(any(feature="gles", feature="webgl"))))]
impl PrimitiveTypeToGl for PrimitiveType{
    fn to_gl(self) -> gl::types::GLenum {
        match self{
            PrimitiveType::Triangles => gl::TRIANGLES,
            PrimitiveType::TriangleStrip => gl::TRIANGLE_STRIP,
            PrimitiveType::TriangleFan => gl::TRIANGLE_FAN,
            PrimitiveType::Lines => gl::LINES,
            PrimitiveType::LineStrip => gl::LINE_STRIP,
            PrimitiveType::LineLoop => gl::LINE_LOOP,
            PrimitiveType::LinesAdjacency => gl::LINES_ADJACENCY,
            PrimitiveType::LineStripAdjacency => gl::LINE_STRIP_ADJACENCY,
            PrimitiveType::Points => gl::POINTS,
            PrimitiveType::Patches => gl::PATCHES,
        }
    }
}

/// Mesh primitive type to gles primitive type
#[cfg(any(feature="gles", feature="webgl"))]
impl PrimitiveTypeToGl for PrimitiveType{
    fn to_gl(self) -> gl::types::GLenum {
        match self{
            PrimitiveType::Triangles => gl::TRIANGLES,
            PrimitiveType::TriangleStrip => gl::TRIANGLE_STRIP,
            PrimitiveType::TriangleFan => gl::TRIANGLE_FAN,
            PrimitiveType::Lines => gl::LINES,
            PrimitiveType::LineStrip => gl::LINE_STRIP,
            PrimitiveType::LineLoop => gl::LINE_LOOP,
            PrimitiveType::Points => gl::POINTS,
            _ => unimplemented!()
        }
    }
}