File: modelanimation_segments.cpp

package info (click to toggle)
freespace2 24.2.0%2Brepack-1
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 43,716 kB
  • sloc: cpp: 595,001; ansic: 21,741; python: 1,174; sh: 457; makefile: 248; xml: 181
file content (1478 lines) | stat: -rw-r--r-- 54,877 bytes parent folder | download | duplicates (2)
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
#include "model/animation/modelanimation_segments.h"

#include "render/3d.h"

namespace animation {

	ModelAnimationSegment* ModelAnimationSegmentSerial::copy() const {
		auto newCopy = new ModelAnimationSegmentSerial();
		for (const auto& segment : m_segments) {
			newCopy->m_segments.push_back(std::shared_ptr<ModelAnimationSegment>(segment->copy()));
		}
		return newCopy;
	}

	void ModelAnimationSegmentSerial::recalculate(ModelAnimationSubmodelBuffer& base, ModelAnimationSubmodelBuffer& currentAnimDelta, polymodel_instance* pmi) {
		float& duration = m_duration[pmi->id];
		duration = 0.0f;

		for (const auto& segment : m_segments) {
			segment->recalculate(base, currentAnimDelta, pmi);

			duration += segment->getDuration(pmi->id);

			//To properly recalculate, we actually need to fully calculate the previous' segment's final delta
			segment->calculateAnimation(base, segment->getDuration(pmi->id), pmi->id);
			segment->calculateAnimation(currentAnimDelta, segment->getDuration(pmi->id), pmi->id);
		}
	}

	void ModelAnimationSegmentSerial::calculateAnimation(ModelAnimationSubmodelBuffer& base, float time, int pmi_id) const {
		size_t animationCnt = 0;
		while (time >= 0.0f && animationCnt < m_segments.size()) {
			float timeLocal = time;
			//Make sure that each segment actually stops at its end
			if (timeLocal > m_segments[animationCnt]->getDuration(pmi_id))
				timeLocal = m_segments[animationCnt]->getDuration(pmi_id);
			m_segments[animationCnt]->calculateAnimation(base, timeLocal, pmi_id);

			time -= m_segments[animationCnt]->getDuration(pmi_id);
			animationCnt++;
		}
	}

	void ModelAnimationSegmentSerial::executeAnimation(const ModelAnimationSubmodelBuffer& state, float timeboundLower, float timeboundUpper, ModelAnimationDirection direction, int pmi_id) {
		for (const auto& segment : m_segments) {
			if (timeboundLower < segment->getDuration(pmi_id)) {
				segment->executeAnimation(state, fmaxf(0.0f, timeboundLower), fminf(timeboundUpper, segment->getDuration(pmi_id)), direction, pmi_id);
			}

			timeboundLower -= segment->getDuration(pmi_id);
			timeboundUpper -= segment->getDuration(pmi_id);

			if (timeboundUpper < 0)
				return;
		}
	}

	void ModelAnimationSegmentSerial::exchangeSubmodelPointers(ModelAnimationSet& replaceWith) {
		for (const auto& segment : m_segments)
			segment->exchangeSubmodelPointers(replaceWith);
	}

	void ModelAnimationSegmentSerial::addSegment(std::shared_ptr<ModelAnimationSegment> segment) {
		m_segments.push_back(std::move(segment));
	}
	
	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentSerial::parser(ModelAnimationParseHelper* data) {
		auto submodelOverride = ModelAnimationParseHelper::parseSubmodel();

		ignore_white_space();
		auto segment = std::shared_ptr<ModelAnimationSegmentSerial>(new ModelAnimationSegmentSerial());

		while (!optional_string("+End Segment")) {
			if (submodelOverride)
				data->parentSubmodel = submodelOverride;

			segment->addSegment(data->parseSegment());
			ignore_white_space();
		}

		return segment;
	}


	ModelAnimationSegment* ModelAnimationSegmentParallel::copy() const {
		auto newCopy = new ModelAnimationSegmentParallel();
		for (const auto& segment : m_segments) {
			newCopy->m_segments.push_back(std::shared_ptr<ModelAnimationSegment>(segment->copy()));
		}
		return newCopy;
	}

	void ModelAnimationSegmentParallel::recalculate(ModelAnimationSubmodelBuffer& base, ModelAnimationSubmodelBuffer& currentAnimDelta, polymodel_instance* pmi) {
		float& duration = m_duration[pmi->id];
		duration = 0.0f;

		for (const auto& segment : m_segments) {
			ModelAnimationSubmodelBuffer baseCopy = base;
			segment->recalculate(baseCopy, currentAnimDelta, pmi);

			//recalculate total duration if necessary
			float newDur = segment->getDuration(pmi->id);
			duration = newDur > duration ? newDur : duration;
		}

	}

	void ModelAnimationSegmentParallel::calculateAnimation(ModelAnimationSubmodelBuffer& base, float time, int pmi_id) const {
		for (const auto& segment : m_segments) {
			float timeLocal = time;
			//Make sure that no segment runs over its length
			if (timeLocal > segment->getDuration(pmi_id))
				timeLocal = segment->getDuration(pmi_id);
			
			segment->calculateAnimation(base, timeLocal, pmi_id);
		}
	}

	void ModelAnimationSegmentParallel::executeAnimation(const ModelAnimationSubmodelBuffer& state, float timeboundLower, float timeboundUpper, ModelAnimationDirection direction, int pmi_id) {
		for (const auto& segment : m_segments) {
			if (timeboundLower < segment->getDuration(pmi_id)) {
				segment->executeAnimation(state, timeboundLower, fminf(timeboundUpper, segment->getDuration(pmi_id)), direction, pmi_id);
			}
		}
	}

	void ModelAnimationSegmentParallel::exchangeSubmodelPointers(ModelAnimationSet& replaceWith) {
		for (const auto& segment : m_segments)
			segment->exchangeSubmodelPointers(replaceWith);
	}

	void ModelAnimationSegmentParallel::addSegment(std::shared_ptr<ModelAnimationSegment> segment) {
		m_segments.push_back(std::move(segment));
	}
	
	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentParallel::parser(ModelAnimationParseHelper* data) {
		auto submodelOverride = ModelAnimationParseHelper::parseSubmodel();

		ignore_white_space();
		auto segment = std::shared_ptr<ModelAnimationSegmentParallel>(new ModelAnimationSegmentParallel());

		while (!optional_string("+End Segment")) {
			if (submodelOverride)
				data->parentSubmodel = submodelOverride;

			segment->addSegment(data->parseSegment());
			ignore_white_space();
		}

		return segment;
	}


	ModelAnimationSegmentWait::ModelAnimationSegmentWait(float time) : m_time(time) { }

	ModelAnimationSegment* ModelAnimationSegmentWait::copy() const {
		return new ModelAnimationSegmentWait(*this);
	}
	
	void ModelAnimationSegmentWait::recalculate(ModelAnimationSubmodelBuffer& /*base*/, ModelAnimationSubmodelBuffer& /*currentAnimDelta*/, polymodel_instance* pmi) {
		m_duration[pmi->id] = m_time;
	};
	
	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentWait::parser(ModelAnimationParseHelper* /*data*/) {
		required_string("+Time:");
		float time = 0.0f;
		stuff_float(&time);
		auto segment = std::shared_ptr<ModelAnimationSegmentWait>(new ModelAnimationSegmentWait(time));

		return segment;
	}

	ModelAnimationSegmentSetOrientation::ModelAnimationSegmentSetOrientation(std::shared_ptr<ModelAnimationSubmodel> submodel, const angles& angle, ModelAnimationCoordinateRelation isAngleRelative) :
		m_submodel(std::move(submodel)), m_targetAngle(angle), m_relationType(isAngleRelative) { }
	ModelAnimationSegmentSetOrientation::ModelAnimationSegmentSetOrientation(std::shared_ptr<ModelAnimationSubmodel> submodel, const matrix& orientation, ModelAnimationCoordinateRelation isAngleRelative) :
			m_submodel(std::move(submodel)), m_targetOrientation(orientation), m_relationType(isAngleRelative) { }
		
