summaryrefslogtreecommitdiff
path: root/Runtime/Graphics/Transform.cpp
blob: eaa9bdb4ae830a8a76ad62248303f99da15fa6f1 (plain)
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
#include "UnityPrefix.h"
#include "Transform.h"
#include "Runtime/Serialize/TransferFunctions/SerializeTransfer.h"
#include "Runtime/BaseClasses/SupportedMessageOptimization.h"
#include "Runtime/Serialize/SerializationMetaFlags.h"
#include "Runtime/Utilities/Word.h"
#include "Runtime/BaseClasses/IsPlaying.h"
#include "Runtime/Utilities/RecursionLimit.h"
#include "Runtime/Utilities/Prefetch.h"
#include "Runtime/Utilities/ValidateArgs.h"
#include "Runtime/Misc/BuildSettings.h"

#if UNITY_EDITOR
#include "Editor/Src/SceneInspector.h"
static Transform::HierarchyChangedCallback* gHierarchyChangedCallback = NULL;
static Transform::HierarchyChangedCallbackSetParent* gHierarchyChangedSetParentCallback = NULL;
#endif

static Transform* FindActiveTransformWithPathImpl (const char* path, GameObject& go, bool needsToBeRoot);

// parentTransform * (translation * rotation * scale)

#if DEBUGMODE
#define ASSERT_ROTATION if (!CompareApproximately (SqrMagnitude (m_LocalRotation), 1.0F)) { AssertStringObject(Format("transform.rotation of '%s' is no longer valid, due to a bad input value. Input rotation is %f, %f, %f, %f.", GetName(), q.x, q.y, q.z, q.w), this); }
#else
#define ASSERT_ROTATION
#endif

#pragma message ("Move this away")
inline float InverseSafe (float f)
{
	if (Abs (f) > Vector3f::epsilon)
		return 1.0F / f;
	else
		return 0.0F;
		
}

inline Vector3f InverseSafe (const Vector3f& v)
{
	return Vector3f (InverseSafe (v.x), InverseSafe (v.y), InverseSafe (v.z));
}

static float MakeNiceAbs(float f)
{
	union
	{
		float f;
		UInt32 n;
	} u;
	u.f = f;

	int exponent = ((u.n & 0x7F800000) >> 23) - 127;

	if(exponent >= 24)
		return f;
	
	if(exponent <= -24)
		return 0;

	UInt32 v = (UInt32)f;
	float fraction = f - v;
                   
	if(fraction < 0.00001f)
		return v;

	if(fraction > 0.99999f)
		return v + 1;

	return f;
}

static float MakeNice(float f)
{
	if(f >= 0)
		return MakeNiceAbs(f);
	else
		return -MakeNiceAbs(-f);
}

Vector3f MakeNice(const Vector3f& v)
{
	return Vector3f(MakeNice(v[0]), MakeNice(v[1]), MakeNice(v[2]));
}




Transform::Transform (MemLabelId label, ObjectCreationMode mode)
:	Super(label, mode)
//,   m_Children (Transform::TransformComList::allocator_type(*baseAllocator))
#if UNITY_EDITOR
,	m_VisibleRootValid(false)
#endif
,	m_CachedTransformType(kNoScaleTransform)
,	m_HasCachedTransformMatrix(false)
,	m_HasChanged(false)
{
	m_InternalTransformType = kNoScaleTransform;
	m_SupportsTransformChanged = 0;

#if UNITY_EDITOR
	// Create hint that will make euler angles at editor time match those in play mode
	// 
	m_LocalEulerAnglesHint.x = 179.999f;
	m_LocalEulerAnglesHint.y = 179.999f;
	m_LocalEulerAnglesHint.z = 179.999f;
	#endif
}

void Transform::Reset ()
{
	Super::Reset ();
	m_LocalRotation = Quaternionf::identity ();
	
	m_LocalPosition = Vector3f::zero;
	m_LocalScale = Vector3f::one;
	
#if UNITY_EDITOR
	m_LocalEulerAnglesHint.x = 0;
	m_LocalEulerAnglesHint.y = 0;
	m_LocalEulerAnglesHint.z = 0;
#endif
	
	RecalculateTransformType ();
	
	
	m_HasCachedTransformMatrix = false;
	m_HasChanged = true;

	if (GetGameObjectPtr())
		SendTransformChanged (kPositionChanged | kRotationChanged | kScaleChanged | kParentingChanged);

#if ENABLE_EDITOR_HIERARCHY_ORDERING
	m_Order = 0;
#endif
}

Transform::~Transform ()
{
#if UNITY_EDITOR
	if (m_VisibleRootValid)
		GetSceneTracker().GetVisibleRootTransforms().erase(m_VisibleRootIterator);
#endif
}

Transform::iterator Transform::Find( const Transform* child )
{
	iterator it, itEnd = end();
	for( it = begin(); it != itEnd; ++it )
	{
		if( *it == child )
			return it;
	}
	return itEnd;
}

void Transform::RemoveFromParent ()
{
//	Assert(!IsPersistent());
	
	// If it has an father, remove this from fathers children
	Transform* father = GetParent ();
	if (father != NULL)
	{
//		Assert(!father->IsPersistent());
		
		TransformComList& children = father->m_Children;
		// Fastpath try back of children array
		if (!children.empty() != 0 && &*children.back() == this)
		{
			children.pop_back();
		}
		// Find this in fathers children list
		else
		{
			iterator i = father->Find(this);
			if (i != children.end ())
				children.erase (i);
		}
		
		father->SetDirty ();
	}
}

void Transform::ClearChildrenParentPointer ()
{
	for (int i=0;i<m_Children.size();i++)
	{
		Transform* cur = m_Children[i];
		
		AssertIf(cur == NULL || cur->GetParent() != this);
		if (cur && cur->GetParent() == this)
			cur->m_Father = NULL;
	}
}

void Transform::ClearChild (Transform* child)
{
	iterator found = Find(child);
	if (found != m_Children.end())
		m_Children.erase(found);
}

Matrix3x3f Transform::GetWorldScale () const
{
	Matrix3x3f invRotation;
	QuaternionToMatrix (Inverse (GetRotation ()), invRotation);
	Matrix3x3f scaleAndRotation = GetWorldRotationAndScale ();
	return invRotation * scaleAndRotation;
}

Vector3f Transform::GetWorldScaleLossy () const
{
	Matrix3x3f rot = GetWorldScale ();
	return Vector3f (rot.Get (0, 0), rot.Get (1, 1), rot.Get (2, 2));
}


