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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657

/*!
 * Physics systems and components in Mutiny, Right now mostly collisions
 */
pub mod components;
use ncollide3d::world::{CollisionGroups, GeometricQueryType, CollisionWorld, CollisionObjectHandle, CollisionObjects};
use ncollide3d::bounding_volume::*;
use ncollide3d::shape::*;
use ncollide3d::transformation::ToTriMesh;
use ncollide3d::procedural;
use ncollide3d::query::Ray;
use ncollide3d::narrow_phase::ContactPairs;
#[cfg(feature="blender")]
use rinblender;
use rinecs::{self, Entities, EntitiesThreadLocal, Read, Write, Entity, CreationContext,};
use rin::math::*;
use rin::graphics::{self, CameraExt, NodeRef, Vertex};
use std::marker::PhantomData;
use smallvec::SmallVec;
use std::cmp::Ordering;
use std::fmt::{self, Debug};
use crate::transformation::{Transformation, PreviousTransformation};
#[cfg(feature="skinning")]
use crate::skinning::components::{SkeletonRef, AnimatedGeometry};
use serde::{Serialize, Deserialize};
use rin::graphics::IndexT;
use crate::Scene;

pub struct Physics;

impl crate::Bundle for Physics{
    fn setup(self, _world: &mut Scene){
    }

    fn register(world: &mut Scene){
        world.register_component::<components::RigidBody>();
        world.register_component::<Shape>();
        world.register_component::<Isometry>();
        world.register_component::<Offset>();
        world.register_component::<CollisionHandle>();
    }
}

#[derive(Component, Clone)]
#[debug_as_string]
pub struct Shape(pub ShapeHandle<f32>);

impl Debug for Shape{
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result{
        fmt.debug_tuple("mutiny::physics::Shape")
            .finish()
    }
}

#[derive(Component, Clone, Copy, Debug)]
#[debug_as_string]
pub struct Isometry(pub Isometry3);

#[derive(Component, Clone, Copy, Debug)]
#[debug_as_string]
pub struct Offset(pub Isometry3);

#[derive(Component, Clone, Copy, Debug)]
#[debug_as_string]
pub struct CollisionHandle(pub CollisionObjectHandle);

#[cfg(any(feature="gl", feature="gles", feature="webgl"))]
pub mod gpu{
    use rin::graphics as graphics;
    use rin::gl as gl;

    #[derive(Component, Debug)]
    #[debug_as_string]
    pub struct DebugGeometry(pub gl::SimpleVao<graphics::Vertex3D>);
}

pub trait MouseGroup{
    fn mouse_group() -> Self;
}

pub struct Collisions<Group: Into<usize>, UserData = rinecs::Entity>{
    pub world: CollisionWorld<f32, UserData>,
    pub contacts_query: GeometricQueryType<f32>,
    _marker: PhantomData<Group>
}

unsafe impl<Group: Into<usize>> Send for Collisions<Group>{}

pub fn ray_from_screen(screen_pos: &Pnt2, camera_pos: &Pnt3, viewport: &Rect<i32>, projection: &Mat4, view: &Mat4) -> Ray<f32>{
    let x = 2.0f32 * (screen_pos.x - viewport.pos.x as f32) / viewport.width as f32 - 1.0f32;
    let y = 1.0f32 - 2.0f32 * (screen_pos.y - viewport.pos.y as f32) / viewport.height as f32;
    let ray_nds = vec3(x,y,1.0);
    let ray_clip = vec4!(ray_nds.xy(), -1.0, 1.0);
    let ray_eye = projection.try_inverse().unwrap() * ray_clip;
    let ray_eye = vec4!(ray_eye.xy(), -1.0, 0.0);
    let ray_world = (view.fast_orthonormal_inverse() * ray_eye).xyz();
    let ray_dir = ray_world.normalize();
    Ray::new(*camera_pos, ray_dir)
}