	ModelAnimationSegment* ModelAnimationSegmentSetOrientation::copy() const {
		return new ModelAnimationSegmentSetOrientation(*this);
	}

	void ModelAnimationSegmentSetOrientation::recalculate(ModelAnimationSubmodelBuffer& base, ModelAnimationSubmodelBuffer& currentAnimDelta, polymodel_instance* pmi) {
		int pmi_id = pmi->id;
		if (m_relationType == ModelAnimationCoordinateRelation::RELATIVE_COORDS) {
			if (m_targetAngle) {
				vm_angles_2_matrix(&m_instances[pmi_id].rot, &(*m_targetAngle));
			}
			else if (m_targetOrientation) {
				m_instances[pmi_id].rot = *m_targetOrientation;
			}
		}
		else {
			//In Absolute mode we need to undo the previously applied rotation to make sure we actually end up at the target rotation despite having only a delta we output, as opposed to just overwriting the value
			matrix unrotate, target;
			const ModelAnimationData<>& submodel = (m_relationType == ModelAnimationCoordinateRelation::ABSOLUTE_COORDS ? base[m_submodel].data : currentAnimDelta[m_submodel].data);

			vm_copy_transpose(&unrotate, &submodel.orientation);

			if (m_targetAngle) {
				vm_angles_2_matrix(&target, &(*m_targetAngle));
			}
			else if (m_targetOrientation) {
				target = *m_targetOrientation;
			}

			vm_matrix_x_matrix(&m_instances[pmi_id].rot, &target, &unrotate);
		}

		m_duration[pmi_id] = 0.0f;
	}

	void ModelAnimationSegmentSetOrientation::calculateAnimation(ModelAnimationSubmodelBuffer& base, float /*time*/, int pmi_id) const {
		ModelAnimationData<true> data;
		data.orientation = m_instances.at(pmi_id).rot;

		base[m_submodel].data.applyDelta(data);
		base[m_submodel].modified = true;
	}

	void ModelAnimationSegmentSetOrientation::exchangeSubmodelPointers(ModelAnimationSet& replaceWith) {
		m_submodel = replaceWith.getSubmodel(m_submodel);
	}
	
	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentSetOrientation::parser(ModelAnimationParseHelper* data) {
		angles angle;

		required_string("+Angle:");
		stuff_angles_deg_phb(&angle);
		ModelAnimationCoordinateRelation relationType = ModelAnimationParseHelper::parseCoordinateRelation();

		auto submodel = ModelAnimationParseHelper::parseSubmodel();

		if (!submodel) {
			if (data->parentSubmodel) 
				submodel = data->parentSubmodel;
			else
				error_display(1, "Set Orientation has no target submodel!");
		}

		auto segment = std::shared_ptr<ModelAnimationSegmentSetOrientation>(new ModelAnimationSegmentSetOrientation(submodel, angle, relationType));

		return segment;
	}


	ModelAnimationSegmentSetOffset::ModelAnimationSegmentSetOffset(std::shared_ptr<ModelAnimationSubmodel> submodel, const vec3d& offset, ModelAnimationCoordinateRelation isOffsetRelative) :
		  m_submodel(std::move(submodel)), m_target(offset), m_relationType(isOffsetRelative) { }

	ModelAnimationSegment* ModelAnimationSegmentSetOffset::copy() const {
		return new ModelAnimationSegmentSetOffset(*this);
	}

	void ModelAnimationSegmentSetOffset::recalculate(ModelAnimationSubmodelBuffer& base, ModelAnimationSubmodelBuffer& currentAnimDelta, polymodel_instance* pmi) {
		int pmi_id = pmi->id;
		if (m_relationType == ModelAnimationCoordinateRelation::RELATIVE_COORDS) {
			m_instances[pmi_id].offset = m_target;
		}
		else {
			//In Absolute mode we need to undo the previously applied translation to make sure we actually end up at the target despite having only a delta we output, as opposed to just overwriting the value
			const ModelAnimationData<>& submodel = (m_relationType == ModelAnimationCoordinateRelation::ABSOLUTE_COORDS ? base[m_submodel].data : currentAnimDelta[m_submodel].data);
			m_instances[pmi_id].offset = m_target - submodel.position;
		}

		m_duration[pmi_id] = 0.0f;
	}

	void ModelAnimationSegmentSetOffset::calculateAnimation(ModelAnimationSubmodelBuffer& base, float /*time*/, int pmi_id) const {
		ModelAnimationData<true> data;
		data.position = m_instances.at(pmi_id).offset;

		base[m_submodel].data.applyDelta(data);
		base[m_submodel].modified = true;
	}

	void ModelAnimationSegmentSetOffset::exchangeSubmodelPointers(ModelAnimationSet& replaceWith) {
		m_submodel = replaceWith.getSubmodel(m_submodel);
	}

	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentSetOffset::parser(ModelAnimationParseHelper* data) {
		vec3d target;

		required_string("+Target:");
		stuff_vec3d(&target);
		ModelAnimationCoordinateRelation relationType = ModelAnimationParseHelper::parseCoordinateRelation();

		auto submodel = ModelAnimationParseHelper::parseSubmodel();

		if (!submodel) {
			if (data->parentSubmodel)
				submodel = data->parentSubmodel;
			else
				error_display(1, "Set Offset has no target submodel!");
		}

		auto segment = std::shared_ptr<ModelAnimationSegmentSetOffset>(new ModelAnimationSegmentSetOffset(submodel, target, relationType));

		return segment;
	}


	ModelAnimationSegmentSetAngle::ModelAnimationSegmentSetAngle(std::shared_ptr<ModelAnimationSubmodel> submodel, float angle) :
		m_submodel(std::move(submodel)), m_angle(angle) { }

	ModelAnimationSegment* ModelAnimationSegmentSetAngle::copy() const {
		return new ModelAnimationSegmentSetAngle(*this);
	}

	void ModelAnimationSegmentSetAngle::recalculate(ModelAnimationSubmodelBuffer& /*base*/, ModelAnimationSubmodelBuffer& /*currentAnimDelta*/, polymodel_instance* pmi) {
		angles angs = vmd_zero_angles;
		auto submodel_info = m_submodel->findSubmodel(pmi).second;
		if (submodel_info == nullptr) {
			m_rot = vmd_identity_matrix;
			m_duration[pmi->id] = 0.0f;
			return;
		}

		switch (submodel_info->rotation_axis_id)
		{
			case MOVEMENT_AXIS_X:
			angs.p = m_angle;
			vm_angles_2_matrix(&m_rot, &angs);
			break;

		case MOVEMENT_AXIS_Y:
			angs.h = m_angle;
			vm_angles_2_matrix(&m_rot, &angs);
			break;

		case MOVEMENT_AXIS_Z:
			angs.b = m_angle;
			vm_angles_2_matrix(&m_rot, &angs);
			break;

		default:
			vm_quaternion_rotate(&m_rot, m_angle, &submodel_info->rotation_axis);
			break;
		}

		m_duration[pmi->id] = 0.0f;
	}

	void ModelAnimationSegmentSetAngle::calculateAnimation(ModelAnimationSubmodelBuffer& base, float /*time*/, int /*pmi_id*/) const {
		ModelAnimationData<true> data;
		data.orientation = m_rot;
		
		base[m_submodel].data.applyDelta(data);
		base[m_submodel].modified = true;
	}

	void ModelAnimationSegmentSetAngle::exchangeSubmodelPointers(ModelAnimationSet& replaceWith) {
		m_submodel = replaceWith.getSubmodel(m_submodel);
	}
	
	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentSetAngle::parser(ModelAnimationParseHelper* data) {
		float angle;

		required_string("+Angle:");
		stuff_float(&angle);

		auto submodel = ModelAnimationParseHelper::parseSubmodel();

		if (!submodel) {
			if (data->parentSubmodel)
				submodel = data->parentSubmodel;
			else
				error_display(1, "Set Angle has no target submodel!");
		}

		auto segment = std::shared_ptr<ModelAnimationSegmentSetAngle>(new ModelAnimationSegmentSetAngle(submodel, fl_radians(angle)));

		return segment;
	}