Matrix3x3f Transform::GetWorldRotationAndScale () const
{
	Matrix3x3f scale;
	scale.SetScale (m_LocalScale);

	Matrix3x3f rotation;
	QuaternionToMatrix (m_LocalRotation, rotation);
	
	Transform* parent = GetParent ();
	if (parent)
	{
		///@TODO optimize: Special case multiplication
		Matrix3x3f parentTransform = parent->GetWorldRotationAndScale ();
		return parentTransform * rotation * scale;
	}
	else
	{
		return rotation * scale;
	}
}

bool Transform::SetParent (Transform* newFather, SetParentOption options)
{
	if (GetGameObject().IsDestroying() || (newFather && newFather->GetGameObject().IsDestroying()))
		return false;

	if (IS_CONTENT_NEWER_OR_SAME (kUnityVersion4_0_a1))
	{
		if ( (GetParent () && GetParent ()->GetGameObject().IsActivating()) || (newFather && newFather->GetGameObject().IsActivating()))
		{
			ErrorStringObject ("Cannot change GameObject hierarchy while activating or deactivating the parent.", this);
			return false;
		}
	}
	
	// Make sure that the new father is not a child of this transform.
	Transform* cur;
	for (cur=newFather;cur != NULL;cur = cur->m_Father)
	{
		if (this == cur)
			return false;
	}
	
	if ((options & kAllowParentingFromPrefab) ==  0)
	{
		if (IsPrefabParent() || (newFather && newFather->IsPrefabParent()))
		{
			ErrorString("Setting the parent of a transform which resides in a prefab is disabled to prevent data corruption.");
			return false;
		}	
	}

//	if (IsPersistent() || (newFather && newFather->IsPersistent()))
//	{
//		ErrorString("Setting the parent of a transform on an asset is not allowed!");
//		return false;
//	}	

	// Save the old position in worldspace
	Vector3f worldPosition = GetPosition ();
	Quaternionf worldRotation = GetRotation ();
	Matrix3x3f worldScale = GetWorldRotationAndScale ();

	// If it already has an father, remove this from fathers children
	Transform* father = GetParent ();
	if (father != NULL)
	{
		// Find this in fathers children list
		iterator i = father->Find( this );
		AssertIf (i == father->end ());
		father->m_Children.erase (i);
		father->SetDirty ();
	}
	
	#if UNITY_EDITOR
	if (newFather)
	{
		///@TODO: This can use binary search because we should be able to assume that the children array is already sorted
		iterator i = newFather->begin();
		iterator end = newFather->end();
		
		for (;i!=end;i++)
		{
		#if ENABLE_EDITOR_HIERARCHY_ORDERING
			if (CompareDepths(this, (*i)))
		#else
			if (SemiNumericCompare(GetName(), (**i).GetName()) < 0)
		#endif
			{
				newFather->m_Children.insert (i, this);
				break;
			}
		}
		if (i == end)
			newFather->m_Children.push_back (this);
		
		newFather->SetDirty ();
	}
	#else
	if (newFather)
	{
		newFather->m_Children.push_back (this);
		newFather->SetDirty ();
	}
	#endif
	
	m_Father = newFather;

	if (!(options & kDisableTransformMessage))
	{
		if (options & kWorldPositionStays)
		{
			// Restore old position so they stay at the same position in worldspace
			SetRotationSafe (worldRotation);
			SetPosition (worldPosition);
			SetWorldRotationAndScale ( worldScale );
			SendTransformChanged (kParentingChanged);
		}
		else
			SendTransformChanged (kPositionChanged | kRotationChanged | kScaleChanged | kParentingChanged);
	}
		
	#if UNITY_EDITOR
	if (gHierarchyChangedSetParentCallback)
		gHierarchyChangedSetParentCallback (this, father, newFather);
	#endif
	SetDirty ();
	SetCacheDirty();

	return true;
}


#if UNITY_EDITOR

#if ENABLE_EDITOR_HIERARCHY_ORDERING
bool Transform::CompareVisibleRoots::operator() (const VisibleRootKey& lhs, const VisibleRootKey& rhs) const
{
	bool orderCompare = lhs.first != rhs.first;
	if (orderCompare)
		return lhs.first < rhs.first;
	else
	{
		VisibleRootSecondaryKey lhsSecondaryKey = lhs.second;
		VisibleRootSecondaryKey rhsSecondaryKey = rhs.second;
		int compare = SemiNumericCompare(lhsSecondaryKey.first, rhsSecondaryKey.first);
		if (compare != 0)
			return compare < 0;
		return lhsSecondaryKey.second < rhsSecondaryKey.second;
	}
}
#else
bool Transform::CompareVisibleRoots::operator() (const VisibleRootKey& lhs, const VisibleRootKey& rhs) const
{
	int compare = SemiNumericCompare(lhs.first, rhs.first);
	if (compare != 0)
		return compare < 0;
	return lhs.second < rhs.second;
}
#endif

// Cannot be called Repeat as there is already another function with that name (which does currently not work for negative numbers)
inline float RepeatWorking (float t, float length)
{
	return (t - (floor (t / length) * length));
}

void Transform::SyncLocalEulerAnglesHint ()
{
	if (IsWorldPlaying())
		return;
	
	Vector3f newEuler = QuaternionToEuler(m_LocalRotation) * Rad2Deg(1);
	
	newEuler.x = RepeatWorking(newEuler.x - m_LocalEulerAnglesHint.x + 180.0F, 360.0F) + m_LocalEulerAnglesHint.x - 180.0F;
	newEuler.y = RepeatWorking(newEuler.y - m_LocalEulerAnglesHint.y + 180.0F, 360.0F) + m_LocalEulerAnglesHint.y - 180.0F;
	newEuler.z = RepeatWorking(newEuler.z - m_LocalEulerAnglesHint.z + 180.0F, 360.0F) + m_LocalEulerAnglesHint.z - 180.0F;
	
	m_LocalEulerAnglesHint = MakeNice(newEuler);
}
#endif

void Transform::SetLocalEulerAngles (const Vector3f& eulerAngles)
{
	ABORT_INVALID_VECTOR3 (eulerAngles, localEulerAngles, transform)
	
	SetLocalRotationSafe (EulerToQuaternion (eulerAngles * Deg2Rad (1)));
	
	#if UNITY_EDITOR
	if (!IsWorldPlaying())
	{
		m_LocalEulerAnglesHint = MakeNice(eulerAngles);
	}
	#endif
}

Vector3f Transform::GetLocalEulerAngles ()
{
	#if UNITY_EDITOR
	if (!IsWorldPlaying())
	{
		if ( !CompareApproximately (EulerToQuaternion (m_LocalEulerAnglesHint * Deg2Rad(1)), m_LocalRotation) )
			SyncLocalEulerAnglesHint ();
		
		return m_LocalEulerAnglesHint;
	}
	else
	{
		Quaternionf rotation = NormalizeSafe (m_LocalRotation);
		return QuaternionToEuler (rotation) * Rad2Deg (1);
	}
	#else
	Quaternionf rotation = NormalizeSafe (m_LocalRotation);
	return QuaternionToEuler (rotation) * Rad2Deg (1);
	#endif
}


