mujoco-react 8.4.1 → 8.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -18
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -109,32 +109,28 @@ import { useEffect, useRef } from "react";
|
|
|
109
109
|
import { z } from "zod";
|
|
110
110
|
import { useMujoco, useBeforePhysicsStep, useAfterPhysicsStep } from "mujoco-react";
|
|
111
111
|
|
|
112
|
-
const CtrlCommand = z.
|
|
113
|
-
type: z.literal("ctrl_command"),
|
|
114
|
-
ctrl: z.array(z.number()),
|
|
115
|
-
});
|
|
116
|
-
|
|
117
|
-
type CtrlCommand = z.infer<typeof CtrlCommand>;
|
|
118
|
-
|
|
119
|
-
function parseSocketMessage(data: string): CtrlCommand | null {
|
|
112
|
+
const CtrlCommand = z.preprocess((data) => {
|
|
120
113
|
try {
|
|
121
|
-
|
|
122
|
-
return parsed.success ? parsed.data : null;
|
|
114
|
+
return typeof data === "string" ? JSON.parse(data) : data;
|
|
123
115
|
} catch {
|
|
124
|
-
return
|
|
116
|
+
return undefined;
|
|
125
117
|
}
|
|
126
|
-
}
|
|
118
|
+
}, z.object({
|
|
119
|
+
type: z.literal("ctrl_command"),
|
|
120
|
+
ctrl: z.array(z.number()),
|
|
121
|
+
}));
|
|
127
122
|
|
|
128
123
|
function useWebSocketControls(url: string) {
|
|
129
124
|
const wsRef = useRef<WebSocket | null>(null);
|
|
130
|
-
const
|
|
125
|
+
const latestCtrlRef = useRef<number[] | null>(null);
|
|
131
126
|
|
|
132
127
|
useEffect(() => {
|
|
133
128
|
const ws = new WebSocket(url);
|
|
134
129
|
wsRef.current = ws;
|
|
135
130
|
|
|
136
131
|
ws.onmessage = (evt) => {
|
|
137
|
-
|
|
132
|
+
const command = CtrlCommand.safeParse(evt.data);
|
|
133
|
+
if (command.success) latestCtrlRef.current = command.data.ctrl;
|
|
138
134
|
};
|
|
139
135
|
|
|
140
136
|
return () => ws.close();
|
|
@@ -142,10 +138,10 @@ function useWebSocketControls(url: string) {
|
|
|
142
138
|
|
|
143
139
|
// Apply incoming actuator controls each physics step.
|
|
144
140
|
useBeforePhysicsStep((model, data) => {
|
|
145
|
-
const
|
|
146
|
-
if (!
|
|
147
|
-
for (let i = 0; i < Math.min(
|
|
148
|
-
data.ctrl[i] =
|
|
141
|
+
const ctrl = latestCtrlRef.current;
|
|
142
|
+
if (!ctrl) return;
|
|
143
|
+
for (let i = 0; i < Math.min(ctrl.length, model.nu); i++) {
|
|
144
|
+
data.ctrl[i] = ctrl[i];
|
|
149
145
|
}
|
|
150
146
|
});
|
|
151
147
|
|