	static constexpr float angles::*pbh[] = { &angles::p, &angles::b, &angles::h };

	ModelAnimationSegmentRotation::ModelAnimationSegmentRotation(std::shared_ptr<ModelAnimationSubmodel> submodel, tl::optional<angles> targetAngle, tl::optional<angles> velocity, tl::optional<float> time, tl::optional<angles> acceleration, ModelAnimationCoordinateRelation relationType) :
		m_submodel(std::move(submodel)), m_targetAngle(targetAngle), m_velocity(velocity), m_time(time), m_acceleration(acceleration), m_relationType(relationType) { }

	ModelAnimationSegment* ModelAnimationSegmentRotation::copy() const {
		return new ModelAnimationSegmentRotation(*this);
	}

	void ModelAnimationSegmentRotation::recalculate(ModelAnimationSubmodelBuffer& base, ModelAnimationSubmodelBuffer& currentAnimDelta, polymodel_instance* pmi) {
		Assertion(!(m_targetAngle.has_value() ^ m_velocity.has_value() ^ m_time.has_value()), "Tried to run over- or underdefined rotation. Define exactly two out of 'time', 'velocity', and 'angle'!");

		instance_data& instanceData = m_instances[pmi->id];
		auto submodel_info = m_submodel->findSubmodel(pmi).second;
		if (submodel_info == nullptr) {
			m_duration[pmi->id] = 0.0f;
			return;
		}

		if (m_targetAngle) { //If we have an angle specified, use it.
			if (m_relationType != ModelAnimationCoordinateRelation::RELATIVE_COORDS) {
				const ModelAnimationData<>& submodel = (m_relationType == ModelAnimationCoordinateRelation::ABSOLUTE_COORDS ? base[m_submodel].data : currentAnimDelta[m_submodel].data);

				matrix orientTransp, target, diff;
				const angles& targetAngle = *m_targetAngle;
				vm_copy_transpose(&orientTransp, &submodel.orientation);
				vm_angles_2_matrix(&target, &targetAngle);
				vm_matrix_x_matrix(&diff, &target, &orientTransp);
				vm_extract_angles_matrix_alternate(&instanceData.m_actualTarget, &diff);
			}
			else
				instanceData.m_actualTarget = *m_targetAngle;
		}
		else { //If we don't have an angle specified, calculate it. This implies we must have velocity and time.
			const angles& v = *m_velocity;
			const float& t = *m_time;

			if (m_acceleration) { //Consider acceleration to calculate the angle
				//Let the following equations define our accelerated and braked movement, under the assumption that 2 * ta <= t.
				//d : distance, v : max velocity, a : acceleration, t : total time, ta : time spent accelerating (and breaking)
				//v = a * ta
				//d = v * (t - 2 * ta) + 1/2 * 2 * a * ta^2
				//this simplifies to d = (v(a * t - v))/a and ta = v / a
				//if 2 * ta <= t does not hold, it's just d = 1/2 * 2 * a * (t/2)^2 -> this implies that the acceleration is too small to reach the target velocity within the specified time.
				angles a = *m_acceleration;
				angles at;

				for (float angles::* i : pbh) {
					a.*i = copysignf(a.*i, v.*i);
					at.*i = fmaxf(v.*i / a.*i, t / 2.0f);
				}
				instanceData.m_actualAccel = a;
				instanceData.m_accelTime = at;

				for (float angles::* i : pbh)
					instanceData.m_actualTarget.*i = 2.0f * v.*i / a.*i <= t ? (v.*i * (a.*i * t - v.*i)) / a.*i: a.*i * (t * t / 4.0f);

			}
			else { //Don't consider acceleration, assume instant velocity.
				for (float angles::* i : pbh)
					instanceData.m_actualTarget.*i = v.*i * t;
			}
		}

		if (m_velocity) { //If we have velocity specified, use it.
			instanceData.m_actualVelocity = *m_velocity;
		}
		else { //If we don't have velocity specified, calculate it. This implies we must have an angle and time.
			const float& t = *m_time;
			const angles& d = instanceData.m_actualTarget;

			if (m_acceleration) { //Consider acceleration to calculate the velocity
				//Assume equations from calc angles case, but solve for ta and v now, under the assumption that these roots have a real solution.
				//v = 1/2*(|a|*t-sqrt(|a|)*sqrt(|a|*t^2-4*|d|))*sign(d) and ta = 1/2*(t-(sqrt(|a|*t^2-4*|d|)/sqrt(|a|)))
				//If the roots don't have a real solution, it's v = a * t/2, and ta = 1/2*t -> this implies that the acceleration is too small to reach the target distance within the specified time.

				angles a = *m_acceleration;
				for (float angles::* i : pbh)
					a.*i = copysignf(a.*i, d.*i);
				instanceData.m_actualAccel = a;

				angles at{ 0,0,0 };

				for (float angles::* i : pbh) {
					float a_abs = fabsf(a.*i);
					float radicant = a_abs * t * t - 4 * fabsf(d.*i);
					if (radicant >= 0) {
						instanceData.m_actualVelocity.*i = copysignf(0.5f * (a_abs * t - sqrtf(a_abs) * sqrtf(radicant)), d.*i);
						at.*i = 0.5f * (t - (sqrtf(radicant) / sqrtf(a_abs)));
					}
					else {
						instanceData.m_actualVelocity.*i = a.*i * t / 2.0f;
						at.*i = t / 2.0f;
					}
				}

				instanceData.m_accelTime = at;
			}
			else { //Don't consider acceleration, assume instant velocity.
				for (float angles::* i : pbh)
					instanceData.m_actualVelocity.*i = d.*i / t;
			}

		}

		if (m_time) { //If we have time specified, use it.
			const float& time = *m_time;
			m_duration[pmi->id] = time;

			angles actualTime{ 0,0,0 };
			for (float angles::* i : pbh)
				actualTime.*i = time;

			instanceData.m_actualTime = actualTime;

			if (time <= 0.0f) {

				Error(LOCATION, "Tried to rotate submodel %s in %.2f seconds. Rotation time must be positive and nonzero!", submodel_info->name, time);
			}
		}
		else { //Calc time
			float& duration = m_duration[pmi->id] = 0.0f;

			angles& v = instanceData.m_actualVelocity;
			const angles& d = instanceData.m_actualTarget;

			angles actualAccel{ 0,0,0 };
			angles accelTime{ 0,0,0 };
			angles actualTime{ 0,0,0 };

			for (float angles::* i : pbh) {
				if (d.*i != 0.0f) {
					if (v.*i == 0.0f) {
						Warning(LOCATION, "Tried to rotate submodel %s by %.2f, but velocity was 0! Rotating with velocity 1...", submodel_info->name, d.*i);
						v.*i = 1;
					}

					v.*i = copysignf(v.*i, d.*i);

					float durationAxis = 0.0f;

					if (m_acceleration) { //Consider acceleration to calculate the time
						//Assume equations from calc angles case, but solve for ta and t now, with the resulting ta <= t / 2.
						//t = v/a+d/v and ta = v/a
						//If thus d/v < v/a, it's t = 2*sqrt(d/a), and ta = 1/2*t -> this implies that the acceleration is too small to reach the target velocity within the specified distance.
						float a = copysignf((*m_acceleration).*i, d.*i);
						actualAccel.*i = a;

						float va = v.*i / a;
						float dv = d.*i / v.*i;

						if (dv >= va) {
							durationAxis = va + dv;
							accelTime.*i = va;
						}
						else {
							durationAxis = 2.0f * sqrtf(d.*i / a);
							accelTime.*i = durationAxis / 2.0f;
						}
					}
					else {
						durationAxis = d.*i / v.*i;
					}

					duration = duration < durationAxis ? durationAxis : duration;
					actualTime.*i = durationAxis;
				}
			}
			
			if (m_acceleration) {
				instanceData.m_actualAccel = actualAccel;
				instanceData.m_accelTime = accelTime;
			}

			instanceData.m_actualTime = actualTime;
		}
	}