void Transform::SetLocalPosition (const Vector3f& inTranslation)
{
	ABORT_INVALID_VECTOR3 (inTranslation, localPosition, transform);
	m_LocalPosition = inTranslation;
	SetDirty ();
	SendTransformChanged (kPositionChanged);
}

void Transform::SetLocalRotation (const Quaternionf& q)
{
	ABORT_INVALID_QUATERNION (q, localRotation, transform);
	m_LocalRotation = q;

#if UNITY_EDITOR
	SyncLocalEulerAnglesHint ();
#endif
	ASSERT_ROTATION

	SetDirty ();
	SendTransformChanged (kRotationChanged);
}

void Transform::SetLocalRotationSafe (const Quaternionf& q)
{
	SetLocalRotation (NormalizeSafe(q));
}

void Transform::SetRotation (const Quaternionf& q)
{
	Transform* father = GetParent ();
	if (father != NULL)
		SetLocalRotation (Inverse (father->GetRotation ()) * q);
	else
		SetLocalRotation (q);
}

void Transform::SetRotationSafe(const Quaternionf& q) 
{
	ABORT_INVALID_QUATERNION (q, rotation, transform);
	Transform* father = GetParent ();
	if (father != NULL)
		SetLocalRotation (NormalizeSafe (Inverse (father->GetRotation ()) * q));
	else
		SetLocalRotation (NormalizeSafe (q));
}

void Transform::SetPosition (const Vector3f& p)
{
	ABORT_INVALID_VECTOR3 (p, position, transform);

	Vector3f newPosition = p;
	Transform* father = GetParent ();
	if (father != NULL)
		newPosition = father->InverseTransformPoint (newPosition);
		
	SetLocalPosition (newPosition);
}

void Transform::SetPositionWithLocalOffset (const Vector3f& p, const Vector3f& localOffset)
{
	ABORT_INVALID_VECTOR3 (p, positionWithLocalOffset, transform);
	ABORT_INVALID_VECTOR3 (localOffset, positionWithLocalOffset, transform);
	Vector3f newPosition = p - TransformPoint (localOffset) + GetPosition ();
	SetPosition (newPosition);
}	

Vector3f Transform::TransformPointWithLocalOffset (const Vector3f& p, const Vector3f& localOffset) const
{
	return p - TransformPoint (localOffset) + GetPosition ();
}

void Transform::SetWorldRotationAndScale (const Matrix3x3f& scale)
{
	m_LocalScale = Vector3f::one;

	Matrix3x3f inverseRS = GetWorldRotationAndScale ();
	inverseRS.Invert ();
	
	inverseRS = inverseRS * scale;
	
	m_LocalScale.x = inverseRS.Get (0, 0);
	m_LocalScale.y = inverseRS.Get (1, 1);
	m_LocalScale.z = inverseRS.Get (2, 2);

	RecalculateTransformType ();
	SetDirty ();
	SendTransformChanged (kScaleChanged | kRotationChanged | kPositionChanged);
}

void Transform::SetLocalScale (const Vector3f& scale)
{
	ABORT_INVALID_VECTOR3 (scale, localScale, transform);
	m_LocalScale = scale;
	RecalculateTransformType ();
	SetDirty ();
	SendTransformChanged (kScaleChanged | kRotationChanged | kPositionChanged);
}

template<bool Safe, bool Notify>
void Transform::SetPositionAndRotationInternal ( const Vector3f& p, const Quaternionf& q )
{
	ABORT_INVALID_VECTOR3 (p, position, transform);
	ABORT_INVALID_QUATERNION (q, rotation, transform);
	Transform* father = GetParent ();
	if (father != NULL)
	{
		m_LocalPosition = father->InverseTransformPoint (p);
		if ( Safe )
			m_LocalRotation = NormalizeSafe (Inverse (father->GetRotation ()) * q);
		else 
			m_LocalRotation = Inverse (father->GetRotation ()) * q;
	}
	else
	{
		m_LocalPosition = p;
		if ( Safe )
			m_LocalRotation = NormalizeSafe (q);
		else
			m_LocalRotation = q;
	}
#if UNITY_EDITOR
	SyncLocalEulerAnglesHint ();
#endif
	
	ASSERT_ROTATION
	if ( Notify )
	{
		SetDirty ();
		SendTransformChanged ( kPositionChanged | kRotationChanged );
	}
}

void Transform::SetPositionAndRotationWithoutNotification (const Vector3f& p, const Quaternionf& q)
{
	SetPositionAndRotationInternal<false, false>( p, q );
}

void Transform::SetPositionAndRotationSafeWithoutNotification (const Vector3f& p, const Quaternionf& q)
{
	SetPositionAndRotationInternal<true, false>( p, q );
}

void Transform::SetPositionAndRotation (const Vector3f& p, const Quaternionf& q)
{
	SetPositionAndRotationInternal<false, true>( p, q );
}

void Transform::SetPositionAndRotationSafe (const Vector3f& p, const Quaternionf& q)
{
	SetPositionAndRotationInternal<true, true>( p, q );
}

void Transform::SetPositionWithoutNotification (const Vector3f& p)
{
	ABORT_INVALID_VECTOR3 (p, position, transform);
	Transform* father = GetParent ();
	if (father != NULL)
		m_LocalPosition = father->InverseTransformPoint (p);
	else
		m_LocalPosition = p;
}

void Transform::SetRotationWithoutNotification (const Quaternionf& q)
{
	Transform* father = GetParent ();
	if (father != NULL)
		m_LocalRotation = Inverse (father->GetRotation ()) * q;
	else
		m_LocalRotation = q;
}

void Transform::SetLocalPositionAndRotation (const Vector3f& p, const Quaternionf& q)
{
	ABORT_INVALID_VECTOR3 (p, localPosition, transform);
	ABORT_INVALID_QUATERNION (q, localRotation, transform);
	m_LocalPosition = p;
	m_LocalRotation = q;
	
	#if UNITY_EDITOR
	SyncLocalEulerAnglesHint ();
	#endif
	
	ASSERT_ROTATION

	SetDirty ();
	SendTransformChanged (kPositionChanged | kRotationChanged);
}
#if UNITY_EDITOR
void Transform::RegisterHierarchyChangedCallback (HierarchyChangedCallback* callback)
{
	gHierarchyChangedCallback = callback;
}

void Transform::RegisterHierarchyChangedSetParentCallback (HierarchyChangedCallbackSetParent* callback)
{
	gHierarchyChangedSetParentCallback = callback;
}
#endif

