File size: 9,791 Bytes
f9c7324
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import carb
from omni.kit.scripting import BehaviorScript
from omni.isaac.dynamic_control import _dynamic_control
from enum import Enum
from pxr import Gf
from threading import Thread
import marshal,json
import omni.kit.commands
from omni.isaac.core.prims import XFormPrim
import numpy as np
from pxr import Gf, Sdf, Usd, UsdGeom
from omni.isaac.core import SimulationContext, World
import math
from omni.replicator.core import utils
from pxr import PhysxSchema, UsdGeom, UsdPhysics
import math


def find_prim_path_by_name(prim_name: str, root_path: str = "/") -> str:
    """Recursively find the full path by Prim name"""
    stage = omni.usd.get_context().get_stage()
    prim = stage.GetPrimAtPath(root_path)
    
    def _find_prim(prim):
        if prim.GetName() == prim_name:
            return prim.GetPath().pathString
        for child in prim.GetChildren():
            result = _find_prim(child)
            if result:
                return result
        return None
    
    found_path = _find_prim(prim)
    if not found_path:
        raise RuntimeError(f"Prim '{prim_name}' not found under {root_path}")
    return found_path


        
# 1. prim init
# joint_prim = XFormPrim(find_prim_path_by_name("fridge_E_body_61"))
# right_revolutejoint_path = find_prim_path_by_name("RevoluteJoint_fridge_right")
# left_revolutejoint_path = find_prim_path_by_name("RevoluteJoint_fridge_left")

# 2. articulation Root prim
root_articulation_prim = find_prim_path_by_name("fridge_E_body_61")
stage = omni.usd.get_context().get_stage()
# 3. joint name 
joint_names = ["RevoluteJoint_fridge_left","RevoluteJoint_fridge_right"]
joint_threshold = 0.4
# 4. Joint information
joints_info = {}
for joint_name in joint_names:
    joint_prim_path = find_prim_path_by_name(joint_name)
    joint_prim_obj = stage.GetPrimAtPath(joint_prim_path)
    joint = UsdPhysics.RevoluteJoint(joint_prim_obj)
    
    joints_info[joint_name] = {
        'prim': joint,
        'lower_limit': joint.GetLowerLimitAttr().Get(),
        'upper_limit': joint.GetUpperLimitAttr().Get()
    }

# 5. Joint limits and limit differences
joint_limits = {}
joint_limit_diffs = {}

for i, joint_name in enumerate(joint_names):
    joint_limits[joint_name] = {
        'lower': joints_info[joint_name]['lower_limit'],
        'upper': joints_info[joint_name]['upper_limit']
    }
    joint_limit_diffs[joint_name] = (
        joints_info[joint_name]['upper_limit'] - joints_info[joint_name]['lower_limit']
    )
# joint_limit_diff1 = joint_limit_diffs[joint_names[0]]
# joint_limit_diff2 = joint_limit_diffs[joint_names[1]]
# 5. light prim
light_scopes=[
     XFormPrim(find_prim_path_by_name("fridge_light"))
]