	void ModelAnimationSegmentRotation::calculateAnimation(ModelAnimationSubmodelBuffer& base, float time, int pmi_id) const {
		const instance_data& instanceData = m_instances.at(pmi_id);

		angles currentRot{ 0,0,0 };

		if (instanceData.m_actualAccel) {
			const angles& a = *instanceData.m_actualAccel;
			const angles& at = *instanceData.m_accelTime;
			const angles& v = instanceData.m_actualVelocity;
			const angles& t = instanceData.m_actualTime;

			for (float angles::* i : pbh) {
				float acceltime1 = fminf(time, at.*i);
				currentRot.*i = 0.5f * a.*i * acceltime1 * acceltime1;
				
				float lineartime = fminf(time - at.*i, t.*i - 2.0f * at.*i);
				if (lineartime > 0) {
					currentRot.*i += v.*i * lineartime;
				}

				float acceltime2 = fminf(time - (t.*i - at.*i), at.*i);
				if (acceltime2 > 0) {
					//Cap this to 0, as it could get negative if it rotates "longer than its duration" (which happens when a different axis takes longer to rotate)
					float accel2dist = at.*i * a.*i * acceltime2 - 0.5f * a.*i * acceltime2 * acceltime2;
					if(std::signbit(a.*i))
						currentRot.*i += fminf(accel2dist, 0.0f);
					else
						currentRot.*i += fmaxf(accel2dist, 0.0f);
				}
			}
		}
		else {
			for (float angles::* i : pbh)// Linear Rotation
				currentRot.*i = instanceData.m_actualVelocity.*i * time;
		}

		for (float angles::* i : pbh) { // Clamp rotation to actual target
			if (instanceData.m_actualTarget.*i < 0) {
				currentRot.*i = fmaxf(instanceData.m_actualTarget.*i, currentRot.*i);
			}
			else {
				currentRot.*i = fminf(instanceData.m_actualTarget.*i, currentRot.*i);
			}
		}

		matrix orient;
		vm_angles_2_matrix(&orient, &currentRot);

		ModelAnimationData<true> delta;
		delta.orientation = orient;

		base[m_submodel].data.applyDelta(delta);
		base[m_submodel].modified = true;
	}

	void ModelAnimationSegmentRotation::exchangeSubmodelPointers(ModelAnimationSet& replaceWith) {
		m_submodel = replaceWith.getSubmodel(m_submodel);
	}
	
	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentRotation::parser(ModelAnimationParseHelper* data) {
		tl::optional<angles> angle, velocity, acceleration;
		tl::optional<float> time;
		ModelAnimationCoordinateRelation relationType = ModelAnimationCoordinateRelation::RELATIVE_COORDS;

		if (optional_string("+Angle:")) {
			angles parse;
			stuff_angles_deg_phb(&parse);
			angle = std::move(parse);
			relationType = ModelAnimationParseHelper::parseCoordinateRelation();
		}

		if (optional_string("+Velocity:")) {
			angles parse;
			stuff_angles_deg_phb(&parse);
			velocity = std::move(parse);
		}

		if (optional_string("+Time:")) {
			float parse;
			stuff_float(&parse);
			time = parse;
		}

		if (angle.has_value() ^ velocity.has_value() ^ time.has_value()) {
			error_display(1, "Rotation must have exactly two values out of angle, velocity and time specified!");
		}

		if (optional_string("+Acceleration:")) {
			angles parse;
			stuff_angles_deg_phb(&parse);
			acceleration = std::move(parse);
		}

		auto submodel = ModelAnimationParseHelper::parseSubmodel();
		if (!submodel) {
			if (data->parentSubmodel)
				submodel = data->parentSubmodel;
			else
				error_display(1, "Rotation has no target submodel!");
		}

		auto segment = std::shared_ptr<ModelAnimationSegmentRotation>(new ModelAnimationSegmentRotation(submodel, angle, velocity, time, acceleration, relationType));

		return segment;
	}


	ModelAnimationSegmentAxisRotation::ModelAnimationSegmentAxisRotation(std::shared_ptr<ModelAnimationSubmodel> submodel, tl::optional<float> targetAngle, tl::optional<float> velocity, tl::optional<float> time, tl::optional<float> acceleration, const vec3d& axis) :
			m_submodel(std::move(submodel)), m_targetAngle(targetAngle), m_velocity(velocity), m_time(time), m_acceleration(acceleration) {
		vm_vec_copy_normalize(&m_axis, &axis);
	}

	ModelAnimationSegment* ModelAnimationSegmentAxisRotation::copy() const {
		return new ModelAnimationSegmentAxisRotation(*this);
	}

	void ModelAnimationSegmentAxisRotation::recalculate(ModelAnimationSubmodelBuffer& /*base*/, ModelAnimationSubmodelBuffer& /*currentAnimDelta*/, polymodel_instance* pmi) {
		Assertion(!(m_targetAngle.has_value() ^ m_velocity.has_value() ^ m_time.has_value()), "Tried to run over- or underdefined rotation. Define exactly two out of 'time', 'velocity', and 'angle'!");

		instance_data& instanceData = m_instances[pmi->id];
		auto submodel_info = m_submodel->findSubmodel(pmi).second;
		if (submodel_info == nullptr) {
			m_duration[pmi->id] = 0.0f;
			return;
		}

		if (m_targetAngle) { //If we have an angle specified, use it.
			instanceData.m_actualTarget = *m_targetAngle;
		}
		else { //If we don't have an angle specified, calculate it. This implies we must have velocity and time.
			const float& v = *m_velocity;
			const float& t = *m_time;

			if (m_acceleration) { //Consider acceleration to calculate the angle
				//Let the following equations define our accelerated and braked movement, under the assumption that 2 * ta <= t.
				//d : distance, v : max velocity, a : acceleration, t : total time, ta : time spent accelerating (and breaking)
				//v = a * ta
				//d = v * (t - 2 * ta) + 1/2 * 2 * a * ta^2
				//this simplifies to d = (v(a * t - v))/a and ta = v / a
				//if 2 * ta <= t does not hold, it's just d = 1/2 * 2 * a * (t/2)^2 -> this implies that the acceleration is too small to reach the target velocity within the specified time.
				float a = *m_acceleration;
				a = copysignf(a, v);
				instanceData.m_actualAccel = a;
				instanceData.m_accelTime = fmaxf(v / a, t / 2.0f);
				
				instanceData.m_actualTarget = 2.0f * v / a <= t ? (v * (a * t - v)) / a: a * (t * t / 4.0f);

			}
			else { //Don't consider acceleration, assume instant velocity.
				instanceData.m_actualTarget = v * t;
			}
		}

		if (m_velocity) { //If we have velocity specified, use it.
			instanceData.m_actualVelocity = *m_velocity;
		}
		else { //If we don't have velocity specified, calculate it. This implies we must have an angle and time.
			const float& t = *m_time;
			const float& d = instanceData.m_actualTarget;

			if (m_acceleration) { //Consider acceleration to calculate the velocity
				//Assume equations from calc angles case, but solve for ta and v now, under the assumption that these roots have a real solution.
				//v = 1/2*(|a|*t-sqrt(|a|)*sqrt(|a|*t^2-4*|d|))*sign(d) and ta = 1/2*(t-(sqrt(|a|*t^2-4*|d|)/sqrt(|a|)))
				//If the roots don't have a real solution, it's v = a * t/2, and ta = 1/2*t -> this implies that the acceleration is too small to reach the target distance within the specified time.

				float a = *m_acceleration;
				float at;
				a = copysignf(a, d);
				instanceData.m_actualAccel = a;
				
				float a_abs = fabsf(a);
				float radicant = a_abs * t * t - 4 * fabsf(d);
				if (radicant >= 0) {
					instanceData.m_actualVelocity = copysignf(0.5f * (a_abs * t - sqrtf(a_abs) * sqrtf(radicant)), d);
					at = 0.5f * (t - (sqrtf(radicant) / sqrtf(a_abs)));
				}
				else {
					instanceData.m_actualVelocity = a * t / 2.0f;
					at = t / 2.0f;
				}
				
				instanceData.m_accelTime = at;
			}
			else { //Don't consider acceleration, assume instant velocity.
				instanceData.m_actualVelocity = d / t;
			}

		}

		if (m_time) { //If we have time specified, use it.
			const float& time = *m_time;
			m_duration[pmi->id] = time;

			instanceData.m_actualTime = time;

			if (time <= 0.0f) {
				Error(LOCATION, "Tried to rotate submodel %s in %.2f seconds. Rotation time must be positive and nonzero!", submodel_info->name, time);
			}
		}
		else { //Calc time
			float& duration = m_duration[pmi->id] = 0.0f;

			float& v = instanceData.m_actualVelocity;
			const float& d = instanceData.m_actualTarget;

			float actualAccel = 0;
			float accelTime = 0;
			
			if (d != 0.0f) {
				if (v == 0.0f) {
					Warning(LOCATION, "Tried to rotate submodel %s by %.2f, but velocity was 0! Rotating with velocity 1...", submodel_info->name, d);
					v = 1;
				}

				v = copysignf(v, d);

				if (m_acceleration) { //Consider acceleration to calculate the time
					//Assume equations from calc angles case, but solve for ta and t now, with the resulting ta <= t / 2.
					//t = v/a+d/v and ta = v/a
					//If thus d/v < v/a, it's t = 2*sqrt(d/a), and ta = 1/2*t -> this implies that the acceleration is too small to reach the target velocity within the specified distance.
					float a = copysignf(*m_acceleration, d);
					actualAccel = a;

					float va = v / a;
					float dv = d / v;

					if (dv >= va) {
						duration = va + dv;
						accelTime = va;
					}
					else {
						duration = 2.0f * sqrtf(d / a);
						accelTime = duration / 2.0f;
					}
				}
				else {
					duration = d / v;
				}
			}
			

			if (m_acceleration) {
				instanceData.m_actualAccel = actualAccel;
				instanceData.m_accelTime = accelTime;
			}

			instanceData.m_actualTime = duration;
		}
	}