UInt32 Transform::CalculateSupportedMessages ()
{
	if (GetGameObject().WillHandleMessage(kTransformChanged))
		return kSupportsTransformChanged;
	else
		return 0;
}

void Transform::MakeEditorValuesLookNice()
{
	m_LocalScale = MakeNice(m_LocalScale);
	m_LocalPosition = MakeNice(m_LocalPosition);
}

void Transform::SupportedMessagesDidChange (int mask)
{
	Super::SupportedMessagesDidChange(mask);
	m_SupportsTransformChanged = mask & kSupportsTransformChanged;
}

void Transform::SendTransformChanged (int changeMask)
{
	bool parentingChanged = changeMask & kParentingChanged;

	// Fastpath if we don't support any TransformChanged callbacks on this game object
	if (!m_SupportsTransformChanged && !parentingChanged)
	{
		m_HasCachedTransformMatrix = false;
		m_HasChanged = true;

		TransformComList::iterator i;
		TransformComList::iterator end = m_Children.end ();
		for (i = m_Children.begin ();i != end;i++)
		{
			Transform* child = *i;
			child->SendTransformChanged (changeMask | kPositionChanged);
		}
		
		return;
	}
	
	m_HasCachedTransformMatrix = false;
	m_HasChanged = true;

	// NOTE: SetCacheDirty() doesn't need to be called here since SendTransformChanged traverses the transform hierarchy anyway

	GameObject& go = GetGameObject ();
	if (m_SupportsTransformChanged)
	{
		MessageData data;
		data.SetData (changeMask, ClassID (int));
		go.SendMessageAny (kTransformChanged, data);
	}
	
	if (parentingChanged)
		go.TransformParentHasChanged ();
	
	TransformComList::iterator i;
	TransformComList::iterator end = m_Children.end ();
	for (i = m_Children.begin ();i != end;i++)
	{
		Transform* child = *i;
		child->SendTransformChanged (changeMask | kPositionChanged);
	}
}

void Transform::SetCacheDirty()
{
	m_HasCachedTransformMatrix = false;
	m_HasChanged = true;
	
	TransformComList::iterator end = m_Children.end ();
	for (TransformComList::iterator i = m_Children.begin (); i != end; ++i)
		(*i)->SetCacheDirty();
}

void Transform::BroadcastMessageAny(const MessageIdentifier& messageID, MessageData& data)
{
	GameObject* go = GetGameObjectPtr ();
	if (go)
		go->SendMessageAny (messageID, data);
	
	TransformComList::iterator i;
	for (i = m_Children.begin ();i != m_Children.end ();i++)
		(**i).BroadcastMessageAny (messageID, data);
}

void Transform::RotateAroundLocal (const Vector3f& localAxis, float rad)
{
	AssertIf (!CompareApproximately (Magnitude (localAxis), 1.0F));

	Quaternionf q = AxisAngleToQuaternion (localAxis, rad);
	m_LocalRotation = Normalize (q * m_LocalRotation);
	#if UNITY_EDITOR
	SyncLocalEulerAnglesHint ();
	#endif
	
	SetDirty ();
	SendTransformChanged (kRotationChanged);
}

void Transform::RotateAroundLocalSafe (const Vector3f& localAxis, float rad)
{
	if (SqrMagnitude (localAxis) > Vector3f::epsilon)
		RotateAroundLocal (Normalize (localAxis), rad);
}

void Transform::RotateAround (const Vector3f& worldAxis, float rad)
{
	AssertIf (!CompareApproximately (Magnitude (worldAxis), 1.0F));

	Vector3f localAxis = InverseTransformDirection(worldAxis);

	Quaternionf q = AxisAngleToQuaternion (localAxis, rad);
	m_LocalRotation = Normalize (m_LocalRotation * q);
	#if UNITY_EDITOR
	SyncLocalEulerAnglesHint ();
	#endif
	
	SetDirty ();
	SendTransformChanged (kRotationChanged);
}

void Transform::RotateAroundSafe (const Vector3f& worldAxis, float rad)
{
	Vector3f localAxis = InverseTransformDirection(worldAxis);
	if (SqrMagnitude (localAxis) > Vector3f::epsilon)
	{
		localAxis = Normalize (localAxis);
		Quaternionf q = AxisAngleToQuaternion (localAxis, rad);
		m_LocalRotation = Normalize (m_LocalRotation * q);
		#if UNITY_EDITOR
		SyncLocalEulerAnglesHint ();
		#endif
	
		SetDirty ();
		SendTransformChanged (kRotationChanged);
	}	
}

Vector3f Transform::GetPosition () const
{
	Vector3f worldPos = m_LocalPosition;
	Transform* cur = GetParent ();
	while (cur)
	{
		worldPos.Scale (cur->m_LocalScale);
		worldPos = RotateVectorByQuat (cur->m_LocalRotation, worldPos);
		worldPos += cur->m_LocalPosition;
		
		cur = cur->GetParent ();
	}
	
	return worldPos;
}

Quaternionf Transform::GetRotation ()const
{
	Quaternionf worldRot = m_LocalRotation;
	Transform* cur = GetParent ();
	while (cur)
	{
		worldRot = cur->m_LocalRotation * worldRot;
		cur = cur->GetParent ();
	}
	
	return worldRot;
}


void Transform::GetPositionAndRotation (Vector3f& pos, Quaternionf& q) const
{
	Vector3f worldPos = m_LocalPosition;
	Quaternionf worldRot = m_LocalRotation;
	Transform* cur = GetParent ();
	while (cur)
	{
		worldPos.Scale (cur->m_LocalScale);
		worldPos = RotateVectorByQuat (cur->m_LocalRotation, worldPos);
		worldPos += cur->m_LocalPosition;
		
		worldRot = cur->m_LocalRotation * worldRot;
		
		cur = cur->GetParent ();
	}
	
	pos = worldPos;
	q = worldRot;
}

static TransformType DetectActualNegativeScale (int type, const Transform* transform)
{
	type &= ~kOddNegativeScaleTransform;

	// Calculate if we need to flip the back facing when rendering
	// We need to use backface rendering if one or three scale axes are negative (odd count)
	// In this case we enable kOddNegativeScaleTransform flag

	Transform* cur = (Transform *)transform;
	while (cur)
	{
		TransformType parentType = (TransformType)cur->m_InternalTransformType;
		// kOddNegativeScaleTransform is XOR against parent (odd+odd=even, odd+even=odd, even+even=even), other bits are OR
		type = ((type | parentType) & ~kOddNegativeScaleTransform) | ((type ^ parentType) & kOddNegativeScaleTransform);
		cur = cur->GetParent ();
	}

	return (TransformType)type;
}