pub fn ray_from_screen_camera(screen_pos: &Pnt2, viewport: &Rect<i32>, camera: &CameraExt) -> Ray<f32>{
    ray_from_screen(screen_pos, &camera.position(), viewport, &camera.projection(), &camera.view())
}

pub fn ray_shape_intersection<T, S>(ray: &Ray<T>, m: &Isometry3<T>, shape: &S) -> Option<Pnt3<T>>
where T: alga::general::Real, S: ncollide3d::query::RayCast<T>
{
    shape.toi_with_ray(&one(), &ray, true).map(|toi| ray.origin + ray.dir * toi)
}

impl<Group: Into<usize> + Copy, UserData> Collisions<Group, UserData>{
    pub fn new() -> Collisions<Group, UserData>{
        let world = CollisionWorld::new(0.02);
        let contacts_query = GeometricQueryType::Contacts(0.0, 0.0);
        Collisions{
            world,
            contacts_query,
            _marker: PhantomData
        }
    }

    pub fn add(&mut self,
        group: Group,
        whitelist: &[Group],
        blacklist: &[Group],
        data: UserData,
        shape: ShapeHandle<f32>,
        iso: Isometry3) -> CollisionObjectHandle
    {
        let mut groups = CollisionGroups::new();
        groups.set_membership(&[group.into()]);
        for &group in whitelist {
            groups.modify_whitelist(group.into(), true)
        }
        for &group in blacklist {
            groups.modify_blacklist(group.into(), true)
        }
        self.world.add(iso, shape, groups, self.contacts_query, data)
    }

    pub fn remove(&mut self, handles: &[CollisionObjectHandle]) {
        self.world.remove(handles)
    }

    pub fn update(&mut self){
        self.world.update();
    }

    pub fn contacts(&self) -> ContactPairs<f32, UserData>{
        self.world.contact_pairs()
    }

    pub fn set_position(&mut self, handle: CollisionObjectHandle, iso: Isometry3){
        self.world.set_position(handle, iso);
    }

    pub fn objects(&self) -> CollisionObjects<f32, UserData>{
        self.world.collision_objects()
    }
}

impl<Group: Into<usize> + Copy + MouseGroup, UserData> Collisions<Group, UserData>{
    pub fn mouse_select(&self, whitelist: &[Group], blacklist: &[Group], mouse: &Pnt2, viewport: &Rect<i32>, camera: &CameraExt) -> Option<&UserData>{
        let ray = ray_from_screen_camera(mouse, viewport, camera);
        let mut collision_groups = CollisionGroups::new();
        collision_groups.set_membership(&[Group::mouse_group().into()]);
        for &group in whitelist {
            collision_groups.modify_whitelist(group.into(), true);
        }
        for &group in blacklist {
            collision_groups.modify_blacklist(group.into(), true);
        }
        let ray_collisions = self.world.interferences_with_ray(&ray, &collision_groups);
        ray_collisions
            .min_by_key(|c| NonNan::new(c.1.toi).unwrap())
            .map(|(obj, _intersection)| obj.data())
    }
}

impl<Group: Into<usize> + Copy, UserData: From<rinecs::Entity>> Collisions<Group, UserData>{
    pub fn add_entity<C: CreationContext>(&mut self,
        group: Group,
        whitelist: &[Group],
        blacklist: &[Group],
        world: &mut C,
        entity: Entity,
        shape: ShapeHandle<f32>,
        iso: Isometry3) -> CollisionObjectHandle
    {
        let handle = self.add(group, whitelist, blacklist, entity.into(), shape, iso);
        world.add_component_to(&entity, CollisionHandle(handle));
        handle
    }