	void ModelAnimationSegmentAxisRotation::calculateAnimation(ModelAnimationSubmodelBuffer& base, float time, int pmi_id) const {
		const instance_data& instanceData = m_instances.at(pmi_id);

		float currentRot = 0;

		if (instanceData.m_actualAccel) {
			const float& a = *instanceData.m_actualAccel;
			const float& at = *instanceData.m_accelTime;
			const float& v = instanceData.m_actualVelocity;
			const float& t = instanceData.m_actualTime;

			float acceltime1 = fminf(time, at);
			currentRot = 0.5f * a * acceltime1 * acceltime1;

			float lineartime = fminf(time - at, t - 2.0f * at);
			if (lineartime > 0) {
				currentRot += v * lineartime;
			}

			float acceltime2 = fminf(time - (t - at), at);
			if (acceltime2 > 0) {
				//Cap this to 0, as it could get negative if it rotates "longer than its duration" (which happens when a different axis takes longer to rotate)
				float accel2dist = at * a * acceltime2 - 0.5f * a * acceltime2 * acceltime2;
				if(std::signbit(a))
					currentRot += fminf(accel2dist, 0.0f);
				else
					currentRot += fmaxf(accel2dist, 0.0f);
			}
			
		}
		else {
			// Linear Rotation
			currentRot = instanceData.m_actualVelocity * time;
		}

		// Clamp rotation to actual target
		if (instanceData.m_actualTarget < 0) {
			currentRot = fmaxf(instanceData.m_actualTarget, currentRot);
		}
		else {
			currentRot = fminf(instanceData.m_actualTarget, currentRot);
		}
		
		matrix orient;
		vm_quaternion_rotate(&orient, currentRot, &m_axis);

		ModelAnimationData<true> delta;
		delta.orientation = orient;

		base[m_submodel].data.applyDelta(delta);
		base[m_submodel].modified = true;
	}

	void ModelAnimationSegmentAxisRotation::exchangeSubmodelPointers(ModelAnimationSet& replaceWith) {
		m_submodel = replaceWith.getSubmodel(m_submodel);
	}

	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentAxisRotation::parser(ModelAnimationParseHelper* data) {
		tl::optional<float> angle, velocity, acceleration, time;
		vec3d axis;

		required_string("+Axis:");
		stuff_vec3d(&axis);
		
		if (optional_string("+Angle:")) {
			float parse;
			stuff_float(&parse);
			angle = fl_radians(parse);
		}

		if (optional_string("+Velocity:")) {
			float parse;
			stuff_float(&parse);
			velocity = fl_radians(parse);
		}

		if (optional_string("+Time:")) {
			float parse;
			stuff_float(&parse);
			time = parse;
		}

		if (angle.has_value() ^ velocity.has_value() ^ time.has_value()) {
			error_display(1, "Axis Rotation must have exactly two values out of angle, velocity and time specified!");
		}

		if (optional_string("+Acceleration:")) {
			float parse;
			stuff_float(&parse);
			acceleration = fl_radians(parse);
		}

		auto submodel = ModelAnimationParseHelper::parseSubmodel();
		if (!submodel) {
			if (data->parentSubmodel)
				submodel = data->parentSubmodel;
			else
				error_display(1, "Rotation has no target submodel!");
		}

		auto segment = std::shared_ptr<ModelAnimationSegmentAxisRotation>(new ModelAnimationSegmentAxisRotation(submodel, angle, velocity, time, acceleration, axis));

		return segment;
	}
	

	ModelAnimationSegmentTranslation::ModelAnimationSegmentTranslation(std::shared_ptr<ModelAnimationSubmodel> submodel, tl::optional<vec3d> target, tl::optional<vec3d> velocity, tl::optional<float> time, tl::optional<vec3d> acceleration, CoordinateSystem coordType, ModelAnimationCoordinateRelation relationType) :
		m_submodel(std::move(submodel)), m_target(target), m_velocity(velocity), m_time(time), m_acceleration(acceleration), m_coordType(coordType), m_relationType(relationType) { }

	ModelAnimationSegment* ModelAnimationSegmentTranslation::copy() const {
		return new ModelAnimationSegmentTranslation(*this);
	}