static TransformType UpdateTransformType (TransformType type, const Transform* transform)
{
	if ((type & kOddNegativeScaleTransform) != 0)
		type = DetectActualNegativeScale (type, transform);

	// kNonUniformScaleTransform 'overwrites' kUniformScaleTransform
	if ((type & kNonUniformScaleTransform) != 0)
		type &= ~kUniformScaleTransform;

	Assert ((type & (kNonUniformScaleTransform|kUniformScaleTransform)) != (kNonUniformScaleTransform|kUniformScaleTransform));
	return type;
}


TransformType Transform::GetPositionAndRotationWithTransformType (Vector3f& worldPos, Quaternionf& worldRot) const
{
	TransformType type = (TransformType)m_InternalTransformType;
	
	worldPos = m_LocalPosition;
	worldRot = m_LocalRotation;
	Transform* cur = GetParent ();
	while (cur)
	{
		TransformType parentType = (TransformType)cur->m_InternalTransformType;
		// kOddNegativeScaleTransform is XOR against parent (odd+odd=even, odd+even=odd, even+even=even), other bits are OR
		type = ((type | parentType) & ~kOddNegativeScaleTransform) | ((type ^ parentType) & kOddNegativeScaleTransform);
		
		worldPos.Scale (cur->m_LocalScale);
		worldPos = RotateVectorByQuat (cur->m_LocalRotation, worldPos);
		worldPos += cur->m_LocalPosition;
		
		worldRot = cur->m_LocalRotation * worldRot;
		
		cur = cur->GetParent ();
	}
	
	// kNonUniformScaleTransform 'overwrites' kUniformScaleTransform
	if ((type & kNonUniformScaleTransform) != 0)
		type &= ~kUniformScaleTransform;
	Assert ((type & (kNonUniformScaleTransform|kUniformScaleTransform)) != (kNonUniformScaleTransform|kUniformScaleTransform));
	
	return type;
}

TransformType Transform::CalculateTransformMatrix (Matrix4x4f& transform) const
{
	//@TODO: Does this give any performance gain??
	Prefetch(m_CachedTransformMatrix.GetPtr());
	if (m_HasCachedTransformMatrix)
	{
		CopyMatrix(m_CachedTransformMatrix.GetPtr(), transform.GetPtr());
		return (TransformType)m_CachedTransformType;
	}

	const Transform* transforms[32];
	int transformCount = 1;
	TransformType type = (TransformType)0;
	Matrix4x4f temp;

	{
		// collect all transform that need CachedTransformMatrix update
		transforms[0] = this;
		Transform* parent = NULL;
		for (parent = GetParent(); parent != NULL && !parent->m_HasCachedTransformMatrix; parent = parent->GetParent())
		{
			transforms[transformCount++] = parent;
			// reached maximum of transforms that we can calculate - fallback to old method
			if (transformCount == 31)
			{
				parent = parent->GetParent();
				if (parent)
				{
					type = parent->CalculateTransformMatrixIterative(temp);
					Assert(parent->m_HasCachedTransformMatrix);
				}
				break;
			}
		}

		// storing parent of last transform (can be null), the transform itself won't be updated
		transforms[transformCount] = parent;
		Assert(transformCount <= 31);
	}		

	// iterate transforms from lowest parent
	for (int i = transformCount - 1; i >= 0; --i)
	{
		const Transform* t = transforms[i];
		const Transform* parent = transforms[i + 1];
		if (parent)
		{
			Assert(parent->m_HasCachedTransformMatrix);
			// Build the local transform into temp
			type |= t->CalculateLocalTransformMatrix(temp);				
			type |= (TransformType)parent->m_CachedTransformType;
			MultiplyMatrices4x4(&parent->m_CachedTransformMatrix, &temp, &t->m_CachedTransformMatrix);
		}
		else
		{
			// Build the local transform into m_CachedTransformMatrix
			type |= t->CalculateLocalTransformMatrix(t->m_CachedTransformMatrix);
		}
		// store cached transform
		t->m_CachedTransformType = UpdateTransformType(type, t);
		t->m_HasCachedTransformMatrix = true;
	}

	Assert(m_HasCachedTransformMatrix);
	CopyMatrix(m_CachedTransformMatrix.GetPtr(), transform.GetPtr());
	return (TransformType)m_CachedTransformType;
}


// This method doesn't cache all transforms - just the last one, but can calculate
// more than 32 transforms. CalculateTransformMatrix caches all results
TransformType Transform::CalculateTransformMatrixIterative (Matrix4x4f& transform) const
{
	if (m_HasCachedTransformMatrix)
	{
		CopyMatrix(m_CachedTransformMatrix.GetPtr(), transform.GetPtr());
		return (TransformType)m_CachedTransformType;
	}

	// Build the local transform
	TransformType type = CalculateLocalTransformMatrix(transform);

	Transform* parent = GetParent ();
	Matrix4x4f temp;
	while (parent != NULL)
	{
		if (parent->m_HasCachedTransformMatrix)
		{
			type |= (TransformType)parent->m_CachedTransformType;
			MultiplyMatrices4x4 (&parent->m_CachedTransformMatrix, &transform, &temp);
			// no need to iterate further - we got world transform
			parent = NULL;
		}
		else
		{
			Matrix4x4f parentTransform;
			type |= parent->CalculateLocalTransformMatrix(parentTransform);
			MultiplyMatrices4x4 (&parentTransform, &transform, &temp);
			parent = parent->GetParent ();
		}
		CopyMatrix (temp.GetPtr(), transform.GetPtr());
	}

	CopyMatrix(transform.GetPtr(), m_CachedTransformMatrix.GetPtr()) ;
	m_CachedTransformType = UpdateTransformType(type, this);
	m_HasCachedTransformMatrix = true;
	return type;
}


TransformType Transform::CalculateLocalTransformMatrix(Matrix4x4f& matrix) const
{
	TransformType type = (TransformType)m_InternalTransformType;
	if (type == kNoScaleTransform)
		matrix.SetTR(m_LocalPosition, m_LocalRotation);
	else
		matrix.SetTRS(m_LocalPosition, m_LocalRotation, m_LocalScale);
	return type;
}