    #[cfg(feature="skinning")]
    fn add_character<C: CreationContext, V: Vertex<Position = Vec4> + Serialize + Deserialize<'static> + 'static>(&mut self,
        group: Group,
        whitelist: &[Group],
        blacklist: &[Group],
        world: &mut C,
        character_entity: &Entity,
        character_models: &[Entity]) -> CollisionObjectHandle
    {
        let (mins, maxs) = {
            let character_models = world.iter_for_entities::<(
                Read<Transformation>,
                Read<AnimatedGeometry<V>>,
                Read<SkeletonRef>,
            ), _>(character_models.iter().cloned());
            let mut vertices = character_models.flat_map(|(trafo, geom, skeleton_ref)|{
                let skeleton_trafo = world
                    .component_for::<Transformation>(skeleton_ref)
                    .unwrap();
                let skeleton_scale = skeleton_trafo.scale();
                let inv_scale = vec3!(1./skeleton_scale.x, 1./skeleton_scale.y, 1./skeleton_scale.z);
                let scale = trafo.global_scale().component_mul(&inv_scale);
                geom.geom.iter().map(move |v| v.position().xyz().component_mul(&scale).to_pnt())
            });

            let first = vertices.next().unwrap();
            vertices.fold((first, first), |(mins, maxs), v|{
                let mins = pnt3( mins.x.min(v.x), mins.y.min(v.y), mins.z.min(v.z) );
                let maxs = pnt3( maxs.x.max(v.x), maxs.y.max(v.y), maxs.z.max(v.z) );
                (mins, maxs)
            })
        };

        let bounding = AABB::new(mins, maxs);
        let cuboid = Cuboid::new(bounding.half_extents());
        let offset = Isometry3::new(bounding.center().to_vec(), zero());
        let trimesh = procedural_to_rinmesh(&cuboid.to_trimesh(()), &offset, &vec3!(1.));
        let shape = ShapeHandle::new(cuboid);
        let trafo = world
            .component_for::<Transformation>(&character_entity)
            .unwrap()
            .clone();
        let iso = to_iso(&trafo.node);
        let handle = self.add_entity(group, whitelist, blacklist, world, *character_entity,
            shape.clone(), iso * offset);

        world.add_component_to(character_entity, Shape(shape));
        world.add_component_to(character_entity, Isometry(iso));
        world.add_component_to(character_entity, Offset(offset));
        // world.add_component_to(&character_entity.character, Geometry(trimesh));
        handle
    }

    pub fn remove_entity<C: CreationContext>(&mut self, entity: &Entity, entities: &mut C){
        let handle = entities.component_for::<CollisionHandle>(entity).unwrap();
        debug!("Removing handle {:?} for entity {}", *handle, entity.guid());
        self.remove(&[handle.0]);
    }

    fn updater<'a, I: Iterator<Item = (Entity, &'a CollisionHandle, &'a Transformation, &'a Offset, &'a mut Isometry)>>(&mut self, trafos: I){
        for (e, handle, trafo, offset, physics_trafo) in trafos{
            physics_trafo.0 = to_iso(&trafo.node);
            self.world.set_position(handle.0, physics_trafo.0 * offset.0);
        }
        self.world.update();
    }

    pub fn update_entities(&mut self, entities: &Entities){
        // Use a filter struct
        let trafos = entities.iter_for::<(
                Entity,
                Read<CollisionHandle>,
                Read<Transformation>,
                Read<Offset>,
                Write<Isometry>
            )>();
        self.updater(trafos);
    }

    pub fn update_entities_thread_local(&mut self, entities: &EntitiesThreadLocal){
        let trafos = entities.iter_for::<(
            Entity,
            Read<CollisionHandle>,
            Read<Transformation>,
            Read<Offset>,
            Write<Isometry>
        )>();
        self.updater(trafos);
    }
}

// pub struct Settings<Group: Into<usize>, Data: From<Entity>>{
//     pub character_entity: Option<blender_loader::CharacterEntity>,
//     pub npcs: Vec<blender_loader::CharacterEntity>,
//     pub character_group: Group,
//     pub npcs_group: Group,
//     pub other_models_group: Group,
//     pub collisions: Arc<RwLock<Collisions<Group, Data>>>
// }