	void ModelAnimationSegmentTranslation::recalculate(ModelAnimationSubmodelBuffer& base, ModelAnimationSubmodelBuffer& currentAnimDelta, polymodel_instance* pmi) {
		Assertion(!(m_target.has_value() ^ m_velocity.has_value() ^ m_time.has_value()), "Tried to run over- or underdefined translation. Define exactly two out of 'time', 'velocity', and 'vector'!");

		instance_data& instanceData = m_instances[pmi->id];
		auto submodel_info = m_submodel->findSubmodel(pmi).second;
		if (submodel_info == nullptr) {
			m_duration[pmi->id] = 0.0f;
			return;
		}

		if (m_target) { //If we have an target specified, use it.
			if (m_relationType != ModelAnimationCoordinateRelation::RELATIVE_COORDS) {
				const ModelAnimationData<>& submodel = (m_relationType == ModelAnimationCoordinateRelation::ABSOLUTE_COORDS ? base[m_submodel].data : currentAnimDelta[m_submodel].data);
				instanceData.m_actualTarget = *m_target - submodel.position;
			}
			else
				instanceData.m_actualTarget = *m_target;
		}
		else { //If we don't have a target specified, calculate it. This implies we must have velocity and time.
			const vec3d& v = *m_velocity;
			const float& t = *m_time;

			if (m_acceleration) { //Consider acceleration to calculate the angle
				//Let the following equations define our accelerated and braked movement, under the assumption that 2 * ta <= t.
				//d : distance, v : max velocity, a : acceleration, t : total time, ta : time spent accelerating (and breaking)
				//v = a * ta
				//d = v * (t - 2 * ta) + 1/2 * 2 * a * ta^2
				//this simplifies to d = (v(a * t - v))/a and ta = v / a
				//if 2 * ta <= t does not hold, it's just d = 1/2 * 2 * a * (t/2)^2 -> this implies that the acceleration is too small to reach the target velocity within the specified time.
				vec3d a = *m_acceleration;
				vec3d at;

				for (size_t i = 0; i < 3; i++) {
					a.a1d[i] = copysignf(a.a1d[i], v.a1d[i]);
					at.a1d[i] = fmaxf(v.a1d[i] / a.a1d[i], t / 2.0f);
				}
				instanceData.m_actualAccel = a;
				instanceData.m_accelTime = at;

				for (size_t i = 0; i < 3; i++)
					instanceData.m_actualTarget.a1d[i] = 2.0f * v.a1d[i] / a.a1d[i] <= t ? (v.a1d[i] * (a.a1d[i] * t - v.a1d[i])) / a.a1d[i] : a.a1d[i] * (t * t / 4.0f);

			}
			else { //Don't consider acceleration, assume instant velocity.
				for (size_t i = 0; i < 3; i++)
					instanceData.m_actualTarget.a1d[i] = v.a1d[i] * t;
			}
		}

		if (m_velocity) { //If we have velocity specified, use it.
			instanceData.m_actualVelocity = *m_velocity;
		}
		else { //If we don't have velocity specified, calculate it. This implies we must have an angle and time.
			const float& t = *m_time;
			const vec3d& d = instanceData.m_actualTarget;

			if (m_acceleration) { //Consider acceleration to calculate the velocity
				//Assume equations from calc angles case, but solve for ta and v now, under the assumption that these roots have a real solution.
				//v = 1/2*(|a|*t-sqrt(|a|)*sqrt(|a|*t^2-4*|d|))*sign(d) and ta = 1/2*(t-(sqrt(|a|*t^2-4*|d|)/sqrt(|a|)))
				//If the roots don't have a real solution, it's v = a * t/2, and ta = 1/2*t -> this implies that the acceleration is too small to reach the target distance within the specified time.

				vec3d a = *m_acceleration;
				for (size_t i = 0; i < 3; i++)
					a.a1d[i] = copysignf(a.a1d[i], d.a1d[i]);
				instanceData.m_actualAccel = a;

				vec3d at{ {{ 0,0,0}} };

				for (size_t i = 0; i < 3; i++) {
					float a_abs = fabsf(a.a1d[i]);
					float radicant = a_abs * t * t - 4 * fabsf(d.a1d[i]);
					if (radicant >= 0) {
						instanceData.m_actualVelocity.a1d[i] = copysignf(0.5f * (a_abs * t - sqrtf(a_abs) * sqrtf(radicant)), d.a1d[i]);
						at.a1d[i] = 0.5f * (t - (sqrtf(radicant) / sqrtf(a_abs)));
					}
					else {
						instanceData.m_actualVelocity.a1d[i] = a.a1d[i] * t / 2.0f;
						at.a1d[i] = t / 2.0f;
					}
				}

				instanceData.m_accelTime = at;
			}
			else { //Don't consider acceleration, assume instant velocity.
				for (size_t i = 0; i < 3; i++)
					instanceData.m_actualVelocity.a1d[i] = d.a1d[i] / t;
			}

		}

		if (m_time) { //If we have time specified, use it.
			const float& time = *m_time;
			m_duration[pmi->id] = time;

			vec3d actualTime{ {{ 0,0,0 }} };
			for (float& timeAxis : actualTime.a1d)
				timeAxis = time;

			instanceData.m_actualTime = actualTime;

			if (time <= 0.0f) {

				Error(LOCATION, "Tried to translate submodel %s in %.2f seconds. Rotation time must be positive and nonzero!", submodel_info->name, time);
			}
		}
		else { //Calc time
			float& duration = m_duration[pmi->id] = 0.0f;

			vec3d& v = instanceData.m_actualVelocity;
			const vec3d& d = instanceData.m_actualTarget;

			vec3d actualAccel{ {{ 0,0,0 }} };
			vec3d accelTime{ {{ 0,0,0 }} };
			vec3d actualTime{ {{ 0,0,0 }} };

			for (size_t i = 0; i < 3; i++) {
				if (d.a1d[i] != 0.0f) {
					if (v.a1d[i] == 0.0f) {
						Warning(LOCATION, "Tried to translate submodel %s by %.2f, but velocity was 0! Rotating with velocity 1...", submodel_info->name, d.a1d[i]);
						v.a1d[i] = 1;
					}

					v.a1d[i] = copysignf(v.a1d[i], d.a1d[i]);

					float durationAxis = 0.0f;

					if (m_acceleration) { //Consider acceleration to calculate the time
						//Assume equations from calc angles case, but solve for ta and t now, with the resulting ta <= t / 2.
						//t = v/a+d/v and ta = v/a
						//If thus d/v < v/a, it's t = 2*sqrt(d/a), and ta = 1/2*t -> this implies that the acceleration is too small to reach the target velocity within the specified distance.
						float a = copysignf((*m_acceleration).a1d[i], d.a1d[i]);
						actualAccel.a1d[i] = a;

						float va = v.a1d[i] / a;
						float dv = d.a1d[i] / v.a1d[i];

						if (dv >= va) {
							durationAxis = va + dv;
							accelTime.a1d[i] = va;
						}
						else {
							durationAxis = 2.0f * sqrtf(d.a1d[i] / a);
							accelTime.a1d[i] = durationAxis / 2.0f;
						}
					}
					else {
						durationAxis = d.a1d[i] / v.a1d[i];
					}

					duration = duration < durationAxis ? durationAxis : duration;
					actualTime.a1d[i] = durationAxis;
				}
			}

			if (m_acceleration) {
				instanceData.m_actualAccel = actualAccel;
				instanceData.m_accelTime = accelTime;
			}

			instanceData.m_actualTime = actualTime;
		}

		if (CoordinateSystem::COORDS_LOCAL_AT_START == m_coordType) {
			instanceData.m_rotationAtStart = base[m_submodel].data.orientation;
		}
	}

	void ModelAnimationSegmentTranslation::calculateAnimation(ModelAnimationSubmodelBuffer& base, float time, int pmi_id) const {
		const instance_data& instanceData = m_instances.at(pmi_id);

		vec3d currentOffset{ {{ 0,0,0 }} };

		if (instanceData.m_actualAccel) {
			const vec3d& a = *instanceData.m_actualAccel;
			const vec3d& at = *instanceData.m_accelTime;
			const vec3d& v = instanceData.m_actualVelocity;
			const vec3d& t = instanceData.m_actualTime;

			for (size_t i = 0; i < 3; i++) {
				float acceltime1 = fminf(time, at.a1d[i]);
				currentOffset.a1d[i] = 0.5f * a.a1d[i] * acceltime1 * acceltime1;

				float lineartime = fminf(time - at.a1d[i], t.a1d[i] - 2.0f * at.a1d[i]);
				if (lineartime > 0) {
					currentOffset.a1d[i] += v.a1d[i] * lineartime;
				}

				float acceltime2 = fminf(time - (t.a1d[i] - at.a1d[i]), at.a1d[i]);
				if (acceltime2 > 0) {
					//Cap this to 0, as it could get negative if it translates "longer than its duration" (which happens when a different axis takes longer to translate)
					float accel2dist = at.a1d[i] * a.a1d[i] * acceltime2 - 0.5f * a.a1d[i] * acceltime2 * acceltime2;
					if (std::signbit(a.a1d[i]))
						currentOffset.a1d[i] += fminf(accel2dist, 0.0f);
					else
						currentOffset.a1d[i] += fmaxf(accel2dist, 0.0f);
				}
			}
		}
		else {
			for (size_t i = 0; i < 3; i++)// Linear translation
				currentOffset.a1d[i] = instanceData.m_actualVelocity.a1d[i] * time;
		}

		for (size_t i = 0; i < 3; i++) { // Clamp translation to actual target
			if (instanceData.m_actualTarget.a1d[i] < 0) {
				currentOffset.a1d[i] = fmaxf(instanceData.m_actualTarget.a1d[i], currentOffset.a1d[i]);
			}
			else {
				currentOffset.a1d[i] = fminf(instanceData.m_actualTarget.a1d[i], currentOffset.a1d[i]);
			}
		}

		vec3d finalOffset = currentOffset;
		auto& submodelInstance = base[m_submodel];

		switch (m_coordType) {
		case CoordinateSystem::COORDS_LOCAL_AT_START:
			//Use the local coordinates this submodel had at the start of this animation, if no other animations would be running. Useful for cases where your movement shouldn't be modified by anything else
			vm_vec_rotate(&finalOffset, &currentOffset, &instanceData.m_rotationAtStart);
			break;
		case CoordinateSystem::COORDS_LOCAL_CURRENT:
			//Use the local coordinates this submodel has right now, including all other animations running. Useful if you want your submodel to move visibly on it's own axes
			vm_vec_rotate(&finalOffset, &currentOffset, &submodelInstance.data.orientation);
			break;
		case CoordinateSystem::COORDS_PARENT:
		default:
			//Trivial case. Specified coordinates are assumed to be in relation to this submodel's coordinate system (dependent on its parent's rotation, but not on its own).
			//No rotation necessary.
			break;
		}

		ModelAnimationData<true> delta;
		delta.position = finalOffset;

		submodelInstance.data.applyDelta(delta);
		submodelInstance.modified = true;
	}

