summaryrefslogtreecommitdiff
path: root/indra/llcharacter/llkeyframemotion.cpp
blob: 0345212695e09a3ee660204746443d89a9ba6e56 (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
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
/** 
 * @file llkeyframemotion.cpp
 * @brief Implementation of LLKeyframeMotion class.
 *
 * $LicenseInfo:firstyear=2001&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

//-----------------------------------------------------------------------------
// Header Files
//-----------------------------------------------------------------------------
#include "linden_common.h"

#include "llmath.h"
#include "llanimationstates.h"
#include "llassetstorage.h"
#include "lldatapacker.h"
#include "llcharacter.h"
#include "llcriticaldamp.h"
#include "lldir.h"
#include "llendianswizzle.h"
#include "llkeyframemotion.h"
#include "llquantize.h"
#include "m3math.h"
#include "message.h"
#include "llfilesystem.h"

//-----------------------------------------------------------------------------
// Static Definitions
//-----------------------------------------------------------------------------
LLKeyframeDataCache::keyframe_data_map_t	LLKeyframeDataCache::sKeyframeDataMap;

//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
static F32 JOINT_LENGTH_K = 0.7f;
static S32 MAX_ITERATIONS = 20;
static S32 MIN_ITERATIONS = 1;
static S32 MIN_ITERATION_COUNT = 2;
static F32 MAX_PIXEL_AREA_CONSTRAINTS = 80000.f;
static F32 MIN_PIXEL_AREA_CONSTRAINTS = 1000.f;
static F32 MIN_ACCELERATION_SQUARED = 0.0005f * 0.0005f;

static F32 MAX_CONSTRAINTS = 10;

//-----------------------------------------------------------------------------
// JointMotionList
//-----------------------------------------------------------------------------
LLKeyframeMotion::JointMotionList::JointMotionList()
	: mDuration(0.f),
	  mLoop(FALSE),
	  mLoopInPoint(0.f),
	  mLoopOutPoint(0.f),
	  mEaseInDuration(0.f),
	  mEaseOutDuration(0.f),
	  mBasePriority(LLJoint::LOW_PRIORITY),
	  mHandPose(LLHandMotion::HAND_POSE_SPREAD),
	  mMaxPriority(LLJoint::LOW_PRIORITY)
{
}

LLKeyframeMotion::JointMotionList::~JointMotionList()
{
	for_each(mConstraints.begin(), mConstraints.end(), DeletePointer());
	mConstraints.clear();
	for_each(mJointMotionArray.begin(), mJointMotionArray.end(), DeletePointer());
	mJointMotionArray.clear();
}

U32 LLKeyframeMotion::JointMotionList::dumpDiagInfo()
{
	S32	total_size = sizeof(JointMotionList);

	for (U32 i = 0; i < getNumJointMotions(); i++)
	{
		LLKeyframeMotion::JointMotion* joint_motion_p = mJointMotionArray[i];

		LL_INFOS() << "\tJoint " << joint_motion_p->mJointName << LL_ENDL;
		if (joint_motion_p->mUsage & LLJointState::SCALE)
		{
			LL_INFOS() << "\t" << joint_motion_p->mScaleCurve.mNumKeys << " scale keys at " 
			<< joint_motion_p->mScaleCurve.mNumKeys * sizeof(ScaleKey) << " bytes" << LL_ENDL;

			total_size += joint_motion_p->mScaleCurve.mNumKeys * sizeof(ScaleKey);
		}
		if (joint_motion_p->mUsage & LLJointState::ROT)
		{
			LL_INFOS() << "\t" << joint_motion_p->mRotationCurve.mNumKeys << " rotation keys at " 
			<< joint_motion_p->mRotationCurve.mNumKeys * sizeof(RotationKey) << " bytes" << LL_ENDL;

			total_size += joint_motion_p->mRotationCurve.mNumKeys * sizeof(RotationKey);
		}
		if (joint_motion_p->mUsage & LLJointState::POS)
		{
			LL_INFOS() << "\t" << joint_motion_p->mPositionCurve.mNumKeys << " position keys at " 
			<< joint_motion_p->mPositionCurve.mNumKeys * sizeof(PositionKey) << " bytes" << LL_ENDL;

			total_size += joint_motion_p->mPositionCurve.mNumKeys * sizeof(PositionKey);
		}
	}
	LL_INFOS() << "Size: " << total_size << " bytes" << LL_ENDL;

	return total_size;
}

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// ****Curve classes
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------
// ScaleCurve::ScaleCurve()
//-----------------------------------------------------------------------------
LLKeyframeMotion::ScaleCurve::ScaleCurve()
{
	mInterpolationType = LLKeyframeMotion::IT_LINEAR;
	mNumKeys = 0;
}

//-----------------------------------------------------------------------------
// ScaleCurve::~ScaleCurve()
//-----------------------------------------------------------------------------
LLKeyframeMotion::ScaleCurve::~ScaleCurve() 
{
	mKeys.clear();
	mNumKeys = 0;
}

//-----------------------------------------------------------------------------
// getValue()
//-----------------------------------------------------------------------------
LLVector3 LLKeyframeMotion::ScaleCurve::getValue(F32 time, F32 duration)
{
	LLVector3 value;

	if (mKeys.empty())
	{
		value.clearVec();
		return value;
	}
	
	key_map_t::iterator right = mKeys.lower_bound(time);
	if (right == mKeys.end())
	{
		// Past last key
		--right;
		value = right->second.mScale;
	}
	else if (right == mKeys.begin() || right->first == time)
	{
		// Before first key or exactly on a key
		value = right->second.mScale;
	}
	else
	{
		// Between two keys
		key_map_t::iterator left = right; --left;
		F32 index_before = left->first;
		F32 index_after = right->first;
		ScaleKey& scale_before = left->second;
		ScaleKey& scale_after = right->second;
		if (right == mKeys.end())
		{
			scale_after = mLoopInKey;
			index_after = duration;
		}

		F32 u = (time - index_before) / (index_after - index_before);
		value = interp(u, scale_before, scale_after);
	}
	return value;
}

//-----------------------------------------------------------------------------
// interp()
//-----------------------------------------------------------------------------
LLVector3 LLKeyframeMotion::ScaleCurve::interp(F32 u, ScaleKey& before, ScaleKey& after)
{
	switch (mInterpolationType)
	{
	case IT_STEP:
		return before.mScale;

	default:
	case IT_LINEAR:
	case IT_SPLINE:
		return lerp(before.mScale, after.mScale, u);
	}
}

//-----------------------------------------------------------------------------
// RotationCurve::RotationCurve()
//-----------------------------------------------------------------------------
LLKeyframeMotion::RotationCurve::RotationCurve()
{
	mInterpolationType = LLKeyframeMotion::IT_LINEAR;
	mNumKeys = 0;
}

//-----------------------------------------------------------------------------
// RotationCurve::~RotationCurve()
//-----------------------------------------------------------------------------
LLKeyframeMotion::RotationCurve::~RotationCurve()
{
	mKeys.clear();
	mNumKeys = 0;
}

//-----------------------------------------------------------------------------
// RotationCurve::getValue()
//-----------------------------------------------------------------------------
LLQuaternion LLKeyframeMotion::RotationCurve::getValue(F32 time, F32 duration)
{
	LLQuaternion value;

	if (mKeys.empty())
	{
		value = LLQuaternion::DEFAULT;
		return value;
	}
	
	key_map_t::iterator right = mKeys.lower_bound(time);
	if (right == mKeys.end())
	{
		// Past last key
		--right;
		value = right->second.mRotation;
	}
	else if (right == mKeys.begin() || right->first == time)
	{
		// Before first key or exactly on a key
		value = right->second.mRotation;
	}
	else
	{
		// Between two keys
		key_map_t::iterator left = right; --left;
		F32 index_before = left->first;
		F32 index_after = right->first;
		RotationKey& rot_before = left->second;
		RotationKey& rot_after = right->second;
		if (right == mKeys.end())
		{
			rot_after = mLoopInKey;
			index_after = duration;
		}

		F32 u = (time - index_before) / (index_after - index_before);
		value = interp(u, rot_before, rot_after);
	}
	return value;
}

//-----------------------------------------------------------------------------
// interp()
//-----------------------------------------------------------------------------
LLQuaternion LLKeyframeMotion::RotationCurve::interp(F32 u, RotationKey& before, RotationKey& after)
{
	switch (mInterpolationType)
	{
	case IT_STEP:
		return before.mRotation;

	default:
	case IT_LINEAR:
	case IT_SPLINE:
		return nlerp(u, before.mRotation, after.mRotation);
	}
}


//-----------------------------------------------------------------------------
// PositionCurve::PositionCurve()
//-----------------------------------------------------------------------------
LLKeyframeMotion::PositionCurve::PositionCurve()
{
	mInterpolationType = LLKeyframeMotion::IT_LINEAR;
	mNumKeys = 0;
}

//-----------------------------------------------------------------------------
// PositionCurve::~PositionCurve()
//-----------------------------------------------------------------------------
LLKeyframeMotion::PositionCurve::~PositionCurve()
{
	mKeys.clear();
	mNumKeys = 0;
}

//-----------------------------------------------------------------------------
// PositionCurve::getValue()
//-----------------------------------------------------------------------------
LLVector3 LLKeyframeMotion::PositionCurve::getValue(F32 time, F32 duration)
{
	LLVector3 value;

	if (mKeys.empty())
	{
		value.clearVec();
		return value;
	}
	
	key_map_t::iterator right = mKeys.lower_bound(time);
	if (right == mKeys.end())
	{
		// Past last key
		--right;
		value = right->second.mPosition;
	}
	else if (right == mKeys.begin() || right->first == time)
	{
		// Before first key or exactly on a key
		value = right->second.mPosition;
	}
	else
	{
		// Between two keys
		key_map_t::iterator left = right; --left;
		F32 index_before = left->first;
		F32 index_after = right->first;
		PositionKey& pos_before = left->second;
		PositionKey& pos_after = right->second;
		if (right == mKeys.end())
		{
			pos_after = mLoopInKey;
			index_after = duration;
		}

		F32 u = (time - index_before) / (index_after - index_before);
		value = interp(u, pos_before, pos_after);
	}

	llassert(value.isFinite());
	
	return value;
}

//-----------------------------------------------------------------------------
// interp()
//-----------------------------------------------------------------------------
LLVector3 LLKeyframeMotion::PositionCurve::interp(F32 u, PositionKey& before, PositionKey& after)
{
	switch (mInterpolationType)
	{
	case IT_STEP:
		return before.mPosition;
	default:
	case IT_LINEAR:
	case IT_SPLINE:
		return lerp(before.mPosition, after.mPosition, u);
	}
}


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// JointMotion class
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// JointMotion::update()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::JointMotion::update(LLJointState* joint_state, F32 time, F32 duration)
{
	// this value being 0 is the cause of https://jira.lindenlab.com/browse/SL-22678 but I haven't 
	// managed to get a stack to see how it got here. Testing for 0 here will stop the crash.
	if ( joint_state == NULL )
	{
		return;
	}

	U32 usage = joint_state->getUsage();

	//-------------------------------------------------------------------------
	// update scale component of joint state
	//-------------------------------------------------------------------------
	if ((usage & LLJointState::SCALE) && mScaleCurve.mNumKeys)
	{
		joint_state->setScale( mScaleCurve.getValue( time, duration ) );
	}

	//-------------------------------------------------------------------------
	// update rotation component of joint state
	//-------------------------------------------------------------------------
	if ((usage & LLJointState::ROT) && mRotationCurve.mNumKeys)
	{
		joint_state->setRotation( mRotationCurve.getValue( time, duration ) );
	}

	//-------------------------------------------------------------------------
	// update position component of joint state
	//-------------------------------------------------------------------------
	if ((usage & LLJointState::POS) && mPositionCurve.mNumKeys)
	{
		joint_state->setPosition( mPositionCurve.getValue( time, duration ) );
	}
}


//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// LLKeyframeMotion class
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// LLKeyframeMotion()
// Class Constructor
//-----------------------------------------------------------------------------
LLKeyframeMotion::LLKeyframeMotion(const LLUUID &id) 
	: LLMotion(id),
		mJointMotionList(NULL),
		mPelvisp(NULL),
		mLastSkeletonSerialNum(0),
		mLastUpdateTime(0.f),
		mLastLoopedTime(0.f),
		mAssetStatus(ASSET_UNDEFINED)
{

}


//-----------------------------------------------------------------------------
// ~LLKeyframeMotion()
// Class Destructor
//-----------------------------------------------------------------------------
LLKeyframeMotion::~LLKeyframeMotion()
{
	for_each(mConstraints.begin(), mConstraints.end(), DeletePointer());
	mConstraints.clear();
}

//-----------------------------------------------------------------------------
// create()
//-----------------------------------------------------------------------------
LLMotion *LLKeyframeMotion::create(const LLUUID &id)
{
	return new LLKeyframeMotion(id);
}

//-----------------------------------------------------------------------------
// getJointState()
//-----------------------------------------------------------------------------
LLPointer<LLJointState>& LLKeyframeMotion::getJointState(U32 index)
{
	llassert_always (index < mJointStates.size());
	return mJointStates[index];
}

//-----------------------------------------------------------------------------
// getJoint()
//-----------------------------------------------------------------------------
LLJoint* LLKeyframeMotion::getJoint(U32 index)
{
	llassert_always (index < mJointStates.size());
	LLJoint* joint = mJointStates[index]->getJoint();
	
	//Commented out 06-28-11 by Aura.
	//llassert_always (joint);
	return joint;
}

//-----------------------------------------------------------------------------
// LLKeyframeMotion::onInitialize(LLCharacter *character)
//-----------------------------------------------------------------------------
LLMotion::LLMotionInitStatus LLKeyframeMotion::onInitialize(LLCharacter *character)
{
	mCharacter = character;
	
	LLUUID* character_id;

	// asset already loaded?
	switch(mAssetStatus)
	{
	case ASSET_NEEDS_FETCH:
		// request asset
		mAssetStatus = ASSET_FETCHED;

        if (mID.notNull())
        {
            LL_DEBUGS("Animation") << "Requesting data fetch for: " << mID << LL_ENDL;
            character_id = new LLUUID(mCharacter->getID());
            gAssetStorage->getAssetData(mID,
                                        LLAssetType::AT_ANIMATION,
                                        onLoadComplete,
                                        (void*)character_id,
                                        FALSE);
        }
        else
        {
            LL_INFOS("Animation") << "Attempted to fetch animation " << mName << " with null id for character " << mCharacter->getID() << LL_ENDL;
        }

		return STATUS_HOLD;
	case ASSET_FETCHED:
		return STATUS_HOLD;
	case ASSET_FETCH_FAILED:
		return STATUS_FAILURE;
	case ASSET_LOADED:
		return STATUS_SUCCESS;
	default:
		// we don't know what state the asset is in yet, so keep going
		// check keyframe cache first then file cache then asset request
		break;
	}

	LLKeyframeMotion::JointMotionList* joint_motion_list = LLKeyframeDataCache::getKeyframeData(getID());

	if(joint_motion_list)
	{
		// motion already existed in cache, so grab it
		mJointMotionList = joint_motion_list;

		mJointStates.reserve(mJointMotionList->getNumJointMotions());
		
		// don't forget to allocate joint states
		// set up joint states to point to character joints
		for(U32 i = 0; i < mJointMotionList->getNumJointMotions(); i++)
		{
			JointMotion* joint_motion = mJointMotionList->getJointMotion(i);
			if (LLJoint *joint = mCharacter->getJoint(joint_motion->mJointName))
			{
				LLPointer<LLJointState> joint_state = new LLJointState;
				mJointStates.push_back(joint_state);
				joint_state->setJoint(joint);
				joint_state->setUsage(joint_motion->mUsage);
				joint_state->setPriority(joint_motion->mPriority);
			}
			else
			{
				// add dummy joint state with no associated joint
				mJointStates.push_back(new LLJointState);
			}
		}
		mAssetStatus = ASSET_LOADED;
		setupPose();
		return STATUS_SUCCESS;
	}

	//-------------------------------------------------------------------------
	// Load named file by concatenating the character prefix with the motion name.
	// Load data into a buffer to be parsed.
	//-------------------------------------------------------------------------
	U8 *anim_data;
	S32 anim_file_size;

	BOOL success = FALSE;
	LLFileSystem* anim_file = new LLFileSystem(mID, LLAssetType::AT_ANIMATION);
	if (!anim_file || !anim_file->getSize())
	{
		delete anim_file;
		anim_file = NULL;
		
		// request asset over network on next call to load
		mAssetStatus = ASSET_NEEDS_FETCH;

		return STATUS_HOLD;
	}
	else
	{
		anim_file_size = anim_file->getSize();
		anim_data = new(std::nothrow) U8[anim_file_size];
		if (anim_data)
		{
			success = anim_file->read(anim_data, anim_file_size);	/*Flawfinder: ignore*/
		}
		else
		{
			LL_WARNS() << "Failed to allocate buffer: " << anim_file_size << mID << LL_ENDL;
		}
		delete anim_file;
		anim_file = NULL;
	}

	if (!success)
	{
		LL_WARNS() << "Can't open animation file " << mID << LL_ENDL;
		mAssetStatus = ASSET_FETCH_FAILED;
		return STATUS_FAILURE;
	}

	LL_DEBUGS() << "Loading keyframe data for: " << getName() << ":" << getID() << " (" << anim_file_size << " bytes)" << LL_ENDL;

	LLDataPackerBinaryBuffer dp(anim_data, anim_file_size);

	if (!deserialize(dp, getID()))
	{
		LL_WARNS() << "Failed to decode asset for animation " << getName() << ":" << getID() << LL_ENDL;
		mAssetStatus = ASSET_FETCH_FAILED;
		return STATUS_FAILURE;
	}

	delete []anim_data;

	mAssetStatus = ASSET_LOADED;
	return STATUS_SUCCESS;
}

