-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathIK.lua
More file actions
1578 lines (1467 loc) · 58.6 KB
/
Copy pathIK.lua
File metadata and controls
1578 lines (1467 loc) · 58.6 KB
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
local simIK = loadPlugin('simIK')
local simEigen = require'simEigen'
local class = require('middleclass')
local sim = require('sim')
local sim2 = require('sim-2')
local checkargs = require('checkargs-2')
local properties = require('middleclassProperties')
-- module-level bookkeeping that is genuinely cross-cutting (set elsewhere, e.g. python bindings):
local __ = {}
--==================================================================
-- internal (env is passed explicitly because these are pure helpers)
--==================================================================
function simIK._getObjectPose(env, handle, rel)
rel = rel or simIK.handle_world
local p, q = simIK.getObjectTransformation(env, handle, rel)
return {p[1], p[2], p[3], q[1], q[2], q[3], q[4]}
end
function simIK:_setObjectPose(env, handle, p, rel)
rel = rel or simIK.handle_world
return simIK.setObjectTransformation(env, handle, {p[1], p[2], p[3]}, {p[4], p[5], p[6], p[7]}, rel)
end
--==================================================================
-- IK object class
--==================================================================
local IKObject = class('IKObject')
properties.enable(IKObject)
IKObject.static.property('objectType', {
type = sim.propertytype_string,
flags = sim.propertyinfo_silent | sim.propertyinfo_notwritable | sim.propertyinfo_modelhashexclude,
info = {description = "The object type"},
get = function(self)
local t = simIK.getObjectType(self._ik.handle, self.handle)
local retVal = 'unknown'
local items = {[simIK.objecttype_dummy] = 'dummy', [simIK.objecttype_joint] = 'joint'}
local r = items[t]
if r then
retVal = r
end
return retVal
end,
})
function IKObject:setPose(p, opt)
p = checkargs.checkargsEx({funcName = 'IKObject:setPose'}, {
{type = 'pose'},
}, p)
opt = opt or {}
local hRel = -1
if opt.relativeToObject then
hRel = opt.relativeToObject.handle
end
simIK.setObjectTransformation(self._ik.handle, self.handle, p.t:data(), p.q:data(), hRel)
end
function IKObject:getPose(opt)
opt = opt or {}
local hRel = -1
if opt.relativeToObject then
hRel = opt.relativeToObject.handle
end
local t, q = simIK.getObjectTransformation(self._ik.handle, self.handle, hRel)
return simEigen.Pose(t, q)
end
function IKObject:setPosition(p, opt)
p = checkargs.checkargsEx({funcName = 'IKObject:setPosition'}, {
{type = 'vector3'},
}, p)
opt = opt or {}
local hRel = -1
if opt.relativeToObject then
hRel = opt.relativeToObject.handle
end
local t, q = simIK.getObjectTransformation(self._ik.handle, self.handle, hRel)
simIK.setObjectTransformation(self._ik.handle, self.handle, p:data(), q, hRel)
end
function IKObject:getPosition(opt)
opt = opt or {}
local hRel = -1
if opt.relativeToObject then
hRel = opt.relativeToObject.handle
end
local t, q = simIK.getObjectTransformation(self._ik.handle, self.handle, hRel)
return simEigen.Vector(t)
end
function IKObject:setQuaternion(p, opt)
p = checkargs.checkargsEx({funcName = 'IKObject:setQuaternion'}, {
{type = 'quaternion'},
}, p)
opt = opt or {}
local hRel = -1
if opt.relativeToObject then
hRel = opt.relativeToObject.handle
end
local t, q = simIK.getObjectTransformation(self._ik.handle, self.handle, hRel)
simIK.setObjectTransformation(self._ik.handle, self.handle, t, p:data(), hRel)
end
function IKObject:getQuaternion(opt)
opt = opt or {}
local hRel = -1
if opt.relativeToObject then
hRel = opt.relativeToObject.handle
end
local t, q = simIK.getObjectTransformation(self._ik.handle, self.handle, hRel)
return simEigen.Quaternion(q)
end
function IKObject:initialize(ik, objectHandle)
self._ik = ik
self.handle = objectHandle
end
--==================================================================
-- IK joint class
--==================================================================
local IKJoint = class("IKJoint", IKObject)
properties.enable(IKJoint)
IKJoint.static.property('passive', {
type = sim.propertytype_bool,
info = {description = "Whether the joint participates in IK resolution"},
get = function(self)
return simIK.getJointMode(self._ik.handle, self.handle) == simIK.jointmode_passive
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKJoint.passive property'}, {
{type = 'bool'},
}, value)
local v = simIK.jointmode_ik
if value then
v = simIK.jointmode_passive
end
simIK.setJointMode(self._ik.handle, self.handle, v)
end,
})
IKJoint.static.property('jointPosition', {
type = sim.propertytype_float,
info = {description = "The prismatic/revolute joint's linear/angular displacement"},
get = function(self)
return simIK.getJointPosition(self._ik.handle, self.handle)
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKJoint.position property'}, {
{type = 'float'},
}, value)
simIK.setJointPosition(self._ik.handle, self.handle, value)
end,
})
IKJoint.static.property('jointQuaternion', {
type = sim.propertytype_quaternion,
info = {description = "The spherical joint's orientation"},
get = function(self)
local p, q = simIK.getJointTransformation(self._ik.handle, self.handle)
return simEigen.quaternion(q)
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKJoint.quaternion property'}, {
{type = 'quaternion'},
}, value)
simIK.setSphericalJointRotation(self._ik.handle, self.handle, value:data())
end,
})
IKJoint.static.property('jointConfiguration', {
type = sim.propertytype_floatarray,
info = {description = "The joint's configuration. 1 value for prismatic and revolute joints, 4 values for a spherical joint"},
get = function(self)
local retVal
if simIK.getJointType(self._ik.handle, self.handle) == simIK.jointtype_spherical then
local p, q = simIK.getJointTransformation(self._ik.handle, self.handle)
retVal = q:data()
else
retVal = {simIK.getJointPosition(self._ik.handle, self.handle)}
end
return retVal
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKJoint.configuration property'}, {
{type = 'table', itemType = 'float', size = "1..4"},
}, value)
if simIK.getJointType(self._ik.handle, self.handle) == simIK.jointtype_spherical then
simIK.setSphericalJointRotation(self._ik.handle, self.handle, value)
else
simIK.setJointPosition(self._ik.handle, self.handle, value[1])
end
end,
})
IKJoint.static.property('weight', {
type = sim.propertytype_float,
info = {description = "The joint weight"},
get = function(self)
return simIK.getJointWeight(self._ik.handle, self.handle)
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKJoint.weight property'}, {
{type = 'float'},
}, value)
simIK.setJointWeight(self._ik.handle, self.handle, value)
end,
})
IKJoint.static.property('limitMargin', {
type = sim.propertytype_float,
info = {description = "The joint limit margin"},
get = function(self)
return simIK.getJointLimitMargin(self._ik.handle, self.handle)
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKJoint.limitMargin property'}, {
{type = 'float'},
}, value)
simIK.setJointLimitMargin(self._ik.handle, self.handle, value)
end,
})
IKJoint.static.property('maxStepSize', {
type = sim.propertytype_float,
info = {description = "The joint maximum step size"},
get = function(self)
return simIK.getJointMaxStepSize(self._ik.handle, self.handle)
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKJoint.maxStepSize property'}, {
{type = 'float'},
}, value)
simIK.setJointMaxStepSize(self._ik.handle, self.handle, value)
end,
})
IKJoint.static.property('jointType', {
type = sim.propertytype_string,
flags = sim.propertyinfo_silent | sim.propertyinfo_notwritable | sim.propertyinfo_modelhashexclude,
info = {description = "The joint type"},
get = function(self)
local t = simIK.getJointType(self._ik.handle, self.handle)
local retVal = 'unknown'
local items = {[simIK.jointtype_prismatic] = 'prismatic', [simIK.jointtype_revolute] = 'revolute', [simIK.jointtype_spherical] = 'spherical'}
local r = items[t]
if r then
retVal = r
end
return retVal
end,
})
IKJoint.static.property('bounds', {
type = sim.propertytype_floatarray,
flags = sim.propertyinfo_silent | sim.propertyinfo_notwritable | sim.propertyinfo_modelhashexclude,
info = {description = "The joint lower and upper bounds"},
get = function(self)
local t = simIK.getJointType(self._ik.handle, self.handle)
local cycl, interv = simIK.getJointInterval(self._ik.handle, self.handle)
local retVal = {}
if t ~= simIK.jointtype_spherical then
if cycl then
retVal = {-math.pi, math.pi}
else
retVal = {interv[1], interv[1] + interv[2]}
end
end
return retVal
end,
})
IKJoint.static.property('searchMetric', {
type = sim.propertytype_float,
info = {description = "The joint weight in search operations"},
get = function(self)
return self._searchMetric
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKJoint.searchMetric property'}, {
{type = 'float'},
}, value)
self._searchMetric = value
end,
})
function IKJoint:initialize(ik, objectHandle)
IKObject.initialize(self, ik, objectHandle)
self._searchMetric = 1.0
end
--==================================================================
-- IK element class
--==================================================================
local IKElement = class('IKElement')
properties.enable(IKElement)
IKElement.static.property('constraints', {
type = sim.propertytype_int,
info = {description = "Element constraints"},
get = function(self)
return simIK.getElementConstraints(self._ik.handle, self._group.handle, self.handle)
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKElement.constraints property'}, {
{type = 'int'},
}, value)
simIK.setElementConstraints(self._ik.handle, self._group.handle, self.handle, value)
end,
})
IKElement.static.property('enabled', {
type = sim.propertytype_bool,
info = {description = "Element enable state"},
get = function(self)
return simIK.getElementFlags(self._ik.handle, self._group.handle, self.handle) & 1
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKElement.enabled property'}, {
{type = 'bool'},
}, value)
value = value and 1 or 0
simIK.setElementFlags(self._ik.handle, self._group.handle, self.handle, value)
end,
})
IKElement.static.property('precision', {
type = sim.propertytype_floatarray,
info = {description = "Element precision"},
get = function(self)
return simIK.getElementPrecision(self._ik.handle, self._group.handle, self.handle)
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKElement.precision property'}, {
{type = 'table', itemType = 'float', size = 2},
}, value)
simIK.setElementPrecision(self._ik.handle, self._group.handle, self.handle, value)
end,
})
IKElement.static.property('weights', {
type = sim.propertytype_floatarray,
info = {description = "Element weights"},
get = function(self)
return simIK.getElementWeights(self._ik.handle, self._group.handle, self.handle)
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKElement.weights property'}, {
{type = 'table', itemType = 'float', size = 2},
}, value)
simIK.setElementWeights(self._ik.handle, self._group.handle, self.handle, value)
end,
})
function IKElement:initialize(ik, group, elementHandle, opt)
self._ik = ik
self._group = group
self.handle = elementHandle
opt = opt or {}
checkargs.checkfields({funcName = 'IKElement:new'}, {
{name = 'precision', type = 'table', size = 2, itemType = 'float', nullable = true},
{name = 'weights', type = 'table', size = 3, itemType = 'float', nullable = true},
{name = 'constraints', type = 'int', nullable = true},
{name = 'enabled', type = 'bool', nullable = true},
}, opt)
if opt.precision then
simIK.setElementPrecision(self._ik.handle, self._group.handle, self.handle, opt.precision)
end
if opt.weights then
simIK.setElementWeights(self._ik.handle, self._group.handle, self.handle, opt.weights)
end
if opt.enabled then
simIK.setElementFlags(self._ik.handle, self._group.handle, self.handle, opt.enabled and 1 or 0)
end
end
--==================================================================
-- IK group class
--==================================================================
local IKGroup = class('IKGroup')
properties.enable(IKGroup)
IKGroup.static.property('method', {
type = sim.propertytype_int,
info = {description = "Group calculation method"},
get = function(self)
local m, damp, it = simIK.getGroupCalculation(self._ik.handle, self.handle)
local retVal = 'unknown'
local items = {[simIK.method_pseudo_inverse] = 'pseudoInverse', [simIK.method_undamped_pseudo_inverse] = 'undampedPseudoInverse', [simIK.method_damped_least_squares] = 'dampedLeastSquares', [simIK.method_jacobian_transpose] = 'jacobianTranspose'}
local r = items[m]
if r then
retVal = r
end
return retVal
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKGroup.method property'}, {
{enum = {pseudoInverse = simIK.method_pseudo_inverse, undampedPseudoInverse = simIK.method_undamped_pseudo_inverse, dampedLeastSquares = simIK.method_damped_least_squares, jacobianTranspose = simIK.method_jacobian_transpose}},
}, value)
local m, damp, it = simIK.getGroupCalculation(self._ik.handle, self.handle)
simIK.setGroupCalculation(self._ik.handle, self.handle, value, damp, it)
end,
})
IKGroup.static.property('maxIterations', {
type = sim.propertytype_int,
info = {description = "Maximum number of iterations"},
get = function(self)
local m, damp, it = simIK.getGroupCalculation(self._ik.handle, self.handle)
return it
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKGroup.maxIterations property'}, {
{type = 'int'},
}, value)
local m, damp, it = simIK.getGroupCalculation(self._ik.handle, self.handle)
simIK.setGroupCalculation(self._ik.handle, self.handle, m, damp, value)
end,
})
IKGroup.static.property('damping', {
type = sim.propertytype_float,
info = {description = "Damping coefficient"},
get = function(self)
local m, damp, it = simIK.getGroupCalculation(self._ik.handle, self.handle)
return damp
end,
set = function(self, value)
value = checkargs.checkargsEx({funcName = 'IKGroup.damping property'}, {
{type = 'float'},
}, value)
local m, damp, it = simIK.getGroupCalculation(self._ik.handle, self.handle)
simIK.setGroupCalculation(self._ik.handle, self.handle, m, value, it)
end,
})
function IKGroup:initialize(ik, groupHandle, opt)
self._ik = ik
self.handle = groupHandle
self.elements = {}
self.joints = {}
opt = opt or {}
checkargs.checkfields({funcName = 'IKGroup:new'}, {
{name = 'method', enum = {pseudoInverse = simIK.method_pseudo_inverse, undampedPseudoInverse = simIK.method_undamped_pseudo_inverse, dampedLeastSquares = simIK.method_damped_least_squares, jacobianTranspose = simIK.method_jacobian_transpose}, nullable = true},
{name = 'damping', type = 'float', nullable = true},
{name = 'maxIterations', type = 'int', range = '1..*', nullable = true},
{name = 'enabled', type = 'bool', nullable = true},
{name = 'ignoreMaxSteps', type = 'bool', nullable = true},
{name = 'restoreOnBadLinTol', type = 'bool', nullable = true},
{name = 'restoreOnBadAngTol', type = 'bool', nullable = true},
{name = 'avoidLimits', type = 'bool', nullable = true},
{name = 'stopOnLimitHit', type = 'bool', nullable = true},
}, opt)
local meth, damp, it = simIK.getGroupCalculation(self._ik.handle, self.handle)
if opt.method then
meth = opt.method
end
if opt.damping then
damp = opt.damping
end
if opt.maxIterations then
it = opt.maxIterations
end
simIK.setGroupCalculation(self._ik.handle, self.handle, meth, damp, it)
local fl = simIK.getGroupFlags(self._ik.handle, self.handle)
if opt.enabled ~= nil then
fl = fl & simIK.group_enabled
if not opt.enabled then
fl = fl - simIK.group_enabled
end
end
if opt.ignoreMaxSteps ~= nil then
fl = fl & simIK.group_ignoremaxsteps
if not opt.ignoreMaxSteps then
fl = fl - simIK.group_ignoremaxsteps
end
end
if opt.restoreOnBadLinTol ~= nil then
fl = fl & simIK.group_restoreonbadlintol
if not opt.restoreOnBadLinTol then
fl = fl - simIK.group_restoreonbadlintol
end
end
if opt.restoreOnBadAngTol ~= nil then
fl = fl & simIK.group_restoreonbadangtol
if not opt.restoreOnBadAngTol then
fl = fl - simIK.group_restoreonbadangtol
end
end
if opt.avoidLimits ~= nil then
fl = fl & simIK.group_avoidlimits
if not opt.avoidLimits then
fl = fl - simIK.group_avoidlimits
end
end
if opt.stopOnLimitHit ~= nil then
fl = fl & simIK.group_stoponlimithit
if not opt.stopOnLimitHit then
fl = fl - simIK.group_stoponlimithit
end
end
simIK.setGroupFlags(self._ik.handle, self.handle, fl)
end
function IKGroup:solve(opt)
local retVal = false
local reason = simIK.calc_notperformed
local achievedPrecision = {0.0, 0.0}
local ok
for k, v in pairs(self.elements) do
if not v.passive then
ok = true
break
end
end
if ok then
opt = opt or {}
checkargs.checkfields({funcName = 'IKGroup:solve'}, {
{name = 'debug', type = 'int', default = 0},
{name = 'syncWorlds', type = 'bool', default = true},
{name = 'allowError', type = 'bool', default = true},
}, opt)
if opt.syncWorlds then
self:syncFromSim()
end
retVal, reason, achievedPrecision = self._ik:_handleGroups({self.handle}, opt)
if (reason & (simIK.calc_notperformed | simIK.calc_cannotinvert | simIK.calc_invalidcallbackdata)) == 0 then
-- no serious error
if opt.allowError then
retVal = true
if opt.syncWorlds then
self:syncToSim()
end
else
retVal = (reason == 0)
end
else
-- serious error
retVal = false
end
self._ik:_debugGroupIfNeeded(self.handle, opt.debug)
if (not retVal) and opt.syncWorlds then
self:syncFromSim() -- not really necessary, but better to keep IK world ordered
end
end
return retVal, reason, achievedPrecision
end
function IKGroup:addElementFromScene(base, tip, target, const, opt)
base, tip, target, const, opt = checkargs.checkargsEx({funcName = 'addElementFromScene'}, {
{type = 'handle', nullable = true},
{type = 'handle'},
{type = 'handle'},
{type = 'int'},
{type = 'table', nullable = true},
}, base, tip, target, const, opt)
local ik = self._ik
local baseH = -1
if base then
baseH = base.handle
end
local tipH = tip.handle
local targetH = target.handle
opt = opt or {}
local elementHandle, simToIkMap = ik:_addElementFromScene(self.handle, baseH, tipH, targetH, const)
opt.constraints = const
local element = IKElement(ik, self, elementHandle, opt)
self.elements[elementHandle] = element
-- Wrap simIK objects:
for k, v in pairs(simToIkMap) do
if self._ik.objects[k] == nil then
if simIK.getObjectType(ik.handle, v) == simIK.objecttype_joint then
local joint = IKJoint(ik, v)
ik.objects[k] = joint
ik.joints[k] = joint
else
local obj = IKObject(ik, v)
ik.objects[k] = obj
end
end
end
local obj = tip.parent
while obj ~= base do
if obj.type == 'joint' and ik.joints[obj.handle] then
self.joints[obj.handle] = ik.joints[obj.handle]
end
obj = obj.parent
end
self.simToIkMap = simToIkMap
return element
end
function IKGroup:syncFromSim()
local ikEnv = self._ik.handle
local lb = sim.setStepping(true)
local groupData = self._ik._ikGroupData[self.handle]
for k, v in pairs(groupData.joints) do
if sim.isHandle(k) then
if sim.getJointType(k) == sim.joint_spherical then
simIK.setSphericalJointMatrix(ikEnv, v, sim.getJointMatrix(k))
else
simIK.setJointPosition(ikEnv, v, sim.getJointPosition(k))
end
else
-- probably a joint in a dependency relation that was removed
simIK.eraseObject(ikEnv, v)
groupData.joints[k] = nil
self._ik._simToIkMap[k] = nil
end
end
for i = 1, #groupData.targetTipBaseTriplets do
simIK.setObjectMatrix(ikEnv,
groupData.targetTipBaseTriplets[i][4], sim.getObjectMatrix(
groupData.targetTipBaseTriplets[i][1], groupData.targetTipBaseTriplets[i][3]
), groupData.targetTipBaseTriplets[i][6]
)
end
sim.setStepping(lb)
end
function IKGroup:syncToSim()
local ikEnv = self._ik.handle
local lb = sim.setStepping(true)
local groupData = self._ik._ikGroupData[self.handle]
for k, v in pairs(groupData.joints) do
if sim.isHandle(k) then
if sim.getJointType(k) == sim.joint_spherical then
if sim.getJointMode(k) ~= sim.jointmode_dynamic or not sim.isDynamicallyEnabled(k) then
sim.setSphericalJointMatrix(k, simIK.getJointMatrix(ikEnv, v))
end
else
if sim.getJointMode(k) == sim.jointmode_dynamic and sim.isDynamicallyEnabled(k) then
sim.setJointTargetPosition(k, simIK.getJointPosition(ikEnv, v))
else
sim.setJointPosition(k, simIK.getJointPosition(ikEnv, v))
end
end
else
simIK.eraseObject(ikEnv, v)
groupData.joints[k] = nil
self._ik._simToIkMap[k] = nil
end
end
sim.setStepping(lb)
end
--==================================================================
-- IK class
--==================================================================
local IK = class('IK')
function IK:initialize()
self.handle = simIK.createEnvironment()
self.objects = {}
self.joints = {}
self.groups = {}
self._groupMap = {}
-- internal use:
self._ikGroupData = {}
self._ikGroupHandles = {}
self._simToIkMap = {}
self._ikDebug = nil
self.constraint_x = simIK.constraint_x
self.constraint_y = simIK.constraint_y
self.constraint_z = simIK.constraint_z
self.constraint_alphabeta = simIK.constraint_alpha_beta
self.constraint_gamma = simIK.constraint_gamma
self.constraint_position = simIK.constraint_position
self.constraint_orientation = simIK.constraint_orientation
self.constraint_pose = simIK.constraint_pose
self.result_notperformed = simIK.result_not_performed
self.result_success = simIK.result_success
self.result_fail = simIK.result_fail
self.calc_notperformed = simIK.calc_notperformed
self.calc_cannotinvert = simIK.calc_cannotinvert
self.calc_notwithintolerance = simIK.calc_notwithintolerance
self.calc_stepstoobig = simIK.calc_stepstoobig
self.calc_limithit = simIK.calc_limithit
self.calc_invalidcallbackdata = simIK.calc_invalidcallbackdata
end
function IK:createGroup(opt)
local groupHandle = simIK.createIkGroup(self.handle)
self._ikGroupHandles[#self._ikGroupHandles + 1] = groupHandle
local group = IKGroup(self, groupHandle, opt)
self.groups[#self.groups + 1] = group
self._groupMap[groupHandle] = group
return group
end
function IK:syncFromSim()
local lb = sim.setStepping(true)
for g = 1, #self.groups do
self.groups[g]:syncFromSim()
end
sim.setStepping(lb)
end
function IK:syncToSim()
local lb = sim.setStepping(true)
for g = 1, #self.groups do
self.groups[g]:syncToSim()
end
sim.setStepping(lb)
end
function IK:_debugGroupIfNeeded(ikGroup, debugFlags)
local groupData = self._ikGroupData[ikGroup]
if not groupData then return end
local p = sim.getIntProperty(sim.handle_app, 'signal.simIK.debug_world', {noError = true})
if (p and (p & 1) ~= 0) or ((debugFlags & 1) ~= 0) then
local lb = sim.setStepping(true)
groupData.visualDebug = {}
for i = 1, #groupData.targetTipBaseTriplets do
groupData.visualDebug[i] = self:_createDebugOverlay(
groupData.targetTipBaseTriplets[i][5],
groupData.targetTipBaseTriplets[i][6]
)
end
sim.setStepping(lb)
else
if groupData.visualDebug then
for i = 1, #groupData.visualDebug do
self:_eraseDebugOverlay(groupData.visualDebug[i])
end
end
groupData.visualDebug = {}
end
end
function IK:_addElementFromScene(ikGroup, simBase, simTip, simTarget, constraints)
local ikEnv = self.handle
local lb = sim.setStepping(true)
local groupData = self._ikGroupData[ikGroup]
-- simToIkMap is scoped by env (not by group) to avoid duplicates:
local simToIkMap = self._simToIkMap
if not groupData then
groupData = {joints = {}, targetTipBaseTriplets = {}}
self._ikGroupData[ikGroup] = groupData
end
local function createIkJointFromSimJoint(simJoint)
local t = sim.getJointType(simJoint)
local ikJoint = simIK.createJoint(ikEnv, t)
local c, interv = sim.getJointInterval(simJoint)
simIK.setJointInterval(ikEnv, ikJoint, c, interv)
local sp = sim.getFloatProperty(simJoint, 'screwLead')
simIK.setJointScrewLead(ikEnv, ikJoint, sp)
if t == sim.joint_spherical then
simIK.setSphericalJointMatrix(ikEnv, ikJoint, sim.getJointMatrix(simJoint))
else
simIK.setJointPosition(ikEnv, ikJoint, sim.getJointPosition(simJoint))
end
return ikJoint
end
local function iterateAndAdd(theTip, theBase)
local ikPrevIterator = -1
local simIterator = theTip
while true do
local ikIterator = -1
if simToIkMap[simIterator] then
ikIterator = simToIkMap[simIterator]
else
if sim.getObjectType(simIterator) ~= sim.sceneobject_joint then
ikIterator = simIK.createDummy(ikEnv)
else
ikIterator = createIkJointFromSimJoint(simIterator)
end
simToIkMap[simIterator] = ikIterator
simIK.setObjectMatrix(self.handle, ikIterator, sim.getObjectMatrix(simIterator), simIK.handle_world)
end
if sim.getObjectType(simIterator) == sim.sceneobject_joint then
groupData.joints[simIterator] = ikIterator
end
if ikPrevIterator ~= -1 then
simIK.setObjectParent(ikEnv, ikPrevIterator, ikIterator)
end
local newSimIterator = sim.getObjectParent(simIterator)
if simIterator == theBase or newSimIterator == -1 then break end
simIterator = newSimIterator
ikPrevIterator = ikIterator
end
end
iterateAndAdd(simTip, -1) -- add the whole chain down to world, otherwise subtle bugs!
local ikTip = simToIkMap[simTip]
local ikBase = -1
if simBase ~= -1 then ikBase = simToIkMap[simBase] end
iterateAndAdd(simTarget, -1) -- add the whole target chain down to world too!
local ikTarget = simToIkMap[simTarget]
simIK.setTargetDummy(ikEnv, ikTip, ikTarget)
groupData.targetTipBaseTriplets[#groupData.targetTipBaseTriplets + 1] = {
simTarget, simTip, simBase, ikTarget, ikTip, ikBase,
}
-- joint dependencies (slaves/masters/passives):
local simJoints = sim.getObjectsInTree(sim.handle_scene, sim.sceneobject_joint)
local slaves = {}
local masters = {}
local passives = {}
for i = 1, #simJoints do
local jo = simJoints[i]
if sim.getJointMode(jo) == sim.jointmode_dependent then
local dep, off, mult = sim.getJointDependency(jo)
if dep ~= -1 then
slaves[#slaves + 1] = jo
masters[#masters + 1] = dep
else
passives[#passives + 1] = jo
end
end
end
for i = 1, #passives do
local ikJo = simToIkMap[passives[i]]
if ikJo then simIK.setJointMode(ikEnv, ikJo, simIK.jointmode_passive) end
end
for i = 1, #slaves do
local slave = slaves[i]
local master = masters[i]
local ikJo_s = simToIkMap[slave]
local ikJo_m = simToIkMap[master]
if ikJo_s == nil then
ikJo_s = createIkJointFromSimJoint(slave)
simToIkMap[slave] = ikJo_s
simIK.setObjectMatrix(self.handle, ikJo_s, sim.getObjectMatrix(slave), simIK.handle_world)
groupData.joints[slave] = ikJo_s
end
if ikJo_m == nil then
ikJo_m = createIkJointFromSimJoint(master)
simToIkMap[master] = ikJo_m
simIK.setObjectMatrix(self.handle, ikJo_m, sim.getObjectMatrix(master), simIK.handle_world)
groupData.joints[master] = ikJo_m
end
local dep, off, mult = sim.getJointDependency(slave)
self:_setJointDependency(ikJo_s, ikJo_m, off, mult)
end
local ikElement = simIK.addElement(ikEnv, ikGroup, ikTip)
simIK.setElementBase(ikEnv, ikGroup, ikElement, ikBase, -1)
simIK.setElementConstraints(ikEnv, ikGroup, ikElement, constraints)
sim.setStepping(lb)
return ikElement, simToIkMap
end
function IK:remove()
local lb = sim.setStepping(true)
for k, v in pairs(self._ikGroupData) do
if v.visualDebug then
for i = 1, #v.visualDebug do
self:_eraseDebugOverlay(v.visualDebug[i])
end
end
end
self.groups = {}
self.objects = {}
self.joints = {}
self._groupMap = {}
self._ikGroupData = {}
self._ikGroupHandles = {}
self._simToIkMap = {}
if self.handle then
simIK._eraseEnvironment(self.handle)
self.handle = nil
end
sim.setStepping(lb)
end
function IK:_findConfig(...)
local ikGroup, joints, thresholdDist, maxTime, metric, callback, auxData = checkargs({
{type = 'int'},
{type = 'table', size = '1..*', item_type = 'int'},
{type = 'float', default = 0.1},
{type = 'float', default = 0.5},
{type = 'table', size = 4, item_type = 'float', default = {1, 1, 1, 0.1}, nullable = true},
{type = 'any', default_nil = true, nullable = true},
{type = 'any', default_nil = true, nullable = true},
}, ...)
local env = self.handle
local lb = sim.setStepping(true)
if metric == nil then metric = {1, 1, 1, 0.1} end
local __callback
function __ikcb(config)
local fun = _G
if string.find(__callback, "%.") then
for w in __callback:gmatch("[^%.]+") do
if fun[w] then fun = fun[w] end
end
else
fun = fun[__callback]
end
if type(fun) == 'function' then
return fun(config, auxData)
end
end
local funcNm, t
if callback then
__callback = reify(callback)
funcNm = '__ikcb'
t = sim.getScript(sim.handle_self)
end
-- IK:_findConfig is a different table than simIK._findConfig, so no recursion here:
local retVal = simIK._findConfig(env, ikGroup, joints, thresholdDist, maxTime * 1000, metric, funcNm, t)
sim.setStepping(lb)
return retVal
end
function IK:_debugJacobianDisplay(inData)
local groupData = self._ikGroupData[inData.group.handle]
local groupIdStr = string.format('env:%d/group:%d', self.handle, inData.group.handle)
local simQML
pcall(function() simQML = require 'simQML' end)
if simQML then
if groupData.jacobianDebug == nil then
groupData.jacobianDebug = {qmlEngine = simQML.createEngine()}
function jacobianDebugClicked()
jacobianDebugPrint = true
end
simQML.setEventHandler(groupData.jacobianDebug.qmlEngine, 'dispatchEventsToFunctions')
simQML.loadData(
groupData.jacobianDebug.qmlEngine, [[
import QtQuick 2.12
import QtQuick.Window 2.12
import CoppeliaSimPlugin 1.0
PluginWindow {
id: mainWindow
width: cellSize * cols
height: cellSize * rows
title: "Jacobian ]] .. groupIdStr .. [["
readonly property string groupId: "]] .. groupIdStr .. [["
property int rows: 6
property int cols: 12
readonly property int cellSize: 15
property real absMin: 0
property real absMax: 0.001
property bool initMax: true
property var jacobianData: {
var _t = []
for(var iy = 0; iy < rows; iy++) {
var _r = []
for(var ix = 0; ix < cols; ix++) {
var z = iy/rows - ix/cols
z = Math.sign(z) * Math.pow(10, 3 * Math.abs(z))
_r.push(z)
}
_t.push(_r)
}
return _t
}
function colorMap(value) {
var min = Math.log10(Math.max(0.00001, absMin))
var max = Math.log10(absMax)
var sign = Math.sign(value)
value = Math.max(0, Math.min(1, (Math.log10(Math.abs(value)) - min) / Math.max(1e-9, max - min)))
var c = x => Math.min(Math.max(x, 0), 1)
var r = c(sign * value)
var b = c(-sign * value)
return Qt.rgba(1 - b, 1 - 0.6 * (r + b), 1 - r)
}
Column {
Repeater {
model: mainWindow.rows
Row {
readonly property int i: index
readonly property var rowData: mainWindow.jacobianData[i] || new Array(mainWindow.cols).fill(0)
Repeater {