TransformType Transform::CalculateTransformMatrixDisableNonUniformScale (Matrix4x4f& transform, Matrix4x4f& scaleOnly, float& uniformScale) const
{
	// Use CalculateTransformMatrix in order to take advantage of the cached transform.
	// Only non-uniform scaled meshes need to take the slower code path.
/*	TransformType cachedTransformType = CalculateTransformMatrix (transform);
	if (!IsNonUniformScaleTransform(cachedTransformType))
	{
		uniformScale = Magnitude(transform.GetAxisX());
		scaleOnly.SetIdentity();
		return cachedTransformType;
	}
*/

	// Build the local transform!
	TransformType type = (TransformType)m_InternalTransformType;
	uniformScale = m_LocalScale.x;
	if (type == kNoScaleTransform)
		transform.SetTR (m_LocalPosition, m_LocalRotation);
	else
		transform.SetTRS (m_LocalPosition, m_LocalRotation, m_LocalScale);

	// @TBD: cache parent transform and reuse it across CalculateTransformXXX funcs
	Transform* parent = GetParent ();
	Matrix4x4f temp;
	while (parent != NULL)
	{
		Matrix4x4f parentTransform;
		
		TransformType parentType = (TransformType)parent->m_InternalTransformType;
		// kOddNegativeScaleTransform is XOR against parent (odd+odd=even, odd+even=odd, even+even=even), other bits are OR
		type = ((type | parentType) & ~kOddNegativeScaleTransform) | ((type ^ parentType) & kOddNegativeScaleTransform);

		if (parentType == kNoScaleTransform)
			parentTransform.SetTR (parent->m_LocalPosition, parent->m_LocalRotation);
		else
			parentTransform.SetTRS (parent->m_LocalPosition, parent->m_LocalRotation, parent->m_LocalScale);
		uniformScale *= parent->m_LocalScale.x;
		
		MultiplyMatrices4x4 (&parentTransform, &transform, &temp);
		CopyMatrix (temp.GetPtr(), transform.GetPtr());
		parent = parent->GetParent ();
	}
	
	// kNonUniformScaleTransform 'overwrites' kUniformScaleTransform
	if ((type & kNonUniformScaleTransform) != 0)
		type &= ~kUniformScaleTransform;
	DebugAssert ((type & (kNonUniformScaleTransform|kUniformScaleTransform)) != (kNonUniformScaleTransform|kUniformScaleTransform));

	// uniform or no scale
	if (!IsNonUniformScaleTransform(type))
	{
		scaleOnly.SetIdentity();
		return type;
	}
	// non-uniform scale
	else
	{
		// Calculate scaleOnlyMatrix (In order to scale the mesh with the non-uniform scale)
		Matrix4x4f worldToLocalMatrixNoScale;
		GetWorldToLocalMatrixNoScale (worldToLocalMatrixNoScale);
		MultiplyMatrices4x4(&worldToLocalMatrixNoScale, &transform, &scaleOnly);
		scaleOnly.Get (0,3) = 0.0F;
		scaleOnly.Get (1,3) = 0.0F;
		scaleOnly.Get (2,3) = 0.0F;

		// Calculate the matrix without any scale applied
		GetLocalToWorldMatrixNoScale (transform);
		uniformScale = 1.0F;
		
		return type;
	}
}


TransformType Transform::CalculateTransformMatrixDisableScale (Matrix4x4f& matrix) const
{
	Vector3f worldPos;
	Quaternionf worldRot;
	TransformType type = GetPositionAndRotationWithTransformType(worldPos, worldRot);
	
	matrix.SetTR (worldPos, worldRot);
		return type;
}

TransformType Transform::CalculateTransformMatrixScaleDelta (Matrix4x4f& m) const
{
	Matrix4x4f scaledMatrix;
	TransformType type = CalculateTransformMatrix (scaledMatrix);
	// Affine matrix?
	if ((type & (kUniformScaleTransform | kNonUniformScaleTransform)) == 0)
	{
		m.SetIdentity ();
		return type;
	}
	else
	{
		Matrix4x4f tmp;
		GetWorldToLocalMatrixNoScale (tmp);
		MultiplyMatrices4x4(&tmp, &scaledMatrix, &m);
		m.Get (0,3) = 0.0F;
		m.Get (1,3) = 0.0F;
		m.Get (2,3) = 0.0F;
		return type;
	}
}

Matrix4x4f Transform::GetWorldToLocalMatrixNoScale () const
{
	Matrix4x4f m;
	GetWorldToLocalMatrixNoScale(m);
	return m;
}

const Matrix4x4f& Transform::GetWorldToLocalMatrixNoScale (Matrix4x4f& m) const
{
	Vector3f pos;
	Quaternionf rot;
	GetPositionAndRotation(pos, rot);
	m.SetTRInverse (pos, rot);
	return m;
}

Matrix4x4f Transform::GetLocalToWorldMatrixNoScale () const
{
	Matrix4x4f m;
	GetLocalToWorldMatrixNoScale(m);
	return m;
}

const Matrix4x4f& Transform::GetLocalToWorldMatrixNoScale (Matrix4x4f& m) const
{
	Quaternionf rot; Vector3f pos;
	GetPositionAndRotation(pos, rot);
	m.SetTR (pos, rot);
	return m;
}

Matrix4x4f Transform::GetWorldToLocalMatrix () const
{
	Matrix4x4f m, temp;
	m.SetTRInverse (m_LocalPosition, m_LocalRotation);
	if (m_InternalTransformType != kNoScaleTransform)
	{
		Matrix4x4f scale;
		scale.SetScale (InverseSafe (m_LocalScale));
		MultiplyMatrices4x4 (&scale, &m, &temp);
		CopyMatrix (temp.GetPtr(), m.GetPtr());
	}
	
	Transform* father = GetParent ();
	if (father != NULL)
	{
		Matrix4x4f parentMat = father->GetWorldToLocalMatrix();
		MultiplyMatrices4x4 (&m, &parentMat, &temp);
		CopyMatrix (temp.GetPtr(), m.GetPtr());
	}
	
	return m;
}


Matrix4x4f Transform::GetLocalToWorldMatrix () const
{
	Matrix4x4f m;
	CalculateTransformMatrix (m);
	return m;
}

Vector3f Transform::TransformDirection (const Vector3f& inDirection) const
{
	return RotateVectorByQuat (GetRotation (), inDirection);
}

Vector3f Transform::InverseTransformDirection (const Vector3f& inDirection) const
{
	return RotateVectorByQuat (Inverse(GetRotation()), inDirection);
}

Vector3f Transform::InverseTransformPoint (const Vector3f& inPosition) const
{
	Vector3f newPosition, localPosition;
	Transform* father = GetParent ();
	if (father)
		localPosition = father->InverseTransformPoint (inPosition);
	else
		localPosition = inPosition;

	localPosition -= m_LocalPosition;
	newPosition = RotateVectorByQuat (Inverse(m_LocalRotation), localPosition);
	if (m_InternalTransformType != kNoScaleTransform)
		newPosition.Scale (InverseSafe (m_LocalScale));

	return newPosition;
}

Vector3f Transform::TransformPoint (const Vector3f& inPoint) const
{
	Vector3f worldPos = inPoint;

	const Transform* cur = this;
	while (cur)
	{
		worldPos.Scale (cur->m_LocalScale);
		worldPos = RotateVectorByQuat (cur->m_LocalRotation, worldPos);
		worldPos += cur->m_LocalPosition;
		
		cur = cur->GetParent ();
	}
	return worldPos;
}

