4076c0b70b3d44f54003ef02492212e82cb132d0
[sdk] / ecere / src / gfx / 3D / Object.ec
1 namespace gfx3D;
2
3 import "Display"
4
5 public enum FrustumPlacement { outside, inside, intersecting };
6
7 public class ObjectFormat
8 {
9    class_data const char * extension;
10    class_property const char * extension
11    {
12       set { class_data(extension) = value; }
13       get { return class_data(extension); }
14    }
15
16    virtual bool ::Load(Object object, const char * fileName, DisplaySystem displaySystem);
17 };
18
19 // TODO: Review these:
20 public class ObjectFlags
21 {
22 public:
23    bool root:1, viewSpace:1, ownMesh:1, translucent:1, flipWindings:1, keysLoaded:1, transform:1, mesh:1, light:1, camera:1, localMatrixSet:1;
24    int hierarchy:16:16;
25 };
26
27 public struct Transform
28 {
29    Vector3D position;
30    Quaternion orientation;
31    Vector3Df scaling;
32 };
33
34 /*static float ease(float t, float a, float b)
35 {
36    float k;
37    float s = a + b;
38
39    if (s == 0.0f) return t;
40    if (s > 1.0f)
41    {
42       a /= s;
43       b /= s;
44    }
45    k = 1.0f/(2.0f-a-b);
46    if (t < a) return (k/a)*t*t;
47    if (t < 1.0f - b) return k*(2.0f * t - a);
48    t = 1.0f - t;
49    return 1.0f - (k/b)*t*t;
50 }*/
51
52 public enum FrameTrackType : uint16 { position = 1, rotation, scaling, fov, roll, colorChange, morph, hotSpot, fallOff, hide };
53
54 public class FrameTrackBits
55 {
56    FrameTrackType type;
57    bool loop:1;
58 };
59
60 public struct FrameKey
61 {
62    unsigned int frame;
63    float tension, continuity, bias;
64    float easeFrom, easeTo;
65    union
66    {
67       Vector3Df position;
68       Quaternion orientation;
69       Vector3Df scaling;
70       float roll;
71       float fov;
72       ColorRGB color;
73       float hotSpot;
74       float fallOff;
75    };
76 };
77
78 enum SplinePart { splinePoint, splineA, splineB };
79
80 public class FrameTrack : struct
81 {
82    FrameTrack prev, next;
83    FrameTrackBits type;
84    unsigned int numKeys;
85    FrameKey * keys;
86
87    void Free(void)
88    {
89       delete keys;
90    }
91
92    ~FrameTrack()
93    {
94       Free();
95    }
96
97    float GetFloat(SplinePart what, unsigned int n)
98    {
99       float value;
100       FrameKey *kn_1, *kn, *kn1;
101       float pn_1, pn, pn1;
102       int d1, d2;
103
104       kn = &keys[n];
105       pn = kn->roll;
106
107       if(what == splinePoint)
108          value = pn;
109       else
110       {
111          if(n == 0)
112          {
113             kn1 = &keys[1];
114             pn1 = kn1->roll;
115
116             if(numKeys == 2)
117             {
118                value = pn1 - pn;
119                value *= 1.0f - kn->tension;
120                return value;
121             }
122             if(type.loop)
123             {
124                kn_1 = &keys[numKeys-2];
125                d1 = keys[numKeys-1].frame - kn_1->frame;
126                d2 = kn1->frame - kn->frame;
127             }
128             else
129             {
130                float a1;
131                value = pn1 - pn;
132                value *= 1.5f;
133
134                a1 = GetFloat(splineA, 1);
135                a1 *= 0.5f;
136
137                value -= a1;
138                value *= 1.0f - kn->tension;
139                return value;
140             }
141          }
142          else if(n == numKeys-1)
143          {
144             kn_1 = &keys[n-1];
145             pn_1 = kn_1->roll;
146
147             if(numKeys == 2)
148             {
149                value = pn - pn_1;
150                value *= 1.0f - kn->tension;
151                return value;
152             }
153             if(type.loop)
154             {
155                kn1 = &keys[1];
156                d1 = kn->frame - kn_1->frame;
157                d2 = kn1->frame - keys[0].frame;
158             }
159             else
160             {
161                float bn_1;
162                value = pn - pn_1;
163                value *= 1.5f;
164
165                bn_1 = GetFloat(splineB, n-1);
166                bn_1 *= 0.5f;
167
168                value -= bn_1;
169                value *= 1.0f - kn->tension;
170                return value;
171             }
172          }
173          else
174          {
175             kn_1 = &keys[n-1];
176             kn1 = &keys[n+1];
177             d1 = kn->frame - kn_1->frame;
178             d2 = kn1->frame - kn->frame;
179          }
180          {
181             float C, adjust;
182             float part1, part2;
183
184             pn_1 = kn_1->roll;
185             pn1 = kn1->roll;
186
187             if(what == splineA)
188             {
189                C = kn->continuity;
190                adjust = (float)d1;
191             }
192             else
193             {
194                C = -kn->continuity;
195                adjust = (float)d2;
196             }
197             adjust /= d1 + d2;
198             adjust = 0.5f + (1.0f - Abs(C))*(adjust - 0.5f);
199
200             part1 = pn - pn_1;
201             part1 *= (1.0f + kn->bias)*(1.0f - C);
202
203             part2 = pn1 - pn;
204             part2 *= (1.0f - kn->bias)*(1.0f + C);
205
206             value = part1 + part2;
207             value *= (1.0f - kn->tension)*adjust;
208          }
209       }
210       return value;
211    }
212
213    void GetVector(Vector3Df vector, SplinePart what, unsigned int n)
214    {
215       FrameKey *kn_1, *kn, *kn1;
216       Vector3Df *pn_1, *pn, *pn1;
217       int d1, d2;
218
219       kn = &keys[n];
220       pn = &kn->position;
221
222       if(what == splinePoint)
223          vector = *pn;
224       else
225       {
226          if(n == 0)
227          {
228             kn1 = &keys[1];
229             pn1 = &kn1->position;
230
231             if(numKeys == 2)
232             {
233                vector.Subtract(pn1, pn);
234                vector.Scale(vector, 1.0f - kn->tension);
235                return;
236             }
237             if(type.loop)
238             {
239                kn_1 = &keys[numKeys-2];
240                d1 = keys[numKeys-1].frame - kn_1->frame;
241                d2 = kn1->frame - kn->frame;
242             }
243             else
244             {
245                Vector3Df a1;
246                vector.Subtract(pn1, pn);
247                vector.Scale(vector, 1.5f);
248
249                GetVector(a1, splineA, 1);
250                a1.Scale(a1, 0.5f);
251
252                vector.Subtract(vector, a1);
253                vector.Scale(vector, 1.0f - kn->tension);
254                return;
255             }
256          }
257          else if(n == numKeys-1)
258          {
259             kn_1 = &keys[n-1];
260             pn_1 = &kn_1->position;
261
262             if(numKeys == 2)
263             {
264                vector.Subtract(pn, pn_1);
265                vector.Scale(vector, 1.0f - kn->tension);
266                return;
267             }
268             if(type.loop)
269             {
270                kn1 = &keys[1];
271                d1 = kn->frame - kn_1->frame;
272                d2 = kn1->frame - keys[0].frame;
273             }
274             else
275             {
276                Vector3Df bn_1;
277                vector.Subtract(pn, pn_1);
278                vector.Scale(vector, 1.5f);
279
280                GetVector(&bn_1, splineB, n-1);
281                bn_1.Scale(bn_1, 0.5f);
282
283                vector.Subtract(vector, bn_1);
284                vector.Scale(vector, 1.0f - kn->tension);
285                return;
286             }
287          }
288          else
289          {
290             kn_1 = &keys[n-1];
291             kn1 = &keys[n+1];
292             d1 = kn->frame - kn_1->frame;
293             d2 = kn1->frame - kn->frame;
294          }
295          {
296             float C, adjust;
297             Vector3Df part1, part2;
298
299             pn_1 = &kn_1->position;
300             pn1 = &kn1->position;
301
302             if(what == splineA)
303             {
304                C = kn->continuity;
305                adjust = (float)d1;
306             }
307             else
308             {
309                C = -kn->continuity;
310                adjust = (float)d2;
311             }
312             adjust /= d1 + d2;
313             adjust = 0.5f + (1.0f - Abs(C))*(adjust - 0.5f);
314
315             part1.Subtract(pn, pn_1);
316             part1.Scale(part1, (1.0f + kn->bias)*(1.0f - C));
317
318             part2.Subtract(pn1, pn);
319             part2.Scale(part2, (1.0f - kn->bias)*(1.0f + C));
320
321             vector.Add(part1, part2);
322             vector.Scale(vector, (1.0f - kn->tension)*adjust);
323          }
324       }
325    }
326
327    void GetQuaternion(Quaternion quat, SplinePart what, unsigned int n)
328    {
329       FrameKey *kn_1, *kn, *kn1;
330       Quaternion *qn_1, *qn, *qn1;
331       int d1, d2;
332
333       kn = &keys[n];
334       qn = &kn->orientation;
335
336       if (what == splinePoint)
337          quat = *qn;
338       else
339       {
340          if(n == 0)
341          {
342             kn1 = &keys[1];
343
344             if (!(type.loop) || numKeys <= 2)
345             {
346                qn1 = &kn1->orientation;
347                quat.Slerp(qn, qn1, (1.0f - kn->tension)*(1.0f + kn->continuity*kn->bias)/3.0f);
348                return;
349             }
350             else
351             {
352                kn_1= &keys[numKeys-2];
353                d1 = keys[numKeys-1].frame - kn_1->frame;
354                d2 = kn1->frame - kn->frame;
355             }
356          }
357          else if (n == numKeys-1)
358          {
359             kn_1 = &keys[n-1];
360
361             if (!(type.loop) || numKeys <= 2)
362             {
363                qn_1 = &kn_1->orientation;
364                quat.Slerp(qn, qn_1, (1.0f - kn->tension)*(1.0f - kn->continuity*kn->bias)/3.0f);
365                return;
366             }
367             else
368             {
369                kn1 = &keys[1];
370                d1 = kn->frame - kn_1->frame;
371                d2 = kn1->frame - keys[0].frame;
372             }
373          }
374          else
375          {
376             kn_1 = &keys[n-1];
377             kn1 = &keys[n+1];
378             d1 = kn->frame - kn_1->frame;
379             d2 = kn1->frame - kn->frame;
380          }
381          {
382             float f, adjust;
383             Quaternion g1, g2, tmp;
384
385             qn_1 = &kn_1->orientation;
386             qn1 = &kn1->orientation;
387
388             if (what == splineA)
389             {
390                f = 1.0f;
391                adjust = (float)d1;
392             }
393             else
394             {
395                f = -1.0f;
396                adjust = (float)d2;
397             }
398             adjust /= d1 + d2;
399             adjust = 0.5f + (1.0f - Abs(kn->continuity))*(adjust - 0.5f);
400
401             g1.Slerp(qn, qn_1,-(1.0f + kn->bias)/3.0f);
402             g2.Slerp(qn, qn1 , (1.0f - kn->bias)/3.0f);
403             tmp.Slerp(g1, g2, 0.5f + f*0.5f*kn->continuity);
404             quat.Slerp(qn, &tmp, f*(kn->tension - 1.0f)*adjust*2.0f);
405          }
406       }
407    }
408
409    void Interpolate(Vector3Df vector, Vector3Df prevVector, Vector3Df nextVector, int prev, int next, float t)
410    {
411       if(!t)
412          vector = prevVector;
413       else
414       {
415          Vector3Df p1 = prevVector, p2 = nextVector;
416          Vector3Df r1, r2;
417
418          GetVector(r1, splineB, prev);
419          GetVector(r2, splineA, next);
420
421          p1.Scale(p1, 2*t*t*t - 3*t*t + 1);
422          p2.Scale(p2,-2*t*t*t + 3*t*t);
423
424          r1.Scale(r1, t*t*t - 2*t*t + t);
425          r2.Scale(r2, t*t*t -   t*t);
426
427          vector = p1;
428          vector.Add(vector, r1);
429          vector.Add(vector, p2);
430          vector.Add(vector, r2);
431       }
432    }
433
434    void InterpolateQuat(Quaternion quat, Quaternion prevQuat, Quaternion nextQuat, int prev, int next, float t)
435    {
436       if(!t)
437          quat = prevQuat;
438       else
439       {
440          Quaternion a, b;
441          Quaternion q0, q1, q2;
442
443          GetQuaternion(b, splineB, prev);
444          GetQuaternion(a, splineA, next);
445
446          q0.Slerp(prevQuat, b, t);
447          q1.Slerp(b, a, t);
448          q2.Slerp(a, nextQuat, t);
449
450          q0.Slerp(q0, q1, t);
451          q1.Slerp(q1, q2, t);
452
453          quat.Slerp(q0, q1, t);
454       }
455    }
456
457    float InterpolateFloat(float prevValue, float nextValue, int prev, int next, float t)
458    {
459       float value;
460       if(!t)
461          value = prevValue;
462       else
463       {
464          float p1 = prevValue, p2 = nextValue;
465
466          float r1 = GetFloat(splineB, prev);
467          float r2 = GetFloat(splineA, next);
468
469          p1 *= 2*t*t*t - 3*t*t + 1;
470          p2 *= -2*t*t*t + 3*t*t;
471
472          r1 *= t*t*t - 2*t*t + t;
473          r2 *= t*t*t -   t*t;
474
475          value = p1 + r1 + p2 + r2;
476       }
477       return value;
478    }
479 };
480
481 static bool FindMaterialAndType(Mesh mesh, Material material, PrimitiveGroupType type)
482 {
483    PrimitiveGroup group;
484    for(group = mesh.groups.first; group; group = group.next)
485       if(group.material == material && group.type == type)
486          return true;
487    return false;
488 }
489
490 public class Object
491 {
492 public:
493    void SetMinMaxRadius(bool processMesh)
494    {
495       Object child;
496
497       if(flags.mesh && mesh)
498       {
499          if(processMesh)
500             mesh.SetMinMaxRadius();
501          min = mesh.min;
502          max = mesh.max;
503          volume = (max.x >= min.x && max.y >= min.y && max.z >= min.z);
504       }
505       else
506       {
507          min = { MAXFLOAT, MAXFLOAT, MAXFLOAT };
508          max = { -MAXFLOAT, -MAXFLOAT, -MAXFLOAT };
509          volume = false;
510       }
511       for(child = children.first; child; child = child.next)
512       {
513          child.SetMinMaxRadius(processMesh);
514
515          if(child.volume)
516          {
517             // Child Local + Child Object Transform
518             Vector3Df points[8] =
519             {
520                { child.min.x, child.min.y, child.min.z },
521                { child.min.x, child.min.y, child.max.z },
522                { child.min.x, child.max.y, child.min.z },
523                { child.min.x, child.max.y, child.max.z },
524                { child.max.x, child.min.y, child.min.z },
525                { child.max.x, child.min.y, child.max.z },
526                { child.max.x, child.max.y, child.min.z },
527                { child.max.x, child.max.y, child.max.z }
528             };
529             int c;
530             for(c = 0; c<8; c++)
531             {
532                Vector3Df point;
533                point.MultMatrix(points[c], child.localMatrix);
534
535                if(point.x < min.x) min.x = point.x;
536                if(point.y < min.y) min.y = point.y;
537                if(point.z < min.z) min.z = point.z;
538
539                if(point.x > max.x) max.x = point.x;
540                if(point.y > max.y) max.y = point.y;
541                if(point.z > max.z) max.z = point.z;
542             }
543             volume = true;
544          }
545       }
546
547       if(volume)
548       {
549          Vector3Df points[8] =
550          {
551             { min.x, min.y, min.z },
552             { min.x, min.y, max.z },
553             { min.x, max.y, min.z },
554             { min.x, max.y, max.z },
555             { max.x, min.y, min.z },
556             { max.x, min.y, max.z },
557             { max.x, max.y, min.z },
558             { max.x, max.y, max.z }
559          };
560          Vector3Df halfExtent;
561          Vector3D halfExtentd;
562
563          // Local
564          center.Add(min, max);
565          center.Scale(center, 0.5f);
566          halfExtent.Subtract(max, min);
567          halfExtent.Scale(halfExtent, 0.5f);
568          radius = halfExtent.length;
569
570          // World
571          {
572             Vector3D min { MAXFLOAT, MAXFLOAT, MAXFLOAT };
573             Vector3D max { -MAXFLOAT, -MAXFLOAT, -MAXFLOAT };
574             int c;
575             for(c = 0; c<8; c++)
576             {
577                Vector3D point;
578                point.MultMatrixf(points[c], matrix);
579
580                if(point.x < min.x) min.x = point.x;
581                if(point.y < min.y) min.y = point.y;
582                if(point.z < min.z) min.z = point.z;
583
584                if(point.x > max.x) max.x = point.x;
585                if(point.y > max.y) max.y = point.y;
586                if(point.z > max.z) max.z = point.z;
587             }
588             wmin = min;
589             wmax = max;
590          }
591          wcenter.Add(wmin, wmax);
592          wcenter.Scale(wcenter, 0.5f);
593
594          halfExtentd.Subtract(wmax, wmin);
595          halfExtentd.Scale(halfExtentd, 0.5);
596          wradius = halfExtentd.length;
597       }
598    }
599
600    void Duplicate(Object model)
601    {
602       if(model)
603       {
604          Object modelChild;
605
606          name = CopyString(model.name);
607          flags = model.flags;
608          flags.ownMesh = false;
609          flags.transform = false;
610          mesh = model.mesh;
611          /*
612          min = model.min;
613          max = model.max;
614          radius = model.radius;
615          */
616          if(parent && !flags.root)
617             matrix.Multiply(localMatrix, parent.matrix);
618          else
619             matrix = localMatrix;
620
621          for(modelChild = model.children.first; modelChild; modelChild = modelChild.next)
622          {
623             Object child { parent = this };
624             child.localMatrix = modelChild.localMatrix;
625             child.transform = modelChild.transform;
626             child.Duplicate(modelChild);
627             children.AddName(child);
628          }
629       }
630    }
631
632    void Free(DisplaySystem displaySystem)
633    {
634       if(this)
635       {
636          Object child;
637
638          while((child = children.first))
639          {
640             children.Remove(child);
641             child.Free(displaySystem);
642
643             // We did not do this before so as to keep transform on reloading for new DisplaySystem
644             // However since children are removed, it seems that purpose has been gone, we'd need
645             // a new mechanism to handle lost resources reloading...
646             delete child;
647          }
648          if(flags.ownMesh && mesh)
649          {
650             DisplaySystem meshDisplaySystem = mesh.displaySystem;
651             mesh.Free(0);
652             if(meshDisplaySystem)
653                meshDisplaySystem.RemoveMesh(mesh);
654             delete mesh;
655          }
656
657          tracks.Free(FrameTrack::Free);
658
659          delete name;
660       }
661    }
662
663    bool Load(const char * fileName, const char * type, DisplaySystem displaySystem)
664    {
665       char ext[MAX_EXTENSION];
666       subclass(ObjectFormat) format;
667       OldLink link;
668       bool result = false;
669
670       if(!type && fileName)
671          type = strlwr(GetExtension(fileName, ext));
672
673       for(link = class(ObjectFormat).derivatives.first; link; link = link.next)
674       {
675          format = link.data;
676          if(format.extension && !strcmp(format.extension, type))
677             break;
678       }
679       if(!link) format = null;
680
681       if(format)
682       {
683          if((format.Load(this, fileName, displaySystem)))
684             result = true;
685       }
686       /*if(!result)
687           ErrorLogCode(GERR_LOAD_OBJECT_FAILED, fileName);*/
688       return result;
689    }
690
691    void FreeMesh(DisplaySystem displaySystem)
692    {
693       if(this)
694       {
695          Object child;
696          mesh.Free(0);
697          for(child = children.first; child; child = child.next)
698             child.FreeMesh(displaySystem);
699       }
700    }
701
702    Object Find(const char * name)
703    {
704       if(this && name)
705       {
706          Object child;
707
708          if(this.name && !strcmp(this.name, name))
709             return this;
710          else
711          {
712             for(child = children.first; child; child = child.next)
713             {
714                Object result = child.Find(name);
715                if(result)
716                   return result;
717             }
718          }
719       }
720       return null;
721    }
722
723    void Initialize(void)
724    {
725       if(this)
726       {
727          transform.scaling = { 1, 1, 1 };
728          transform.orientation = { 1,0,0,0 };
729          flags.root = true;
730          flags.transform = true;
731          matrix.Identity();
732       }
733    }
734
735    Mesh InitializeMesh(DisplaySystem displaySystem)
736    {
737       if(this)
738       {
739          flags.mesh = true;
740          if(!mesh)
741          {
742             mesh = Mesh { };
743             flags.ownMesh = true;
744          }
745          if(mesh)
746          {
747             FillBytes(mesh, 0, sizeof(class Mesh));
748             displaySystem.AddMesh(mesh);
749          }
750          matrix.Identity();
751          return mesh;
752       }
753       return null;
754    }
755
756    bool AddName(Object object, const char * name)
757    {
758       bool result = false;
759       if(this)
760       {
761          char * newName = CopyString(name);
762          object.name = newName;
763          result = children.AddName(object);
764          if(result)
765             object.parent = this;
766          object.flags.transform = true;
767       }
768       return result;
769    }
770
771    // TODO: Add support to Merge Vertex Colors mesh feature
772    bool Merge(DisplaySystem displaySystem)
773    {
774       bool result = false;
775
776       if(!children.first && (!this.flags.mesh || this.flags.ownMesh))
777          result = true;
778       else
779       {
780          Object child, nextChild;
781          int nVertices = 0;
782          MeshFeatures flags = 0;
783          Mesh objectMesh = this.flags.mesh ? mesh : null;
784          bool freeMesh = this.flags.ownMesh;
785
786          // Count total number of vertices
787          if(objectMesh)
788          {
789             flags |= objectMesh.flags;
790             nVertices += objectMesh.nVertices;
791          }
792
793          for(child = children.first; child; child = child.next)
794          {
795             child.Merge(displaySystem);
796             if(child.mesh)
797             {
798                nVertices += child.mesh.nVertices;
799                flags |= child.mesh.flags;
800             }
801          }
802
803          if(!nVertices)
804             return true;
805
806          if(this.flags.camera)
807             delete camera;
808
809          mesh = Mesh { };
810          this.flags.ownMesh = true;
811          this.flags.mesh = true;
812          displaySystem.AddMesh(mesh);
813
814          if(mesh.Allocate(flags, nVertices, displaySystem))
815          {
816             int c;
817             int nTriangles = 0;
818             int vertexOffset = 0;
819             PrimitiveGroup group = null;
820
821             // Merge vertices
822
823             nVertices = 0;
824             if(objectMesh)
825             {
826                for(c = 0; c<objectMesh.nVertices; c++)
827                {
828                   mesh.vertices[nVertices] = objectMesh.vertices[c];
829
830                   if(objectMesh.normals)
831                      mesh.normals[nVertices] = objectMesh.normals[c];
832                   if(objectMesh.texCoords)
833                      mesh.texCoords[nVertices] = objectMesh.texCoords[c];
834
835                   nVertices++;
836                }
837             }
838
839             for(child = children.first; child; child = child.next)
840             {
841                Matrix matrix, normalMatrix;
842
843                matrix = child.localMatrix;
844                /*
845                matrix.Identity();
846                matrix.Scale(child.transform.scaling.x, child.transform.scaling.y, child.transform.scaling.z);
847                matrix.Rotate(child.transform.orientation);
848                */
849
850                normalMatrix = matrix;
851
852                normalMatrix.m[3][0] = 0;
853                normalMatrix.m[3][1] = 0;
854                normalMatrix.m[3][2] = 0;
855
856                // matrix.Translate(child.transform.position.x, child.transform.position.y, child.transform.position.z);
857
858                if(child.flags.mesh && child.mesh)
859                {
860                   for(c = 0; c<child.mesh.nVertices; c++)
861                   {
862                      mesh.vertices[nVertices].MultMatrix(child.mesh.vertices[c], matrix);
863                      if(child.mesh.normals)
864                         mesh.normals[nVertices].MultMatrix(child.mesh.normals[c], normalMatrix);
865                      if(child.mesh.texCoords)
866                         mesh.texCoords[nVertices] = child.mesh.texCoords[c];
867                      nVertices++;
868                   }
869                }
870             }
871
872             // Merge Indexed Primitive Groups
873             while(true)
874             {
875                int nIndices = 0;
876                PrimitiveGroupType type = (PrimitiveGroupType)-1;
877                Material material = null;
878                bool foundGroup = false;
879
880                // Find first group type/material to process and determine how many indices are required
881                if(objectMesh)
882                {
883                   for(group = objectMesh.groups.first; group; group = group.next)
884                   {
885                      if(!foundGroup && !(group.type.vertexRange))
886                      {
887                         if(!FindMaterialAndType(mesh, group.material, group.type))
888                         {
889                            material = group.material;
890                            type = group.type;
891                            nIndices += group.nIndices;
892                            foundGroup = true;
893                         }
894                      }
895                      else if(material == group.material && type == group.type)
896                         nIndices += group.nIndices;
897                   }
898                }
899
900                for(child = children.first; child; child = child.next)
901                {
902                   if(child.flags.mesh && child.mesh)
903                   {
904                      for(group = child.mesh.groups.first; group; group = group.next)
905                      {
906                         if(!foundGroup && !(group.type.vertexRange))
907                         {
908                            if(!FindMaterialAndType(mesh, group.material ? group.material : child.material, group.type))
909                            {
910                               material = group.material ? group.material : child.material;
911                               type = group.type;
912                               nIndices += group.nIndices;
913                               foundGroup = true;
914                            }
915                         }
916                         else if(material == (group.material ? group.material : child.material) && type == group.type)
917                            nIndices += group.nIndices;
918                      }
919                   }
920                }
921
922                // Merge with all similar groups
923                if(foundGroup)
924                {
925                   PrimitiveGroup newGroup = mesh.AddPrimitiveGroup(type, nIndices);
926                   if(newGroup)
927                   {
928                      newGroup.material = material;
929                      nIndices = 0;
930
931                      vertexOffset = 0;
932
933                      if(objectMesh)
934                      {
935                         for(group = objectMesh.groups.first; group; group = group.next)
936                         {
937                            if(newGroup.material == group.material && newGroup.type == group.type)
938                            {
939                               int c;
940                               if(group.type.indices32bit)
941                                  for(c = 0; c<group.nIndices; c++)
942                                     newGroup.indices32[nIndices++] = group.indices32[c] + vertexOffset;
943                               else
944                                  for(c = 0; c<group.nIndices; c++)
945                                     newGroup.indices[nIndices++] = (uint16)(group.indices[c] + vertexOffset);
946                            }
947                         }
948                         vertexOffset += objectMesh.nVertices;
949                      }
950
951                      for(child = children.first; child; child = child.next)
952                      {
953                         if(child.flags.mesh && child.mesh)
954                         {
955                            for(group = child.mesh.groups.first; group; group = group.next)
956                            {
957                               if(newGroup.material == (group.material ? group.material : child.material) &&
958                                  newGroup.type == group.type)
959                               {
960                                  int c;
961                                  if(group.type.indices32bit)
962                                     for(c = 0; c<group.nIndices; c++)
963                                        newGroup.indices32[nIndices++] = group.indices32[c] + vertexOffset;
964                                  else
965                                     for(c = 0; c<group.nIndices; c++)
966                                        newGroup.indices[nIndices++] = (uint16)(group.indices[c] + vertexOffset);
967                               }
968                            }
969                            vertexOffset += child.mesh.nVertices;
970                         }
971                      }
972                      mesh.UnlockPrimitiveGroup(newGroup);
973                   }
974                }
975                else
976                   break;
977             }
978
979             // Merge Non-Indexed Primitive Groups
980             vertexOffset = 0;
981
982             if(objectMesh)
983             {
984                for(group = objectMesh.groups.first; group; group = group.next)
985                {
986                   if(group.type.vertexRange)
987                   {
988                      PrimitiveGroup newGroup = mesh.AddPrimitiveGroup(group.type, 0);
989                      if(newGroup)
990                      {
991                         newGroup.material = group.material;
992                         newGroup.nVertices = group.nVertices;
993                         newGroup.first = group.first + vertexOffset;
994                      }
995                   }
996                }
997                vertexOffset += objectMesh.nVertices;
998             }
999
1000             for(child = children.first; child; child = child.next)
1001             {
1002                if(child.flags.mesh && child.mesh)
1003                {
1004                   for(group = child.mesh.groups.first; group; group = group.next)
1005                   {
1006                      if(group.type.vertexRange)
1007                      {
1008                         PrimitiveGroup newGroup = mesh.AddPrimitiveGroup(group.type, 0);
1009                         if(newGroup)
1010                         {
1011                            newGroup.material = group.material ? group.material : child.material;
1012                            newGroup.nVertices = group.nVertices;
1013                            newGroup.first = group.first + vertexOffset;
1014                         }
1015                      }
1016                   }
1017                   vertexOffset += child.mesh.nVertices;
1018                }
1019             }
1020
1021             // Merge Triangles
1022             if(objectMesh)
1023                nTriangles = objectMesh.nPrimitives;
1024
1025             for(child = children.first; child; child = child.next)
1026             {
1027                if(child.mesh)
1028                   nTriangles += child.mesh.nPrimitives;
1029             }
1030
1031             mesh.primitives = new PrimitiveSingle[nTriangles];
1032             mesh.nPrimitives = 0;
1033             vertexOffset = 0;
1034             if(objectMesh)
1035             {
1036                for(c = 0; c<objectMesh.nPrimitives; c++)
1037                {
1038                   int i;
1039                   PrimitiveSingle * triangle = &mesh.primitives[mesh.nPrimitives++];
1040                   PrimitiveSingle * src = &objectMesh.primitives[c];
1041
1042                   mesh.AllocatePrimitive(triangle, src->type, src->nIndices);
1043                   triangle->material = src->material;
1044                   triangle->middle = src->middle;
1045                   triangle->plane = src->plane;
1046
1047                   //*triangle = *src;
1048                   //src->indices = null;
1049                   //src->data = null;
1050
1051                   if(triangle->type.indices32bit)
1052                      for(i = 0; i<triangle->nIndices; i++)
1053                         triangle->indices32[i] = src->indices32[i] + vertexOffset;
1054                   else
1055                      for(i = 0; i<triangle->nIndices; i++)
1056                         triangle->indices[i] = (uint16)(src->indices[i] + vertexOffset);
1057                   mesh.UnlockPrimitive(triangle);
1058                }
1059                vertexOffset += objectMesh.nVertices;
1060             }
1061
1062             for(child = children.first; child; child = child.next)
1063             {
1064                if(child.flags.mesh && child.mesh)
1065                {
1066                   for(c = 0; c<child.mesh.nPrimitives; c++)
1067                   {
1068                      int i;
1069                      PrimitiveSingle * triangle = &mesh.primitives[mesh.nPrimitives++];
1070                      PrimitiveSingle * src = &child.mesh.primitives[c];
1071
1072                      mesh.AllocatePrimitive(triangle, src->type, src->nIndices);
1073                      triangle->material = src->material ? src->material : child.material;
1074                      triangle->middle = src->middle;
1075                      triangle->plane = src->plane;
1076
1077                      //*triangle = *src;
1078                      //src->indices = null;
1079                      //src->data = null;
1080
1081                      if(triangle->type.indices32bit)
1082                      {
1083                         for(i = 0; i<triangle->nIndices; i++)
1084                            triangle->indices32[i] = src->indices32[i] + vertexOffset;
1085                      }
1086                      else
1087                      {
1088                         for(i = 0; i<triangle->nIndices; i++)
1089                            triangle->indices[i] = (uint16)(src->indices[i] + vertexOffset);
1090                      }
1091                      mesh.UnlockPrimitive(triangle);
1092                   }
1093                   vertexOffset += child.mesh.nVertices;
1094                }
1095             }
1096
1097             // Free children
1098             for(child = children.first; child; child = nextChild)
1099             {
1100                nextChild = child.next;
1101                children.Remove(child);
1102                child.Free(displaySystem);
1103                delete child;
1104             }
1105
1106             mesh.ApplyTranslucency(this);
1107             // this.flags.translucent = true;
1108
1109             result = true;
1110
1111             mesh.Unlock(flags);
1112          }
1113          if(freeMesh && objectMesh)
1114          {
1115             if(objectMesh.displaySystem)
1116                objectMesh.displaySystem.RemoveMesh(objectMesh);
1117             delete objectMesh;
1118          }
1119          SetMinMaxRadius(true);
1120       }
1121       return result;
1122    }
1123
1124    void RotateEuler(Euler rotation, Euler min, Euler max)
1125    {
1126       // WARNING: 'eulerOrientation' is only updated by this function
1127       Euler euler = eulerOrientation;//transform.orientation;
1128       euler.Add(euler, rotation);
1129
1130       if(min && max)
1131       {
1132          if(min.pitch && max.pitch)
1133             euler.pitch = Min(Max(euler.pitch, min.pitch), max.pitch);
1134          if(min.yaw && max.yaw)
1135             euler.yaw = Min(Max(euler.yaw, min.yaw), max.yaw);
1136          if(min.roll && max.roll)
1137             euler.roll = Min(Max(euler.roll, min.roll), max.roll);
1138       }
1139
1140       eulerOrientation = euler;
1141       transform.orientation = euler;
1142       UpdateTransform();
1143    }
1144
1145    void Move(Vector3D direction)
1146    {
1147       Matrix matrix;
1148       Vector3D offset;
1149
1150       matrix.RotationQuaternion(transform.orientation);
1151       offset.MultMatrix(direction, matrix);
1152       transform.position.Add(transform.position, offset);
1153       UpdateTransform();
1154    }
1155
1156    void UpdateTransform(void)
1157    {
1158       SetTransformDirty();
1159       _UpdateTransform();
1160       SetMinMaxRadius(false);
1161    }
1162
1163    void Animate(unsigned int frame)
1164    {
1165       if(this && startFrame != endFrame)
1166       {
1167          while(frame < startFrame) frame += (endFrame - startFrame + 1);
1168          while(frame > endFrame)   frame -= (endFrame - startFrame + 1);
1169
1170          this.frame = frame;
1171          _Animate(frame);
1172          _UpdateTransform();
1173          SetMinMaxRadius(false);
1174       }
1175    }
1176
1177    void DoubleSided(bool flag)
1178    {
1179       if(this)
1180       {
1181          Object child;
1182          mesh.DoubleSided(flag);
1183          for(child = children.first; child; child = child.next)
1184             child.DoubleSided(flag);
1185       }
1186    }
1187
1188    bool IntersectsGroundPolygon(int count, Pointf * pointfs)
1189    {
1190       bool result = false;
1191
1192       Pointf * p1;
1193       Pointf * p2;
1194       double minX = wmin.x, maxX = wmax.x;
1195       double minY = wmin.z, maxY = wmax.z;
1196       double delta = (maxX - minX)/2;
1197       double x = (maxX + minX)/2, y = (maxY + minY)/2;
1198       int c;
1199       for(c = 0; c<count; c++)
1200       {
1201          double d;
1202          p1 = &pointfs[c];
1203          p2 = &pointfs[(c == count-1) ? 0 : (c+1)];
1204
1205          if( (p1->x < minX) &&  (p2->x < minX) )
1206          {
1207             if((p1->y <= y) && (p2->y >  y) )
1208                result ^= true;
1209             else if( (p1->y >  y) && (p2->y <= y) )
1210                result ^= true;
1211          }
1212          else if(!((p1->x > maxX && p2->x > maxX) || (p1->y < minY && p2->y < minY) || (p1->y > maxY && p2->y > maxY)))
1213          {
1214             if(p1->y == p2->y)
1215             {
1216                d = y - p1->y;
1217                if (d < 0) d = -d;
1218                if (d < delta) return true;
1219             }
1220             else if(p1->x == p2->x)
1221             {
1222                d = x - p1->x;
1223                if(d < 0) d = -d;
1224                if(d < delta) return true;
1225                else if(p1->x > x) ;
1226                else if( (p1->y <= y) && (p2->y >  y) )
1227                   result ^= true;
1228                else if( (p1->y >  y) && (p2->y <= y) )
1229                   result ^= true;
1230             }
1231             else
1232             {
1233                float a, b, dy, dx;
1234
1235                a = p2->y - p1->y;
1236                b = p1->x - p2->x;
1237                dy =  a;
1238                dx = -b;
1239                d = a * x + b * y + (p2->x * p1->y) - (p2->y * p1->x);
1240                if (a < 0) a = -a;
1241                if (b < 0) b = -b;
1242                if (d < 0) d = -d;
1243
1244                if(d < a * delta)
1245                   return true;
1246                else if (d < b * delta)
1247                   return true;
1248                else if( ( (p1->y <= y) && (p2->y >  y) ) || ( (p1->y >  y) && (p2->y <= y) ) )
1249                {
1250                   double xdy;
1251
1252                   xdy = (dx * (y - p1->y)) + (dy * p1->x);
1253                   if(dy < 0)
1254                   {
1255                      if(xdy > x * dy)
1256                         result ^= true;
1257                   }
1258                   else if(xdy < x * dy)
1259                      result ^= true;
1260                }
1261             }
1262          }
1263       }
1264       return result;
1265    }
1266
1267    property Transform transform { set { transform = value; eulerOrientation = transform.orientation; } get { value = transform; } };
1268    property Material material { set { material = value; } get { return material; } };
1269    property Vector3Df max { get { value = max; } };
1270    property Vector3Df min { get { value = min; } };
1271    property Vector3Df center { get { value = center; } };
1272    property float radius { get { return radius; } };
1273
1274    property Vector3D wmax { get { value = wmax; } };
1275    property Vector3D wmin { get { value = wmin; } };
1276    property Vector3D wcenter { get { value = wcenter; } };
1277    property double wradius { get { return wradius; } };
1278
1279    property void * tag { set { tag = value; } get { return tag; } };
1280    property int frame { set { Animate(value); } get { return frame; } };
1281    property int startFrame { set { startFrame = value; } get { return startFrame; } };
1282    property int endFrame { set { endFrame = value; } get { return endFrame; } };
1283
1284    property Mesh mesh { set { mesh = value; } get { return mesh; } };
1285    property Camera camera { get { return camera; } }; // Fix this with inheritance? camera inherit from Object?
1286    property Object firstChild { get { return children.first; } };
1287    property Object next { get { return next; } };
1288    property const char * name { get { return name; } };
1289    property Matrix matrix { get { value = matrix; } };
1290    property Object cameraTarget { set { cameraTarget = value; } get { return cameraTarget; } };
1291    property OldList * tracks { /* set { tracks = value; } */ get { return &tracks; } };
1292    property ObjectFlags flags { set { flags = value; } get { return flags; } };
1293
1294 private:
1295    Object()
1296    {
1297       children.offset = (uint)(uintptr)&((Object)0).prev;
1298       transform.scaling = { 1, 1, 1 };
1299       transform.orientation = { 1,0,0,0 };
1300       flags.transform = true;
1301       localMatrix.Identity();
1302    }
1303
1304    ~Object()
1305    {
1306       Free(null);
1307    }
1308
1309    void SetTransformDirty()
1310    {
1311       Object child;
1312       flags.transform = true;
1313       for(child = children.first; child; child = child.next)
1314          child.SetTransformDirty();
1315    }
1316
1317    void _UpdateTransform()
1318    {
1319       if(flags.transform)
1320       {
1321          Object child;
1322
1323          // Cameras / Spot Lights must update their target first
1324          if(flags.camera && cameraTarget && cameraTarget.flags.transform)
1325             cameraTarget.UpdateTransform();
1326          else if(flags.light && light.flags.spot && light.target && light.target.flags.transform)
1327             light.target._UpdateTransform();
1328
1329          if(flags.camera && cameraTarget)
1330          {
1331             // Determine angle to look at target
1332             Vector3D position, direction;
1333             if(flags.root || !parent)
1334                position = transform.position;
1335             else
1336                position.MultMatrix(transform.position, parent.matrix);
1337
1338             direction.Subtract((Vector3D *)cameraTarget.matrix.m[3], position);
1339             transform.orientation.RotationDirection(direction);
1340
1341             // Add the roll
1342             transform.orientation.RotateRoll(roll);
1343          }
1344
1345          if(flags.light && light.flags.spot)
1346          {
1347             // Determine angle to look at target
1348             Vector3D position;
1349             if(flags.root || !parent)
1350                position = transform.position;
1351             else
1352                position.MultMatrix(transform.position, parent.matrix);
1353
1354             if(light.target)
1355                light.direction.Subtract((Vector3D *) light.target.matrix.m[3], position);
1356             else
1357                light.direction = position; // TOCHECK: Why does this happen?
1358
1359             light.direction.Normalize(light.direction);
1360             transform.orientation.RotationDirection(light.direction);
1361          }
1362
1363          if(!flags.localMatrixSet)
1364          {
1365             localMatrix.Identity();
1366             localMatrix.Scale(transform.scaling.x, transform.scaling.y, transform.scaling.z);
1367             localMatrix.Rotate(transform.orientation);
1368             localMatrix.Translate(transform.position.x, transform.position.y, transform.position.z);
1369          }
1370
1371          // Compute transform (with ancestors)
1372          if(flags.root || !parent)
1373             matrix = localMatrix;
1374          else
1375             matrix.Multiply(localMatrix, parent.matrix);
1376
1377          flags.transform = false;
1378
1379          for(child = children.first; child; child = child.next)
1380          {
1381             if(child.flags.transform)
1382                child._UpdateTransform();
1383          }
1384       }
1385    }
1386
1387    void _Animate(unsigned int frame)
1388    {
1389       Object child;
1390       FrameTrack track;
1391
1392       for(track = tracks.first; track; track = track.next)
1393       {
1394          unsigned int c;
1395
1396          if(track.numKeys)
1397          {
1398             unsigned int prev = 0, next = track.numKeys - 1;
1399             FrameKey * prevKey = &track.keys[prev], * nextKey = &track.keys[next];
1400             float t = 0;
1401
1402             for(c = 0; c<track.numKeys; c++)
1403             {
1404                FrameKey * key = track.keys + c;
1405                if(key->frame <= frame) { prevKey = key; prev = c; }
1406                if(key->frame >= frame) { nextKey = key; next = c; break; }
1407             }
1408
1409             if(nextKey->frame != prevKey->frame)
1410                t = ease((float) (frame - prevKey->frame) / (nextKey->frame - prevKey->frame), prevKey->easeFrom, nextKey->easeTo);
1411
1412             switch(track.type.type)
1413             {
1414                case position:
1415                {
1416                   Vector3Df position;
1417                   track.Interpolate(position, prevKey->position, nextKey->position, prev, next, t);
1418                   transform.position = { (double)position.x, (double)position.y, (double)position.z };
1419                   break;
1420                }
1421                case scaling:
1422                   track.Interpolate(transform.scaling, prevKey->scaling, &nextKey->scaling, prev, next, t);
1423                   break;
1424                case rotation:
1425                   track.InterpolateQuat(transform.orientation, prevKey->orientation, nextKey->orientation, prev, next, t);
1426                   break;
1427                // Cameras
1428                case roll:
1429                   roll = track.InterpolateFloat(prevKey->roll, nextKey->roll, prev, next, t);
1430                   break;
1431                case fov:
1432                {
1433                   camera.fov = track.InterpolateFloat(prevKey->fov, nextKey->fov, prev, next, t);
1434                   /*
1435                   double mm = (camera.fov - 5.05659508373109) / 1.13613250717301;
1436                   camera.fov = 1248.58921609766 * pow(mm, -0.895625414990581);
1437                   */
1438                   //camera.Setup(camera.width, camera.height, camera.origin);
1439                   break;
1440                }
1441                // Lights
1442                case colorChange:
1443                {
1444                   track.Interpolate((Vector3Df *)&light.diffuse,
1445                      (Vector3Df *)&prevKey->color, (Vector3Df *)&nextKey->color, prev, next, t);
1446                   light.specular = light.diffuse;
1447                   break;
1448                }
1449                case fallOff:
1450                {
1451                   light.fallOff = track.InterpolateFloat(prevKey->fallOff, nextKey->fallOff, prev, next, t);
1452                   break;
1453                }
1454                case hotSpot:
1455                {
1456                   light.hotSpot = track.InterpolateFloat(prevKey->hotSpot, nextKey->hotSpot, prev, next, t);
1457                   break;
1458                }
1459             }
1460          }
1461       }
1462
1463       for(child = children.first; child; child = child.next)
1464          child._Animate(frame);
1465
1466       flags.transform = true;
1467    }
1468
1469    // Private for now
1470    FrustumPlacement InsideFrustum(Plane * planes)
1471    {
1472       FrustumPlacement result = inside;
1473
1474       int p;
1475       // First test: Sphere
1476       for(p = 0; p<6; p++)
1477       {
1478          Plane * plane = &planes[p];
1479          double dot = plane->normal.DotProduct(wcenter);
1480          double distance = dot + plane->d;
1481          if(distance < -wradius)
1482          {
1483             result = outside;
1484             break;
1485          }
1486          if(Abs(distance) < wradius)
1487             result = intersecting;
1488       }
1489
1490       if(result == intersecting)
1491       {
1492          // Second test: Bounding Box
1493          Vector3D box[8] =
1494          {
1495             { wmin.x, wmin.y, wmin.z },
1496             { wmin.x, wmin.y, wmax.z },
1497             { wmin.x, wmax.y, wmin.z },
1498             { wmin.x, wmax.y, wmax.z },
1499             { wmax.x, wmin.y, wmin.z },
1500             { wmax.x, wmin.y, wmax.z },
1501             { wmax.x, wmax.y, wmin.z },
1502             { wmax.x, wmax.y, wmax.z }
1503          };
1504            int numPlanesAllIn = 0;
1505          for(p = 0; p < 6; p++)
1506          {
1507             Plane * plane = &planes[p];
1508             int i;
1509             int numGoodPoints = 0;
1510             for(i = 0; i < 8; ++i)
1511             {
1512                double dot = plane->normal.DotProduct(box[i]);
1513                double distance = dot + plane->d;
1514                            if(distance > -1)
1515                   numGoodPoints++;
1516                    }
1517                    if(!numGoodPoints)
1518             {
1519                result = outside;
1520                break;
1521             }
1522             if(numGoodPoints == 8)
1523                numPlanesAllIn++;
1524            }
1525            if(numPlanesAllIn == 6)
1526                    result = inside;
1527       }
1528       return result;
1529    }
1530
1531    Object prev, next;
1532    char * name;
1533    public Object parent;
1534    public OldList children;
1535
1536    ObjectFlags flags;
1537
1538    OldList tracks;
1539    unsigned startFrame, endFrame;
1540    int frame;
1541    Vector3Df pivot;
1542
1543    public Transform transform;
1544    public Matrix matrix;
1545    public Matrix localMatrix;
1546
1547    void * tag;
1548    Vector3Df min, max, center;
1549    Vector3D wmin, wmax, wcenter;
1550
1551    bool volume;
1552    float radius;
1553    double wradius;
1554    ColorRGB ambient;
1555
1556    /*public */union
1557    {
1558       // Mesh
1559       struct
1560       {
1561          Mesh mesh;
1562          Material material;
1563       };
1564
1565       // Light
1566       Light light;
1567
1568       // Camera
1569       struct
1570       {
1571          Camera camera;
1572          Object cameraTarget;
1573          double roll;
1574       };
1575    };
1576
1577    public property Light light
1578    {
1579       set
1580       {
1581          light = value;
1582       }
1583       get
1584       {
1585          value = light;
1586       }
1587    }
1588
1589    Euler eulerOrientation;
1590 };