// pub struct System<Group: Into<usize>, Data: From<Entity>>{
//     character_entity: Option<blender_loader::CharacterEntity>,
//     collisions: Collisions<Group, Data>,
// }

// impl<Group: Into<usize> + Copy, Data: From<Entity>> System<Group, Data>{
//     pub fn new(settings: Settings<Group, Data>, world: &mut rinecs::World) -> System<Group, Data>{
//         let mut collisions = Collisions::new();
//         let mut to_add = Vec::new();

//         // Add all models with rigid body set
//         for (entity, trafo, physics, model) in world.entities_thread_local().iter_for::<(ReadEntities, Read<Transformation>, Read<RigidBody>, Read<BlenderModel>)>(){
//             let (shape, trimesh, offset) = shape_and_trimesh(trafo, physics, model, None);
//             let iso = to_iso(&trafo.node);
//             to_add.push((entity,
//                 Shape(shape),
//                 Isometry(iso),
//                 Offset(offset),
//                 GeometrySimple(trimesh)));
//         }

//         for (entity, shape, trafo, offset, gpu_geom) in to_add.into_iter(){
//             collisions.add_entity(
//                 settings.other_models_group,
//                 &[settings.character_group, settings.npcs_group],
//                 &[],
//                 world,
//                 entity,
//                 shape.0.clone(),
//                 trafo.0 * offset.0);
//             world.add_component_to(&entity, shape);
//             world.add_component_to(&entity, trafo);
//             world.add_component_to(&entity, offset);
//             world.add_component_to_thread_local(&entity, gpu_geom);
//         }

//         // Add character
//         if let Some(character_entity) = settings.character_entity.as_ref(){
//             collisions.add_character(
//                 settings.character_group,
//                 &[settings.other_models_group, settings.npcs_group],
//                 &[],
//                 world,
//                 character_entity);
//         }

//         for npc in settings.npcs {
//             collisions.add_character(
//                 settings.npcs_group,
//                 &[settings.other_models_group, settings.character_group],
//                 &[],
//                 world,
//                 &npc);
//         }


//         System{
//             collisions,
//             character_entity: settings.character_entity,
//         }
//     }

//     pub fn upload_gpu_resources(&self, world: &mut World, gl: &gl::Renderer){
//         let entity_vao = world.entities().iter_for::<(
//             ReadEntities,
//             Read<Shape>,
//             Read<GeometrySimple<graphics::Vertex3D>>
//         )>().map(|(entity, _, geom)| {
//             let gpu_geom = geom
//                 .to_simple_vao(gl, &gl::default_attribute_bindings(), gl::STATIC_DRAW).unwrap();
//             (entity, gpu_geom)
//         }).collect::<Vec<_>>();

//         for (entity, gpu_geom) in entity_vao.into_iter(){
//             world.add_component_to_thread_local(&entity, gpu::DebugGeometry(gpu_geom));
//         }
//     }
// }

// impl<'a, Group: Into<usize> + Copy + Send, Data: From<Entity> + Send> rinecs::System<'a> for System<Group, Data>{
//     fn run(&mut self, entities: Entities, _resources: Resources){
//         self.collisions.update_entities(&entities);

//         if let Some(character_entity) = self.character_entity.as_ref(){
//             let char_id = entities
//                 .component_for::<CollisionHandle>(&character_entity.character)
//                 .unwrap()
//                 .uid();
//             let contact = self.collisions.world.contact_pairs()
//                 .find(|pair| pair.0.handle().uid() == char_id || pair.1.handle().uid() == char_id);

//             if let Some(ref contact) = contact {
//                 let other;
//                 let character;
//                 if contact.0.handle().uid() == char_id{
//                     other = &contact.1;
//                     character = &contact.0;
//                 }else{
//                     other = &contact.0;
//                     character = &contact.1;
//                 };