//-----------------------------------------------------------------------------
// setupPose()
//-----------------------------------------------------------------------------
BOOL LLKeyframeMotion::setupPose()
{
	// add all valid joint states to the pose
	for (U32 jm=0; jm<mJointMotionList->getNumJointMotions(); jm++)
	{
		LLPointer<LLJointState> joint_state = getJointState(jm);
		if ( joint_state->getJoint() )
		{
			addJointState( joint_state );
		}
	}

	// initialize joint constraints
	for (JointConstraintSharedData* shared_constraintp : mJointMotionList->mConstraints)
	{
		JointConstraint* constraintp = new JointConstraint(shared_constraintp);
		initializeConstraint(constraintp);
		mConstraints.push_front(constraintp);
	}

	if (mJointMotionList->mConstraints.size())
	{
		mPelvisp = mCharacter->getJoint("mPelvis");
		if (!mPelvisp)
		{
			return FALSE;
		}
	}

	// setup loop keys
	setLoopIn(mJointMotionList->mLoopInPoint);
	setLoopOut(mJointMotionList->mLoopOutPoint);

	return true;
}

//-----------------------------------------------------------------------------
// LLKeyframeMotion::onActivate()
//-----------------------------------------------------------------------------
BOOL LLKeyframeMotion::onActivate()
{
	// If the keyframe anim has an associated emote, trigger it. 
	if( mJointMotionList->mEmoteName.length() > 0 )
	{
		LLUUID emote_anim_id = gAnimLibrary.stringToAnimState(mJointMotionList->mEmoteName);
		// don't start emote if already active to avoid recursion
		if (!mCharacter->isMotionActive(emote_anim_id))
		{
			mCharacter->startMotion( emote_anim_id );
		}
	}

	mLastLoopedTime = 0.f;

	return true;
}

//-----------------------------------------------------------------------------
// LLKeyframeMotion::onUpdate()
//-----------------------------------------------------------------------------
BOOL LLKeyframeMotion::onUpdate(F32 time, U8* joint_mask)
{
    LL_PROFILE_ZONE_SCOPED_CATEGORY_AVATAR;
	// llassert(time >= 0.f);		// This will fire
	time = llmax(0.f, time);

	if (mJointMotionList->mLoop)
	{
		if (mJointMotionList->mDuration == 0.0f)
		{
			time = 0.f;
			mLastLoopedTime = 0.0f;
		}
		else if (mStopped)
		{
			mLastLoopedTime = llmin(mJointMotionList->mDuration, mLastLoopedTime + time - mLastUpdateTime);
		}
		else if (time > mJointMotionList->mLoopOutPoint)
		{
			if ((mJointMotionList->mLoopOutPoint - mJointMotionList->mLoopInPoint) == 0.f)
			{
				mLastLoopedTime = mJointMotionList->mLoopOutPoint;
			}
			else
			{
				mLastLoopedTime = mJointMotionList->mLoopInPoint + 
					fmod(time - mJointMotionList->mLoopOutPoint, 
					mJointMotionList->mLoopOutPoint - mJointMotionList->mLoopInPoint);
			}
		}
		else
		{
			mLastLoopedTime = time;
		}
	}
	else
	{
		mLastLoopedTime = time;
	}

	applyKeyframes(mLastLoopedTime);

	applyConstraints(mLastLoopedTime, joint_mask);

	mLastUpdateTime = time;

	return mLastLoopedTime <= mJointMotionList->mDuration;
}

