-
Notifications
You must be signed in to change notification settings - Fork 8
/
ambf_addon.py
4473 lines (3574 loc) · 187 KB
/
ambf_addon.py
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
# Author: Adnan Munawar
# Email: amunawar@wpi.edu
# Lab: aimlab.wpi.edu
bl_info = {
"name": "Asynchronous Multi-Body Framework (AMBF) Config Creator",
"author": "Adnan Munawar",
"version": (0, 1),
"blender": (3, 0, 0),
"location": "View3D > Add > Mesh > AMBF",
"description": "Helps Generate AMBF Config File and Saves both High and Low Resolution(Collision) Meshes",
"warning": "",
"wiki_url": "https://github.com/WPI-AIM/ambf_addon",
"category": "AMBF",
}
import bpy
import math
import yaml
import os
import sys
from pathlib import Path
import mathutils
from enum import Enum
from collections import OrderedDict, Counter
from datetime import datetime
from bpy.props import BoolProperty, FloatProperty, FloatVectorProperty, BoolVectorProperty
from bpy.props import StringProperty, IntProperty, PointerProperty, EnumProperty, CollectionProperty
from bpy.types import Scene, Operator, Panel, Object, PropertyGroup
# Body Template for the some commonly used of afBody's data
class BodyTemplate:
def __init__(self):
self._adf_data = OrderedDict()
self._adf_data['name'] = ""
self._adf_data['mesh'] = ""
self._adf_data['collision mesh'] = ""
self._adf_data['collision mesh type'] = ""
self._adf_data['mass'] = 0.0
self._adf_data['inertia'] = {'ix': 0.0, 'iy': 0.0, 'iz': 0.0}
self._adf_data['collision margin'] = 0.001
self._adf_data['scale'] = 1.0
self._adf_data['location'] = get_pose_ordered_dict()
self._adf_data['inertial offset'] = get_pose_ordered_dict()
self._adf_data['passive'] = False
# self._adf_data['controller'] = {'linear': {'P': 1000, 'I': 0, 'D': 1},
# 'angular': {'P': 1000, 'I': 0, 'D': 1}}
self._adf_data['color'] = 'random'
# Body Template for the some commonly used of afBody's data
class GhostObjectTemplate:
def __init__(self):
self._adf_data = OrderedDict()
self._adf_data['name'] = ""
self._adf_data['mesh'] = ""
self._adf_data['collision mesh'] = ""
self._adf_data['collision mesh type'] = ""
self._adf_data['collision margin'] = 0.001
self._adf_data['scale'] = 1.0
self._adf_data['location'] = get_pose_ordered_dict()
self._adf_data['passive'] = False
self._adf_data['color'] = 'random'
# Joint Template for the some commonly used of afJoint's data
class JointTemplate:
def __init__(self):
self._adf_data = OrderedDict()
self._adf_data['name'] = ''
self._adf_data['parent'] = ''
self._adf_data['child'] = ''
self._adf_data['parent axis'] = get_xyz_ordered_dict()
self._adf_data['parent pivot'] = get_xyz_ordered_dict()
self._adf_data['child axis'] = get_xyz_ordered_dict()
self._adf_data['child pivot'] = get_xyz_ordered_dict()
self._adf_data['joint limits'] = {'low': -1.2, 'high': 1.2}
self._adf_data['enable feedback'] = False
self._adf_data['passive'] = False
cont_dict = OrderedDict()
cont_dict['P'] = 1000
cont_dict['I'] = 0
cont_dict['D'] = 1
self._adf_data['controller'] = cont_dict
self._adf_data['controller output type'] = 'VELOCITY'
# Global Variables
class CommonConfig:
namespace = ''
num_collision_groups = 20
# Some properties don't exist in Blender are supported in AMBF. If an AMBF file is loaded
# and then resaved, we can capture the extra properties of bodies and joints and take
# them into consideration before re saving the AMBF File so we don't reset those values
loaded_body_map = {}
loaded_joint_map = {}
collision_shape_material = None
collision_shape_material_name = 'collision_shape_material'
collision_shape_material_color = mathutils.Vector((0.8, 0.775, 0.0, 0.4)) # Pick a random color
# https://stackoverflow.com/questions/31605131/dumping-a-dictionary-to-a-yaml-file-while-preserving-order/31609484
def represent_dictionary_order(self, dict_data):
return self.represent_mapping('tag:yaml.org,2002:map', dict_data.items())
def ambf_round(val):
return round(val, bpy.context.scene.ambf_precision)
def setup_yaml():
yaml.add_representer(OrderedDict, represent_dictionary_order)
def set_view_transform_orientation_to_local():
bpy.context.scene.transform_orientation_slots[0].type = 'LOCAL'
# Enum Class for Mesh Type
class MeshType(Enum):
meshSTL = 0
meshOBJ = 1
mesh3DS = 2
meshPLY = 3
def get_extension(val):
if val == MeshType.meshSTL.value:
extension = '.STL'
elif val == MeshType.meshOBJ.value:
extension = '.OBJ'
elif val == MeshType.mesh3DS.value:
extension = '.3DS'
elif val == MeshType.meshPLY.value:
extension = '.PLY'
else:
extension = None
return extension
def skew_mat(v):
m = mathutils.Matrix.Identity(3)
m.Identity(3)
m[0][0] = 0
m[0][1] = -v.z
m[0][2] = v.y
m[1][0] = v.z
m[1][1] = 0
m[1][2] = -v.x
m[2][0] = -v.y
m[2][1] = v.x
m[2][2] = 0
return m
def vec_norm(v):
return math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
def round_vec(v):
for i in range(0, 3):
v[i] = ambf_round(v[i])
return v
# https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d/897677#897677
def rot_matrix_from_vecs(v1, v2):
out = mathutils.Matrix.Identity(3)
vcross = v1.cross(v2)
vdot = v1.dot(v2)
rot_angle = v1.angle(v2)
if abs(rot_angle) < 0.001:
return out
if abs(rot_angle) > 3.14:
# Since the vectors are almost opposite, we need to define a rotation order
nx = mathutils.Vector([1, 0, 0])
temp_ang = v1.angle(nx)
if 0.001 < abs(temp_ang) < 3.14:
axis = v1.cross(nx)
out = out.Rotation(rot_angle, 3, axis)
else:
ny = mathutils.Vector([0, 1, 0])
axis = v1.cross(ny)
out = out.Rotation(rot_angle, 3, axis)
else:
skew_v = skew_mat(vcross)
out = mathutils.Matrix.Identity(3) + skew_v + skew_v @ skew_v * ((1 - vdot) / (vec_norm(vcross) ** 2))
return out
# Get rotation matrix to represent rotation between two vectors
# Brute force implementation
def get_rot_mat_from_vecs(vecA, vecB):
# Angle between two axis
angle = vecA.angle(vecB)
# Axis of rotation between child's joints axis and constraint_axis
if abs(angle) <= 0.1:
# Doesn't matter which axis we chose, the rot mat is going to be identity
# as angle is almost 0
axis = mathutils.Vector([0, 1, 0])
elif abs(angle) >= 3.13:
# This is a more involved case, find out the orthogonal vector to vecA
nx = mathutils.Vector([1, 0, 0])
temp_ang = vecA.angle(nx)
if 0.1 < abs(temp_ang) < 3.13:
axis = vecA.cross(nx)
else:
ny = mathutils.Vector([0, 1, 0])
axis = vecA.cross(ny)
else:
axis = vecA.cross(vecB)
mat = mathutils.Matrix()
# Rotation matrix representing the above angular offset
rot_mat = mat.Rotation(angle, 4, axis)
return rot_mat, angle
def ensure_collision_shape_material():
# Create a use a material only for the first instance
if bpy.data.materials.find(CommonConfig.collision_shape_material_name) == -1:
CommonConfig.collision_shape_material = bpy.data.materials.new(CommonConfig.collision_shape_material_name)
else:
CommonConfig.collision_shape_material = bpy.data.materials[CommonConfig.collision_shape_material_name]
CommonConfig.collision_shape_material.diffuse_color = CommonConfig.collision_shape_material_color
def update_global_namespace(context):
CommonConfig.namespace = context.scene.ambf_namespace
if CommonConfig.namespace[-1] != '/':
print('WARNING, MULTI-BODY NAMESPACE SHOULD END WITH \'/\'')
CommonConfig.namespace += '/'
context.scene.ambf_namespace += CommonConfig.namespace
def set_global_namespace(context, namespace):
CommonConfig.namespace = namespace
if CommonConfig.namespace[-1] != '/':
print('WARNING, MULTI-BODY NAMESPACE SHOULD END WITH \'/\'')
CommonConfig.namespace += '/'
context.scene.ambf_namespace = CommonConfig.namespace
def get_body_namespace(fullname):
last_occurance = fullname.rfind('/')
_body_namespace = ''
if last_occurance >= 0:
# This means that the name contains a namespace
_body_namespace = fullname[0:last_occurance+1]
return _body_namespace
def remove_namespace_prefix(full_name):
last_occurance = full_name.rfind('/')
if last_occurance > 0:
# Body name contains a namespace
_name = full_name[last_occurance+1:]
else:
# Body name doesn't have a namespace
_name = full_name
return _name
def replace_dot_from_object_names(char_subs ='_'):
for obj_handle in bpy.data.objects:
obj_handle.name = obj_handle.name.replace('.', char_subs)
def compare_body_namespace_with_global(fullname):
last_occurance = fullname.rfind('/')
_is_namespace_same = False
_body_namespace = ''
_name = ''
if last_occurance >= 0:
# This means that the name contains a namespace
_body_namespace = fullname[0:last_occurance+1]
_name = fullname[last_occurance+1:]
if CommonConfig.namespace == _body_namespace:
# The CommonConfig namespace is the same as the body namespace
_is_namespace_same = True
else:
# The CommonConfig namespace is different form body namespace
_is_namespace_same = False
else:
# The body's name does not contain and namespace
_is_namespace_same = False
# print("FULLNAME: %s, BODY: %s, NAMESPACE: %s NAMESPACE_MATCHED: %d" %
# (fullname, _name, _body_namespace, _is_namespace_same))
return _is_namespace_same
def add_namespace_prefix(name):
return CommonConfig.namespace + name
def get_grand_parent(body):
grand_parent = body
while grand_parent.parent is not None:
grand_parent = grand_parent.parent
return grand_parent
def downward_tree_pass(body, _heirarichal_bodies_list, _added_bodies_list):
if body is None or _added_bodies_list[body] is True:
return
else:
# print('DOWNWARD TREE PASS: ', body.name)
_heirarichal_bodies_list.append(body)
_added_bodies_list[body] = True
for child in body.children:
downward_tree_pass(child, _heirarichal_bodies_list, _added_bodies_list)
def populate_heirarchial_tree():
# Create a dict with {body, added_flag} elements
# The added_flag is to check if the body has already
# been added
_added_bodies_list = {}
_heirarchial_bodies_list = []
for obj_handle in bpy.data.objects:
_added_bodies_list[obj_handle] = False
for obj_handle in bpy.data.objects:
grand_parent = get_grand_parent(obj_handle)
# print('CALLING DOWNWARD TREE PASS FOR: ', grand_parent.name)
downward_tree_pass(grand_parent, _heirarchial_bodies_list, _added_bodies_list)
for body in _heirarchial_bodies_list:
print(body.name, "--->",)
return _heirarchial_bodies_list
# Courtesy: https://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file
def prepend_comment_to_file(filename, comment):
temp_filename = filename + '.tmp'
with open(filename,'r') as f:
with open(temp_filename, 'w') as f2:
f2.write(comment)
f2.write(f.read())
os.rename(temp_filename, filename)
def select_object(obj_handle, select=True):
obj_handle.select_set(select)
def select_objects(obj_handles, select=True):
for obj_handle in obj_handles:
select_object(obj_handle, select)
def select_all_objects(select):
# First deselect all objects
for obj_handle in bpy.data.objects:
select_object(obj_handle, select)
def hide_object(object, hide):
if object:
# object.hide = hide
object.hide_set(hide)
def is_object_hidden(object):
if object:
# hidden = object.hide
hidden = object.hide_get()
else:
raise ValueError
return hidden
def get_active_object():
active_obj_handle = bpy.context.active_object
return active_obj_handle
def set_active_object(active_object):
# bpy.context.scene.objects.active = active_object
bpy.context.view_layer.objects.active = active_object
def get_selected_objects():
return bpy.context.selected_objects
def make_obj1_parent_of_obj2(obj1, obj2):
select_all_objects(False)
if obj2.parent is None:
select_object(obj2)
select_object(obj1)
set_active_object(obj1)
bpy.ops.object.parent_set(keep_transform=True)
def get_xyz_ordered_dict():
xyz = OrderedDict()
xyz['x'] = 0
xyz['y'] = 0
xyz['z'] = 0
return xyz
def get_rpy_ordered_dict():
rpy = OrderedDict()
rpy['r'] = 0
rpy['p'] = 0
rpy['y'] = 0
return rpy
def get_pose_ordered_dict():
pose = OrderedDict()
pose['position'] = get_xyz_ordered_dict()
pose['orientation'] = get_rpy_ordered_dict()
return pose
# For shapes such as Cylinder, Cone and Ellipse, this function returns
# the major axis by comparing the dimensions of the bounding box
def get_major_axis(dims):
d = dims
axis = {0: 'x', 1: 'y', 2: 'z'}
sum_diff = [abs(d[0] - d[1]) + abs(d[0] - d[2]),
abs(d[1] - d[0]) + abs(d[1] - d[2]),
abs(d[2] - d[0]) + abs(d[2] - d[1])]
# If the bounds are equal, choose the z axis
if sum_diff[0] == sum_diff[1] and sum_diff[1] == sum_diff[2]:
axis_idx = 2
else:
axis_idx = sum_diff.index(max(sum_diff))
return axis[axis_idx], axis_idx
def get_axis_str(axis_idx):
axis_str = None
if axis_idx == 0:
axis_str = 'X'
elif axis_idx == 1:
axis_str = 'Y'
elif axis_idx == 2:
axis_str = 'Z'
return axis_str
def get_axis_idx(axis_str):
axis_idx = None
if axis_str == 'X':
axis_idx = 0
elif axis_str == 'Y':
axis_idx = 1
elif axis_str == 'Z':
axis_idx = 2
return axis_idx
def get_axis_vec_from_str(axis_str):
axis_str = axis_str.upper()
axis_vec = mathutils.Vector((0, 0, 0))
if axis_str == 'X':
axis_vec[0] = 1.0
elif axis_str == 'Y':
axis_vec[1] = 1.0
elif axis_str == 'Z':
axis_vec[2] = 1.0
return axis_vec
# For shapes such as Cylinder, Cone and Ellipse, this function returns
# the median axis (not-major and non-minor or the middle axis) by comparing
# the dimensions of the bounding box
def get_median_axis(dims):
axis = {0: 'x', 1: 'y', 2: 'z'}
maj_ax, maj_ax_idx = get_major_axis(dims)
min_ax, min_ax_idx = get_minor_axis(dims)
med_axis_idx = [1, 1, 1]
med_axis_idx[maj_ax_idx] = 0
med_axis_idx[min_ax_idx] = 0
axis_idx = med_axis_idx.index(max(med_axis_idx))
return axis[axis_idx], axis_idx
# For shapes such as Cylinder, Cone and Ellipse, this function returns
# the minor axis by comparing the dimensions of the bounding box
def get_minor_axis(dims):
d = dims
axis = {0: 'x', 1: 'y', 2: 'z'}
sum_diff = [abs(d[0] - d[1]) + abs(d[0] - d[2]),
abs(d[1] - d[0]) + abs(d[1] - d[2]),
abs(d[2] - d[0]) + abs(d[2] - d[1])]
max_idx = sum_diff.index(max(sum_diff))
min_idx = sum_diff.index(min(sum_diff))
sort_idx = [1, 1, 1]
sort_idx[max_idx] = 0
sort_idx[min_idx] = 0
median_idx = sort_idx.index(max(sort_idx))
return axis[median_idx], median_idx
# Courtesy of:
# https://blender.stackexchange.com/questions/62040/get-center-of-geometry-of-an-object
def compute_local_com(obj_handle):
vcos = [v.co for v in obj_handle.data.vertices]
find_center = lambda l: ( max(l) + min(l)) / 2
x, y, z = [[v[i] for v in vcos] for i in range(3)]
center = [find_center(axis) for axis in [x, y, z]]
for i in range(0, 3):
center[i] = center[i] * obj_handle.scale[i]
return center
def estimate_joint_controller_gain(obj_handle):
if obj_handle.ambf_object_type == 'CONSTRAINT':
parent_obj_handle = obj_handle.ambf_object_parent
child_obj_handle = obj_handle.ambf_object_child
if parent_obj_handle and child_obj_handle:
T_p_w = parent_obj_handle.matrix_world.copy()
T_c_w = child_obj_handle.matrix_world.copy()
T_j_w = obj_handle.matrix_world.copy()
T_p_j = T_j_w.inverted() @ T_p_w
T_c_j = T_j_w.inverted() @ T_c_w
N_j = get_axis_vec_from_str(obj_handle.ambf_constraint_axis)
P_pcom = mathutils.Vector(compute_local_com(parent_obj_handle))
P_pcom_j = T_p_j @ P_pcom
P_ccom = mathutils.Vector(compute_local_com(child_obj_handle))
P_ccom_j = T_c_j @ P_ccom
mass_p = parent_obj_handle.ambf_rigid_body_mass
mass_c = child_obj_handle.ambf_rigid_body_mass
if obj_handle.ambf_constraint_type == 'REVOLUTE':
if P_pcom_j.length > 0.001:
theta_pj = N_j.angle(P_pcom_j)
d_pn = P_pcom_j.length * math.sin(theta_pj)
else:
d_pn = 0.0
if P_ccom_j.length > 0.001:
theta_cj = N_j.angle(P_ccom_j)
d_cn = P_ccom_j.length * math.sin(theta_cj)
else:
d_cn = 0.0
# The gains should be scaled according the sum of these
# distances
holding_torque = (mass_p * mass_p * d_pn + mass_c * mass_c * d_cn)
print('Holding Torque:, ', holding_torque)
if holding_torque == 0.0:
holding_torque = 0.001
# Lets define at what error do we want to apply the holding torque
error_deg = 1.0
Kp = holding_torque / ((error_deg / 180.0) * math.pi)
Ki = Kp / 100.0
Kd = Kp / 100.0
print('Kp:, ', Kp)
print('Kd:, ', Kd)
obj_handle.ambf_constraint_controller_p_gain = Kp
obj_handle.ambf_constraint_controller_i_gain = Ki
obj_handle.ambf_constraint_controller_d_gain = Kd
elif obj_handle.ambf_constraint_type == 'PRISMATIC':
holding_effort = (mass_p + mass_c)
error_m = 0.001
Kp = holding_effort / error_m
Ki = Kp / 100.0
Kd = Kp / 100.0
print('Kp:, ', Kp)
print('Kd:, ', Kd)
obj_handle.ambf_constraint_controller_p_gain = Kp
obj_handle.ambf_constraint_controller_i_gain = Ki
obj_handle.ambf_constraint_controller_d_gain = Kd
def inertia_of_mesh(obj_handle, mass=None):
if mass == None:
mass = obj_handle.ambf_rigid_body_mass
num_vertices = len(obj_handle.data.vertices)
dm = mass / num_vertices
I = mathutils.Vector((0, 0, 0))
# Tripple Summation or Integral
for v in obj_handle.data.vertices:
I[0] = I[0] + dm * (v.co[1]*v.co[1] + v.co[2] * v.co[2])
I[1] = I[1] + dm * (v.co[0]*v.co[0] + v.co[2] * v.co[2])
I[2] = I[2] + dm * (v.co[0]*v.co[0] + v.co[1] * v.co[1])
return I
def inertia_of_box(mass, lx, ly, lz):
I = mathutils.Vector((0, 0, 0))
I[0] = (1.0 / 12.0) * mass * (ly*ly + lz*lz)
I[1] = (1.0 / 12.0) * mass * (lx*lx + lz*lz)
I[2] = (1.0 / 12.0) * mass * (lx*lx + ly*ly)
return I
def inertia_of_sphere(mass, r):
I = mathutils.Vector((0, 0, 0))
r2 = r * r
I[0] = (2.0 / 5.0) * mass * r2
I[1] = (2.0 / 5.0) * mass * r2
I[2] = (2.0 / 5.0) * mass * r2
return I
def inertia_of_cylinder(mass, r, h, axis):
I = mathutils.Vector((0, 0, 0))
r2 = r * r
h2 = h * h
I[axis] = (1/2) * mass * r2
I[(axis + 1) % 3] = (1/4) * mass * r2 + (1/12) * mass * h2
I[(axis + 2) % 3] = (1/4) * mass * r2 + (1/12) * mass * h2
return I
def inertia_of_cone(mass, r, h, axis):
I = mathutils.Vector((0, 0, 0))
r2 = r * r
h2 = h * h
I[axis] = (3/10) * mass * r2
I[(axis + 1) % 3] = (3/20) * mass * r2 + (3/5) * mass * h2
I[(axis + 2) % 3] = (3/20) * mass * r2 + (3/5) * mass * h2
return I
def inertia_of_capsule(mass, r, h_total, axis):
I = mathutils.Vector((0, 0, 0))
h = h_total - (r * 2) # Get the length of main cylinder
if h <= 0.001:
# This means that this obj_handle shape is essentially a sphere, not a capsule
I = inertia_of_sphere(mass, r)
else:
r2 = r * r
h2 = h * h
# Factor the mass: (mass of hemisphere) / (mass of cylinder)
mass_factor = (2 * r) / (3 * h)
m_hs = mass * mass_factor
m_cy = mass * (1 - mass_factor)
I[axis] = (1/2) * m_cy * r2 + (4 / 5) * m_hs * r2
I[(axis + 1) % 3] = (1 / 12) * m_cy * (h2 + (3 * r2)) + 2 * m_hs * ((2 * r2 / 5) + (h2 / 2) + ((3/8) * h * r))
I[(axis + 2) % 3] = (1 / 12) * m_cy * (h2 + (3 * r2)) + 2 * m_hs * ((2 * r2 / 5) + (h2 / 2) + ((3/8) * h * r))
return I
def calculate_principal_inertia(obj_handle):
# Calculate Ixx, Iyy and Izz
mass = obj_handle.ambf_rigid_body_mass
# For now, handle the calculation of the compound shape inertia as the convex hull's inertia
if obj_handle.ambf_collision_type in ['MESH', 'COMPOUND_SHAPE']:
I = inertia_of_mesh(obj_handle)
elif obj_handle.ambf_collision_type == 'SINGULAR_SHAPE':
prop_group = obj_handle.ambf_collision_shape_prop_collection.items()[0]
coll_shape_obj_handle = prop_group[1]
lx = coll_shape_obj_handle.ambf_collision_shape_xyz_dims[0]
ly = coll_shape_obj_handle.ambf_collision_shape_xyz_dims[1]
lz = coll_shape_obj_handle.ambf_collision_shape_xyz_dims[2]
radius = coll_shape_obj_handle.ambf_collision_shape_radius
height = coll_shape_obj_handle.ambf_collision_shape_height
axis = get_axis_idx(coll_shape_obj_handle.ambf_collision_shape_axis.upper())
if coll_shape_obj_handle.ambf_collision_shape == 'BOX':
I = inertia_of_box(mass, lx, ly, lz)
elif coll_shape_obj_handle.ambf_collision_shape == 'SPHERE':
I = inertia_of_sphere(mass, radius)
elif coll_shape_obj_handle.ambf_collision_shape == 'CYLINDER':
I = inertia_of_cylinder(mass, radius, height, axis)
elif coll_shape_obj_handle.ambf_collision_shape == 'CONE':
I = inertia_of_cone(mass, radius, height, axis)
elif coll_shape_obj_handle.ambf_collision_shape == 'CAPSULE':
I = inertia_of_capsule(mass, radius, height, axis)
else:
print('ERROR!, Not an understood shape or mesh')
return
# Parallel Axis Theorem
off = obj_handle.ambf_rigid_body_linear_inertial_offset
I[0] = I[0] + mass * (off[1] ** 2 + off[2] ** 2)
I[1] = I[1] + mass * (off[0] ** 2 + off[2] ** 2)
I[2] = I[2] + mass * (off[0] ** 2 + off[1] ** 2)
ix = ambf_round(I[0])
iy = ambf_round(I[1])
iz = ambf_round(I[2])
print(ix, iy, iz)
return I
def create_capsule(height, radius, axis='Z'):
if axis.upper() == 'X':
axis_vec = mathutils.Vector((1.0, 0.0, 0.0))
rot_axis_angle = mathutils.Vector((0.0, math.pi/2.0, 0.0))
elif axis.upper() == 'Y':
axis_vec = mathutils.Vector((0.0, 1.0, 0.0))
rot_axis_angle = mathutils.Vector((math.pi/2.0, 0.0, 0.0))
elif axis.upper() == 'Z':
axis_vec = mathutils.Vector((0.0, 0.0, 1.0))
rot_axis_angle = mathutils.Vector((0.0, 0.0, 0.0))
else:
raise ValueError
caps_dist = height/2.0 - radius
trunk_length = height - (2 * radius)
bpy.ops.mesh.primitive_uv_sphere_add(radius=radius)
sphere1 = get_active_object()
sphere1.matrix_world.translation = sphere1.matrix_world.translation + axis_vec * caps_dist
bpy.ops.mesh.primitive_uv_sphere_add(radius=radius)
sphere2 = get_active_object()
sphere2.matrix_world.translation = sphere2.matrix_world.translation - axis_vec * caps_dist
bpy.ops.mesh.primitive_cylinder_add(radius=radius, depth=trunk_length, rotation=rot_axis_angle)
cylinder = get_active_object()
select_object(sphere1)
select_object(sphere2)
set_active_object(cylinder)
bpy.ops.object.join()
def load_blender_mesh(context, mesh_filepath, name):
result = True
if mesh_filepath.suffix in ['.stl', '.STL']:
bpy.ops.import_mesh.stl(filepath=str(mesh_filepath.resolve()))
elif mesh_filepath.suffix in ['.obj', '.OBJ']:
_manually_select_obj_handle = True
bpy.ops.import_scene.obj(filepath=str(mesh_filepath.resolve()), axis_up='Z', axis_forward='Y')
# Hack, .3ds and .obj imports do not make the imported obj_handle active. A hack is
# to capture the selected objects in this case.
set_active_object(context.selected_objects[0])
elif mesh_filepath.suffix in ['.dae', '.DAE']:
bpy.ops.wm.collada_import(filepath=str(mesh_filepath.resolve()))
# If we are importing .dae meshes, they can import stuff other than meshes, such as cameras etc.
# We should remove these extra things and only keep the meshes
for temp_obj_handle in context.selected_objects:
if temp_obj_handle.type == 'MESH':
obj_handle = temp_obj_handle
# set_active_object(obj_handle)
else:
bpy.data.objects.remove(temp_obj_handle)
so = bpy.context.selected_objects
if len(so) > 1:
set_active_object(so[0])
bpy.ops.object.join()
so[0].name = name
obj_handle = get_active_object()
# The lines below are essential in joint the multiple meshes
# defined in the .dae into one mesh, secondly, making sure that
# the origin of the mesh is what it is supposed to be as
# using the join() function call alters the mesh origin
trans_o = obj_handle.matrix_world.copy()
obj_handle.matrix_world.identity()
obj_handle.data.transform(trans_o)
# Kind of a hack, blender is spawning the collada file
# a 90 deg offset along the axis axis, this is to correct that
# Maybe this will not be needed in future versions of blender
r_x = mathutils.Matrix.Rotation(-pi / 2, 4, 'X')
obj_handle.data.transform(r_x)
else:
set_active_object(so[0])
elif mesh_filepath.suffix in ['.3ds', '.3DS']:
_manually_select_obj_handle = True
bpy.ops.import_scene.autodesk_3ds(filepath=str(mesh_filepath.resolve()))
# Hack, .3ds and .obj imports do not make the imported obj_handle active. A hack is
# to capture the selected objects in this case.
set_active_object(context.selected_objects[0])
elif mesh_filepath.suffix == '':
bpy.ops.object.empty_add(type='PLAIN_AXES')
else:
# We failed, mark as false
result = False
return result
def save_blender_mesh(obj_handle, mesh_filepath, mesh_type, use_mesh_modifiers):
hide_state = is_object_hidden(obj_handle)
hide_object(obj_handle, False)
select_object(obj_handle, True)
mesh_filepath = mesh_filepath + '.' + mesh_type
if mesh_type == 'STL':
bpy.ops.export_mesh.stl(filepath=mesh_filepath, use_selection=True,
use_mesh_modifiers=use_mesh_modifiers)
elif mesh_type == 'OBJ':
bpy.ops.export_scene.obj(filepath=mesh_filepath, axis_up='Z', axis_forward='Y',
use_selection=True, use_mesh_modifiers=use_mesh_modifiers)
elif mesh_type == '3DS':
# 3DS doesn't support suppressing modifiers, so we explicitly
# toggle them to save as high res and low res meshes
# STILL BUGGY
for mod in obj_handle.modifiers:
mod.show_viewport = True
bpy.ops.export_scene.autodesk_3ds(filepath=mesh_filepath, use_selection=True)
elif mesh_type == 'PLY':
# .PLY export has a bug in which it only saves the mesh that is
# active in context of view. Hence we explicitly select this object
# as active in the scene on top of being selected
set_active_object(obj_handle)
bpy.ops.export_mesh.ply(filepath=mesh_filepath, use_mesh_modifiers=use_mesh_modifiers)
set_active_object(None)
else:
raise Exception('High Res Mesh Format Not Specified/Understood')
select_object(obj_handle, False)
hide_object(obj_handle, hide_state)
def add_collision_shape_property(obj_handle, shape_type=None):
obj_handle.ambf_collision_shape_prop_collection.add()
cnt = len(obj_handle.ambf_collision_shape_prop_collection.items())
prop_tuple = obj_handle.ambf_collision_shape_prop_collection.items()[cnt - 1]
if shape_type is not None:
prop_tuple[1].ambf_collision_shape = shape_type
collision_shape_create_visual(obj_handle, prop_tuple[1])
return prop_tuple[1]
def remove_collision_shape_property(obj_handle, idx=None):
cnt = len(obj_handle.ambf_collision_shape_prop_collection.items())
if idx is None:
idx = cnt - 1
if idx < 0 or idx >= cnt:
print('ERROR! Object ', obj_handle.name, ' has only ', cnt, ' collision props')
print('ERROR! Cannot remove at Idx: ', idx)
return
shape_prop = obj_handle.ambf_collision_shape_prop_collection.items()[cnt - 1][1]
coll_shape_obj_handle = shape_prop.ambf_collision_shape_pointer
bpy.data.objects.remove(coll_shape_obj_handle)
obj_handle.ambf_collision_shape_prop_collection.remove(cnt - 1)
def estimate_collision_shape_geometry(obj_handle):
if obj_handle.ambf_object_type == 'RIGID_BODY':
if len(obj_handle.ambf_collision_shape_prop_collection.items()) == 0:
add_collision_shape_property(obj_handle)
# Don't bother if the shape is a compound shape for now. Let the
# user calculate the geometries.
if obj_handle.ambf_collision_type in ['MESH', 'SINGULAR_SHAPE']:
dims = obj_handle.dimensions.copy()
prop_group = obj_handle.ambf_collision_shape_prop_collection.items()[0][1]
# Now we need to find out the geometry of the shape
if prop_group.ambf_collision_shape == 'BOX':
prop_group.ambf_collision_shape_disable_update_cbs = True
prop_group.ambf_collision_shape_xyz_dims[0] = dims[0]
prop_group.ambf_collision_shape_xyz_dims[1] = dims[1]
prop_group.ambf_collision_shape_xyz_dims[2] = dims[2]
prop_group.ambf_collision_shape_disable_update_cbs = False
collision_shape_update_dimensions(prop_group)
elif prop_group.ambf_collision_shape == 'SPHERE':
prop_group.ambf_collision_shape_radius = max(dims) / 2
elif prop_group.ambf_collision_shape in ['CYLINDER', 'CONE', 'CAPSULE']:
major_ax_char, major_ax_idx = get_major_axis(dims)
median_ax_char, median_ax_idx = get_median_axis(dims)
prop_group.ambf_collision_shape_radius = dims[median_ax_idx] / 2.0
prop_group.ambf_collision_shape_height = dims[major_ax_idx]
prop_group.ambf_collision_shape_axis = major_ax_char.upper()
def collision_shape_update_dimensions(shape_prop):
if shape_prop.ambf_collision_shape_disable_update_cbs:
return
coll_shape_obj_handle = shape_prop.ambf_collision_shape_pointer
if coll_shape_obj_handle is None:
return
height = shape_prop.ambf_collision_shape_height
radius = shape_prop.ambf_collision_shape_radius
lx = shape_prop.ambf_collision_shape_xyz_dims[0]
ly = shape_prop.ambf_collision_shape_xyz_dims[1]
lz = shape_prop.ambf_collision_shape_xyz_dims[2]
lx = ambf_round(lx)
ly = ambf_round(ly)
lz = ambf_round(lz)
dim_old = coll_shape_obj_handle.dimensions.copy()
scale_old = coll_shape_obj_handle.scale.copy()
if shape_prop.ambf_collision_shape == 'BOX':
coll_shape_obj_handle.scale[0] = scale_old[0] * lx / dim_old[0]
coll_shape_obj_handle.scale[1] = scale_old[1] * ly / dim_old[1]
coll_shape_obj_handle.scale[2] = scale_old[2] * lz / dim_old[2]
elif shape_prop.ambf_collision_shape in ['CONE', 'CYLINDER', 'CAPSULE', 'SPHERE']:
dir_axis = get_axis_idx(shape_prop.ambf_collision_shape_axis.upper())
height_old = coll_shape_obj_handle.dimensions[dir_axis]
radius_old = coll_shape_obj_handle.dimensions[(dir_axis + 1) % 3]
if shape_prop.ambf_collision_shape == 'SPHERE':
coll_shape_obj_handle.scale = scale_old * radius / radius_old * 2
else: # For Cylinder, Cone and Capsule
coll_shape_obj_handle.scale[dir_axis] = scale_old[dir_axis] * height / height_old
coll_shape_obj_handle.scale[(dir_axis + 1) % 3] = scale_old[(dir_axis + 1) % 3] * radius / radius_old * 2
coll_shape_obj_handle.scale[(dir_axis + 2) % 3] = scale_old[(dir_axis + 2) % 3] * radius / radius_old * 2
def collision_shape_update_local_offset(obj_handle, shape_prop):
if shape_prop.ambf_collision_shape_disable_update_cbs:
return
coll_shape_obj_handle = shape_prop.ambf_collision_shape_pointer
if coll_shape_obj_handle is None:
return
scale_old = coll_shape_obj_handle.scale.copy()
T_p_w = obj_handle.matrix_world.copy()
coll_shape_obj_handle.matrix_world = T_p_w
euler_rot = mathutils.Euler((shape_prop.ambf_collision_shape_angular_offset[0],
shape_prop.ambf_collision_shape_angular_offset[1],
shape_prop.ambf_collision_shape_angular_offset[2]), 'ZYX')
# Shape Offset in Inertial Frame
R_c_p = euler_rot.to_matrix()
T_c_p = R_c_p.to_4x4()
T_c_p.translation.x = shape_prop.ambf_collision_shape_linear_offset[0]
T_c_p.translation.y = shape_prop.ambf_collision_shape_linear_offset[1]
T_c_p.translation.z = shape_prop.ambf_collision_shape_linear_offset[2]
coll_shape_obj_handle.matrix_world = T_p_w @ T_c_p
coll_shape_obj_handle.scale = scale_old
def set_3d_cursor_location(location):
bpy.context.scene.cursor.location = location
def collision_shape_create_visual(obj_handle, shape_prop_group):
cur_active_obj_handle = get_active_object()
set_3d_cursor_location([0, 0, 0])
select_all_objects(False)
if shape_prop_group.ambf_collision_shape_pointer is None:
height = shape_prop_group.ambf_collision_shape_height
radius = shape_prop_group.ambf_collision_shape_radius
lx = shape_prop_group.ambf_collision_shape_xyz_dims[0]
ly = shape_prop_group.ambf_collision_shape_xyz_dims[1]
lz = shape_prop_group.ambf_collision_shape_xyz_dims[2]
if shape_prop_group.ambf_collision_shape == 'BOX':
bpy.ops.mesh.primitive_cube_add(size=1.0)
coll_shape_obj_handle = get_active_object()
coll_shape_obj_handle.scale[0] = lx
coll_shape_obj_handle.scale[1] = ly
coll_shape_obj_handle.scale[2] = lz
elif shape_prop_group.ambf_collision_shape == 'SPHERE':
bpy.ops.mesh.primitive_uv_sphere_add(radius=radius)
elif shape_prop_group.ambf_collision_shape in ['CONE', 'CYLINDER', 'CAPSULE']:
if shape_prop_group.ambf_collision_shape_axis == 'X':
dir_axis = 0
rot_axis = mathutils.Vector((0, 1, 0)) # Choose y axis for rot
rot_angle = math.pi/2
elif shape_prop_group.ambf_collision_shape_axis == 'Y':
dir_axis = 1
rot_axis = mathutils.Vector((1, 0, 0)) # Choose y axis for rot
rot_angle = -math.pi/2
else:
dir_axis = 2
rot_axis = mathutils.Vector((0, 0, 1))
rot_angle = 0
rpy_rot = rot_axis * rot_angle
if shape_prop_group.ambf_collision_shape == 'CONE':
bpy.ops.mesh.primitive_cone_add(rotation=rpy_rot, radius1=radius, depth=height)
elif shape_prop_group.ambf_collision_shape == 'CYLINDER':
bpy.ops.mesh.primitive_cylinder_add(rotation=rpy_rot, radius=radius, depth=height)
elif shape_prop_group.ambf_collision_shape == 'CAPSULE':
# There is no primitive for capsule in Blender, so we
# have to use a workaround using the sphere