//                 let other_pos = other.position().translation.vector.to_pnt();
//                 let other_aabb = other.shape().aabb(other.position());
//                 let prev_trafo = entities
//                     .component_for::<PreviousTransformation>(&character_entity.character)
//                     .unwrap()
//                     .clone();
//                 let mut trafo = entities
//                     .component_for_mut::<Transformation>(&character_entity.character)
//                     .unwrap();
//                 let curr_distance = distance(&other_pos, &trafo.global_position());

//                 let charac_pos = &character.position().translation.vector;
//                 let mins = other_aabb.mins();
//                 let maxs = other_aabb.maxs();
//                 if mins.x < charac_pos.x && mins.y < charac_pos.y && mins.z < charac_pos.z &&
//                    maxs.x > charac_pos.x && maxs.y > charac_pos.y && maxs.z > charac_pos.z
//                 {
//                     // inside check that we are getting away
//                     if curr_distance > distance(&other_pos, &prev_trafo.global_position()){
//                         trafo.node = prev_trafo.0;
//                     }
//                 }else{
//                     if curr_distance < distance(&other_pos, &prev_trafo.global_position()){
//                         trafo.node = prev_trafo.0;
//                         //self.rotation_node = prev_rotation_node;
//                         //let node = self.node().clone();
//                         //world.set_position_for(char_id, &node);
//                     }
//                 }
//             }
//         }
//     }
// }

#[cfg(feature="blender")]
fn collide_convex_hull(mesh: &rinblender::Mesh, scale: Vec3) -> Option<ConvexHull<f32>>{
    let vertices = mesh.mvert.iter()
        .map(|v| v.position.component_mul(&scale).to_pnt())
        .collect::<Vec<_>>();

    //TODO: add indices if there are any in the original mesh
    ConvexHull::try_from_points(&vertices)
}

#[cfg(feature="blender")]
fn blend_mesh_indices(blend_mesh: &rinblender::Mesh, offset: usize) -> Vec<Pnt3<usize>>{
    if blend_mesh.mvert.is_empty() || blend_mesh.mloop.is_empty(){
        return vec![];
    }

    let loops = &blend_mesh.mloop;
    blend_mesh.mpoly.iter().flat_map(|poly|{
        let loopstart = poly.loopstart as usize;
        let totloop = poly.totloop;
        if totloop == 4{
            let v0 = loops[loopstart].v as usize + offset;
            let v1 = loops[loopstart+1].v as usize + offset;
            let v2 = loops[loopstart+2].v as usize + offset;
            let v3 = loops[loopstart+3].v as usize + offset;
            vec![Pnt3::new(v0,v1,v2),  Pnt3::new(v2,v3,v0)]
        }else if totloop == 3{
            let v0 = loops[loopstart].v as usize + offset;
            let v1 = loops[loopstart+1].v as usize + offset;
            let v2 = loops[loopstart+2].v as usize + offset;
            vec![Pnt3::new(v0, v1, v2)]
        }else if totloop > 4{
            let v0 = loops[loopstart];
            loops[loopstart + 1 .. loopstart + totloop as usize]
                .windows(2)
                .map(|v1v2| pnt3!(v0.v as usize + offset, v1v2[0].v as usize + offset, v1v2[1].v as usize + offset))
                .collect()
        }else{
            vec![]
        }
    }).collect()
}

#[cfg(feature="blender")]
fn collide_blend_mesh(mesh: &rinblender::Mesh, scale: Vec3) -> TriMesh<f32>{
    let vertices = mesh.mvert.iter()
        .map(|v| v.position.component_mul(&scale).to_pnt())
        .collect();

    let indices = blend_mesh_indices(mesh, 0);

    TriMesh::new(
        vertices,
        indices,
        None,
    )
}