template<class TransferFunction> inline
void Transform::Transfer (TransferFunction& transfer) 
{
	Super::Transfer (transfer);
	TRANSFER_SIMPLE (m_LocalRotation);
	TRANSFER_SIMPLE (m_LocalPosition);
	TRANSFER_SIMPLE (m_LocalScale);

	//TRANSFER_EDITOR_ONLY_HIDDEN (m_LocalEulerAnglesHint);

	// This needs to be here since eg. Mesh collider queries the recalculate transform type.
	// and awakefromload might not have been called already.
	if (transfer.IsReading())
		RecalculateTransformType ();
	
	// When cloning objects for prefabs and instantiate, we don't use serialization to duplicate the hierarchy,
	// we duplicate the hierarchy directly
	if (SerializePrefabIgnoreProperties(transfer))
	{
		transfer.Transfer (m_Children, "m_Children", kHideInEditorMask | kStrongPPtrMask | kIgnoreWithInspectorUndoMask);	
		transfer.Transfer (m_Father, "m_Father", kHideInEditorMask | kIgnoreWithInspectorUndoMask);
	}

#if ENABLE_EDITOR_HIERARCHY_ORDERING
	TRANSFER_EDITOR_ONLY_HIDDEN(m_Order);
#endif
}

void Transform::RecalculateTransformType ()
{
	// #pragma message ("Compare approximately is bad due to epsilon changing with the size of the value")
	if (CompareApproximately (m_LocalScale.x, m_LocalScale.y, 0.0001F) && CompareApproximately (m_LocalScale.y, m_LocalScale.z, 0.0001F))
	{
		if (CompareApproximately( m_LocalScale.x, 1.0F, 0.0001F ))
		{
			m_InternalTransformType = kNoScaleTransform;
		}
		else 
		{
			m_InternalTransformType = kUniformScaleTransform;
			if (m_LocalScale.x < 0.0F) 
			{
				m_InternalTransformType = kOddNegativeScaleTransform | kNonUniformScaleTransform;
			}
		}
	}
	else
	{
		m_InternalTransformType = kNonUniformScaleTransform;

		int hasOddNegativeScale = m_LocalScale.x * m_LocalScale.y * m_LocalScale.z < 0.0F ? 1 : 0;
		m_InternalTransformType |= (TransformType)(hasOddNegativeScale * kOddNegativeScaleTransform);
	}
}

void Transform::AwakeFromLoad (AwakeFromLoadMode awakeMode)
{
	Super::AwakeFromLoad (awakeMode);
	SetCacheDirty();
	
	// Only call SendTransformChanged if it was really changed eg. 
	// by a propepertyeditor or datatemplate propagation but not if it was loaded from disk
	
	if ((awakeMode & kDidLoadFromDisk) == 0)
	{
		// This is for all kinds of non-serialization Awakes.
		// eg. animation. Because Transfer already recalculates
		RecalculateTransformType ();

		SendTransformChanged (kPositionChanged | kRotationChanged | kScaleChanged);
	}
	
	#if UNITY_EDITOR
	if (gHierarchyChangedCallback)
		gHierarchyChangedCallback (this);
	#endif
}

inline void MakeValidFloat (float* f)
{
	if (!IsFinite (*f))
		*f = 0.0F;
}

void Transform::CheckConsistency ()
{
	Super::CheckConsistency ();
	MakeValidFloat (&m_LocalRotation.x);
	MakeValidFloat (&m_LocalRotation.y);
	MakeValidFloat (&m_LocalRotation.z);
	MakeValidFloat (&m_LocalRotation.w);
	MakeValidFloat (&m_LocalPosition.x);
	MakeValidFloat (&m_LocalPosition.y);
	MakeValidFloat (&m_LocalPosition.z);
	MakeValidFloat (&m_LocalScale.x);
	MakeValidFloat (&m_LocalScale.y);
	MakeValidFloat (&m_LocalScale.z);
	m_LocalRotation = NormalizeSafe (m_LocalRotation);
	#if UNITY_EDITOR
	SyncLocalEulerAnglesHint ();
	#endif
	
	// Check if father has this as child
	Transform* father = m_Father;
	if (father)
	{
		if ( father->Find(this) == father->m_Children.end ())
			father->m_Children.push_back (this);
	}

	// Check if all children are available and have this as father.  Also make
	// sure that any of our children is on the list exactly once.
	for (int i=0;i<m_Children.size ();i++)
	{
		Transform* child = m_Children[i];
		Assert(child != this);
		
		if (child == NULL)
		{
			ErrorStringObject ("CheckConsistency: Transform child can't be loaded", this);
			iterator it = m_Children.begin () + i;
			m_Children.erase (it);
			i--;
			continue;
		}

		Transform* parent = child->m_Father;
		
		#if UNITY_EDITOR
		// We only try to fix the parent pointer in the Editor as we don't want to risk breaking existing players.
		if (parent == NULL) 
		{
			child->m_Father = this;
			ErrorStringObject ("CheckConsistency: Restored Transform child parent pointer from NULL", child);
			continue;
		}
		#endif
		
		if (parent != this)
		{
			iterator it = m_Children.begin () + i;
			m_Children.erase (it);
			i--;
			ErrorStringObject ("CheckConsistency: Transform child has another parent", child);
			continue;
		}

		// Look for and remove multiple occurrences.
		bool occursMultipleTimes = false;
		for (int j = i + 1; j < m_Children.size ();)
		{
			Transform* otherChild = m_Children[j];
			if (otherChild == child)
			{
				occursMultipleTimes = true;
				m_Children.erase (m_Children.begin () + j);
			}
			else
				++j;
		}
		if (occursMultipleTimes)
		{
			ErrorStringObject ("CheckConsistency: Transform child is linked multiple times to parent; removed extraneous links from parent", child);
		}
	}
}
#if ENABLE_EDITOR_HIERARCHY_ORDERING
void Transform::SetOrder(SInt32 order)
{
	m_Order = order; 
	SetDirty(); 

	if (gHierarchyChangedCallback)
		gHierarchyChangedCallback (this);

	SendTransformChanged (kParentingChanged);
}

int Transform::CompareDepths(Transform* lhs, Transform* rhs)
 {
	bool orderCompare = lhs->GetOrder() != rhs->GetOrder();
	if (orderCompare)
		return lhs->GetOrder() < rhs->GetOrder();
	else
	{
		const char* lhsName = lhs ? lhs->GetName() : "";
		const char* rhsName = rhs ? rhs->GetName() : "";
		return SemiNumericCompare(lhsName, rhsName) < 0;
	}
 }