//-----------------------------------------------------------------------------
// applyKeyframes()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::applyKeyframes(F32 time)
{
	llassert_always (mJointMotionList->getNumJointMotions() <= mJointStates.size());
	for (U32 i=0; i<mJointMotionList->getNumJointMotions(); i++)
	{
		mJointMotionList->getJointMotion(i)->update(mJointStates[i],
													  time, 
													  mJointMotionList->mDuration );
	}

	LLJoint::JointPriority* pose_priority = (LLJoint::JointPriority* )mCharacter->getAnimationData("Hand Pose Priority");
	if (pose_priority)
	{
		if (mJointMotionList->mMaxPriority >= *pose_priority)
		{
			mCharacter->setAnimationData("Hand Pose", &mJointMotionList->mHandPose);
			mCharacter->setAnimationData("Hand Pose Priority", &mJointMotionList->mMaxPriority);
		}
	}
	else
	{
		mCharacter->setAnimationData("Hand Pose", &mJointMotionList->mHandPose);
		mCharacter->setAnimationData("Hand Pose Priority", &mJointMotionList->mMaxPriority);
	}
}

//-----------------------------------------------------------------------------
// applyConstraints()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::applyConstraints(F32 time, U8* joint_mask)
{
	//TODO: investigate replacing spring simulation with critically damped motion

	// re-init constraints if skeleton has changed
	if (mCharacter->getSkeletonSerialNum() != mLastSkeletonSerialNum)
	{
		mLastSkeletonSerialNum = mCharacter->getSkeletonSerialNum();
		for (JointConstraint* constraintp : mConstraints)
		{
			initializeConstraint(constraintp);
		}
	}

	// apply constraints
	for (JointConstraint* constraintp : mConstraints)
	{
		applyConstraint(constraintp, time, joint_mask);
	}
}

//-----------------------------------------------------------------------------
// LLKeyframeMotion::onDeactivate()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::onDeactivate()
{
	for (JointConstraint* constraintp : mConstraints)
	{
		deactivateConstraint(constraintp);
	}
}

//-----------------------------------------------------------------------------
// setStopTime()
//-----------------------------------------------------------------------------
// time is in seconds since character creation
void LLKeyframeMotion::setStopTime(F32 time)
{
	LLMotion::setStopTime(time);

	if (mJointMotionList->mLoop && mJointMotionList->mLoopOutPoint != mJointMotionList->mDuration)
	{
		F32 start_loop_time = mActivationTimestamp + mJointMotionList->mLoopInPoint;
		F32 loop_fraction_time;
		if (mJointMotionList->mLoopOutPoint == mJointMotionList->mLoopInPoint)
		{
			loop_fraction_time = 0.f;
		}
		else
		{
			loop_fraction_time = fmod(time - start_loop_time, 
				mJointMotionList->mLoopOutPoint - mJointMotionList->mLoopInPoint);
		}
		mStopTimestamp = llmax(time, 
			(time - loop_fraction_time) + (mJointMotionList->mDuration - mJointMotionList->mLoopInPoint) - getEaseOutDuration());
	}
}

//-----------------------------------------------------------------------------
// initializeConstraint()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::initializeConstraint(JointConstraint* constraint)
{
	JointConstraintSharedData *shared_data = constraint->mSharedData;

	S32 joint_num;
	LLVector3 source_pos = mCharacter->getVolumePos(shared_data->mSourceConstraintVolume, shared_data->mSourceConstraintOffset);
	LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[0]);
	if ( !cur_joint )
	{
		return;
	}
	
	F32 source_pos_offset = dist_vec(source_pos, cur_joint->getWorldPosition());

	constraint->mTotalLength = constraint->mJointLengths[0] = dist_vec(cur_joint->getParent()->getWorldPosition(), source_pos);
	
	// grab joint lengths
	for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
	{
		cur_joint = getJointState(shared_data->mJointStateIndices[joint_num])->getJoint();
		if (!cur_joint)
		{
			return;
		}
		constraint->mJointLengths[joint_num] = dist_vec(cur_joint->getWorldPosition(), cur_joint->getParent()->getWorldPosition());
		constraint->mTotalLength += constraint->mJointLengths[joint_num];
	}

	// store fraction of total chain length so we know how to shear the entire chain towards the goal position
	for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
	{
		constraint->mJointLengthFractions[joint_num] = constraint->mJointLengths[joint_num] / constraint->mTotalLength;
	}

	// add last step in chain, from final joint to constraint position
	constraint->mTotalLength += source_pos_offset;

	constraint->mSourceVolume = mCharacter->findCollisionVolume(shared_data->mSourceConstraintVolume);
	constraint->mTargetVolume = mCharacter->findCollisionVolume(shared_data->mTargetConstraintVolume);
}

//-----------------------------------------------------------------------------
// activateConstraint()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::activateConstraint(JointConstraint* constraint)
{
	JointConstraintSharedData *shared_data = constraint->mSharedData;
	constraint->mActive = TRUE;
	S32 joint_num;

	// grab ground position if we need to
	if (shared_data->mConstraintTargetType == CONSTRAINT_TARGET_TYPE_GROUND)
	{
		LLVector3 source_pos = mCharacter->getVolumePos(shared_data->mSourceConstraintVolume, shared_data->mSourceConstraintOffset);
		LLVector3 ground_pos_agent;
		mCharacter->getGround(source_pos, ground_pos_agent, constraint->mGroundNorm);
		constraint->mGroundPos = mCharacter->getPosGlobalFromAgent(ground_pos_agent + shared_data->mTargetConstraintOffset);
	}

	for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
	{
		LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[joint_num]);
		if ( !cur_joint )
		{
			return;
		}
		constraint->mPositions[joint_num] = (cur_joint->getWorldPosition() - mPelvisp->getWorldPosition()) * ~mPelvisp->getWorldRotation();
	}

	constraint->mWeight = 1.f;
}

//-----------------------------------------------------------------------------
// deactivateConstraint()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::deactivateConstraint(JointConstraint *constraintp)
{
	if (constraintp->mSourceVolume)
	{
		constraintp->mSourceVolume->mUpdateXform = FALSE;
	}

	if (constraintp->mSharedData->mConstraintTargetType != CONSTRAINT_TARGET_TYPE_GROUND)
	{
		if (constraintp->mTargetVolume)
		{
			constraintp->mTargetVolume->mUpdateXform = FALSE;
		}
	}
	constraintp->mActive = FALSE;
}