pub fn rinmesh_to_trimesh(mesh: &graphics::Mesh3D, scale: Vec3) -> TriMesh<f32>{
    let vertices = mesh.iter()
        .map(|v| v.position.component_mul(&scale).to_pnt())
        .collect();

    let indices = if mesh.indices().is_empty(){
        mesh.vertices().chunks(3).enumerate()
            .map(|(idx, _)| pnt3(idx*3, idx*3+1, idx*3+2))
            .collect::<Vec<_>>()
    }else{
        mesh.indices().chunks(3)
            .map(|idx| pnt3(idx[0] as usize, idx[1] as usize, idx[2] as usize))
            .collect()
    };

    TriMesh::new(
        vertices,
        indices,
        None,
    )
}

#[inline]
fn transform(p: Pnt3, offset: &Isometry3, scale: &Vec3) -> Pnt3{
    (offset * p).to_vec().component_mul(scale).to_pnt()
}

#[cfg(feature="blender")]
fn bounding_box(mesh: &rinblender::Mesh, node: &graphics::Node, scale: Option<Vec3>) -> AABB<f32>{
    let one = Isometry3::identity();
    let scale = scale.unwrap_or(vec3!(1.)).component_mul(&node.global_scale());
    aabb(&collide_blend_mesh(mesh, scale), &one)
}

fn trimesh_to_rinmesh(trimesh: &TriMesh<f32>, scale: Vec3) -> graphics::Mesh3D{
    let vertices = trimesh.vertices().iter()
        .map(|p| graphics::vertex3d(p.to_vec().component_mul(&scale)) );
    let indices = trimesh.indices().iter()
        .flat_map(|p| SmallVec::from([p.x as IndexT, p.y as IndexT, p.z as IndexT]))
        .collect();
    graphics::Mesh::from_vertices_indices(vertices.collect(), indices)
}

pub fn procedural_to_rinmesh(trimesh: &procedural::TriMesh<f32>, offset: &Isometry3, scale: &Vec3) -> graphics::Mesh3D{
    let vertices = trimesh.coords.iter().map(|p| p.to_vec())
        .map(|p| {
            let pos = transform(p.to_pnt(), offset, scale);
            graphics::vertex3d(pos.to_vec())
        });

    let indices = match trimesh.indices {
        procedural::IndexBuffer::Unified(ref indices) => indices.iter()
            .flat_map(|p| SmallVec::from([p.x as IndexT, p.y as IndexT, p.z as IndexT]))
            .collect(),
        procedural::IndexBuffer::Split(ref indices) => {
            indices.iter()
                .flat_map(|p|{
                    SmallVec::from([p.x.x as IndexT, p.y.x as IndexT, p.z.x as IndexT])
                })
                .collect()
        }
    };

    graphics::Mesh::from_vertices_indices(vertices.collect(), indices)
}

pub fn to_iso(n: &graphics::Node) -> Isometry3{
    Isometry3::from_parts(Translation::from(n.global_position().to_vec()), n.global_orientation())
}