	void ModelAnimationSegmentTranslation::exchangeSubmodelPointers(ModelAnimationSet& replaceWith) {
		m_submodel = replaceWith.getSubmodel(m_submodel);
	}

	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentTranslation::parser(ModelAnimationParseHelper* data) {
		tl::optional<vec3d> offset, velocity, acceleration;
		tl::optional<float> time;
		CoordinateSystem coordSystem = CoordinateSystem::COORDS_PARENT;
		ModelAnimationCoordinateRelation relationType = ModelAnimationCoordinateRelation::RELATIVE_COORDS;

		if (optional_string("+Vector:")) {
			vec3d parse;
			stuff_vec3d(&parse);
			offset = std::move(parse);
			relationType = ModelAnimationParseHelper::parseCoordinateRelation();
		}

		if (optional_string("+Velocity:")) {
			vec3d parse;
			stuff_vec3d(&parse);
			velocity = std::move(parse);
		}

		if (optional_string("+Time:")) {
			float parse;
			stuff_float(&parse);
			time = parse;
		}

		if (offset.has_value() ^ velocity.has_value() ^ time.has_value()) {
			error_display(1, "Translation must have exactly two values out of vector, velocity and time specified!");
		}

		if (optional_string("+Acceleration:")) {
			vec3d parse;
			stuff_vec3d(&parse);
			acceleration = std::move(parse);
		}

		if (optional_string("+Coordinate System:")) {
			switch (optional_string_one_of(3, "Parent", "Local at start", "Local current")) {
			case 0:
				coordSystem = CoordinateSystem::COORDS_PARENT;
				break;
			case 1:
				coordSystem = CoordinateSystem::COORDS_LOCAL_AT_START;
				break;
			case 2:
				coordSystem = CoordinateSystem::COORDS_LOCAL_CURRENT;
				break;
			default:
				error_display(0, "Unknown translation coordinate system! Assuming 'Parent'.");
				break;
			}
		}

		auto submodel = ModelAnimationParseHelper::parseSubmodel();
		if (!submodel) {
			if (data->parentSubmodel)
				submodel = data->parentSubmodel;
			else
				error_display(1, "Translation has no target submodel!");
		}

		auto segment = std::shared_ptr<ModelAnimationSegmentTranslation>(new ModelAnimationSegmentTranslation(submodel, offset, velocity, time, acceleration, coordSystem, relationType));

		return segment;
	}


	ModelAnimationSegmentSoundDuring::ModelAnimationSegmentSoundDuring(std::shared_ptr<ModelAnimationSegment> segment, gamesnd_id start, gamesnd_id end, gamesnd_id during, bool flipIfReversed, bool abortPlayingSounds, float radius, std::shared_ptr<ModelAnimationSubmodel> submodel, tl::optional<vec3d> position) :
		m_segment(std::move(segment)), m_submodel(submodel), m_position(std::move(position)), m_radius(radius), m_start(start), m_end(end), m_during(during), m_flipIfReversed(flipIfReversed), m_abortSoundIfRunning(abortPlayingSounds) { }

	ModelAnimationSegment* ModelAnimationSegmentSoundDuring::copy() const {
		auto newCopy = new ModelAnimationSegmentSoundDuring(*this);
		newCopy->m_segment = std::shared_ptr<ModelAnimationSegment>(newCopy->m_segment->copy());
		return newCopy;
	}

	void ModelAnimationSegmentSoundDuring::recalculate(ModelAnimationSubmodelBuffer& base, ModelAnimationSubmodelBuffer& currentAnimDelta, polymodel_instance* pmi) {
		m_segment->recalculate(base, currentAnimDelta, pmi);
		m_duration[pmi->id] = m_segment->getDuration(pmi->id);
	}

	void ModelAnimationSegmentSoundDuring::calculateAnimation(ModelAnimationSubmodelBuffer& base, float time, int pmi_id) const {
		m_segment->calculateAnimation(base, time, pmi_id);
	}

	void ModelAnimationSegmentSoundDuring::executeAnimation(const ModelAnimationSubmodelBuffer& state, float timeboundLower, float timeboundUpper, ModelAnimationDirection direction, int pmi_id) {
		polymodel_instance* pmi = model_get_instance(pmi_id);

		if (timeboundLower <= 0.0f && 0.0f <= timeboundUpper) {
			if (!m_flipIfReversed || direction == ModelAnimationDirection::FWD)
				playStartSnd(pmi);
			else
				playEndSnd(pmi);
		}

		if (0.0f < timeboundLower && timeboundUpper < m_duration.at(pmi_id)) {
			if (m_during.isValid() && (!m_instances[pmi_id].currentlyPlaying.isValid() || !snd_is_playing(m_instances[pmi_id].currentlyPlaying)))
				m_instances[pmi_id].currentlyPlaying = playSnd(pmi, m_during, true);
		}

		if (timeboundLower <= m_duration.at(pmi_id) && m_duration.at(pmi_id) <= timeboundUpper) {
			if (!m_flipIfReversed || direction == ModelAnimationDirection::FWD)
				playEndSnd(pmi);
			else
				playStartSnd(pmi);
		}
		m_segment->executeAnimation(state, timeboundLower, timeboundUpper, direction, pmi_id);
	}

	void ModelAnimationSegmentSoundDuring::exchangeSubmodelPointers(ModelAnimationSet& replaceWith) {
		m_segment->exchangeSubmodelPointers(replaceWith);
	}

	void ModelAnimationSegmentSoundDuring::playStartSnd(polymodel_instance* pmi) {
		if (m_abortSoundIfRunning && snd_is_playing(m_instances[pmi->id].currentlyPlaying))
			snd_stop(m_instances[pmi->id].currentlyPlaying);
		
		if(m_start.isValid())
			m_instances[pmi->id].currentlyPlaying = playSnd(pmi, m_start, false);
	}
	void ModelAnimationSegmentSoundDuring::playEndSnd(polymodel_instance* pmi) {
		if (m_abortSoundIfRunning && snd_is_playing(m_instances[pmi->id].currentlyPlaying))
			snd_stop(m_instances[pmi->id].currentlyPlaying);

		if (m_end.isValid()) 
			m_instances[pmi->id].currentlyPlaying = playSnd(pmi, m_end, false);
	}