class CupboardControl(BehaviorScript):
    def on_init(self):
        self.phsx_freq = 120
        self.joint_handles = []
        self.dc = _dynamic_control.acquire_dynamic_control_interface() 
        light_scopes[0].set_visibility(False)  
        # light_scopes[1].set_visibility(False)
        # init_pose
        # self.local_pose_button, self.local_ort_button_down = joint_prim.get_local_pose()
        # self.local_pose_door, self.local_ort_drawer_up = door_prim.get_local_pose()
        
        # Find Root
        self.art = self.dc.get_articulation(root_articulation_prim)
        if self.art == _dynamic_control.INVALID_HANDLE:
            print('the prim is not an articulation')
   
   
    def on_destroy(self):
        pass

    def on_play(self):
        # 
        self.simulation_context = SimulationContext(
            stage_units_in_meters=1.0,
            physics_dt=1.0/120,
            rendering_dt=1.0/120
        )
       
    def on_pause(self):
        pass

    def on_stop(self):
        self.init_start=True
        # for light in light_scopes:
        #     light.set_visibility(False)
        light_scopes[0].set_visibility(False) 
        # light_scopes[1].set_visibility(False) 
        # back to initial pose
        # joint_prim.set_local_pose(translation=self.local_pose_button)
        pass

    def on_update(self, current_time: float, delta_time: float):
        if delta_time <= 0:
            return
        self.active_art()
        self.apply_behavior() 

    def active_art(self):
        # Find Root
        self.art = self.dc.get_articulation(root_articulation_prim)
        if self.art == _dynamic_control.INVALID_HANDLE:
            print('the prim is not an articulation')
        self.dc.wake_up_articulation(self.art)
        
        # Find joint  
        self.joint_handles = []
        for joint_name in joint_names:
            self.joint_handles.append( self.dc.find_articulation_dof(self.art, joint_name))
    
    def apply_behavior(self):
        self.light_control()
        self.damping_stiffness_change()
        self.target_pose_control()
        
        
    def light_control(self):
        self.left_joint_state = self.dc.get_dof_state(self.joint_handles[0], _dynamic_control.STATE_ALL).pos
        self.right_joint_state =  self.dc.get_dof_state(self.joint_handles[1], _dynamic_control.STATE_ALL).pos
        # print("self.Joint1_state",self.Joint1_state)
            # 联合判断双门状态
        doors_open = [
            self.left_joint_state > math.radians(30),
            self.right_joint_state > math.radians(30)
        ]

        # 灯光控制逻辑
        current_visibility = light_scopes[0].get_visibility()
        if any(doors_open):
            if not current_visibility:
                for light in light_scopes:
                    light.set_visibility(True)
        else:
            if current_visibility:
                for light in light_scopes:
                    light.set_visibility(False)
                    
        # if self.right_joint_state > math.radians(30) :
        #     if light_scopes[0].get_visibility() == False:
        #         for light in light_scopes:
        #             light.set_visibility(True)
        #         # self.dc.set_dof_position_target(self.joint_handles[1], 140)

        # elif self.right_joint_state < math.radians(30):
        #     if light_scopes[0].get_visibility() == True:
        #         for light in light_scopes:
        #             light.set_visibility(False)
                # self.dc.set_dof_position_target(self.joint_handles[1], 0)

    
    def damping_stiffness_change(self):
 
        for i, joint_name in enumerate(joint_names):
            # Get joint state
            joint_state = self.dc.get_dof_state(self.joint_handles[i], _dynamic_control.STATE_ALL).pos
            # Get joint drive API
            joint_drive_path = stage.GetPrimAtPath(find_prim_path_by_name(joint_name))
            joint_drive = UsdPhysics.DriveAPI.Get(joint_drive_path, "angular")
            # Get joint limit difference and set stiffness
            
            joint_limit_diff = joint_limit_diffs[joint_names[i]]
            joint_drive.GetStiffnessAttr().Set(self.calculate_stiffness(joint_state))
            # stiffness = joint_drive.GetStiffnessAttr().Get()
            # damping = joint_drive.GetDampingAttr().Get()
            # print(f"{joint_name} - Stiffness: {stiffness}, Damping: {damping}")
    def calculate_stiffness(self,joint_state):
        """Calculate stiffness value based on joint angle
        
        Args:
            joint_state (float): Joint angle (radians)
            joint_limit (float): Joint limit value
            
        Returns:
            float: Stiffness value
        """
        max_stiffness = 20 # 最大刚度
        # max_stiffness = 50 # 最大刚度
        min_stiffness = 2   # 最小刚度
        decay_rate = 3   # 衰减率
        # 使用指数衰减函数计算刚度
        if abs(joint_state) >= abs(math.radians(joint_threshold * (joints_info[joint_names[i]]['upper_limit']+joints_info[joint_names[i]]['lower_limit']))):
            return min_stiffness
        
        # 计算刚度值:stiffness = max_stiffness * e^(-decay_rate * angle)
        stiffness = max_stiffness * math.exp(-decay_rate * abs(joint_state))
        
        # 确保刚度值在最小值和最大值之间
        return max(min_stiffness, min(stiffness, max_stiffness))       
    
    def target_pose_control(self):
        for i, joint_handle in enumerate(self.joint_handles):
            # Get joint state
            joint_state = self.dc.get_dof_state(joint_handle, _dynamic_control.STATE_ALL).pos
            
            # print("joint_state", joint_state)
            # print("joints_info[joint_names[i]]['upper_limit']", joints_info[joint_names[i]]['upper_limit'])
            # Get joint limit difference
            # Set target position based on joint state                     
            if abs(joints_info[joint_names[i]]['lower_limit']) <= math.radians(abs(joints_info[joint_names[i]]['upper_limit'])):
                if joint_state > math.radians(joint_threshold * (joints_info[joint_names[i]]['upper_limit']+joints_info[joint_names[i]]['lower_limit'])):
                    
                    self.dc.set_dof_position_target(joint_handle, math.radians(joints_info[joint_names[i]]['upper_limit']))
                else:
                    self.dc.set_dof_position_target(joint_handle, math.radians(joints_info[joint_names[i]]['lower_limit']))
            else:
                if joint_state < math.radians(joint_threshold * (joints_info[joint_names[i]]['upper_limit']+joints_info[joint_names[i]]['lower_limit'])):
                    self.dc.set_dof_position_target(joint_handle, math.radians(joints_info[joint_names[i]]['lower_limit']))
                else:
                    self.dc.set_dof_position_target(joint_handle, math.radians(joints_info[joint_names[i]]['upper_limit']))
            # print("self.dc.get_dof_position_target=",self.dc.get_dof_position_target(joint_handle))