// fn shape_and_trimesh(trafo: &Transformation, rigid_body: &RigidBody, geometry: &BlenderModel, scale: Option<Vec3>) -> (ShapeHandle<f32>, graphics::Mesh3D, Isometry3){
//     let node = &trafo.node;
//     let node_scale = scale.unwrap_or(vec3!(1.)).component_mul(&node.global_scale());
//     let inv_scale = vec3!(1./node_scale.x, 1./node_scale.y, 1./node_scale.z);
//     let mesh = geometry.mesh();
//     match rigid_body.shape{
//         rinblender::RigidBodyShape::ConvexHull => {
//             let convex_hull = collide_convex_hull(mesh, node_scale).unwrap();
//             let trimesh = {
//                 let vertices = convex_hull.points().iter()
//                     .map(|p| graphics::vertex3d(p.to_vec().component_mul(&inv_scale)));
//                 graphics::Mesh::from_iter_and_type(vertices, graphics::PrimitiveType::Points)
//             };
//             (ShapeHandle::new(convex_hull), trimesh, one())
//         }
//         rinblender::RigidBodyShape::Mesh => {
//             let collide_mesh = collide_blend_mesh(mesh, node_scale);
//             let trimesh = trimesh_to_rinmesh(&collide_mesh, inv_scale);
//             (ShapeHandle::new(collide_mesh), trimesh, one())
//         }
//         rinblender::RigidBodyShape::Sphere => {
//             let one = Isometry3::identity();
//             let bounding = bounding_sphere(&collide_blend_mesh(mesh, node_scale), &one);
//             let radius = bounding.radius();
//             let ball = Ball::new(radius);
//             let center = bounding.center();
//             let offset = Isometry3::new(center.to_vec(), vec3(Deg(90.).to_rad().value(), 0.,0.));
//             let trimesh = procedural_to_rinmesh(&ball.to_trimesh((10,10)), &offset, &inv_scale);
//             (ShapeHandle::new(ball), trimesh, offset)
//         }
//         rinblender::RigidBodyShape::Cone => {
//             let bounding = bounding_box(mesh, &node, scale);
//             let radius = bounding.half_extents().x.max(bounding.half_extents().y);
//             let half_height = bounding.half_extents().z;
//             let center = bounding.center();
//             let cone = Cone::new(half_height, radius);
//             let offset = Isometry3::new(center.to_vec(), vec3(Deg(90.).to_rad().value(), 0.,0.));
//             let trimesh = procedural_to_rinmesh(&cone.to_trimesh(10), &offset, &inv_scale);
//             // TODO: uncomment once cone implements shape
//             // (ShapeHandle::new(cone), trimesh, offset)
//             unimplemented!()
//         }
//         rinblender::RigidBodyShape::Cylinder => {
//             let bounding = bounding_box(mesh, &node, scale);
//             let radius = bounding.half_extents().x.max(bounding.half_extents().y);
//             let half_height = bounding.half_extents().z;
//             let center = bounding.center();
//             let cylinder = Cylinder::new(half_height, radius);
//             let offset = Isometry3::new(center.to_vec(), vec3(Deg(90.).to_rad().value(), 0.,0.));
//             let trimesh = procedural_to_rinmesh(&cylinder.to_trimesh(10), &offset, &inv_scale);
//             // TODO: uncomment once cone implements shape
//             // (ShapeHandle::new(cylinder), trimesh, offset)
//             unimplemented!()
//         }
//         rinblender::RigidBodyShape::Capsule => {
//             let bounding = bounding_box(mesh, &node, scale);
//             let radius = bounding.half_extents().x.max(bounding.half_extents().y);
//             let half_height = bounding.half_extents().z;
//             let center = bounding.center();
//             let capsule = Capsule::new(half_height, radius);
//             let offset = Isometry3::new(center.to_vec(), vec3(Deg(90.).to_rad().value(), 0.,0.));
//             let trimesh = procedural_to_rinmesh(&capsule.to_trimesh((10, 10)), &offset, &inv_scale);
//             // TODO: uncomment once cone implements shape
//             // (ShapeHandle::new(capsule), trimesh, offset)
//             unimplemented!()
//         }
//         rinblender::RigidBodyShape::Cuboid => {
//             //let one = Iso3::identity();
//             let bounding = bounding_box(mesh, &node, scale);
//             let cuboid = Cuboid::new(bounding.half_extents());
//             let cuboid_trimesh = cuboid.to_trimesh(());
//             let center = bounding.center();
//             let offset = Isometry3::new(center.to_vec(), zero());
//             let trimesh = procedural_to_rinmesh(&cuboid_trimesh, &offset, &inv_scale);
//             (ShapeHandle::new(cuboid), trimesh, offset)
//         }
//     }
// }

#[derive(PartialEq,PartialOrd)]
pub struct NonNan(pub f32);

impl NonNan {
    pub fn new(val: f32) -> Option<NonNan> {
        if val.is_nan() {
            None
        } else {
            Some(NonNan(val))
        }
    }
}

impl Eq for NonNan {}

impl Ord for NonNan {
    fn cmp(&self, other: &NonNan) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}