//-----------------------------------------------------------------------------
// applyConstraint()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::applyConstraint(JointConstraint* constraint, F32 time, U8* joint_mask)
{
	JointConstraintSharedData *shared_data = constraint->mSharedData;
	if (!shared_data) return;

	LLVector3		positions[MAX_CHAIN_LENGTH];
	const F32*		joint_lengths = constraint->mJointLengths;
	LLVector3		velocities[MAX_CHAIN_LENGTH - 1];
	LLQuaternion	old_rots[MAX_CHAIN_LENGTH];
	S32				joint_num;

	if (time < shared_data->mEaseInStartTime)
	{
		return;
	}

	if (time > shared_data->mEaseOutStopTime)
	{
		if (constraint->mActive)
		{
			deactivateConstraint(constraint);
		}
		return;
	}

	if (!constraint->mActive || time < shared_data->mEaseInStopTime)
	{
		activateConstraint(constraint);
	}

	LLJoint* root_joint = getJoint(shared_data->mJointStateIndices[shared_data->mChainLength]);
	if (! root_joint) 
	{
		return;
	}
	
	LLVector3 root_pos = root_joint->getWorldPosition();
//	LLQuaternion root_rot = 
	root_joint->getParent()->getWorldRotation();
//	LLQuaternion inv_root_rot = ~root_rot;

//	LLVector3 current_source_pos = mCharacter->getVolumePos(shared_data->mSourceConstraintVolume, shared_data->mSourceConstraintOffset);

	//apply underlying keyframe animation to get nominal "kinematic" joint positions
	for (joint_num = 0; joint_num <= shared_data->mChainLength; joint_num++)
	{
		LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[joint_num]);
		if (!cur_joint)
		{
			return;
		}
		
		if (joint_mask[cur_joint->getJointNum()] >= (0xff >> (7 - getPriority())))
		{
			// skip constraint
			return;
		}
		old_rots[joint_num] = cur_joint->getRotation();
		cur_joint->setRotation(getJointState(shared_data->mJointStateIndices[joint_num])->getRotation());
	}


	LLVector3 keyframe_source_pos = mCharacter->getVolumePos(shared_data->mSourceConstraintVolume, shared_data->mSourceConstraintOffset);
	LLVector3 target_pos;

	switch(shared_data->mConstraintTargetType)
	{
	case CONSTRAINT_TARGET_TYPE_GROUND:
		target_pos = mCharacter->getPosAgentFromGlobal(constraint->mGroundPos);
//		LL_INFOS() << "Target Pos " << constraint->mGroundPos << " on " << mCharacter->findCollisionVolume(shared_data->mSourceConstraintVolume)->getName() << LL_ENDL;
		break;
	case CONSTRAINT_TARGET_TYPE_BODY:
		target_pos = mCharacter->getVolumePos(shared_data->mTargetConstraintVolume, shared_data->mTargetConstraintOffset);
		break;
	default:
		break;
	}
	
	LLVector3 norm;
	LLJoint *source_jointp = NULL;
	LLJoint *target_jointp = NULL;

	if (shared_data->mConstraintType == CONSTRAINT_TYPE_PLANE)
	{
		switch(shared_data->mConstraintTargetType)
		{
		case CONSTRAINT_TARGET_TYPE_GROUND:
			norm = constraint->mGroundNorm;
			break;
		case CONSTRAINT_TARGET_TYPE_BODY:
			target_jointp = mCharacter->findCollisionVolume(shared_data->mTargetConstraintVolume);
			if (target_jointp)
			{
				// *FIX: do proper normal calculation for stretched
				// spheres (inverse transpose)
				norm = target_pos - target_jointp->getWorldPosition();
			}

			if (norm.isExactlyZero())
			{
				source_jointp = mCharacter->findCollisionVolume(shared_data->mSourceConstraintVolume);
				norm = -1.f * shared_data->mSourceConstraintOffset;
				if (source_jointp)	
				{
					norm = norm * source_jointp->getWorldRotation();
				}
			}
			norm.normVec();
			break;
		default:
			norm.clearVec();
			break;
		}
		
		target_pos = keyframe_source_pos + (norm * ((target_pos - keyframe_source_pos) * norm));
	}

	if (constraint->mSharedData->mChainLength != 0 &&
		dist_vec_squared(root_pos, target_pos) * 0.95f > constraint->mTotalLength * constraint->mTotalLength)
	{
		constraint->mWeight = LLSmoothInterpolation::lerp(constraint->mWeight, 0.f, 0.1f);
	}
	else
	{
		constraint->mWeight = LLSmoothInterpolation::lerp(constraint->mWeight, 1.f, 0.3f);
	}

	F32 weight = constraint->mWeight * ((shared_data->mEaseOutStopTime == 0.f) ? 1.f : 
		llmin(clamp_rescale(time, shared_data->mEaseInStartTime, shared_data->mEaseInStopTime, 0.f, 1.f), 
		clamp_rescale(time, shared_data->mEaseOutStartTime, shared_data->mEaseOutStopTime, 1.f, 0.f)));

	LLVector3 source_to_target = target_pos - keyframe_source_pos;
	
	S32 max_iteration_count = ll_round(clamp_rescale(
										  mCharacter->getPixelArea(),
										  MAX_PIXEL_AREA_CONSTRAINTS,
										  MIN_PIXEL_AREA_CONSTRAINTS,
										  (F32)MAX_ITERATIONS,
										  (F32)MIN_ITERATIONS));

	if (shared_data->mChainLength)
	{
		LLJoint* end_joint = getJoint(shared_data->mJointStateIndices[0]);
		
		if (!end_joint)
		{
			return;
		}
		
		LLQuaternion end_rot = end_joint->getWorldRotation();

		// slam start and end of chain to the proper positions (rest of chain stays put)
		positions[0] = lerp(keyframe_source_pos, target_pos, weight);
		positions[shared_data->mChainLength] = root_pos;

		// grab keyframe-specified positions of joints	
		for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
		{
			LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[joint_num]);
			
			if (!cur_joint)
			{
				return;
			}
			
			LLVector3 kinematic_position = cur_joint->getWorldPosition() + 
				(source_to_target * constraint->mJointLengthFractions[joint_num]);

			// convert intermediate joint positions to world coordinates
			positions[joint_num] = ( constraint->mPositions[joint_num] * mPelvisp->getWorldRotation()) + mPelvisp->getWorldPosition();
			F32 time_constant = 1.f / clamp_rescale(constraint->mFixupDistanceRMS, 0.f, 0.5f, 0.2f, 8.f);
//			LL_INFOS() << "Interpolant " << LLSmoothInterpolation::getInterpolant(time_constant, FALSE) << " and fixup distance " << constraint->mFixupDistanceRMS << " on " << mCharacter->findCollisionVolume(shared_data->mSourceConstraintVolume)->getName() << LL_ENDL;
			positions[joint_num] = lerp(positions[joint_num], kinematic_position, 
				LLSmoothInterpolation::getInterpolant(time_constant, FALSE));
		}

		S32 iteration_count;
		for (iteration_count = 0; iteration_count < max_iteration_count; iteration_count++)
		{
			S32 num_joints_finished = 0;
			for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
			{
				// constraint to child
				LLVector3 acceleration = (positions[joint_num - 1] - positions[joint_num]) * 
					(dist_vec(positions[joint_num], positions[joint_num - 1]) - joint_lengths[joint_num - 1]) * JOINT_LENGTH_K;
				// constraint to parent
				acceleration  += (positions[joint_num + 1] - positions[joint_num]) * 
					(dist_vec(positions[joint_num + 1], positions[joint_num]) - joint_lengths[joint_num]) * JOINT_LENGTH_K;

				if (acceleration.magVecSquared() < MIN_ACCELERATION_SQUARED)
				{
					num_joints_finished++;
				}

				velocities[joint_num - 1] = velocities[joint_num - 1] * 0.7f;
				positions[joint_num] += velocities[joint_num - 1] + (acceleration * 0.5f);
				velocities[joint_num - 1] += acceleration;
			}

			if ((iteration_count >= MIN_ITERATION_COUNT) && 
				(num_joints_finished == shared_data->mChainLength - 1))
			{
//				LL_INFOS() << iteration_count << " iterations on " << 
//					mCharacter->findCollisionVolume(shared_data->mSourceConstraintVolume)->getName() << LL_ENDL;
				break;
			}
		}

		for (joint_num = shared_data->mChainLength; joint_num > 0; joint_num--)
		{
			LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[joint_num]);
			
			if (!cur_joint)
			{
				return;
			}
			LLJoint* child_joint = getJoint(shared_data->mJointStateIndices[joint_num - 1]);
			if (!child_joint)
			{
				return;
			}
			
			LLQuaternion parent_rot = cur_joint->getParent()->getWorldRotation();

			LLQuaternion cur_rot = cur_joint->getWorldRotation();
			LLQuaternion fixup_rot;
			
			LLVector3 target_at = positions[joint_num - 1] - positions[joint_num];
			LLVector3 current_at;

			// at bottom of chain, use point on collision volume, not joint position
			if (joint_num == 1)
			{
				current_at = mCharacter->getVolumePos(shared_data->mSourceConstraintVolume, shared_data->mSourceConstraintOffset) -
					cur_joint->getWorldPosition();
			}
			else
			{
				current_at = child_joint->getPosition() * cur_rot;
			}
			fixup_rot.shortestArc(current_at, target_at);

			LLQuaternion target_rot = cur_rot * fixup_rot;
			target_rot = target_rot * ~parent_rot;

			if (weight != 1.f)
			{
				LLQuaternion cur_rot = getJointState(shared_data->mJointStateIndices[joint_num])->getRotation();
				target_rot = nlerp(weight, cur_rot, target_rot);
			}

			getJointState(shared_data->mJointStateIndices[joint_num])->setRotation(target_rot);
			cur_joint->setRotation(target_rot);
		}

		LLQuaternion end_local_rot = end_rot * ~end_joint->getParent()->getWorldRotation();

		if (weight == 1.f)
		{
			getJointState(shared_data->mJointStateIndices[0])->setRotation(end_local_rot);
		}
		else
		{
			LLQuaternion cur_rot = getJointState(shared_data->mJointStateIndices[0])->getRotation();
			getJointState(shared_data->mJointStateIndices[0])->setRotation(nlerp(weight, cur_rot, end_local_rot));
		}

		// save simulated positions in pelvis-space and calculate total fixup distance
		constraint->mFixupDistanceRMS = 0.f;
		F32 delta_time = llmax(0.02f, llabs(time - mLastUpdateTime));
		for (joint_num = 1; joint_num < shared_data->mChainLength; joint_num++)
		{
			LLVector3 new_pos = (positions[joint_num] - mPelvisp->getWorldPosition()) * ~mPelvisp->getWorldRotation();
			constraint->mFixupDistanceRMS += dist_vec_squared(new_pos, constraint->mPositions[joint_num]) / delta_time;
			constraint->mPositions[joint_num] = new_pos;
		}
		constraint->mFixupDistanceRMS *= 1.f / (constraint->mTotalLength * (F32)(shared_data->mChainLength - 1));
		constraint->mFixupDistanceRMS = (F32) sqrt(constraint->mFixupDistanceRMS);

		//reset old joint rots
		for (joint_num = 0; joint_num <= shared_data->mChainLength; joint_num++)
		{
			LLJoint* cur_joint = getJoint(shared_data->mJointStateIndices[joint_num]);
			if (!cur_joint)
			{
				return;
			}

			cur_joint->setRotation(old_rots[joint_num]);
		}
	}
	// simple positional constraint (pelvis only)
	else if (getJointState(shared_data->mJointStateIndices[0])->getUsage() & LLJointState::POS)
	{
		LLVector3 delta = source_to_target * weight;
		LLPointer<LLJointState> current_joint_state = getJointState(shared_data->mJointStateIndices[0]);
		LLQuaternion parent_rot = current_joint_state->getJoint()->getParent()->getWorldRotation();
		delta = delta * ~parent_rot;
		current_joint_state->setPosition(current_joint_state->getJoint()->getPosition() + delta);
	}
}

