-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjoint_manager.txt
2219 lines (1731 loc) · 76 KB
/
joint_manager.txt
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
--@name Joint Manager
--@author legokidlogan
--@server
--@include lkl/gcolors.txt
--@include lkl/lib_ik_old.txt
--@include lkl/extra_timers.txt
--@include lkl/simple_ratelimit.txt
--@include lkl/table_clone_deep.txt
--@include lkl/jm_default_joints.txt
--@include lkl/jm_default_poses.txt
--@include lkl/jm_default_anims.txt
----- VERY OLD -----
local tableInsert = table.insert
local stringExplode = string.explode
extraTimerPrecision = extraTimerPrecision or 2
ikDisableWire = true
require( "lkl/gcolors.txt" )
require( "lkl/lib_ik_old.txt" )
require( "lkl/extra_timers.txt" )
require( "lkl/simple_ratelimit.txt" )
require( "lkl/table_clone_deep.txt" )
-- Typical orientation definers.
-- For limb/finger-like joints, the default values given here will work best with models where Forward is the longest axis (such as with SProps)
-- These are used for defining most TrueForward/TrueRight/TrueUp values for joints, and are relative to the model's standard orientations.
vecTypicalForward = vecTypicalForward or Vector( 1, 0, 0 )
vecTypicalRight = vecTypicalRight or Vector( 0, 1, 0 )
vecTypicalUp = vecTypicalUp or Vector( 0, 0, 1 )
-- Typical orientation definers, but for joints on the left side of the body.
-- Usually these are the same as the non-mirrored directions, except the up direction is reversed.
vecMirrorForward = vecMirrorForward or vecTypicalForward
vecMirrorRight = vecMirrorRight or vecTypicalRight
vecMirrorUp = vecMirrorUp or -vecTypicalUp
-- Typical inverse-kinimatics points.
-- These are relative to the joint's 'true' orientations, and are scaled by half of the object's box size.
-- It's highly unlikely that you will need to modify these, but you still can.
vecTypicalIKOrigin = vecTypicalIKOrigin or Vector( -1, 0, 0 )
vecTypicalIKEnd = vecTypicalIKEnd or Vector( 1, 0, 0 )
vecMirrorIKOrigin = vecMirrorIKOrigin or Vector( -1, 0, 0 )
vecMirrorIKEnd = vecMirrorIKEnd or Vector( 1, 0, 0 )
--[[
NOTE: Like the rest of my starfall scripts, you MUST handle wire inputs and outputs like this with global tables:
inputNames = inputNames or {}
inputTypes = inputTypes or {}
outputNames = outputNames or {}
outputTypes = outputTypes or {}
table.insert( inputNames, "Blah" )
table.insert( inputTypes, "Blah" )
table.insert( outputNames, "Blah" )
table.insert( outputTypes, "Blah" )
require( "lkl/blah.txt" )
wire.adjustInputs( inputNames, inputTypes )
wire.adjustOutputs( outputNames, outputTypes )
-- This allows for dependencies to add onto the wire ports safely and easily.
--]]
-- Config:
-- Each chip will likely have wildly different joint configs to handle a specific setup and design.
-- In the parent chip include'ing this file, make sure to define jointConfig as a non-local table before require()'ing this.
-- Whether you define the three config tables directly in the parent chip or via an include, MAKE SURE YOU SET THE CONFIGS BEFORE THIS FILE GETS require()'d !
-- Additionally, do not try to modify the configs after this file has been require()'d, the new info will NOT get applied.
-- NEVER put two consecutive underscores ("__") in the names for your joints, as it is used for wire indexing.
-- To attach a joint to one of the non-joint bases, set Parent = "BASE__baseID", where baseID is that base's order in the wire inputs.
-- It's recommended to have bases be models/hunter/plates/plate.mdl or something similar.
-- Default config:
jointConfig = jointConfig or {
NumBases = 1,
SeparateInputs = true, -- Whether the inputs for joints should be separated or combined into a single array input. For the array, the order matches the order used for the jointConfig.
UpdateInterval = 100, -- Update rate for the joints, in milliseconds. A smaller number means smoother joints, but more CPU usage and server lag. Min value is 15, as servers with a tickrate of 66 cannot go faster.
UpdateIntervalHoldables = 100, -- UpdateInterval, but for holdables.
QuotaCheckMult = 1, -- Multiplies against CPU quota checks, lower values mean JM will try to stay below a lower threshold. Recommended to not touch.
}
-- These three are *very* important configs for setting up the bone structure, poses, and animations. There are examples of each in the provided files. Make sure to define these tables globaly!
jointInfos = jointInfos or require( "lkl/jm_default_joints.txt" )
jointPoses = jointPoses or require( "lkl/jm_default_poses.txt" )
jointAnims = jointAnims or require( "lkl/jm_default_anims.txt" )
-- End Config
local mMax = math.max
local mMin = math.min
local mClamp = math.clamp
local mAbs = math.abs
local mSign = math.sign
local mSqrt = math.sqrt
local mFloor = math.floor
local tableEmpty = table.empty
local realtime = timer.realtime
local timerCreateExtra = timer.createExtra
local timerSimpleExtra = timer.simpleExtra
local timerRemoveExtra = timer.removeExtra
local cpuAverage = cpuAverage
local cpuTotalAverage = cpuTotalAverage
projectNameID = projectNameID or "JointManager." .. chip():entIndex()
inputNames = inputNames or {}
inputTypes = inputTypes or {}
jointEnts = jointEnts or {}
jointLookup = jointLookup or {}
jointNameToID = jointNameToID or {}
jointBaseEnts = jointBaseEnts or {}
jointHoldables = jointHoldables or {}
jointHoldableLookup = jointHoldableLookup or {}
jointHoldableCount = #jointHoldables
jointActivePoses = jointActivePoses or {}
jointActiveAnims = jointActiveAnims or {}
jointRemoteFuncs = jointRemoteFuncs or {}
jointAnimDurationTotals = jointAnimDurationTotals or {}
--jointManips = jointManips or {}
jointRemotePrefix = "LKL_JointManager_RemoteFunc_"
local initialized = false
local forceTPose = false
local nextIndManip = 1
local nextIndHoldable = 1
local prevManipProcessTime = realtime()
local prevHodableProcessTime = realtime()
local numBases = jointConfig.NumBases or 1
local separateInputs = jointConfig.SeparateInputs
local updateInterval = jointConfig.UpdateInterval or 50
local updateIntervalHoldables = jointConfig.UpdateIntervalHoldables or 50
local quotaMaxVal = cpuMax() * mClamp( jointConfig.QuotaCheckMult or 1, 0, 1 )
--local jointInfos = jointConfig.Joints
local jointCount = #jointInfos
local jointsWithBaseParents = {}
local jointsWithBaseParentsCount = 0
local jointManips = {}
--local jointManipOrders = {} --------------------------------------
--local jointManipOrderLookup = {} --------------------------------------
local jointPosesFormatted = {}
local jointAnimKFPosesFormatted = {}
local jointAnimKFManipsFormatted = {}
local jointAnimKFHoldablesFormatted = {}
local jointAnimCurrentKeyframes = {}
local wireEnts = {}
local wireNames = {}
--local jointHoldableParams = {}
local printName = "[" .. projectNameID .. "]"
local chipLink = wire.getWirelink( chip() )
local ang0 = Angle( 0, 0, 0 )
local vecRightNeg = Vector( 1, -1, 1 )
local vecForward = Vector( 1, 0, 0 )
local vecRight = Vector( 0, 1, 0 )
local vecUp = Vector( 0, 0, 1 )
updateInterval = mMax( updateInterval, 15 ) / 1000
updateIntervalHoldables = mMax( updateIntervalHoldables, 15 ) / 1000
local function getInputInfo( name )
if type( name ) ~= "string" then return end
local info = stringExplode( "__", name )
local id = info[2]
if id then
id = tonumber( id )
if id < 1 then
id = false
end
end
return info[1], id, info[3]
end
local function addRemoteFunc( funcName, func )
jointRemoteFuncs[jointRemotePrefix .. funcName] = func
end
local function getKeyframeOrCopy( animData, kfInd, kfData, prevInds )
kfData = kfData or animData[kfInd] or {}
prevInds = prevInds or {}
local copyInd = kfData.CopyInd
if not copyInd then return kfData end
--prevInds[copyInd] = true
--if prevInds[kfInd] then return {} end -- Avoid circular copy loops
if prevInds[copyInd] then return kfData end -- Avoid circular copy loops
prevInds[copyInd] = true
if not kfData.CopyComplete then
local overrideData = kfData.OverrideData
local sourceData = getKeyframeOrCopy( animData, copyInd, nil, prevInds )
kfData = table.cloneDeep( sourceData )
animData[kfInd] = kfData
if overrideData then
for key, value in pairs( overrideData ) do
kfData[key] = value
end
kfData.OverrideData = overrideData
end
kfData.CopyInd = copyInd
kfData.CopyComplete = true
end
return kfData
end
do
tableInsert( inputNames, "Holdables" )
tableInsert( inputTypes, "ARRAY" )
for i = 1, numBases do
tableInsert( inputNames, "Base__" .. i )
tableInsert( inputTypes, "ENTITY" )
end
for i = 1, jointCount do
local jointInfo = jointInfos[i]
local name = jointInfo.Name
local parentName, parentBaseID = getInputInfo( jointInfo.Parent )
if parentName == "BASE" then
if not parentBaseID then
parentBaseID = 1
jointInfo.Parent = "BASE__" .. parentBaseID
end
jointInfo.ParentIsBase = true
jointInfo.ParentBaseID = parentBaseID
jointsWithBaseParentsCount = jointsWithBaseParentsCount + 1
jointsWithBaseParents[jointsWithBaseParentsCount] = i
else
jointInfo.ParentID = false
jointInfo.ParentIsBase = false
end
local trueForward = jointInfo.TrueForward
local trueRight = jointInfo.TrueRight
local trueUp = jointInfo.TrueUp
local forwardModified = trueForward ~= Vector( 1, 0, 0 )
local rightModified = trueRight ~= Vector( 0, -1, 0 )
local upModified = trueUp ~= Vector( 0, 0, 1 )
jointNameToID[name] = i
jointInfo.ID = i
jointInfo.ForwardModified = forwardModified
jointInfo.RightModified = rightModified
jointInfo.UpModified = upModified
end
for i = 1, jointCount do
local jointInfo = jointInfos[i]
local parentName = getInputInfo( jointInfo.Parent )
if not jointInfo.ParentIsBase then
jointInfo.ParentID = jointInfo.ParentID or jointNameToID[parentName] or 1
end
end
for animName, animData in pairs( jointAnims ) do
local durationTotal = 0
for kfInd, kfData in pairs( animData ) do
if type( kfData ) == "table" then
kfData = getKeyframeOrCopy( animData, kfInd, kfData )
durationTotal = durationTotal + ( kfData.Duration or 0 )
end
end
jointAnimDurationTotals[animName] = durationTotal
end
if separateInputs then
for i = 1, jointCount do
local jointInfo = jointInfos[i]
tableInsert( inputNames, "Joint__" .. i .. "__" .. jointInfo.Name )
tableInsert( inputTypes, "ENTITY" )
end
else
tableInsert( inputNames, "Joints" )
tableInsert( inputTypes, "ARRAY" )
end
wire.adjustInputs( inputNames, inputTypes )
end
local function quotaAlert( msg )
print(
c_white, printName .. " ",
c_alert_red, "Exceeded perf limits on ",
c_pale_yellow, msg
)
end
local function getUsageLimit( frac )
frac = frac or 0.9
local myUsage = cpuAverage()
local otherChipsUsage = cpuTotalAverage() - myUsage
return quotaMaxVal * frac - otherChipsUsage
end
local function checkQuota( usageLimit, msg )
local belowQuota = cpuAverage() < usageLimit
if belowQuota or not msg then return belowQuota end
simpleRatelimit( quotaAlert, 1, "QuotaExceeded__" .. msg, msg )
end
local function formatPose( poseName ) -- Prepares a pose for faster usage with manipulateJoints(), doing it on the fly for faster startup times (and coroutines are a hassle)
local poseForm = jointPosesFormatted[poseName]
if poseForm then return poseForm end
local poseData = jointPoses[poseName]
local poseIDs = {}
local poseAngs = {}
local count = 0
for jointName, ang in pairs( poseData ) do
count = count + 1
poseIDs[count] = jointName
poseAngs[count] = ang
end
poseForm = {
IDs = poseIDs,
Angs = poseAngs
}
jointPosesFormatted[poseName] = poseForm
return poseForm
end
local function createHoldableParamFuncGen( func, holdInd, endAtTime )
if type( func ) ~= "function" then return function() return func end end
if endAtTime then
return function( isReverse )
if isReverse then
return function( timeEx, parent )
timeEx = endAtTime - timeEx
if timeEx >= endAtTime then
setHoldableParams( holdInd, false )
return nil
end
return func( timeEx, parent )
end
end
return function( timeEx, parent )
if timeEx >= endAtTime then
setHoldableParams( holdInd, false )
return nil
end
return func( timeEx, parent )
end
end
end
return function( isReverse )
if isReverse then
return function( timeEx, parent )
return func( -timeEx, parent )
end
end
return func
end
end
local function formatKeyframe( animName, kfInd )
if not animName then return end
local animData = jointAnims[animName]
if not animData then return end
local kfData = getKeyframeOrCopy( animData, kfInd )
local kfDuration = mAbs( kfData.Duration or 0 )
local numKeyframes = animData.Count or #animData
if kfDuration == 0 then return end
local animPoseForms = jointAnimKFPosesFormatted[animName]
local animManipForms = jointAnimKFManipsFormatted[animName]
local animHoldableForms = jointAnimKFHoldablesFormatted[animName]
if not animPoseForms then
animPoseForms = {}
jointAnimKFPosesFormatted[animName] = animPoseForms
end
if not animManipForms then
animManipForms = {}
jointAnimKFManipsFormatted[animName] = animManipForms
end
if not animHoldableForms then
animHoldableForms = {}
jointAnimKFHoldablesFormatted[animName] = animHoldableForms
end
local kfPoseForms = animPoseForms[kfInd]
local kfManipForms = animManipForms[kfInd]
local kfHoldableForms = animHoldableForms[kfInd]
if kfPoseForms or kfManipForms or kfHoldableForms then return kfPoseForms, kfManipForms, kfHoldableForms end -- Anim has already been formatted previously
-- Format pose for keyframe (primarily just clamp and store time values to fit into keyframes)
local kfPoses = kfData.Poses or {}
local poseCount = 0
kfPoseForms = {}
for poseName, poseArgs in pairs( kfPoses ) do
if not jointPoses[poseName] then continue end
local poseSmoothTime = ( poseArgs.SmoothTime or kfDuration )
local poseDuration = ( poseArgs.Duration or kfDuration )
poseSmoothTime = mClamp( poseSmoothTime, -kfDuration, kfDuration )
poseDuration = mClamp( poseDuration, -kfDuration, kfDuration )
--[[
if poseDuration == 0 then
poseDuration = kfDuration
end
--]]
poseCount = poseCount + 1
kfPoseForms[poseCount] = {
Name = poseName,
SmoothTime = poseSmoothTime,
Duration = poseDuration,
FlexScale = poseArgs.FlexScale or 1,
ForceIsOverride = poseArgs.ForceIsOverride,
}
end
kfPoseForms.Count = poseCount
animPoseForms[kfInd] = kfPoseForms
-- Format manips for keyframe
local kfManips = {}
local manipIDs = {}
local manipAngs = {}
local manipAngsByName = {}
local manipPrevAngs = {}
local manipPrevAngsByName = {}
local manipSmoothTimes = {}
--local manipDurations = {}
--local manipFlexScales = {}
local manipIsOverrides = {}
local manipDisableVals = {}
local manipCount = 0
kfManips = table.cloneDeep( kfData.Manips or kfData.Manipulations or {} )
kfData.EffManips = kfManips -- Don't override original data when adjusting info to account for previous keyframes
if kfInd > 1 then
local _, prevKfManipForms = formatKeyframe( animName, kfInd - 1 )
manipPrevAngs = table.cloneDeep( prevKfManipForms.Angs ) -- Don't touch the target angles of the previous keyframe
manipPrevAngsByName = table.cloneDeep( prevKfManipForms.AngsByName )
-- This keyframe should smoothly 'reset' hanging manips from the previous frame, so add more target angles for this frame
for jointName, manipArgs in pairs( manipPrevAngsByName ) do
if not kfManips[jointName] and ( manipArgs.Ang or ang0 ) ~= ang0 then
kfManips[jointName] = {
Ang = Angle( 0, 0, 0 ),
SmoothTime = kfDuration,
--Duration = kfDuration,
--FlexScale = 1,
IsOverride = manipArgs.IsOverride,
}
end
end
end
for jointName, manipArgs in pairs( kfManips ) do
local manipSmoothTime = mAbs( manipArgs.SmoothTime or kfDuration )
--local manipDuration = mAbs( manipArgs.Duration or kfDuration )
local ang = manipArgs.Ang or Angle( 0, 0, 0 )
--[[
manipDuration = mMin( manipDuration, kfDuration )
if manipDuration == 0 then
manipDuration = kfDuration
end
--]]
--manipSmoothTime = mMin( manipSmoothTime, manipDuration )
manipSmoothTime = mMin( manipSmoothTime, kfDuration )
manipCount = manipCount + 1
manipIDs[manipCount] = jointName
manipAngs[manipCount] = ang
manipAngsByName[jointName] = ang
manipSmoothTimes[manipCount] = manipSmoothTime
--manipDurations[manipCount] = manipDuration
--manipFlexScales[manipCount] = manipArgs.FlexScale or 1
manipIsOverrides[manipCount] = manipArgs.IsOverride
manipDisableVals[manipCount] = -1
if kfInd == 1 then
manipPrevAngsByName[jointName] = Angle( 0, 0, 0 )
manipPrevAngs[manipCount] = Angle( 0, 0, 0 )
elseif not manipPrevAngsByName[jointName] then -- Ensure our initial and target angle lists have matching counts
manipPrevAngsByName[jointName] = Angle( 0, 0, 0 )
tableInsert( manipPrevAngs, Angle( 0, 0, 0 ) )
end
end
kfManipForms = {
Count = manipCount,
IDs = manipIDs,
Angs = manipAngs,
AngsByName = manipAngsByName,
PrevAngs = manipPrevAngs,
PrevAngsByName = manipPrevAngsByName,
SmoothTimes = manipSmoothTimes,
--Durations = manipDurations,
--FlexScales = manipFlexScales,
IsOverrides = manipIsOverrides,
DisableVals = manipDisableVals,
}
animManipForms[kfInd] = kfManipForms
-- Format holdable params for keyframe
local kfHolds = kfData.HoldParams or kfData.HoldableParams or kfData.HoldableParameters or kfData.HoldParameters or {}
local holdCount = 0
kfHoldableForms = {}
for holdInd, holdArgs in pairs( kfHolds ) do
local posFunc = holdArgs.Pos or holdArgs.PosFunc
local angFunc = holdArgs.Ang or holdArgs.AngFunc
local endWithKeyframe = holdArgs.EndWithKeyframe
local endWithAnim = holdArgs.EndWithAnim
local endAtTime
if endWithKeyframe then
endAtTime = kfDuration
elseif endWithAnim then
endAtTime = kfDuration
for i = kfInd + 1, numKeyframes do
local otherKfData = animData[i] or {}
endAtTime = endAtTime + mAbs( otherKfData.Duration or 0 )
end
end
local posFuncGen = createHoldableParamFuncGen( posFunc, holdInd, endAtTime )
local angFuncGen = createHoldableParamFuncGen( angFunc, holdInd, endAtTime )
holdCount = holdCount + 1
kfHoldableForms[holdCount] = {
HoldableInd = holdInd,
JointIdentifier = holdArgs.JointIdentifier,
PosFuncGen = posFuncGen,
AngFuncGen = angFuncGen,
}
end
kfHoldableForms.Count = holdCount
animHoldableForms[kfInd] = kfHoldableForms
return kfPoseForms, kfManipForms, kfHoldableForms
end
-- Clears the cached data for a given pose (or all if provided nil) so you can edit the pose somewhat on the fly.
-- Expect abnormal behavior if you run this while the pose is actively playing. This is mainly intended for things like a pose/animation creator.
-- Poses get cached whenever they get called upon.
function jointClearPoseCache( poseName )
if not poseName then
tableEmpty( jointPosesFormatted )
return
end
jointPosesFormatted[poseName] = nil
end
addRemoteFunc( "JointClearPoseCache", jointClearPoseCache )
-- Same as jointClearPoseCache(), but for animations.
function jointClearAnimCache( animName )
if not animName then
tableEmpty( jointAnimKFPosesFormatted )
tableEmpty( jointAnimKFManipsFormatted )
tableEmpty( jointAnimKFHoldablesFormatted )
tableEmpty( jointAnimDurationTotals )
return
end
jointAnimKFPosesFormatted[animName] = nil
jointAnimKFManipsFormatted[animName] = nil
jointAnimKFHoldablesFormatted[animName] = nil
jointAnimDurationTotals[animName] = nil
end
addRemoteFunc( "JointClearAnimCache", jointClearAnimCache )
function jointUnparentChildren( ent )
local children = ent.jointChildren
if not children then return end
for k, v in pairs( children ) do -- Will unparent regardless of the table using numerical or ent indeces
if type( k ) == "Entity" and isValid( k ) then
k:setParent( nil )
elseif type( v ) == "Entity" and isValid( v ) then
v:setParent( nil )
end
end
end
addRemoteFunc( "JointUnparentChildren", jointUnparentChildren )
function jointParentChildren( ent )
if not isValid( ent ) then return end
local children = ent.jointChildren
if not children then return end
for k, v in pairs( children ) do -- Will parent regardless of the table using numerical or ent indeces
if type( k ) == "Entity" and isValid( k ) then
k:setParent( nil )
k:setParent( ent )
elseif type( v ) == "Entity" and isValid( v ) then
v:setParent( nil )
v:setParent( ent )
end
end
end
addRemoteFunc( "JointParentChildren", jointParentChildren )
function jointIDAndEntFromAny( jointEntOrNameOrInd )
local id
local joint
local jointInputType = type( jointEntOrNameOrInd )
if jointInputType == "number" then
id = jointEntOrNameOrInd
joint = jointEnts[id]
elseif jointInputType == "string" then
id = jointNameToID[jointEntOrNameOrInd]
joint = jointEnts[id]
elseif jointInputType == "Entity" then
joint = jointEntOrNameOrInd
id = jointLookup[joint]
end
return id, isValid( joint ) and joint
end
addRemoteFunc( "JointIDAndEntFromAny", jointIDAndEntFromAny )
function jointGetTrueDirs( ent, jointInfo, skipForward, skipRight, skipUp )
if not isValid( ent ) then return end
jointInfo = jointInfo or ent.jointInfo
if not jointInfo then
return ent:getForward(), ent:getRight(), ent:getUp()
end
local trueForward
local trueRight
local trueUp
if not skipForward and jointInfo.ForwardModified then
trueForward = ent:getForward():rotateAroundAxis( jointInfo.ForwardAdjustAxis, jointInfo.ForwardAdjustDeg )
else
trueForward = ent:getForward()
end
if not skipRight and jointInfo.RightModified then
trueRight = ent:getRight():rotateAroundAxis( jointInfo.RightAdjustAxis, jointInfo.RightAdjustDeg )
else
trueRight = ent:getRight()
end
if not skipUp and jointInfo.UpModified then
trueUp = ent:getUp():rotateAroundAxis( jointInfo.UpAdjustAxis, jointInfo.UpAdjustDeg )
else
trueUp = ent:getUp()
end
return trueForward, trueRight, trueUp
end
addRemoteFunc( "JointGetTrueDirs", jointGetTrueDirs )
function convertTrueLocalToStandardLocal( ent, locPos )
if not isValid( ent ) then return locPos end
if not locPos then return locPos end
local jointInfo = ent.jointInfo
if not jointInfo then
return locPos
end
local forwardAxis = jointInfo.TrueForward or vecForward
local rightAxis = jointInfo.TrueRight or vecRight
local upAxis = jointInfo.TrueUp or vecUp
return locPos[1] * forwardAxis + locPos[2] * rightAxis + locPos[3] * upAxis
end
addRemoteFunc( "ConvertTrueLocalToStandardLocal", convertTrueLocalToStandardLocal )
function convertStandardLocalToTrueLocal( ent, locPos )
if not isValid( ent ) then return locPos end
if not locPos then return locPos end
local jointInfo = ent.jointInfo
if not jointInfo then
return locPos
end
local forwardAxis = jointInfo.TrueForward or vecForward
local rightAxis = jointInfo.TrueRight or vecRight
local upAxis = jointInfo.TrueUp or vecUp
return Vector( locPos:dot( forwardAxis ), locPos:dot( rightAxis ), locPos:dot( upAxis ) )
end
addRemoteFunc( "ConvertStandardLocalToTrueLocal", convertStandardLocalToTrueLocal )
function intendedWorldAngToJointAng( jointIdentifier, worldAng )
local _, joint = jointIDAndEntFromAny( jointIdentifier )
if not joint then return end
local parent = joint.jointParent
if not isValid( parent ) then return end
local parentPos = parent:getPos()
local rotAxisWorldPitch = parent:localToWorld( joint.jointRotAxisPitch ) - parentPos
local rotAxisWorldYaw = parent:localToWorld( joint.jointRotAxisYaw ) - parentPos
local rotAxisWorldRoll = parent:localToWorld( joint.jointRotAxisRoll ) - parentPos
local initAng = parent:localToWorldAngles( joint.jointInitAngStandard )
local CQ = initAng:getQuaternion()
local TQ = worldAng:getQuaternion()
local Q = TQ / CQ
local rotAxis = Q:getRotationAxis()
local rotAmount = Q:getRotationAngle()
local finalAng = Angle(
rotAmount * rotAxis:dot( rotAxisWorldPitch ),
rotAmount * rotAxis:dot( rotAxisWorldYaw ),
rotAmount * rotAxis:dot( rotAxisWorldRoll )
)
return finalAng
end
addRemoteFunc( "IntendedWorldAngToJointAng", intendedWorldAngToJointAng )
local function getIKUpAndBend( joint, parent, lineDir, tiltDeg )
tiltDeg = tiltDeg or 0
local parentPos = parent:getPos()
local initUpDir = parent:localToWorld( joint.jointRotAxisYaw ) - parentPos
local ikUpDir = initUpDir:rotateAroundAxis( lineDir, -tiltDeg )
local bendDir = lineDir:cross( ikUpDir )
local bendLengthCheck = bendDir[1]^2 + bendDir[2]^2 + bendDir[3]^2
if bendLengthCheck ~= 1 then -- If parentAUp and lineDir are not perpendicular, bendDir isn't a unit vector and needs to be fixed
bendDir = bendDir / mSqrt( bendLengthCheck )
end
return ikUpDir, bendDir
end
local function getIKJointAng( joint, parent, _targetOriginPos, targetEndPos, ikUpDir )
local parentPos = parent:getPos()
local hingePosWorld = parent:localToWorld( joint.jointHingePosFromParent )
local rotAxisWorldPitch = parent:localToWorld( joint.jointRotAxisPitch ) - parentPos
local rotAxisWorldYaw = parent:localToWorld( joint.jointRotAxisYaw ) - parentPos
local rotAxisWorldRoll = parent:localToWorld( joint.jointRotAxisRoll ) - parentPos
local initEndPosWorld = parent:localToWorld( joint.jointIKEndFromParent )
local initHingeToEndAngWorld = ( initEndPosWorld - hingePosWorld ):getAngleEx( rotAxisWorldYaw )
local targetHingeToEndAngWorld = ( targetEndPos - hingePosWorld ):getAngleEx( ikUpDir )
local CQ = initHingeToEndAngWorld:getQuaternion()
local TQ = targetHingeToEndAngWorld:getQuaternion()
local Q = TQ / CQ
local rotAxis = Q:getRotationAxis()
local rotAmount = Q:getRotationAngle()
--local initAngWorld = parent:localToWorldAngles( joint.jointInitAngStandard )
--local intendedAngWorld = initAngWorld:rotateAroundAxis( rotAxis, rotAmount )
local finalAng = Angle(
rotAmount * rotAxis:dot( rotAxisWorldPitch ),
rotAmount * rotAxis:dot( rotAxisWorldYaw ),
rotAmount * rotAxis:dot( rotAxisWorldRoll )
)
return finalAng
--return finalAng, intendedAngWorld
end
--[[
--]]
function jointTwoSegIK( jointIdentifierA, jointIdentifierB, endPos, tiltDeg )
local _, jointA = jointIDAndEntFromAny( jointIdentifierA )
local _, jointB = jointIDAndEntFromAny( jointIdentifierB )
if not jointA or not jointB then return end
local parentA = jointA.jointParent
local parentB = jointB.jointParent
if not isValid( parentA ) or not isValid( parentB ) then return end -- ALL joints should have a valid parent if you're moving them!
local startPos = parentA:localToWorld( jointA.jointIKOriginFromParent )
local lineDir = endPos - startPos
local L = lineDir:getLength()
local LA = jointA.jointIKLength
local LB = jointB.jointIKLength
lineDir = lineDir / L
local ikUpDir, bendDir = getIKUpAndBend( jointA, parentA, lineDir, tiltDeg )
local bendPos = ikTwoSeg( startPos, endPos, LA, LB, bendDir, lineDir, L )
local tiltSign = tiltDeg == 0 and 1 or mSign( tiltDeg )
ikUpDir = ( bendPos - startPos ):cross( ikUpDir ):getNormalized() * tiltSign
local finalAngA = getIKJointAng( jointA, parentA, startPos, bendPos, ikUpDir )
local finalAngB = getIKJointAng( jointB, parentB, bendPos, endPos, ikUpDir )
return finalAngA, finalAngB, bendPos
end
addRemoteFunc( "JointTwoSegIK", jointTwoSegIK )
--[[
--]]
function jointThreeSegIK( jointIdentifierA, jointIdentifierB, jointIdentifierC, endPos, LX, tiltDeg1, tiltDeg2 )
local _, jointA = jointIDAndEntFromAny( jointIdentifierA )
local _, jointB = jointIDAndEntFromAny( jointIdentifierB )
local _, jointC = jointIDAndEntFromAny( jointIdentifierC )
if not jointA or not jointB or not jointC then return end
local parentA = jointA.jointParent
local parentB = jointB.jointParent
local parentC = jointC.jointParent
if not isValid( parentA ) or not isValid( parentB ) or not isValid( parentC ) then return end -- ALL joints should have a valid parent if you're moving them!
--local startPos = jointA:localToWorld( jointA.jointIKOrigin )
local startPos = parentA:localToWorld( jointA.jointIKOriginFromParent )
local lineDir1 = endPos - startPos
local L1 = lineDir1:getLength()
local LA = jointA.jointIKLength
local LB = jointB.jointIKLength
local LC = jointC.jointIKLength
lineDir1 = lineDir1 / L1
local ikUpDir1, bendDir1 = getIKUpAndBend( jointA, parentA, lineDir1, tiltDeg1 )
local bendPos1 = ikTwoSeg( startPos, endPos, LA, LX, bendDir1, lineDir1, L1 )
local lineDir2 = endPos - bendPos1
local L2 = LX
lineDir2 = lineDir2 / L2
local ikUpDir2, bendDir2 = getIKUpAndBend( jointB, parentB, lineDir2, tiltDeg2 )
local bendPos2 = ikTwoSeg( bendPos1, endPos, LB, LC, bendDir2, lineDir2, L2 )
local tiltSign1 = tiltDeg1 == 0 and 1 or mSign( tiltDeg1 )
local tiltSign2 = tiltDeg2 == 0 and 1 or mSign( tiltDeg2 )
ikUpDir1 = ( bendPos1 - startPos ):cross( ikUpDir1 ):getNormalized() * tiltSign1
ikUpDir2 = ( bendPos2 - bendPos1 ):cross( ikUpDir2 ):getNormalized() * tiltSign2
local finalAngA = getIKJointAng( jointA, parentA, startPos, bendPos1, ikUpDir1 )
local finalAngB = getIKJointAng( jointB, parentB, bendPos1, bendPos2, ikUpDir2 )
local finalAngC = getIKJointAng( jointC, parentC, bendPos2, endPos, ikUpDir2 )
return finalAngA, finalAngB, finalAngC, bendPos1, bendPos2
end
addRemoteFunc( "JointThreeSegIK", jointThreeSegIK )
--[[
--]]
function jointFourSegIK( jointIdentifierA, jointIdentifierB, jointIdentifierC, jointIdentifierD, endPos, LX1, LX2, tiltDeg1, tiltDeg2, tiltDeg3 )
local _, jointA = jointIDAndEntFromAny( jointIdentifierA )
local _, jointB = jointIDAndEntFromAny( jointIdentifierB )
local _, jointC = jointIDAndEntFromAny( jointIdentifierC )
local _, jointD = jointIDAndEntFromAny( jointIdentifierD )
if not jointA or not jointB or not jointC or not jointD then return end
local parentA = jointA.jointParent
local parentB = jointB.jointParent
local parentC = jointC.jointParent
local parentD = jointD.jointParent
if not isValid( parentA ) or not isValid( parentB ) or not isValid( parentC ) or not isValid( parentD ) then return end -- ALL joints should have a valid parent if you're moving them!
local startPos = parentA:localToWorld( jointA.jointIKOriginFromParent )
local lineDir1 = endPos - startPos
local L1 = lineDir1:getLength()
local LA = jointA.jointIKLength
local LB = jointB.jointIKLength
local LC = jointC.jointIKLength
local LD = jointD.jointIKLength
lineDir1 = lineDir1 / L1
local ikUpDir1, bendDir1 = getIKUpAndBend( jointA, parentA, lineDir1, tiltDeg1 )
local bendPos1 = ikTwoSeg( startPos, endPos, LA, LX1, bendDir1, lineDir1, L1 )
local lineDir2 = endPos - bendPos1
local L2 = LX1
lineDir2 = lineDir2 / L2
local ikUpDir2, bendDir2 = getIKUpAndBend( jointB, parentB, lineDir2, tiltDeg2 )
local bendPos2 = ikTwoSeg( bendPos1, endPos, LB, LX2, bendDir2, lineDir2, L2 )
local lineDir3 = endPos - bendPos2
local L3 = LX2
lineDir3 = lineDir3 / L3
local ikUpDir3, bendDir3 = getIKUpAndBend( jointC, parentC, lineDir3, tiltDeg3 )
local bendPos3 = ikTwoSeg( bendPos2, endPos, LC, LD, bendDir3, lineDir3, L3 )
local tiltSign1 = tiltDeg1 == 0 and 1 or mSign( tiltDeg1 )
local tiltSign2 = tiltDeg2 == 0 and 1 or mSign( tiltDeg2 )
local tiltSign3 = tiltDeg3 == 0 and 1 or mSign( tiltDeg3 )
ikUpDir1 = ( bendPos1 - startPos ):cross( ikUpDir1 ):getNormalized() * tiltSign1
ikUpDir2 = ( bendPos2 - bendPos1 ):cross( ikUpDir2 ):getNormalized() * tiltSign2
ikUpDir3 = ( bendPos3 - bendPos2 ):cross( ikUpDir3 ):getNormalized() * tiltSign3
local finalAngA = getIKJointAng( jointA, parentA, startPos, bendPos1, ikUpDir1 )
local finalAngB = getIKJointAng( jointB, parentB, bendPos1, bendPos2, ikUpDir2 )
local finalAngC = getIKJointAng( jointC, parentC, bendPos2, bendPos3, ikUpDir3 )
local finalAngD = getIKJointAng( jointD, parentD, bendPos3, endPos, ikUpDir3 )
return finalAngA, finalAngB, finalAngC, finalAngD, bendPos1, bendPos2, bendPos3
end
addRemoteFunc( "JointFourSegIK", jointFourSegIK )