	sound_handle ModelAnimationSegmentSoundDuring::playSnd(polymodel_instance* pmi, const gamesnd_id& sound, bool loop) {
		if (m_submodel != nullptr && pmi->objnum >= 0) {
			auto submodel = m_submodel->findSubmodel(pmi);
			if (submodel.first != nullptr) {
				const object& obj = Objects[pmi->objnum];

				vec3d pnt;
				model_instance_local_to_global_point(&pnt, m_position ? &(*m_position) : &vmd_zero_vector, pmi->id, (int)(submodel.first - pmi->submodel), &obj.orient, &obj.pos);

				return snd_play_3d(gamesnd_get_game_sound(sound), &pnt, &View_position, m_radius, nullptr, loop ? 1 : 0);
			}
		}

		if(loop)
			return snd_play_looping(gamesnd_get_game_sound(sound));
		else
			return snd_play(gamesnd_get_game_sound(sound));
	}
	
	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentSoundDuring::parser(ModelAnimationParseHelper* data) {
		gamesnd_id start_sound;
		gamesnd_id loop_sound;
		gamesnd_id end_sound;
		float snd_rad = 0.0f;
		
		auto submodel = ModelAnimationParseHelper::parseSubmodel();
		if (!submodel) {
			if (data->parentSubmodel)
				submodel = data->parentSubmodel;
		}

		parse_game_sound("+Start:", &start_sound);
		parse_game_sound("+Loop:", &loop_sound);
		parse_game_sound("+End:", &end_sound);

		if (optional_string("+Radius:")) {
			stuff_float(&snd_rad);
		}

		tl::optional<vec3d> position = tl::nullopt;
		if (optional_string("+Position:")) {
			if (!submodel)
				error_display(1, "Supplied sound position for animation but no parent submodel. Cannot play sound as 3D without attachment to submodel.");

			vec3d parse;
			stuff_vec3d(&parse);
			position = std::move(parse);
		}

		bool flipIfReversed = optional_string("+Flip When Reversed");
		bool abortSoundIfRunning = !optional_string("+Don't Interrupt Playing Sounds");

		auto segment = std::shared_ptr<ModelAnimationSegmentSoundDuring>(new ModelAnimationSegmentSoundDuring(data->parseSegment(), start_sound, end_sound, loop_sound, flipIfReversed, abortSoundIfRunning, snd_rad, submodel, position));

		return segment;
	}


	ModelAnimationSegmentIK::ModelAnimationSegmentIK(const vec3d& targetPosition, const tl::optional<matrix>& targetRotation)
		: m_targetPosition(targetPosition), m_targetRotation(targetRotation) { }
	
	ModelAnimationSegment* ModelAnimationSegmentIK::copy() const {
		auto* copy = new ModelAnimationSegmentIK(*this);
		copy->m_segment = std::shared_ptr<ModelAnimationSegmentParallel>(static_cast<ModelAnimationSegmentParallel*>(m_segment->copy()));
		
		for(size_t i = 0; i < m_chain.size(); ++i){
			copy->m_chain[i].animSegment = std::static_pointer_cast<ModelAnimationSegmentRotation>(copy->m_segment->m_segments[i]);
		}
		
		return copy;
	};
	
	void ModelAnimationSegmentIK::recalculate(ModelAnimationSubmodelBuffer& base, ModelAnimationSubmodelBuffer& currentAnimDelta, polymodel_instance* pmi) {
		auto ik = std::unique_ptr<ik_solver>(new ik_solver_fabrik());

		polymodel* pm = model_get(pmi->model_num);
		bsp_info* lastSubmodel = nullptr;
		
		for(const auto& chainlink : m_chain) {
			bsp_info* submodel = chainlink.submodel->findSubmodel(pmi).second;
			if(lastSubmodel != nullptr) {
				//Validate chain for current POF
				if(&pm->submodel[submodel->parent] != lastSubmodel){
					Error(LOCATION, "Tried to perform IK on a non-continuous chain. Submodel %s must be an immediate child of the previous chain-link's submodel %s.", submodel->name, lastSubmodel->name);
				}
			}
			lastSubmodel = submodel;
			
			ik->addNode(submodel, chainlink.constraint.get());
		}
		
		ik->solve(m_targetPosition, &(*m_targetRotation));
		
		auto chainlink_it = m_chain.cbegin();
		for(const auto& solvedlink : *ik){
			angles converted;
			vm_extract_angles_matrix_alternate(&converted, &solvedlink.calculatedRot);
			chainlink_it++->animSegment->m_targetAngle = converted;
		}
		
		std::static_pointer_cast<ModelAnimationSegment>(m_segment)->recalculate(base, currentAnimDelta, pmi);
		m_duration[pmi->id] = m_segment->getDuration(pmi->id);
	};
	
	void ModelAnimationSegmentIK::calculateAnimation(ModelAnimationSubmodelBuffer& base, float time, int pmi_id) const {
		std::static_pointer_cast<ModelAnimationSegment>(m_segment)->calculateAnimation(base, time, pmi_id);
	};
	
	void ModelAnimationSegmentIK::exchangeSubmodelPointers(ModelAnimationSet& replaceWith) {
		std::static_pointer_cast<ModelAnimationSegment>(m_segment)->exchangeSubmodelPointers(replaceWith);

		for(auto& chainlink : m_chain)
			chainlink.submodel = replaceWith.getSubmodel(chainlink.submodel);
	};
	
	std::shared_ptr<ModelAnimationSegment> ModelAnimationSegmentIK::parser(ModelAnimationParseHelper* data) {		
		
		vec3d targetPosition;
		tl::optional<matrix> targetRotation;
		
		required_string("+Target Position:");
		stuff_vec3d(&targetPosition);
		
		if(optional_string("+Target Orientation:")){
			matrix targetRot;
			angles angle;
			stuff_angles_deg_phb(&angle);

			vm_angles_2_matrix(&targetRot, &angle);
			
			targetRotation = targetRot;
		}
		
		required_string("+Time:");
		float time;
		stuff_float(&time);
		
		auto segment = std::shared_ptr<ModelAnimationSegmentIK>(new ModelAnimationSegmentIK(targetPosition, targetRotation));
		auto parallel = std::shared_ptr<ModelAnimationSegmentParallel>(new ModelAnimationSegmentParallel());
		segment->m_segment = parallel;
		
		while(optional_string("$Chain Link:")){
			auto submodel = ModelAnimationParseHelper::parseSubmodel();
			if (!submodel) {
				if (data->parentSubmodel)
					submodel = data->parentSubmodel;
				else
					error_display(1, "IK chain link has no target submodel!");
			}

			tl::optional<angles> acceleration;
			if(optional_string("+Acceleration:")){
				angles accel;
				stuff_angles_deg_phb(&accel);
				acceleration = accel;
			}
			
			std::shared_ptr<ik_constraint> constraint;
			if(optional_string("+Constraint:")){
				int type = required_string_one_of(2, "Window", "Hinge");
				switch(type){
					case 0: { //Window
						angles window;
						required_string("Window");
						required_string("+Window Size:");
						stuff_angles_deg_phb(&window);
						constraint = std::shared_ptr<ik_constraint>(new ik_constraint_window(window));
						break;
					}
					case 1: { //Hinge
						vec3d axis;
						required_string("Hinge");
						required_string("+Axis:");
						stuff_vec3d(&axis);
						vm_vec_normalize(&axis);
						constraint = std::shared_ptr<ik_constraint>(new ik_constraint_hinge(axis));
						break;
					}
					default:
						UNREACHABLE("IK constraint of unknown type specified!");
						break;
				}
			}
			else
				constraint = std::shared_ptr<ik_constraint>(new ik_constraint());
			
			auto rotation = std::shared_ptr<ModelAnimationSegmentRotation>(new ModelAnimationSegmentRotation(submodel, tl::optional<angles>({0,0,0}), tl::optional<angles>(), time, acceleration, ModelAnimationCoordinateRelation::ABSOLUTE_COORDS));
			parallel->addSegment(rotation);
			segment->m_chain.push_back({submodel, constraint, rotation});
		}
		
		return segment;
	}
}