-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathsim-1.lua
More file actions
1990 lines (1818 loc) · 68.3 KB
/
sim-1.lua
File metadata and controls
1990 lines (1818 loc) · 68.3 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
-- The is the first versioned sim-namespace
local sim = table.clone(_S.internalApi.sim)
sim.version = 1
for k, v in pairs(_S.internalApi.sim1) do
sim[k] = v
end
local locals = {}
__1 = {} -- sometimes globals are needed (but __1 only for sim-1)
if unpack == nil then
function unpack(...)
sim.addLog(sim.verbosity_scriptwarnings | sim.verbosity_once, "unpack is deprecated. Use table.unpack instead.")
return table.unpack(...)
end
end
sim.addLog = addLog
sim.quitSimulator = quitSimulator
sim.registerScriptFuncHook = registerScriptFuncHook
sim.addDrawingObject = sim.createDrawingObject
sim.loadImage = wrap(sim.loadImage, function(origFunc)
return function(loc, op)
return origFunc(op, loc) -- in sim-1 input args are inverted
end
end)
sim.saveImage = wrap(sim.saveImage, function(origFunc)
return function(img, res, op, fName, qual)
return origFunc(img, res, fName, op, qual) -- in sim-1 input args are ordered differently
end
end)
sim.loadModel = wrap(sim.loadModel, function(origFunc)
return function(loc, op)
local opts = 0
if op then opts = 1 end
return origFunc(loc, opts) -- in sim-1 arg2 is a bool
end
end)
sim.transformBuffer = wrap(sim.transformBuffer, function(origFunc)
return function(a, b, c, d, e)
return origFunc(a, b, e, c, d) -- in sim-1 input arg order has changed
end
end)
function sim.addItemToCollection(c, w, h, o)
return sim.addToCollection(c, h, w, o)
end
sim.callScriptFunction = wrap(sim.callScriptFunction, function(origFunc)
return function(a, b, ...)
if type(a) ~= 'number' then
local tmp = a
a = b
b = tmp
end
return origFunc(a, b, ...)
end
end)
sim.executeScriptString = wrap(sim.executeScriptString, function(origFunc)
return function(a, b, ...)
if type(a) ~= 'number' then
local tmp = a
a = b
b = tmp
end
return origFunc(a, b, ...)
end
end)
function sim.readCustomBufferData(obj, tag)
local retVal = sim.readCustomStringData(obj, tag)
if retVal then
retVal = tobuffer(retVal)
end
return retVal
end
function sim.writeCustomBufferData(obj, tag, data)
return sim.writeCustomStringData(obj, tag, data)
end
function sim.getBufferSignal(sigName)
local retVal = sim.getStringSignal(sigName)
if retVal then
retVal = tobuffer(retVal)
end
return retVal
end
function sim.setBufferSignal(sigName, data)
sim.setStringSignal(sigName, tostring(data))
end
function sim.clearBufferSignal(sigName)
sim.clearStringSignal(sigName)
end
function sim.setStepping(enable)
-- Convenience function, so that we have the same, more intuitive name also with external clients
-- Needs to be overridden by Python wrapper and remote API server code
if type(enable) ~= 'number' then enable = not enable end
return setAutoYield(enable)
end
function sim.acquireLock()
-- needs to be overridden by remote API components
setYieldAllowed(false)
end
function sim.releaseLock()
-- needs to be overridden by remote API components
setYieldAllowed(true)
end
function sim.yield()
if getYieldAllowed() then
local thread, yieldForbidden = coroutine.running()
if not yieldForbidden then coroutine.yield() end
end
end
function sim.step(wait)
-- Convenience function, for a more intuitive name, depending on the context
-- Needs to be overridden by Python wrapper and remote API server code
sim.yield()
end
sim.getObject = wrap(sim.getObject, function(origFunc)
return function(path, options)
options = options or {}
local proxy = -1
local index = -1
local option = 0
if options.proxy then proxy = options.proxy end
if options.index then index = options.index end
if options.noError then option = 1 end
return origFunc(path, index, proxy, option)
end
end)
sim.getObjectFromUid = wrap(sim.getObjectFromUid, function(origFunc)
return function(path, options)
options = options or {}
local option = 0
if options.noError then option = 1 end
return origFunc(path, option)
end
end)
function sim.getObjectHandle(path, options)
options = options or {}
local proxy = -1
local index = -1
local option = 0
if options.proxy then proxy = options.proxy end
if options.index then index = options.index end
if options.noError then option = 1 end
local h = sim._getObjectHandle(path, index, proxy, option)
local c = string.sub(path, 1, 1)
if c ~= '.' and c ~= ':' and c ~= '/' then
sim.addLog(sim.verbosity_scriptwarnings | sim.verbosity_once, "sim.getObjectHandle is deprecated. Use sim.getObject instead.")
end
return h
end
function sim.getObjectAliasRelative(handle, baseHandle, aliasOptions, options)
if handle == baseHandle then return '.' end
aliasOptions = aliasOptions or -1
options = options or {}
local function getPath(h, parent)
parent = parent or -1
local tmp = h
local path = {}
while tmp ~= parent do
if tmp == -1 then return end
table.insert(path, 1, tmp)
tmp = sim.getObjectParent(tmp)
end
return path
end
local path = getPath(handle)
local basePath = getPath(baseHandle)
local commonAncestor = -1
local commonAncestorModel = -1
for i = 1, math.min(#path, #basePath) do
if path[i] == basePath[i] then
commonAncestor = path[i]
if sim.getModelProperty(path[i]) & sim.modelproperty_not_model == 0 then
commonAncestorModel = path[i]
end
else
break
end
end
local function isAncestor(a, h)
-- true iff. h is a (grand-)child of a
if a == h then return true end
local tmp = h
while tmp ~= -1 do
tmp = sim.getObjectParent(tmp)
if tmp == a then return true end
end
return false
end
if commonAncestor == -1 then
return sim.getObjectAlias(handle, aliasOptions)
elseif commonAncestor == baseHandle then
-- simple case: handle is a (grand-)child of baseHandle
local p = getPath(handle, baseHandle)
p = filter(
function(h)
return sim.getModelProperty(h) & sim.modelproperty_not_model == 0 or h == p[#p]
end, p
)
return (options.noDot and '' or './') .. table.join(map(sim.getObjectAlias, p), '/')
elseif commonAncestor == handle then
-- reverse case: go upwards in the hierarchy
for col = 1, 0, -1 do
for up = 0, 30 do
for colcol = 0, 30 do
local p = {}
for _ = 1, col do table.insert(p, ':') end
for _ = 1, colcol do table.insert(p, '::') end
for _ = 1, up do table.insert(p, '..') end
p = table.join(p, '/')
if sim.getObject(p, {proxy = baseHandle, noError = true}) == handle then
return p
end
end
end
end
else
local p_bh_cam = sim.getObjectAliasRelative(commonAncestorModel, baseHandle, aliasOptions)
local p_cam_h = sim.getObjectAliasRelative(
handle, commonAncestorModel, aliasOptions, {noDot = true}
)
if commonAncestorModel ~= -1 and p_bh_cam and p_cam_h then
return p_bh_cam .. '/' .. p_cam_h
end
local p_bh_ca = sim.getObjectAliasRelative(commonAncestor, baseHandle, aliasOptions)
local p_ca_h = sim.getObjectAliasRelative(
handle, commonAncestor, aliasOptions, {noDot = true}
)
if p_bh_ca and p_ca_h then return p_bh_ca .. '/' .. p_ca_h end
end
end
import('checkargs')
require('motion-1').extend(sim)
require('deprecated.old').extend(sim)
require('sim-deprecated').extend(sim)
-- require('deprecated.utils') no! Breaks many things
sim.stopSimulation = wrap(sim.stopSimulation, function(origFunc)
return function(wait)
origFunc()
local t = sim.getObjectInt32Param(sim.getScript(sim.handle_self), sim.scriptintparam_type)
if wait and t ~= sim.scripttype_main and t ~= sim.scripttype_simulation and getYieldAllowed() then
local cnt = 0
while sim.getSimulationState() ~= sim.simulation_stopped and cnt < 20 do -- even if we run in a thread, we might not be able to yield (e.g. across a c-boundary)
cnt = cnt + 1
sim.step()
end
end
end
end)
-- Make sim.registerScriptFuncHook work also with a function as arg 2:
function locals.registerScriptFuncHook(funcNm, func, before)
local retVal
if type(func) == 'string' then
retVal = locals.registerScriptFuncHookOrig(funcNm, func, before)
else
local str = tostring(func)
retVal = locals.registerScriptFuncHookOrig(funcNm, '__1.' .. str, before)
__1[str] = func
end
return retVal
end
locals.registerScriptFuncHookOrig = sim.registerScriptFuncHook
sim.registerScriptFuncHook = locals.registerScriptFuncHook
function sim.getRandom(seed)
if seed then
auxfunc('randseed', seed)
else
return auxFunc('rand')
end
end
function sim.yawPitchRollToAlphaBetaGamma(...)
local yawAngle, pitchAngle, rollAngle = checkargs({
{type = 'float'}, {type = 'float'}, {type = 'float'},
}, ...)
local lb = sim.setStepping(true)
local Rx = sim.buildMatrix({0, 0, 0}, {rollAngle, 0, 0})
local Ry = sim.buildMatrix({0, 0, 0}, {0, pitchAngle, 0})
local Rz = sim.buildMatrix({0, 0, 0}, {0, 0, yawAngle})
local m = sim.multiplyMatrices(Ry, Rx)
m = sim.multiplyMatrices(Rz, m)
local alphaBetaGamma = sim.getEulerAnglesFromMatrix(m)
local alpha = alphaBetaGamma[1]
local beta = alphaBetaGamma[2]
local gamma = alphaBetaGamma[3]
sim.setStepping(lb)
return alpha, beta, gamma
end
function sim.alphaBetaGammaToYawPitchRoll(...)
local alpha, beta, gamma = checkargs({
{type = 'float'}, {type = 'float'}, {type = 'float'}
}, ...)
local lb = sim.setStepping(true)
local m = sim.buildMatrix({0, 0, 0}, {alpha, beta, gamma})
local v = m[9]
if v > 1 then v = 1 end
if v < -1 then v = -1 end
local pitchAngle = math.asin(-v)
local yawAngle, rollAngle
if math.abs(v) < 0.999999 then
rollAngle = math.atan2(m[10], m[11])
yawAngle = math.atan2(m[5], m[1])
else
-- Gimbal lock
rollAngle = math.atan2(-m[7], m[6])
yawAngle = 0
end
sim.setStepping(lb)
return yawAngle, pitchAngle, rollAngle
end
function sim.getQuaternionInverse(q)
return {-q[1], -q[2], -q[3], q[4]}
end
function sim.getObjectsWithTag(tagName, justModels)
local retObjs = {}
local objs = sim.getObjectsInTree(sim.handle_scene)
for i = 1, #objs, 1 do
if (not justModels) or ((sim.getModelProperty(objs[i]) & sim.modelproperty_not_model) == 0) then
local dat = sim.readCustomDataTags(objs[i])
for j = 1, #dat, 1 do
if dat[j] == tagName then
retObjs[#retObjs + 1] = objs[i]
break
end
end
end
end
return retObjs
end
function sim.executeLuaCode(theCode)
local f = loadstring(theCode)
if f then
local a, b = pcall(f)
return a, b
else
return false, 'compilation error'
end
end
function sim.fastIdleLoop(enable)
local data = sim.readCustomStringData(sim.handle_app, '__IDLEFPSSTACKSIZE__')
local stage = 0
local defaultIdleFps
if data and #data > 0 then
data = sim.unpackInt32Table(data)
stage = data[1]
defaultIdleFps = data[2]
else
defaultIdleFps = sim.getInt32Param(sim.intparam_idle_fps)
end
if enable then
stage = stage + 1
else
if stage > 0 then stage = stage - 1 end
end
if stage > 0 then
sim.setInt32Param(sim.intparam_idle_fps, 0)
else
sim.setInt32Param(sim.intparam_idle_fps, defaultIdleFps)
end
sim.writeCustomStringData(
sim.handle_app, '__IDLEFPSSTACKSIZE__', sim.packInt32Table({stage, defaultIdleFps})
)
end
function sim.getLoadedPlugins()
local ret = {}
local index = 0
while true do
local moduleName = sim.getPluginName(index)
if moduleName then
table.insert(ret, moduleName)
else
break
end
index = index + 1
end
return ret
end
function sim.isPluginLoaded(pluginName)
local index = 0
local moduleName = ''
while moduleName do
moduleName = sim.getPluginName(index)
if moduleName == pluginName then return (true) end
index = index + 1
end
return false
end
function sim.loadPlugin(name)
-- legacy plugins
local path = sim.getStringParam(sim.stringparam_application_path)
local plat = sim.getInt32Param(sim.intparam_platform)
local windows, mac, linux = 0, 1, 2
if plat == windows then
path = path .. '\\simExt' .. name .. '.dll'
elseif plat == mac then
path = path .. '/libsimExt' .. name .. '.dylib'
elseif plat == linux then
path = path .. '/libsimExt' .. name .. '.so'
else
error('unknown platform: ' .. plat)
end
return sim.loadModule(path, name)
end
function sim.getUserVariables()
local ng = {}
if __1.initGlobals then
for key, val in pairs(_G) do if not __1.initGlobals[key] then ng[key] = val end end
else
ng = _G
end
-- hide a few additional system variables:
ng.sim_call_type = nil
ng.sim_code_function_to_run = nil
ng.__notFirst__ = nil
ng.__scriptCodeToRun__ = nil
ng._S = nil
ng.__1 = nil
ng.H = nil
ng.restart = nil
return ng
end
function sim.getMatchingPersistentDataTags(...)
local pattern = checkargs({{type = 'string'}}, ...)
local result = {}
for index, value in ipairs(sim.getPersistentDataTags()) do
if value:match(pattern) then result[#result + 1] = value end
end
return result
end
function sim.throttle(t, func, ...)
locals.lastExecTime = locals.lastExecTime or {}
locals.throttleSched = locals.throttleSched or {}
local h = string.dump(func)
local now = sim.getSystemTime()
-- cancel any previous scheduled execution: (see sim.scheduleExecution below)
if locals.throttleSched[h] then
sim.cancelScheduledExecution(locals.throttleSched[h])
locals.throttleSched[h] = nil
end
if locals.lastExecTime[h] == nil or locals.lastExecTime[h] + t < now then
func(...)
locals.lastExecTime[h] = now
else
-- if skipping the call (i.e. because it exceeds target rate)
-- schedule the last call in the future:
locals.throttleSched[h] = sim.scheduleExecution(function(...)
func(...)
locals.lastExecTime[h] = now
end, {...}, locals.lastExecTime[h] + t)
end
end
function locals.schedulerCallback()
local function fn(t, pq)
local item = pq:peek()
if item and item.timePoint <= t then
item.func(table.unpack(item.args or {}))
pq:pop()
fn(t, pq)
end
end
fn(sim.getSystemTime(), locals.scheduler.rtpq)
if sim.getSimulationState() == sim.simulation_advancing_running then
fn(sim.getSimulationTime(), locals.scheduler.simpq)
end
if locals.scheduler.simpq:isempty() and locals.scheduler.rtpq:isempty() then
sim.registerScriptFuncHook('sysCall_nonSimulation', locals.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_sensing', locals.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_suspended', locals.schedulerCallback, true)
locals.scheduler.hook = false
end
end
function sim.scheduleExecution(func, args, timePoint, simTime)
if not locals.scheduler then
local priorityqueue = require 'priorityqueue'
locals.scheduler = {
simpq = priorityqueue(),
rtpq = priorityqueue(),
simTime = {},
nextId = 1,
}
end
local id = locals.scheduler.nextId
locals.scheduler.nextId = id + 1
local pq
if simTime then
pq = locals.scheduler.simpq
locals.scheduler.simTime[id] = true
else
pq = locals.scheduler.rtpq
end
pq:push(timePoint, {
id = id,
func = func,
args = args,
timePoint = timePoint,
simTime = simTime,
})
if not locals.scheduler.hook then
sim.registerScriptFuncHook('sysCall_nonSimulation', locals.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_sensing', locals.schedulerCallback, true)
sim.registerScriptFuncHook('sysCall_suspended', locals.schedulerCallback, true)
locals.scheduler.hook = true
end
return id
end
function sim.cancelScheduledExecution(id)
if not locals.scheduler then return end
local pq = nil
if locals.scheduler.simTime[id] then
locals.scheduler.simTime[id] = nil
pq = locals.scheduler.simpq
else
pq = locals.scheduler.rtpq
end
return pq:cancel(function(item) return item.id == id end)
end
function sim.getAlternateConfigs(...)
local jointHandles, inputConfig, tipHandle, lowLimits, ranges = checkargs({
{type = 'table', item_type = 'int'},
{type = 'table', item_type = 'float'},
{type = 'int', default = -1},
{type = 'table', item_type = 'float', default_nil = true, nullable = true},
{type = 'table', item_type = 'float', default_nil = true, nullable = true},
}, ...)
if #jointHandles < 1 or #jointHandles ~= #inputConfig or
(lowLimits and #jointHandles ~= #lowLimits) or (ranges and #jointHandles ~= #ranges) then
error("Bad table size.")
end
local lb = sim.setStepping(true)
local initConfig = {}
local x = {}
local confS = {}
local err = false
for i = 1, #jointHandles, 1 do
initConfig[i] = sim.getJointPosition(jointHandles[i])
local c, interv = sim.getJointInterval(jointHandles[i])
local t = sim.getJointType(jointHandles[i])
local sp = sim.getObjectFloatParam(jointHandles[i], sim.jointfloatparam_screw_pitch)
if t == sim.joint_revolute and not c then
if sp == 0 then
if inputConfig[i] - math.pi * 2 >= interv[1] or inputConfig[i] + math.pi * 2 <=
interv[1] + interv[2] then
-- We use the low and range values from the joint's settings
local y = inputConfig[i]
while y - math.pi * 2 >= interv[1] do y = y - math.pi * 2 end
x[i] = {y, interv[1] + interv[2]}
end
end
end
if x[i] then
if lowLimits and ranges then
-- the user specified low and range values. Use those instead:
local l = lowLimits[i]
local r = ranges[i]
if r ~= 0 then
if r > 0 then
if l < interv[1] then
-- correct for user bad input
r = r - (interv[1] - l)
l = interv[1]
end
if l > interv[1] + interv[2] then
-- bad user input. No alternative position for this joint
x[i] = {inputConfig[i], inputConfig[i]}
err = true
else
if l + r > interv[1] + interv[2] then
-- correct for user bad input
r = interv[1] + interv[2] - l
end
if inputConfig[i] - math.pi * 2 >= l or inputConfig[i] + math.pi * 2 <=
l + r then
local y = inputConfig[i]
while y < l do y = y + math.pi * 2 end
while y - math.pi * 2 >= l do
y = y - math.pi * 2
end
x[i] = {y, l + r}
else
-- no alternative position for this joint
x[i] = {inputConfig[i], inputConfig[i]}
err = (inputConfig[i] < l) or (inputConfig[i] > l + r)
end
end
else
r = -r
l = inputConfig[i] - r * 0.5
if l < x[i][1] then l = x[i][1] end
local u = inputConfig[i] + r * 0.5
if u > x[i][2] then u = x[i][2] end
x[i] = {l, u}
end
end
end
else
-- there's no alternative position for this joint
x[i] = {inputConfig[i], inputConfig[i]}
end
confS[i] = x[i][1]
end
local configs = {}
if not err then
for i = 1, #jointHandles, 1 do sim.setJointPosition(jointHandles[i], inputConfig[i]) end
local desiredPose = 0
if tipHandle ~= -1 then desiredPose = sim.getObjectMatrix(tipHandle) end
configs =
locals.loopThroughAltConfigSolutions(jointHandles, desiredPose, confS, x, 1, tipHandle)
end
for i = 1, #jointHandles, 1 do sim.setJointPosition(jointHandles[i], initConfig[i]) end
if next(configs) ~= nil then
local simEigen = require('simEigen')
configs = simEigen.Matrix:fromtable(configs)
configs = configs:data()
end
sim.setStepping(lb)
return configs
end
function sim.copyTable(t)
return table.deepcopy(t)
end
function sim.closePath(...)
local path, times = checkargs({
{type = 'table', item_type = 'float', size = '2..*'},
{type = 'table', item_type = 'float', size = '2..*'},
}, ...)
local confCnt = #times
local dof = #path // confCnt
local firstCp = table.slice(path, 1, dof)
local lastCp = table.slice(path, #path - dof + 1, #path)
path = table.add(path, firstCp)
local nl = sim.getPathLengths(table.add(lastCp, firstCp), dof)
times = table.add(times, {times[#times] + nl[2]})
confCnt = confCnt + 1
return path, times
end
function sim.getPathInterpolatedConfig(...)
local path, times, t, method, types = checkargs({
{type = 'table', item_type = 'float', size = '2..*'},
{type = 'table', item_type = 'float', size = '2..*'},
{type = 'float'},
{type = 'table', default = {type = 'linear', strength = 1.0, forceOpen = false}, nullable = true},
{type = 'table', item_type = 'int', size = '1..*', default_nil = true, nullable = true},
}, ...)
method = method or {}
local pathType = method.type or 'linear'
local forceOpen = method.forceOpen == true
local closed = method.closed == true
local strength = method.strength or 1.
-- "forceOpen" can be set if not passing "closed", otherwise it's opposite value
if method.closed ~= nil then
forceOpen = not closed
end
if closed then
path, times = sim.closePath(path, times)
end
local confCnt = #times
local dof = #path // confCnt
if (dof * confCnt ~= #path) or (types and dof ~= #types) then error("Bad table size.") end
if types == nil then
types = {}
for i = 1, dof, 1 do types[i] = 0 end
end
local retVal = {}
local li = 1
local hi = 2
if t < 0 then t = 0 end
-- if confCnt>2 then
if t >= times[#times] then t = times[#times] - 0.00000001 end
local ll, hl
for i = 2, #times, 1 do
li = i - 1
hi = i
ll = times[li]
hl = times[hi]
if hl > t then -- >= gives problems with overlapping points
break
end
end
t = (t - ll) / (hl - ll)
-- else
-- if t>1 then t=1 end
-- end
closed = true -- if path is closed is determined a few lines below
if pathType == 'quadraticBezier' then
local w = math.max(0.05, strength)
for i = 1, dof, 1 do
if (path[i] ~= path[(confCnt - 1) * dof + i]) then
closed = false
break
end
end
if forceOpen then closed = false end
local i0, i1, i2
if t < 0.5 then
if li == 1 and not closed then
retVal = locals.linearInterpolate(locals.getConfig(path, dof, li), locals.getConfig(path, dof, hi), t, types)
else
if t < 0.5 * w then
i0 = li - 1
i1 = li
i2 = hi
if li == 1 then i0 = confCnt - 1 end
local a = locals.linearInterpolate(locals.getConfig(path, dof, i0), locals.getConfig(path, dof, i1), 1 - 0.25 * w + t * 0.5, types)
local b = locals.linearInterpolate(locals.getConfig(path, dof, i1), locals.getConfig(path, dof, i2), 0.25 * w + t * 0.5, types)
retVal = locals.linearInterpolate(a, b, 0.5 + t / w, types)
else
retVal = locals.linearInterpolate(locals.getConfig(path, dof, li), locals.getConfig(path, dof, hi), t, types)
end
end
else
if hi == confCnt and not closed then
retVal = locals.linearInterpolate(locals.getConfig(path, dof, li), locals.getConfig(path, dof, hi), t, types)
else
if t > (1 - 0.5 * w) then
i0 = li
i1 = hi
i2 = hi + 1
if hi == confCnt then i2 = 2 end
t = t - (1 - 0.5 * w)
local a = locals.linearInterpolate(locals.getConfig(path, dof, i0), locals.getConfig(path, dof, i1), 1 - 0.5 * w + t * 0.5, types)
local b = locals.linearInterpolate(locals.getConfig(path, dof, i1), locals.getConfig(path, dof, i2), t * 0.5, types)
retVal = locals.linearInterpolate(a, b, t / w, types)
else
retVal = locals.linearInterpolate(locals.getConfig(path, dof, li), locals.getConfig(path, dof, hi), t, types)
end
end
end
elseif pathType == 'linear' then
retVal = locals.linearInterpolate(locals.getConfig(path, dof, li), locals.getConfig(path, dof, hi), t, types)
end
return retVal
end
function sim.createPath(...)
local retVal
local attrib, intParams, floatParams, col = ...
if type(attrib) == 'number' then
retVal = sim._createPath(attrib, intParams, floatParams, col) -- for backward compatibility
else
local ctrlPts, options, subdiv, smoothness, orientationMode, upVector = checkargs({
{type = 'table', item_type = 'float', size = '14..*'},
{type = 'int', default = 0},
{type = 'int', default = 100},
{type = 'float', default = 1.0},
{type = 'int', default = 0},
{type = 'table', item_type = 'float', size = '3', default = {0, 0, 1}},
}, ...)
local fl = setYieldAllowed(false)
local code = [[function path.shaping(path,pathIsClosed,upVector)
local section={0.02,-0.02,0.02,0.02,-0.02,0.02,-0.02,-0.02,0.02,-0.02}
local color={0.7,0.9,0.9}
local options=0
if pathIsClosed then
options=options|4
end
local shape=sim.generateShapeFromPath(path,section,options,upVector)
sim.setShapeColor(shape,nil,sim.colorcomponent_ambient_diffuse,color)
return shape
end]]
retVal = sim.createDummy(0.04, {0, 0.68, 0.47, 0, 0, 0, 0, 0, 0, 0, 0, 0})
sim.setObjectAlias(retVal, "Path")
local scriptHandle
if sim.getBoolParam(sim.boolparam_usingscriptobjects) then
code = "path = require('models.path_customization-2')\n\n" .. code
scriptHandle = sim.createScript(sim.scripttype_customization, code)
sim.setObjectParent(scriptHandle, retVal)
else
scriptHandle = sim.addScript(sim.scripttype_customization)
code = "path = require('models.deprecated.path_customization')\n\n" .. code
sim.setScriptText(scriptHandle, code)
sim.associateScriptWithObject(scriptHandle, retVal)
end
local prop = sim.getModelProperty(retVal)
sim.setModelProperty(retVal, (prop | sim.modelproperty_not_model) - sim.modelproperty_not_model) -- model
prop = sim.getObjectProperty(retVal)
sim.setObjectProperty(retVal, prop | sim.objectproperty_collapsed)
local data = sim.packTable({ctrlPts, options, subdiv, smoothness, orientationMode, upVector})
sim.setBufferProperty(retVal, "customData.ABC_PATH_CREATION", data)
sim.initScript(scriptHandle)
setYieldAllowed(fl)
end
return retVal
end
function sim.createCollection(arg1, arg2)
local retVal
if type(arg1) == 'string' then
retVal = sim._createCollection(arg1, arg2) -- for backward compatibility
else
if arg1 == nil then arg1 = 0 end
retVal = sim.createCollectionEx(arg1)
end
return retVal
end
function sim.resamplePath(...)
local path, pathLengths, finalConfigCnt, method, types = checkargs({
{type = 'table', item_type = 'float', size = '2..*'},
{type = 'table', item_type = 'float', size = '2..*'},
{type = 'int'},
{type = 'table', default = {type = 'linear', strength = 1.0, forceOpen = false}},
{type = 'table', item_type = 'int', size = '1..*', default_nil = true, nullable = true},
}, ...)
method = table.deepcopy(method) or {}
local closed = method.closed == true
local confCnt = #pathLengths
local dof = math.floor(#path / confCnt)
if dof * confCnt ~= #path or (confCnt < 2) or (types and dof ~= #types) then
error("Bad table size.")
end
if closed then
confCnt = confCnt + 1
path, pathLengths = sim.closePath(path, pathLengths)
method.closed = nil
method.forceOpen = false
end
local retVal = {}
for i = 1, finalConfigCnt, 1 do
local c = sim.getPathInterpolatedConfig(
path, pathLengths, pathLengths[#pathLengths] * (i - 1) / (finalConfigCnt - 1),
method, types
)
for j = 1, dof, 1 do retVal[(i - 1) * dof + j] = c[j] end
end
return retVal
end
function sim.getConfigDistance(...)
local confA, confB, metric, types = checkargs({
{type = 'table', item_type = 'float', size = '1..*'},
{type = 'table', item_type = 'float', size = '1..*'},
{type = 'table', item_type = 'float', default_nil = true, nullable = true},
{type = 'table', item_type = 'int', default_nil = true, nullable = true},
}, ...)
if (#confA ~= #confB) or (metric and #confA ~= #metric) or (types and #confA ~= #types) then
error("Bad table size.")
end
return locals.getConfigDistance(confA, confB, metric, types)
end
function locals.getConfigDistance(confA, confB, metric, types)
if metric == nil then
metric = {}
for i = 1, #confA, 1 do metric[i] = 1 end
end
if types == nil then
types = {}
for i = 1, #confA, 1 do types[i] = 0 end
end
local d = 0
local qcnt = 0
for j = 1, #confA, 1 do
local dd = 0
if types[j] == 0 then
dd = (confB[j] - confA[j]) * metric[j] -- e.g. joint with limits
end
if types[j] == 1 then
local dx = math.atan2(math.sin(confB[j] - confA[j]), math.cos(confB[j] - confA[j]))
local v = confA[j] + dx
dd = math.atan2(math.sin(v), math.cos(v)) * metric[j] -- cyclic rev. joint (-pi;pi)
end
if types[j] == 2 then
qcnt = qcnt + 1
if qcnt == 4 then
qcnt = 0
local m1 = sim.poseToMatrix({0, 0, 0, confA[j - 3], confA[j - 2], confA[j - 1], confA[j - 0]})
local m2 = sim.poseToMatrix({0, 0, 0, confB[j - 3], confB[j - 2], confB[j - 1], confB[j - 0]})
local a, angle = sim.getRotationAxis(m1, m2)
dd = angle * metric[j - 3]
end
end
d = d + dd * dd
end
return math.sqrt(d)
end
function sim.getPathLengths(...)
local simEigen = require('simEigen')
local path, dof, cb = checkargs({
{type = 'table', item_type = 'float', size = '2..*'}, {type = 'int'},
{type = 'any', default_nil = true, nullable = true},
}, ...)
local confCnt = math.floor(#path / dof)
if dof < 1 or (confCnt < 2) then error("Bad table size.") end
local distancesAlongPath = {0}
local totDist = 0
local pM = simEigen.Matrix(confCnt, dof, path)
local metric = {}
local tt = {}
for i = 1, dof, 1 do
if i > 3 then
metric[#metric + 1] = 0.0
else
metric[#metric + 1] = 1.0
end
tt[#tt + 1] = 0
end
for i = 1, pM:rows() - 1, 1 do
local d
if cb then
if type(cb) == 'string' then
d = _G[cb](pM:row(i):data(), pM:row(i + 1):data(), dof)
else
d = cb(pM:row(i):data(), pM:row(i + 1):data(), dof)
end
else
d = sim.getConfigDistance(pM:row(i):data(), pM:row(i + 1):data(), metric, tt)
end
totDist = totDist + d
distancesAlongPath[i + 1] = totDist
end
return distancesAlongPath, totDist
end
function sim.changeEntityColor(...)
local entityHandle, color, colorComponent = checkargs({
{type = 'int'},
{type = 'table', size = 3, item_type = 'float'},
{type = 'int', default = sim.colorcomponent_ambient_diffuse},
}, ...)
local colorData = {}
local objs = {entityHandle}