void Transform::OrderChildrenRecursively()
{
	std::sort(m_Children.begin(), m_Children.end(), Transform::CompareDepths);

	for (int i = 0; i < m_Children.size(); ++i)
	{
		Transform* childTrans = m_Children[i];
		childTrans->OrderChildrenRecursively();
	}
}
#endif

IMPLEMENT_OBJECT_SERIALIZE (Transform)
IMPLEMENT_CLASS (Transform)

static inline int FindSeperator (const char* in)
{
	const char* c = in;
	while (*c != '/' && *c != '\0')
		c++;
	return c - in;
}

Transform* FindRelativeTransformWithPath (Transform& transform, const char* path)
{
	LIMIT_RECURSION (2000, NULL);
	
	if (path[0] == '\0')
		return &transform;
	
	int seperator = FindSeperator (path);
	
	if (path[0] == '/')
		return FindActiveTransformWithPath (path);
	else if (path[0] == '.' && path[1] == '.')
	{
		Transform* parent = transform.GetParent();
		if (path[2] == '/')
		{
			if (parent)
				return FindRelativeTransformWithPath (*parent, path + 3);
			else
				return NULL;
		}			
		else if (path[2] == '\0')
			return parent;
	}

	for (Transform::iterator i=transform.begin ();i != transform.end ();i++)
	{
		Transform& child = **i;
		
		const char* name = child.GetName();
		
		// Early out if size is not the same
		if (strlen(name) != seperator)
			continue;
		
		// continue if the name isn't the same
		const char* n = name;
		int j;
		for (j=0;j<seperator;j++,n++)
			if (path[j] != *n)
				break;
		if (j != seperator)
			continue;
		
		// We found the transform we were searching for
		if (path[seperator] == '\0')
			return &child;
		// Recursively find in the children
		else
		{
			Transform* result = FindRelativeTransformWithPath (child, path + seperator + 1);
			if (result != NULL) 
				return result;
		}
	}
	return NULL;
}

string CalculateTransformPath (const Transform& transform, const Transform* to)
{
	string path;
	const Transform* cur = &transform;
	while (cur != to && cur != NULL)
	{
		if (!path.empty ())
			path = cur->GetName () + ('/' + path);
		else
			path = cur->GetName ();
		cur = cur->GetParent ();
	}
	return path;
}

void AppendTransformPath (string& path, const char* appendName)
{
	if (path.empty())
		path = appendName;
	else
	{
		path += '/';
		path += appendName;
	}
}

void AppendTransformPath (UnityStr& path, const char* appendName)
{
	if (path.empty())
		path = appendName;
	else
	{
		path += '/';
		path += appendName;
	}
}



Transform* FindActiveTransformWithPath (const char* path)
{
	bool needsToBeRoot = path[0] == '/';
	if (path[0] == '/')
		path++;
	
	if (path[0] == 0)
		return NULL;

	GameObjectList::iterator i;

	GameObjectList& tagged = GetGameObjectManager().m_TaggedNodes;
	for (i=tagged.begin();i != tagged.end();i++)
	{	
		Transform* transform = FindActiveTransformWithPathImpl(path, **i, needsToBeRoot);
		if (transform)
			return transform;
	}

	GameObjectList& active = GetGameObjectManager().m_ActiveNodes;
	for (i=active.begin();i != active.end();i++)
	{	
		Transform* transform = FindActiveTransformWithPathImpl(path, **i, needsToBeRoot);
		if (transform)
			return transform;
	}
	
	return NULL;
/*

	for (int i=0;i<gos.size ();i++)
	{
		if (!gos[i]->IsActive ())
			continue;
			
		const string& name = gos[i]->GetName ();
		if (name.find (path, 0, name.size ()) == 0)
		{
			path += name.size ();
			if (path[0] == '/')
				path ++;
				
			Transform* transform = gos[i]->QueryComponent (Transform);
			if (transform)
			{
				if (needsToBeRoot && transform->GetParent())
					continue;

				if (path[0] == 0)
					return transform;
				transform = FindRelativeTransformWithPath (*transform, path);
				if (transform)
					return transform;
			}
		}
	}
	
	return NULL;
*/	
}

static Transform* FindActiveTransformWithPathImpl (const char* path, GameObject& go, bool needsToBeRoot)
{
	AssertIf(!go.IsActive());

	const char* name = go.GetName ();
	size_t size = strlen(name);
	
	if (strncmp(name, path, size) == 0)
	{
		path += size;
		if (path[0] == '/')
			path ++;
			
		Transform* transform = go.QueryComponent (Transform);
		if (transform)
		{
			if (needsToBeRoot && transform->GetParent())
				return NULL;

			if (path[0] == 0 && transform->IsActive())
				return transform;
				
			transform = FindRelativeTransformWithPath (*transform, path);
			if (transform && transform->IsActive())
				return transform;
		}
	}
	return NULL;
}

Transform& Transform::GetRoot ()
{
	Transform* cur = this;
	Transform* curParent = NULL;
	while ((curParent = cur->GetParent ()) != NULL)
		cur = curParent;

	return *cur;
}

bool IsChildOrSameTransform(Transform& transform, Transform& inParent)
{
	Transform* child = &transform;
	while (child)
	{
		if (child == &inParent)
			return true;
		child = child->GetParent();
	}
	return false;
}

#if ENABLE_EDITOR_HIERARCHY_ORDERING
void Transform::GetSortedChildList (Transform::TransformComList& sortedChildren) const
{
	sortedChildren.assign(m_Children.begin(), m_Children.end());
	std::sort(sortedChildren.begin(), sortedChildren.end(), Transform::CompareDepths);
}
#endif

void Transform::SetLocalTRS (const Vector3f& pos, const Quaternionf& rot, const Vector3f& scale)
{
	ABORT_INVALID_VECTOR3 (pos, localPosition, transform);
	ABORT_INVALID_QUATERNION (rot, localRotation, transform);
	m_LocalRotation = NormalizeSafe(rot);
	m_LocalPosition = pos;
	m_LocalScale = scale;
	#if UNITY_EDITOR
	SyncLocalEulerAnglesHint ();
	#endif
	RecalculateTransformType();
	SendTransformChanged(kPositionChanged | kRotationChanged | kScaleChanged);
}

int GetTransformDepth(Transform& transform)
{
	Transform* parent = transform.GetParent();
	int depth = 0;
	while (parent)
	{
		depth++;
		parent = parent->GetParent();
	}
	return depth;	
}

Transform* FindTransformWithName(Transform* root, const char* name)
{
	if (strcmp(root->GetName(), name) == 0)
		return root;
	else
	{
		for (int i = 0; i < root->GetChildrenCount(); i++)
		{
			Transform* ret = FindTransformWithName(&(root->GetChild(i)), name);
			if (ret)
				return ret;
		}
		return NULL;
	}
}