//-----------------------------------------------------------------------------
// deserialize()
//
// allow_invalid_joints should be true when handling existing content, to avoid breakage.
// During upload, we should be more restrictive and reject such animations.
//-----------------------------------------------------------------------------
BOOL LLKeyframeMotion::deserialize(LLDataPacker& dp, const LLUUID& asset_id, bool allow_invalid_joints)
{
	BOOL old_version = FALSE;
	std::unique_ptr<LLKeyframeMotion::JointMotionList> joint_motion_list(new LLKeyframeMotion::JointMotionList);

	//-------------------------------------------------------------------------
	// get base priority
	//-------------------------------------------------------------------------
	S32 temp_priority;
	U16 version;
	U16 sub_version;

	if (!dp.unpackU16(version, "version"))
	{
		LL_WARNS() << "can't read version number for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	if (!dp.unpackU16(sub_version, "sub_version"))
	{
		LL_WARNS() << "can't read sub version number for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	if (version == 0 && sub_version == 1)
	{
		old_version = TRUE;
	}
	else if (version != KEYFRAME_MOTION_VERSION || sub_version != KEYFRAME_MOTION_SUBVERSION)
	{
#if LL_RELEASE
		LL_WARNS() << "Bad animation version " << version << "." << sub_version 
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
#else
		LL_ERRS() << "Bad animation version " << version << "." << sub_version
                  << " for animation " << asset_id << LL_ENDL;
#endif
	}

	if (!dp.unpackS32(temp_priority, "base_priority"))
	{
		LL_WARNS() << "can't read animation base_priority"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}
	joint_motion_list->mBasePriority = (LLJoint::JointPriority) temp_priority;

	if (joint_motion_list->mBasePriority >= LLJoint::ADDITIVE_PRIORITY)
	{
		joint_motion_list->mBasePriority = (LLJoint::JointPriority)((S32)LLJoint::ADDITIVE_PRIORITY-1);
		joint_motion_list->mMaxPriority = joint_motion_list->mBasePriority;
	}
	else if (joint_motion_list->mBasePriority < LLJoint::USE_MOTION_PRIORITY)
	{
		LL_WARNS() << "bad animation base_priority " << joint_motion_list->mBasePriority
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	//-------------------------------------------------------------------------
	// get duration
	//-------------------------------------------------------------------------
	if (!dp.unpackF32(joint_motion_list->mDuration, "duration"))
	{
		LL_WARNS() << "can't read duration"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}
	
	if (joint_motion_list->mDuration > MAX_ANIM_DURATION ||
	    !llfinite(joint_motion_list->mDuration))
	{
		LL_WARNS() << "invalid animation duration"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	//-------------------------------------------------------------------------
	// get emote (optional)
	//-------------------------------------------------------------------------
	if (!dp.unpackString(joint_motion_list->mEmoteName, "emote_name"))
	{
		LL_WARNS() << "can't read optional_emote_animation"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	if(joint_motion_list->mEmoteName==mID.asString())
	{
		LL_WARNS() << "Malformed animation mEmoteName==mID"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	//-------------------------------------------------------------------------
	// get loop
	//-------------------------------------------------------------------------
	if (!dp.unpackF32(joint_motion_list->mLoopInPoint, "loop_in_point") ||
	    !llfinite(joint_motion_list->mLoopInPoint))
	{
		LL_WARNS() << "can't read loop point"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	if (!dp.unpackF32(joint_motion_list->mLoopOutPoint, "loop_out_point") ||
	    !llfinite(joint_motion_list->mLoopOutPoint))
	{
		LL_WARNS() << "can't read loop point"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	if (!dp.unpackS32(joint_motion_list->mLoop, "loop"))
	{
		LL_WARNS() << "can't read loop"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	//SL-17206 hack to alter Female_land loop setting, while current behavior won't be changed serverside
	LLUUID const female_land_anim("ca1baf4d-0a18-5a1f-0330-e4bd1e71f09e");
	LLUUID const formal_female_land_anim("6a9a173b-61fa-3ad5-01fa-a851cfc5f66a");
	if (female_land_anim == asset_id || formal_female_land_anim == asset_id)
	{
		LL_WARNS() << "Animation(" << asset_id << ") won't be looped." << LL_ENDL;
		joint_motion_list->mLoop = FALSE;
	}

	//-------------------------------------------------------------------------
	// get easeIn and easeOut
	//-------------------------------------------------------------------------
	if (!dp.unpackF32(joint_motion_list->mEaseInDuration, "ease_in_duration") ||
	    !llfinite(joint_motion_list->mEaseInDuration))
	{
		LL_WARNS() << "can't read easeIn"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	if (!dp.unpackF32(joint_motion_list->mEaseOutDuration, "ease_out_duration") ||
	    !llfinite(joint_motion_list->mEaseOutDuration))
	{
		LL_WARNS() << "can't read easeOut"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	//-------------------------------------------------------------------------
	// get hand pose
	//-------------------------------------------------------------------------
	U32 word;
	if (!dp.unpackU32(word, "hand_pose"))
	{
		LL_WARNS() << "can't read hand pose"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}
	
	if(word > LLHandMotion::NUM_HAND_POSES)
	{
		LL_WARNS() << "invalid LLHandMotion::eHandPose index: " << word
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}
	
	joint_motion_list->mHandPose = (LLHandMotion::eHandPose)word;

	//-------------------------------------------------------------------------
	// get number of joint motions
	//-------------------------------------------------------------------------
	U32 num_motions = 0;
    S32 rotation_dupplicates = 0;
    S32 position_dupplicates = 0;
	if (!dp.unpackU32(num_motions, "num_joints"))
	{
		LL_WARNS() << "can't read number of joints"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	if (num_motions == 0)
	{
		LL_WARNS() << "no joints"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}
	else if (num_motions > LL_CHARACTER_MAX_ANIMATED_JOINTS)
	{
		LL_WARNS() << "too many joints"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	joint_motion_list->mJointMotionArray.clear();
	joint_motion_list->mJointMotionArray.reserve(num_motions);
	mJointStates.clear();
	mJointStates.reserve(num_motions);

	//-------------------------------------------------------------------------
	// initialize joint motions
	//-------------------------------------------------------------------------

	for(U32 i=0; i<num_motions; ++i)
	{
		JointMotion* joint_motion = new JointMotion;		
		joint_motion_list->mJointMotionArray.push_back(joint_motion);
		
		std::string joint_name;
		if (!dp.unpackString(joint_name, "joint_name"))
		{
			LL_WARNS() << "can't read joint name"
                       << " for animation " << asset_id << LL_ENDL;
			return FALSE;
		}

		if (joint_name == "mScreen" || joint_name == "mRoot")
		{
			LL_WARNS() << "attempted to animate special " << joint_name << " joint"
                       << " for animation " << asset_id << LL_ENDL;
			return FALSE;
		}
				
		//---------------------------------------------------------------------
		// find the corresponding joint
		//---------------------------------------------------------------------
		LLJoint *joint = mCharacter->getJoint( joint_name );
		if (joint)
		{
            S32 joint_num = joint->getJointNum();
			joint_name = joint->getName(); // canonical name in case this is an alias.
//			LL_INFOS() << "  joint: " << joint_name << LL_ENDL;
            if ((joint_num >= (S32)LL_CHARACTER_MAX_ANIMATED_JOINTS) || (joint_num < 0))
            {
                LL_WARNS() << "Joint will be omitted from animation: joint_num " << joint_num 
                           << " is outside of legal range [0-"
                           << LL_CHARACTER_MAX_ANIMATED_JOINTS << ") for joint " << joint->getName()
                           << " for animation " << asset_id << LL_ENDL;
                joint = NULL;
            }
		}
		else
		{
			LL_WARNS() << "invalid joint name: " << joint_name
                       << " for animation " << asset_id << LL_ENDL;
			if (!allow_invalid_joints)
			{
				return FALSE;
			}
		}

		joint_motion->mJointName = joint_name;
		
		LLPointer<LLJointState> joint_state = new LLJointState;
		mJointStates.push_back(joint_state);
		joint_state->setJoint( joint ); // note: can accept NULL
		joint_state->setUsage( 0 );

		//---------------------------------------------------------------------
		// get joint priority
		//---------------------------------------------------------------------
		S32 joint_priority;
		if (!dp.unpackS32(joint_priority, "joint_priority"))
		{
			LL_WARNS() << "can't read joint priority."
                       << " for animation " << asset_id << LL_ENDL;
			return FALSE;
		}

		if (joint_priority < LLJoint::USE_MOTION_PRIORITY)
		{
			LL_WARNS() << "joint priority unknown - too low."
                       << " for animation " << asset_id << LL_ENDL;
			return FALSE;
		}
		
		joint_motion->mPriority = (LLJoint::JointPriority)joint_priority;
		if (joint_priority != LLJoint::USE_MOTION_PRIORITY &&
		    joint_priority > joint_motion_list->mMaxPriority)
		{
			joint_motion_list->mMaxPriority = (LLJoint::JointPriority)joint_priority;
		}

		joint_state->setPriority((LLJoint::JointPriority)joint_priority);

		//---------------------------------------------------------------------
		// scan rotation curve header
		//---------------------------------------------------------------------
		if (!dp.unpackS32(joint_motion->mRotationCurve.mNumKeys, "num_rot_keys") || joint_motion->mRotationCurve.mNumKeys < 0)
		{
			LL_WARNS() << "can't read number of rotation keys"
                       << " for animation " << asset_id << LL_ENDL;
			return FALSE;
		}

		joint_motion->mRotationCurve.mInterpolationType = IT_LINEAR;
		if (joint_motion->mRotationCurve.mNumKeys != 0)
		{
			joint_state->setUsage(joint_state->getUsage() | LLJointState::ROT );
		}

		//---------------------------------------------------------------------
		// scan rotation curve keys
		//---------------------------------------------------------------------
		RotationCurve *rCurve = &joint_motion->mRotationCurve;

		for (S32 k = 0; k < joint_motion->mRotationCurve.mNumKeys; k++)
		{
			F32 time;
			U16 time_short;

			if (old_version)
			{
				if (!dp.unpackF32(time, "time") ||
				    !llfinite(time))
				{
					LL_WARNS() << "can't read rotation key (" << k << ")"
                               << " for animation " << asset_id << LL_ENDL;
					return FALSE;
				}

			}
			else
			{
				if (!dp.unpackU16(time_short, "time"))
				{
					LL_WARNS() << "can't read rotation key (" << k << ")"
                               << " for animation " << asset_id << LL_ENDL;
					return FALSE;
				}

				time = U16_to_F32(time_short, 0.f, joint_motion_list->mDuration);
				
				if (time < 0 || time > joint_motion_list->mDuration)
				{
					LL_WARNS() << "invalid frame time"
                               << " for animation " << asset_id << LL_ENDL;
					return FALSE;
				}
			}
			
			RotationKey rot_key;
			rot_key.mTime = time;
			LLVector3 rot_angles;
			U16 x, y, z;

			if (old_version)
			{
				if (!dp.unpackVector3(rot_angles, "rot_angles"))
				{
					LL_WARNS() << "can't read rot_angles in rotation key (" << k << ")" << LL_ENDL;
					return FALSE;
				}
				if (!rot_angles.isFinite())
				{
					LL_WARNS() << "non-finite angle in rotation key (" << k << ")" << LL_ENDL;
					return FALSE;
				}

				LLQuaternion::Order ro = StringToOrder("ZYX");
				rot_key.mRotation = mayaQ(rot_angles.mV[VX], rot_angles.mV[VY], rot_angles.mV[VZ], ro);
			}
			else
			{
				if (!dp.unpackU16(x, "rot_angle_x"))
				{
					LL_WARNS() << "can't read rot_angle_x in rotation key (" << k << ")" << LL_ENDL;
					return FALSE;
				}
				if (!dp.unpackU16(y, "rot_angle_y"))
				{
					LL_WARNS() << "can't read rot_angle_y in rotation key (" << k << ")" << LL_ENDL;
					return FALSE;
				}
				if (!dp.unpackU16(z, "rot_angle_z"))
				{
					LL_WARNS() << "can't read rot_angle_z in rotation key (" << k << ")" << LL_ENDL;
					return FALSE;
				}

				LLVector3 rot_vec;
				rot_vec.mV[VX] = U16_to_F32(x, -1.f, 1.f);
				rot_vec.mV[VY] = U16_to_F32(y, -1.f, 1.f);
				rot_vec.mV[VZ] = U16_to_F32(z, -1.f, 1.f);

				if(!rot_vec.isFinite())
				{
					LL_WARNS() << "non-finite angle in rotation key (" << k << ")"
						<< " for animation " << asset_id << LL_ENDL;
					return FALSE;
				}				
				rot_key.mRotation.unpackFromVector3(rot_vec);
			}

			if(!rot_key.mRotation.isFinite())
			{
				LL_WARNS() << "non-finite angle in rotation key (" << k << ")"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			rCurve->mKeys[time] = rot_key;
		}

        if (joint_motion->mRotationCurve.mNumKeys > joint_motion->mRotationCurve.mKeys.size())
        {
            rotation_dupplicates++;
            LL_INFOS() << "Motion: " << asset_id << " had dupplicate rotation keys that were removed" << LL_ENDL;
        }

		//---------------------------------------------------------------------
		// scan position curve header
		//---------------------------------------------------------------------
		if (!dp.unpackS32(joint_motion->mPositionCurve.mNumKeys, "num_pos_keys") || joint_motion->mPositionCurve.mNumKeys < 0)
		{
			LL_WARNS() << "can't read number of position keys"
                       << " for animation " << asset_id << LL_ENDL;
			return FALSE;
		}

		joint_motion->mPositionCurve.mInterpolationType = IT_LINEAR;
		if (joint_motion->mPositionCurve.mNumKeys != 0)
		{
			joint_state->setUsage(joint_state->getUsage() | LLJointState::POS );
		}

		//---------------------------------------------------------------------
		// scan position curve keys
		//---------------------------------------------------------------------
		PositionCurve *pCurve = &joint_motion->mPositionCurve;
		BOOL is_pelvis = joint_motion->mJointName == "mPelvis";
		for (S32 k = 0; k < joint_motion->mPositionCurve.mNumKeys; k++)
		{
			U16 time_short;
			PositionKey pos_key;

			if (old_version)
			{
				if (!dp.unpackF32(pos_key.mTime, "time") ||
				    !llfinite(pos_key.mTime))
				{
					LL_WARNS() << "can't read position key (" << k << ")"
                               << " for animation " << asset_id << LL_ENDL;
					return FALSE;
				}
			}
			else
			{
				if (!dp.unpackU16(time_short, "time"))
				{
					LL_WARNS() << "can't read position key (" << k << ")"
                               << " for animation " << asset_id << LL_ENDL;
					return FALSE;
				}

				pos_key.mTime = U16_to_F32(time_short, 0.f, joint_motion_list->mDuration);
			}

			if (old_version)
			{
				if (!dp.unpackVector3(pos_key.mPosition, "pos"))
				{
					LL_WARNS() << "can't read pos in position key (" << k << ")" << LL_ENDL;
					return FALSE;
				}
                
                //MAINT-6162
                pos_key.mPosition.mV[VX] = llclamp( pos_key.mPosition.mV[VX], -LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
                pos_key.mPosition.mV[VY] = llclamp( pos_key.mPosition.mV[VY], -LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
                pos_key.mPosition.mV[VZ] = llclamp( pos_key.mPosition.mV[VZ], -LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
                
			}
			else
			{
				U16 x, y, z;

				if (!dp.unpackU16(x, "pos_x"))
				{
					LL_WARNS() << "can't read pos_x in position key (" << k << ")" << LL_ENDL;
					return FALSE;
				}
				if (!dp.unpackU16(y, "pos_y"))
				{
					LL_WARNS() << "can't read pos_y in position key (" << k << ")" << LL_ENDL;
					return FALSE;
				}
				if (!dp.unpackU16(z, "pos_z"))
				{
					LL_WARNS() << "can't read pos_z in position key (" << k << ")" << LL_ENDL;
					return FALSE;
				}

				pos_key.mPosition.mV[VX] = U16_to_F32(x, -LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
				pos_key.mPosition.mV[VY] = U16_to_F32(y, -LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
				pos_key.mPosition.mV[VZ] = U16_to_F32(z, -LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
			}
			
			if(!pos_key.mPosition.isFinite())
			{
				LL_WARNS() << "non-finite position in key"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}
			
			pCurve->mKeys[pos_key.mTime] = pos_key;

			if (is_pelvis)
			{
				joint_motion_list->mPelvisBBox.addPoint(pos_key.mPosition);
			}
		}

        if (joint_motion->mPositionCurve.mNumKeys > joint_motion->mPositionCurve.mKeys.size())
        {
            position_dupplicates++;
        }

		joint_motion->mUsage = joint_state->getUsage();
	}

    if (rotation_dupplicates > 0)
    {
        LL_INFOS() << "Motion: " << asset_id << " had " << rotation_dupplicates << " dupplicate rotation keys that were removed" << LL_ENDL;
    }

    if (position_dupplicates > 0)
    {
        LL_INFOS() << "Motion: " << asset_id << " had " << position_dupplicates << " dupplicate position keys that were removed" << LL_ENDL;
    }

	//-------------------------------------------------------------------------
	// get number of constraints
	//-------------------------------------------------------------------------
	S32 num_constraints = 0;
	if (!dp.unpackS32(num_constraints, "num_constraints"))
	{
		LL_WARNS() << "can't read number of constraints"
                   << " for animation " << asset_id << LL_ENDL;
		return FALSE;
	}

	if (num_constraints > MAX_CONSTRAINTS || num_constraints < 0)
	{
		LL_WARNS() << "Bad number of constraints... ignoring: " << num_constraints
                   << " for animation " << asset_id << LL_ENDL;
	}
	else
	{
		//-------------------------------------------------------------------------
		// get constraints
		//-------------------------------------------------------------------------
		std::string str;
		for(S32 i = 0; i < num_constraints; ++i)
		{
			// read in constraint data
			std::unique_ptr<JointConstraintSharedData> constraintp(new JointConstraintSharedData);
			U8 byte = 0;

			if (!dp.unpackU8(byte, "chain_length"))
			{
				LL_WARNS() << "can't read constraint chain length"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}
			constraintp->mChainLength = (S32) byte;

			if((U32)constraintp->mChainLength > joint_motion_list->getNumJointMotions())
			{
				LL_WARNS() << "invalid constraint chain length"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			if (!dp.unpackU8(byte, "constraint_type"))
			{
				LL_WARNS() << "can't read constraint type"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}
			
			if( byte >= NUM_CONSTRAINT_TYPES )
			{
				LL_WARNS() << "invalid constraint type"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}
			constraintp->mConstraintType = (EConstraintType)byte;

			const S32 BIN_DATA_LENGTH = 16;
			U8 bin_data[BIN_DATA_LENGTH+1];
			if (!dp.unpackBinaryDataFixed(bin_data, BIN_DATA_LENGTH, "source_volume"))
			{
				LL_WARNS() << "can't read source volume name"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			bin_data[BIN_DATA_LENGTH] = 0; // Ensure null termination
			str = (char*)bin_data;
			constraintp->mSourceConstraintVolume = mCharacter->getCollisionVolumeID(str);
			if (constraintp->mSourceConstraintVolume == -1)
			{
				LL_WARNS() << "not a valid source constraint volume " << str
						   << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			if (!dp.unpackVector3(constraintp->mSourceConstraintOffset, "source_offset"))
			{
				LL_WARNS() << "can't read constraint source offset"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}
			
			if( !(constraintp->mSourceConstraintOffset.isFinite()) )
			{
				LL_WARNS() << "non-finite constraint source offset"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}
			
			if (!dp.unpackBinaryDataFixed(bin_data, BIN_DATA_LENGTH, "target_volume"))
			{
				LL_WARNS() << "can't read target volume name"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			bin_data[BIN_DATA_LENGTH] = 0; // Ensure null termination
			str = (char*)bin_data;
			if (str == "GROUND")
			{
				// constrain to ground
				constraintp->mConstraintTargetType = CONSTRAINT_TARGET_TYPE_GROUND;
			}
			else
			{
				constraintp->mConstraintTargetType = CONSTRAINT_TARGET_TYPE_BODY;
				constraintp->mTargetConstraintVolume = mCharacter->getCollisionVolumeID(str);
				if (constraintp->mTargetConstraintVolume == -1)
				{
					LL_WARNS() << "not a valid target constraint volume " << str
							   << " for animation " << asset_id << LL_ENDL;
					return FALSE;
				}
			}

			if (!dp.unpackVector3(constraintp->mTargetConstraintOffset, "target_offset"))
			{
				LL_WARNS() << "can't read constraint target offset"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			if( !(constraintp->mTargetConstraintOffset.isFinite()) )
			{
				LL_WARNS() << "non-finite constraint target offset"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}
			
			if (!dp.unpackVector3(constraintp->mTargetConstraintDir, "target_dir"))
			{
				LL_WARNS() << "can't read constraint target direction"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			if( !(constraintp->mTargetConstraintDir.isFinite()) )
			{
				LL_WARNS() << "non-finite constraint target direction"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			if (!constraintp->mTargetConstraintDir.isExactlyZero())
			{
				constraintp->mUseTargetOffset = TRUE;
	//			constraintp->mTargetConstraintDir *= constraintp->mSourceConstraintOffset.magVec();
			}

			if (!dp.unpackF32(constraintp->mEaseInStartTime, "ease_in_start") || !llfinite(constraintp->mEaseInStartTime))
			{
				LL_WARNS() << "can't read constraint ease in start time"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			if (!dp.unpackF32(constraintp->mEaseInStopTime, "ease_in_stop") || !llfinite(constraintp->mEaseInStopTime))
			{
				LL_WARNS() << "can't read constraint ease in stop time"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			if (!dp.unpackF32(constraintp->mEaseOutStartTime, "ease_out_start") || !llfinite(constraintp->mEaseOutStartTime))
			{
				LL_WARNS() << "can't read constraint ease out start time"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			if (!dp.unpackF32(constraintp->mEaseOutStopTime, "ease_out_stop") || !llfinite(constraintp->mEaseOutStopTime))
			{
				LL_WARNS() << "can't read constraint ease out stop time"
                           << " for animation " << asset_id << LL_ENDL;
				return FALSE;
			}

			LLJoint* joint = mCharacter->findCollisionVolume(constraintp->mSourceConstraintVolume);
			// get joint to which this collision volume is attached
			if (!joint)
			{
				return FALSE;
			}

			constraintp->mJointStateIndices = new S32[constraintp->mChainLength + 1]; // note: mChainLength is size-limited - comes from a byte

			for (S32 i = 0; i < constraintp->mChainLength + 1; i++)
			{
				LLJoint* parent = joint->getParent();
				if (!parent)
				{
					LL_WARNS() << "Joint with no parent: " << joint->getName()
                               << " Emote: " << joint_motion_list->mEmoteName
                               << " for animation " << asset_id << LL_ENDL;
					return FALSE;
				}
				joint = parent;
				constraintp->mJointStateIndices[i] = -1;
				for (U32 j = 0; j < joint_motion_list->getNumJointMotions(); j++)
				{
					LLJoint* constraint_joint = getJoint(j);
					
					if ( !constraint_joint )
					{
						LL_WARNS() << "Invalid joint " << j
                                   << " for animation " << asset_id << LL_ENDL;
						return FALSE;
					}
					
					if(constraint_joint == joint)
					{
						constraintp->mJointStateIndices[i] = (S32)j;
						break;
					}
				}
				if (constraintp->mJointStateIndices[i] < 0 )
				{
					LL_WARNS() << "No joint index for constraint " << i
                               << " for animation " << asset_id << LL_ENDL;
					return FALSE;
				}
			}

			joint_motion_list->mConstraints.push_front(constraintp.release());
		}
	}

	// *FIX: support cleanup of old keyframe data
    mJointMotionList = joint_motion_list.release(); // release from unique_ptr to member;
	LLKeyframeDataCache::addKeyframeData(getID(),  mJointMotionList);
	mAssetStatus = ASSET_LOADED;

	setupPose();

	return true;
}

//-----------------------------------------------------------------------------
// serialize()
//-----------------------------------------------------------------------------
BOOL LLKeyframeMotion::serialize(LLDataPacker& dp) const
{
	BOOL success = true;

	LL_DEBUGS("BVH") << "serializing" << LL_ENDL;

	success &= dp.packU16(KEYFRAME_MOTION_VERSION, "version");
	success &= dp.packU16(KEYFRAME_MOTION_SUBVERSION, "sub_version");
	success &= dp.packS32(mJointMotionList->mBasePriority, "base_priority");
	success &= dp.packF32(mJointMotionList->mDuration, "duration");
	success &= dp.packString(mJointMotionList->mEmoteName, "emote_name");
	success &= dp.packF32(mJointMotionList->mLoopInPoint, "loop_in_point");
	success &= dp.packF32(mJointMotionList->mLoopOutPoint, "loop_out_point");
	success &= dp.packS32(mJointMotionList->mLoop, "loop");
	success &= dp.packF32(mJointMotionList->mEaseInDuration, "ease_in_duration");
	success &= dp.packF32(mJointMotionList->mEaseOutDuration, "ease_out_duration");
	success &= dp.packU32(mJointMotionList->mHandPose, "hand_pose");
	success &= dp.packU32(mJointMotionList->getNumJointMotions(), "num_joints");

    LL_DEBUGS("BVH") << "version " << KEYFRAME_MOTION_VERSION << LL_ENDL;
    LL_DEBUGS("BVH") << "sub_version " << KEYFRAME_MOTION_SUBVERSION << LL_ENDL;
    LL_DEBUGS("BVH") << "base_priority " << mJointMotionList->mBasePriority << LL_ENDL;
	LL_DEBUGS("BVH") << "duration " << mJointMotionList->mDuration << LL_ENDL;
	LL_DEBUGS("BVH") << "emote_name " << mJointMotionList->mEmoteName << LL_ENDL;
	LL_DEBUGS("BVH") << "loop_in_point " << mJointMotionList->mLoopInPoint << LL_ENDL;
	LL_DEBUGS("BVH") << "loop_out_point " << mJointMotionList->mLoopOutPoint << LL_ENDL;
	LL_DEBUGS("BVH") << "loop " << mJointMotionList->mLoop << LL_ENDL;
	LL_DEBUGS("BVH") << "ease_in_duration " << mJointMotionList->mEaseInDuration << LL_ENDL;
	LL_DEBUGS("BVH") << "ease_out_duration " << mJointMotionList->mEaseOutDuration << LL_ENDL;
	LL_DEBUGS("BVH") << "hand_pose " << mJointMotionList->mHandPose << LL_ENDL;
	LL_DEBUGS("BVH") << "num_joints " << mJointMotionList->getNumJointMotions() << LL_ENDL;

	for (U32 i = 0; i < mJointMotionList->getNumJointMotions(); i++)
	{
		JointMotion* joint_motionp = mJointMotionList->getJointMotion(i);
		success &= dp.packString(joint_motionp->mJointName, "joint_name");
		success &= dp.packS32(joint_motionp->mPriority, "joint_priority");
        success &= dp.packS32(joint_motionp->mRotationCurve.mKeys.size(), "num_rot_keys");

        LL_DEBUGS("BVH") << "Joint " << i
            << " name: " << joint_motionp->mJointName
            << " Rotation keys: " << joint_motionp->mRotationCurve.mKeys.size()
            << " Position keys: " << joint_motionp->mPositionCurve.mKeys.size() << LL_ENDL;
        for (RotationCurve::key_map_t::value_type& rot_pair : joint_motionp->mRotationCurve.mKeys)
		{
			RotationKey& rot_key = rot_pair.second;
			U16 time_short = F32_to_U16(rot_key.mTime, 0.f, mJointMotionList->mDuration);
			success &= dp.packU16(time_short, "time");

			LLVector3 rot_angles = rot_key.mRotation.packToVector3();
			
			U16 x, y, z;
			rot_angles.quantize16(-1.f, 1.f, -1.f, 1.f);
			x = F32_to_U16(rot_angles.mV[VX], -1.f, 1.f);
			y = F32_to_U16(rot_angles.mV[VY], -1.f, 1.f);
			z = F32_to_U16(rot_angles.mV[VZ], -1.f, 1.f);
			success &= dp.packU16(x, "rot_angle_x");
			success &= dp.packU16(y, "rot_angle_y");
			success &= dp.packU16(z, "rot_angle_z");

			LL_DEBUGS("BVH") << "  rot: t " << rot_key.mTime << " angles " << rot_angles.mV[VX] <<","<< rot_angles.mV[VY] <<","<< rot_angles.mV[VZ] << LL_ENDL;
		}

		success &= dp.packS32(joint_motionp->mPositionCurve.mKeys.size(), "num_pos_keys");
		for (PositionCurve::key_map_t::value_type& pos_pair : joint_motionp->mPositionCurve.mKeys)
		{
			PositionKey& pos_key = pos_pair.second;
			U16 time_short = F32_to_U16(pos_key.mTime, 0.f, mJointMotionList->mDuration);
			success &= dp.packU16(time_short, "time");

			U16 x, y, z;
			pos_key.mPosition.quantize16(-LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET, -LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
			x = F32_to_U16(pos_key.mPosition.mV[VX], -LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
			y = F32_to_U16(pos_key.mPosition.mV[VY], -LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
			z = F32_to_U16(pos_key.mPosition.mV[VZ], -LL_MAX_PELVIS_OFFSET, LL_MAX_PELVIS_OFFSET);
			success &= dp.packU16(x, "pos_x");
			success &= dp.packU16(y, "pos_y");
			success &= dp.packU16(z, "pos_z");

			LL_DEBUGS("BVH") << "  pos: t " << pos_key.mTime << " pos " << pos_key.mPosition.mV[VX] <<","<< pos_key.mPosition.mV[VY] <<","<< pos_key.mPosition.mV[VZ] << LL_ENDL;
		}
	}	

	success &= dp.packS32(mJointMotionList->mConstraints.size(), "num_constraints");
    LL_DEBUGS("BVH") << "num_constraints " << mJointMotionList->mConstraints.size() << LL_ENDL;
	for (JointConstraintSharedData* shared_constraintp : mJointMotionList->mConstraints)
	{
		success &= dp.packU8(shared_constraintp->mChainLength, "chain_length");
		success &= dp.packU8(shared_constraintp->mConstraintType, "constraint_type");
		char source_volume[16]; /* Flawfinder: ignore */
		snprintf(source_volume, sizeof(source_volume), "%s",	/* Flawfinder: ignore */
				 mCharacter->findCollisionVolume(shared_constraintp->mSourceConstraintVolume)->getName().c_str()); 
        
		success &= dp.packBinaryDataFixed((U8*)source_volume, 16, "source_volume");
		success &= dp.packVector3(shared_constraintp->mSourceConstraintOffset, "source_offset");
		char target_volume[16];	/* Flawfinder: ignore */
		if (shared_constraintp->mConstraintTargetType == CONSTRAINT_TARGET_TYPE_GROUND)
		{
			snprintf(target_volume,sizeof(target_volume), "%s", "GROUND");	/* Flawfinder: ignore */
		}
		else
		{
			snprintf(target_volume, sizeof(target_volume),"%s", /* Flawfinder: ignore */
					 mCharacter->findCollisionVolume(shared_constraintp->mTargetConstraintVolume)->getName().c_str());	
		}
		success &= dp.packBinaryDataFixed((U8*)target_volume, 16, "target_volume");
		success &= dp.packVector3(shared_constraintp->mTargetConstraintOffset, "target_offset");
		success &= dp.packVector3(shared_constraintp->mTargetConstraintDir, "target_dir");
		success &= dp.packF32(shared_constraintp->mEaseInStartTime, "ease_in_start");
		success &= dp.packF32(shared_constraintp->mEaseInStopTime, "ease_in_stop");
		success &= dp.packF32(shared_constraintp->mEaseOutStartTime, "ease_out_start");
		success &= dp.packF32(shared_constraintp->mEaseOutStopTime, "ease_out_stop");

        LL_DEBUGS("BVH") << "  chain_length " << shared_constraintp->mChainLength << LL_ENDL;
        LL_DEBUGS("BVH") << "  constraint_type " << (S32)shared_constraintp->mConstraintType << LL_ENDL;
        LL_DEBUGS("BVH") << "  source_volume " << source_volume << LL_ENDL;
        LL_DEBUGS("BVH") << "  source_offset " << shared_constraintp->mSourceConstraintOffset << LL_ENDL;
        LL_DEBUGS("BVH") << "  target_volume " << target_volume << LL_ENDL;
        LL_DEBUGS("BVH") << "  target_offset " << shared_constraintp->mTargetConstraintOffset << LL_ENDL;
        LL_DEBUGS("BVH") << "  target_dir " << shared_constraintp->mTargetConstraintDir << LL_ENDL;
        LL_DEBUGS("BVH") << "  ease_in_start " << shared_constraintp->mEaseInStartTime << LL_ENDL;
        LL_DEBUGS("BVH") << "  ease_in_stop " << shared_constraintp->mEaseInStopTime << LL_ENDL;
        LL_DEBUGS("BVH") << "  ease_out_start " << shared_constraintp->mEaseOutStartTime << LL_ENDL;
        LL_DEBUGS("BVH") << "  ease_out_stop " << shared_constraintp->mEaseOutStopTime << LL_ENDL;
	}

	return success;
}

//-----------------------------------------------------------------------------
// getFileSize()
//-----------------------------------------------------------------------------
U32	LLKeyframeMotion::getFileSize()
{
	// serialize into a dummy buffer to calculate required size
	LLDataPackerBinaryBuffer dp;
	serialize(dp);

	return dp.getCurrentSize();
}

//-----------------------------------------------------------------------------
// dumpToFile()
//-----------------------------------------------------------------------------
bool LLKeyframeMotion::dumpToFile(const std::string& name)
{
	bool succ = false;
    if (isLoaded())
    {
        std::string outfile_base;
        if (!name.empty())
        {
            outfile_base = name;
        }
        else if (!getName().empty())
        {
            outfile_base = getName();
        }
        else
        {
            const LLUUID& id = getID();
            outfile_base = id.asString();
        }

		if (gDirUtilp->getExtension(outfile_base).empty())
		{
			outfile_base += ".anim";
		}
		std::string outfilename;
		if (gDirUtilp->getDirName(outfile_base).empty())
		{
			outfilename = gDirUtilp->getExpandedFilename(LL_PATH_LOGS,outfile_base);
		}
		else
		{
			outfilename = outfile_base;
		}
        if (LLFile::isfile(outfilename))
        {
			LL_WARNS() << outfilename << " already exists, write failed" << LL_ENDL;
            return false;
        }

        S32 file_size = getFileSize();
        U8* buffer = new U8[file_size];

        LL_DEBUGS("BVH") << "Dumping " << outfilename << LL_ENDL;
        LLDataPackerBinaryBuffer dp(buffer, file_size);
        if (serialize(dp))
        {
            LLAPRFile outfile;
            outfile.open(outfilename, LL_APR_WPB);
            if (outfile.getFileHandle())
            {
                S32 wrote_bytes = outfile.write(buffer, file_size);
				succ = (wrote_bytes == file_size);
            }
        }
        delete [] buffer;
    }
	return succ;
}

//-----------------------------------------------------------------------------
// getPelvisBBox()
//-----------------------------------------------------------------------------
const LLBBoxLocal &LLKeyframeMotion::getPelvisBBox()
{
	return mJointMotionList->mPelvisBBox;
}

//-----------------------------------------------------------------------------
// setPriority()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::setPriority(S32 priority)
{
	if (mJointMotionList) 
	{
		S32 priority_delta = priority - mJointMotionList->mBasePriority;
		mJointMotionList->mBasePriority = (LLJoint::JointPriority)priority;
		mJointMotionList->mMaxPriority = mJointMotionList->mBasePriority;

		for (U32 i = 0; i < mJointMotionList->getNumJointMotions(); i++)
		{
			JointMotion* joint_motion = mJointMotionList->getJointMotion(i);			
			joint_motion->mPriority = (LLJoint::JointPriority)llclamp(
				(S32)joint_motion->mPriority + priority_delta,
				(S32)LLJoint::LOW_PRIORITY, 
				(S32)LLJoint::HIGHEST_PRIORITY);
			getJointState(i)->setPriority(joint_motion->mPriority);
		}
	}
}

//-----------------------------------------------------------------------------
// setEmote()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::setEmote(const LLUUID& emote_id)
{
	const char* emote_name = gAnimLibrary.animStateToString(emote_id);
	if (emote_name)
	{
		mJointMotionList->mEmoteName = emote_name;
	}
	else
	{
		mJointMotionList->mEmoteName = "";
	}
}

//-----------------------------------------------------------------------------
// setEaseIn()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::setEaseIn(F32 ease_in)
{
	if (mJointMotionList)
	{
		mJointMotionList->mEaseInDuration = llmax(ease_in, 0.f);
	}
}

//-----------------------------------------------------------------------------
// setEaseOut()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::setEaseOut(F32 ease_in)
{
	if (mJointMotionList)
	{
		mJointMotionList->mEaseOutDuration = llmax(ease_in, 0.f);
	}
}


//-----------------------------------------------------------------------------
// flushKeyframeCache()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::flushKeyframeCache()
{
	// TODO: Make this safe to do
// 	LLKeyframeDataCache::clear();
}

//-----------------------------------------------------------------------------
// setLoop()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::setLoop(BOOL loop)
{
	if (mJointMotionList) 
	{
		mJointMotionList->mLoop = loop; 
		mSendStopTimestamp = F32_MAX;
	}
}


//-----------------------------------------------------------------------------
// setLoopIn()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::setLoopIn(F32 in_point)
{
	if (mJointMotionList)
	{
		mJointMotionList->mLoopInPoint = in_point; 
		
		// set up loop keys
		for (U32 i = 0; i < mJointMotionList->getNumJointMotions(); i++)
		{
			JointMotion* joint_motion = mJointMotionList->getJointMotion(i);
			
			PositionCurve* pos_curve = &joint_motion->mPositionCurve;
			RotationCurve* rot_curve = &joint_motion->mRotationCurve;
			ScaleCurve* scale_curve = &joint_motion->mScaleCurve;
			
			pos_curve->mLoopInKey.mTime = mJointMotionList->mLoopInPoint;
			rot_curve->mLoopInKey.mTime = mJointMotionList->mLoopInPoint;
			scale_curve->mLoopInKey.mTime = mJointMotionList->mLoopInPoint;

			pos_curve->mLoopInKey.mPosition = pos_curve->getValue(mJointMotionList->mLoopInPoint, mJointMotionList->mDuration);
			rot_curve->mLoopInKey.mRotation = rot_curve->getValue(mJointMotionList->mLoopInPoint, mJointMotionList->mDuration);
			scale_curve->mLoopInKey.mScale = scale_curve->getValue(mJointMotionList->mLoopInPoint, mJointMotionList->mDuration);
		}
	}
}

//-----------------------------------------------------------------------------
// setLoopOut()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::setLoopOut(F32 out_point)
{
	if (mJointMotionList)
	{
		mJointMotionList->mLoopOutPoint = out_point; 
		
		// set up loop keys
		for (U32 i = 0; i < mJointMotionList->getNumJointMotions(); i++)
		{
			JointMotion* joint_motion = mJointMotionList->getJointMotion(i);
			
			PositionCurve* pos_curve = &joint_motion->mPositionCurve;
			RotationCurve* rot_curve = &joint_motion->mRotationCurve;
			ScaleCurve* scale_curve = &joint_motion->mScaleCurve;
			
			pos_curve->mLoopOutKey.mTime = mJointMotionList->mLoopOutPoint;
			rot_curve->mLoopOutKey.mTime = mJointMotionList->mLoopOutPoint;
			scale_curve->mLoopOutKey.mTime = mJointMotionList->mLoopOutPoint;

			pos_curve->mLoopOutKey.mPosition = pos_curve->getValue(mJointMotionList->mLoopOutPoint, mJointMotionList->mDuration);
			rot_curve->mLoopOutKey.mRotation = rot_curve->getValue(mJointMotionList->mLoopOutPoint, mJointMotionList->mDuration);
			scale_curve->mLoopOutKey.mScale = scale_curve->getValue(mJointMotionList->mLoopOutPoint, mJointMotionList->mDuration);
		}
	}
}

//-----------------------------------------------------------------------------
// onLoadComplete()
//-----------------------------------------------------------------------------
void LLKeyframeMotion::onLoadComplete(const LLUUID& asset_uuid,
									  LLAssetType::EType type,
									  void* user_data, S32 status, LLExtStat ext_status)
{
	LLUUID* id = (LLUUID*)user_data;
		
	std::vector<LLCharacter* >::iterator char_iter = LLCharacter::sInstances.begin();

	while(char_iter != LLCharacter::sInstances.end() &&
			(*char_iter)->getID() != *id)
	{
		++char_iter;
	}
	
	delete id;

	if (char_iter == LLCharacter::sInstances.end())
	{
		return;
	}

	LLCharacter* character = *char_iter;

	// look for an existing instance of this motion
	LLKeyframeMotion* motionp = static_cast<LLKeyframeMotion*> (character->findMotion(asset_uuid));
	if (motionp)
	{
		if (0 == status)
		{
			if (motionp->mAssetStatus == ASSET_LOADED)
			{
				// asset already loaded
				return;
			}
			LLFileSystem file(asset_uuid, type, LLFileSystem::READ);
			S32 size = file.getSize();
			
			U8* buffer = new U8[size];
			file.read((U8*)buffer, size);	/*Flawfinder: ignore*/

			LL_DEBUGS("Animation") << "Loading keyframe data for: " << motionp->getName() << ":" << motionp->getID() << " (" << size << " bytes)" << LL_ENDL;
			
			LLDataPackerBinaryBuffer dp(buffer, size);
			if (motionp->deserialize(dp, asset_uuid))
			{
				motionp->mAssetStatus = ASSET_LOADED;
			}
			else
			{
				LL_WARNS() << "Failed to decode asset for animation " << motionp->getName() << ":" << motionp->getID() << LL_ENDL;
				motionp->mAssetStatus = ASSET_FETCH_FAILED;
			}
			
			delete[] buffer;
		}
		else
		{
			LL_WARNS() << "Failed to load asset for animation " << motionp->getName() << ":" << motionp->getID() << LL_ENDL;
			motionp->mAssetStatus = ASSET_FETCH_FAILED;
		}
	}
	else
	{
		LL_WARNS() << "No existing motion for asset data. UUID: " << asset_uuid << LL_ENDL;
	}
}

//--------------------------------------------------------------------
// LLKeyframeDataCache::dumpDiagInfo()
//--------------------------------------------------------------------
void LLKeyframeDataCache::dumpDiagInfo()
{
	// keep track of totals
	U32 total_size = 0;

	char buf[1024];		/* Flawfinder: ignore */

	LL_INFOS() << "-----------------------------------------------------" << LL_ENDL;
	LL_INFOS() << "       Global Motion Table (DEBUG only)" << LL_ENDL;
	LL_INFOS() << "-----------------------------------------------------" << LL_ENDL;

	// print each loaded mesh, and it's memory usage
	for (keyframe_data_map_t::value_type& data_pair : sKeyframeDataMap)
	{
		U32 joint_motion_kb;

		LLKeyframeMotion::JointMotionList *motion_list_p = data_pair.second;

		LL_INFOS() << "Motion: " << data_pair.first << LL_ENDL;

		joint_motion_kb = motion_list_p->dumpDiagInfo();

		total_size += joint_motion_kb;
	}

	LL_INFOS() << "-----------------------------------------------------" << LL_ENDL;
	LL_INFOS() << "Motions\tTotal Size" << LL_ENDL;
	snprintf(buf, sizeof(buf), "%d\t\t%d bytes", (S32)sKeyframeDataMap.size(), total_size );		/* Flawfinder: ignore */
	LL_INFOS() << buf << LL_ENDL;
	LL_INFOS() << "-----------------------------------------------------" << LL_ENDL;
}


//--------------------------------------------------------------------
// LLKeyframeDataCache::addKeyframeData()
//--------------------------------------------------------------------
void LLKeyframeDataCache::addKeyframeData(const LLUUID& id, LLKeyframeMotion::JointMotionList* joint_motion_listp)
{
	sKeyframeDataMap[id] = joint_motion_listp;
}

//--------------------------------------------------------------------
// LLKeyframeDataCache::removeKeyframeData()
//--------------------------------------------------------------------
void LLKeyframeDataCache::removeKeyframeData(const LLUUID& id)
{
	keyframe_data_map_t::iterator found_data = sKeyframeDataMap.find(id);
	if (found_data != sKeyframeDataMap.end())
	{
		delete found_data->second;
		sKeyframeDataMap.erase(found_data);
	}
}

//--------------------------------------------------------------------
// LLKeyframeDataCache::getKeyframeData()
//--------------------------------------------------------------------
LLKeyframeMotion::JointMotionList* LLKeyframeDataCache::getKeyframeData(const LLUUID& id)
{
	keyframe_data_map_t::iterator found_data = sKeyframeDataMap.find(id);
	if (found_data == sKeyframeDataMap.end())
	{
		return NULL;
	}
	return found_data->second;
}

//--------------------------------------------------------------------
// ~LLKeyframeDataCache::LLKeyframeDataCache()
//--------------------------------------------------------------------
LLKeyframeDataCache::~LLKeyframeDataCache()
{
	clear();
}

//-----------------------------------------------------------------------------
// clear()
//-----------------------------------------------------------------------------
void LLKeyframeDataCache::clear()
{
	for_each(sKeyframeDataMap.begin(), sKeyframeDataMap.end(), DeletePairedPointer());
	sKeyframeDataMap.clear();
}

//-----------------------------------------------------------------------------
// JointConstraint()
//-----------------------------------------------------------------------------
LLKeyframeMotion::JointConstraint::JointConstraint(JointConstraintSharedData* shared_data) : mSharedData(shared_data) 
{
	mWeight = 0.f;
	mTotalLength = 0.f;
	mActive = FALSE;
	mSourceVolume = NULL;
	mTargetVolume = NULL;
	mFixupDistanceRMS = 0.f;

	for (S32 i=0; i<MAX_CHAIN_LENGTH; ++i)
	{
		mJointLengths[i] = 0.f;
		mJointLengthFractions[i] = 0.f;
	}
}

//-----------------------------------------------------------------------------
// ~JointConstraint()
//-----------------------------------------------------------------------------
LLKeyframeMotion::JointConstraint::~JointConstraint()
{
}

// End