07. Basis と Mount のプレイグラウンド
デバイスの マウントトランスフォーム をインタラクティブに操作し、configure.basis、configure.preset、configure.mount がワイヤー上でどのように連携するかを示します。インタラクティブな操作の焦点を configure コマンドに保つため、水平方向の床を固定しています。
このチュートリアルで学べること:
- 基底の並べ替えの設定(
"XZY"→ Y 軸が上のアプリケーションフレーム) - プリセット(
arm_front)の選択と、それが何を設定するかの理解 - 回転クォータニオンを使った、実行時の マウント の上書き(キーボード操作)
- 排他ルール:
mountとpresetは、同じ device configure ブロック内に共存できません - ワンショットの
configureの動作: キーを 1 回押すごとに、configure メッセージが 1 つだけ送信されます - (C++ Glaze)
std::optionalを使った、排他的なフィールドのモデル化
ワークフロー
- 最初のメッセージで、セッションプロファイル、
configure.basis: "XZY"、configure.preset: arm_frontを送信します。固定された床のためにset_cursor_forceの送信を開始します。 - 各ティックで、カーソルの Y を読み取り、
force_y = max(0, (floor_pos - y) * stiffness)を計算して送信します。 - ユーザーがマウント回転キーを押したら、
pending_configure = trueのフラグを立てます。 - 次のティックで、
configure.mountブロックを構築します。そのトランスフォームのrotationは単位クォータニオンです(現在のピッチとヨーから、Z、次いで X の順に合成したもの)。presetは省略します。両者はワイヤー上で排他的だからです。 - リセットキー(
R)で上書きを解除します。次の configure では、再びpresetが使われます。
パラメータ
| 名前 | 既定値 | 用途 |
|---|---|---|
BASIS | "XZY" | 軸の並べ替え — Y 軸が上のアプリケーションフレーム |
DEVICE_PRESET / DEVICE_CONFIG_PRESET | "arm_front" | 名前付きの プリセット — 原点はデバイスのベース |
FLOOR_POS_Y | 0.0 m | 固定された床の平面(アプリケーションの Y 軸) |
STIFFNESS | 1000 N/m | 床のばね定数 |
MOUNT_STEP_DEG | 10° | キー押下ごとの回転量 |
PRINT_EVERY_MS | 200 | テレメトリの間引き間隔 |
操作
| キー | 動作 |
|---|---|
W / S | マウントを、デバイスの +X 軸まわりに ±10° 回転(ピッチ) |
A / D | マウントを、デバイスの +Z 軸まわりに ±10° 回転(ヨー) |
R | マウントをリセット — プリセットに戻します |
H | 操作方法を表示 |
Q | 終了 |
mount と preset は同時に指定できませんサービスは、両方を含む device configure ブロックを拒否します。ユーザーがマウントを上書きすると、このチュートリアルでは、以降のすべての configure から preset を省略します。R を押すと、次の configure で preset が再び有効になり、mount は削除されます。
C++ のバリアントは、バックグラウンドの stdin スレッドで行単位の入力を読み取ります(文字ごとに ENTER を押します)。Python は、メインの非同期ループでリアルタイムにキー入力を取得するため、keyboard パッケージを使用します。ENTER は不要です。キーもコマンドも同じです。
読み取る状態フィールド
data.inverse3[i].state から読み取ります:
cursor_position.y—vec3。床への貫入量の計算に使用しますcurrent_cursor_force— テレメトリ用に報告されます
送信/受信
ペイロードの形式は、すべてのバリアントで同じです。注目すべき違いは、各実装が排他的な mount / preset の分岐をどのように構築するか、そして入力スレッドが WebSocket スレッドにどのように通知するかです。
- Python
- C++ (nlohmann)
- C++ (Glaze)
keyboard パッケージでリアルタイムのキー入力をポーリングする、単一の非同期ループです。pending_configure は、キーハンドラーによって設定されるグローバルフラグで、configure ブロックが送信されるたびにクリアされます。
async with websockets.connect(URI) as websocket:
while True:
msg = await websocket.recv()
data = json.loads(msg)
if first_message:
first_message = False
device_id = data["inverse3"][0]["device_id"]
# Handshake: profile + basis + preset
request_msg = {
"session": {"configure": {"profile": {"name": SLUG}}},
"inverse3": [{
"device_id": device_id,
"configure": build_configure_block(first_handshake=True),
# -> {"basis": {"permutation": "XZY"},
# "preset": {"preset": "arm_front"}}
}],
}
else:
handle_key_inputs() # may set pending_configure = True (classic, not shown)
y = data["inverse3"][0]["state"]["cursor_position"]["y"]
force_y = 0.0 if y > FLOOR_POS_Y else (FLOOR_POS_Y - y) * STIFFNESS
entry = {
"device_id": device_id,
"commands": {"set_cursor_force":
{"vector": {"x": 0.0, "y": force_y, "z": 0.0}}},
}
if pending_configure:
entry["configure"] = build_configure_block(first_handshake=False)
# -> {"mount": {...}} OR {"preset": {...}} (never both)
pending_configure = False
request_msg = {"inverse3": [entry]}
await websocket.send(json.dumps(request_msg))
2 スレッド構成です。バックグラウンドの stdin スレッドが行を読み取り、pending_configure(std::atomic<bool>)を切り替えます。libhv の I/O スレッドは各ティックでそれを確認し、設定されていれば configure を送信します。
std::atomic<bool> pending_configure{false};
ws.onmessage = [&](const std::string &msg) {
const json data = json::parse(msg);
if (!data.contains("inverse3") || data["inverse3"].empty()) return;
const bool do_handshake = first_message;
if (first_message) first_message = false;
const bool do_configure = do_handshake || pending_configure.exchange(false);
json request = {};
if (do_handshake) {
request["session"] = {{"configure", {{"profile",
{{"name", "co.haply.inverse.tutorials:basis-and-mount"}}}}}};
}
request["inverse3"] = json::array();
for (auto &el : data["inverse3"].items()) {
json dev_cmd = {{"device_id", el.value()["device_id"]}};
if (do_configure) {
json cfg = {};
if (do_handshake) cfg["basis"] = {{"permutation", BASIS}};
if (mount_overridden) {
cfg["mount"] = {{"transform", {
{"position", {{"x", 0.0}, {"y", 0.0}, {"z", 0.0}}},
{"rotation", quat_from_xz_deg(mount_angle_x_deg, mount_angle_z_deg)},
{"scale", {{"x", 1.0}, {"y", 1.0}, {"z", 1.0}}},
}}};
} else {
cfg["preset"] = {{"preset", DEVICE_CONFIG_PRESET}};
}
dev_cmd["configure"] = cfg;
}
const float y = el.value()["state"]["cursor_position"]["y"].get<float>();
const float force_y = y > FLOOR_POS_Y ? 0.0f : (FLOOR_POS_Y - y) * STIFFNESS;
dev_cmd["commands"] = {{"set_cursor_force",
{{"vector", {{"x", 0.0}, {"y", force_y}, {"z", 0.0}}}}}};
request["inverse3"].push_back(dev_cmd);
}
ws.send(request.dump());
};
std::thread input_thr(input_thread_func); // stdin reader — flips pending_configure
ws.open("ws://localhost:10001");
while (running.load()) std::this_thread::sleep_for(50ms);
排他ルールは、std::optional<preset_cfg> と std::optional<mount_cfg> によって自然に表現できます。シリアライズされた JSON には、値が設定されている方のみが現れます。プリセット名は enum class としてモデル化され、glz::meta の特殊化によってサービスが期待する文字列へ対応付けられます。
// The preset set modelled as an enum
enum class device_preset {
defaults, arm_front, arm_front_centered,
led_front, led_front_centered, custom,
};
// Glaze meta — serialize the enum as the JSON string the service expects
template <> struct glz::meta<device_preset> {
using enum device_preset;
static constexpr auto value =
enumerate(defaults, arm_front, arm_front_centered,
led_front, led_front_centered, custom);
};
// Transform + the configure block
struct vec3 { float x{}, y{}, z{}; };
struct quat { float w{1.0f}, x{}, y{}, z{}; };
struct transform_t { vec3 position{}; quat rotation{}; vec3 scale{1,1,1}; };
struct preset_cfg { device_preset preset; };
struct basis_cfg { std::string permutation; };
struct mount_cfg { transform_t transform; };
struct device_configure {
std::optional<preset_cfg> preset; // mutually exclusive with mount
std::optional<basis_cfg> basis;
std::optional<mount_cfg> mount; // mutually exclusive with preset
};
// Send / receive
ws.onmessage = [&](const std::string &msg) {
devices_message data{};
if (glz::read<glz_settings>(data, msg)) return;
if (data.inverse3.empty()) return;
const bool do_handshake = first_message.exchange(false);
const bool do_configure = do_handshake || pending_configure.exchange(false);
commands_message out_cmds{};
if (do_handshake) {
out_cmds.session = session_cmd{ /* profile = basis-and-mount */ };
}
for (const auto &dev : data.inverse3) {
device_commands dc{ .device_id = dev.device_id };
if (do_configure) {
device_configure cfg{};
if (do_handshake) cfg.basis = basis_cfg{BASIS};
if (mount_overridden) {
cfg.mount = mount_cfg{ .transform = transform_t{
.rotation = quat_from_xz_deg(mount_angle_x_deg, mount_angle_z_deg)}};
} else {
cfg.preset = preset_cfg{DEVICE_CONFIG_PRESET};
}
dc.configure = std::move(cfg);
}
const float y = dev.state.cursor_position.y;
const float force_y = y > FLOOR_POS_Y ? 0.0f : (FLOOR_POS_Y - y) * STIFFNESS;
dc.commands.set_cursor_force = set_cursor_force_cmd{{0.0f, force_y, 0.0f}};
out_cmds.inverse3.push_back(std::move(dc));
}
std::string out_json;
(void)glz::write_json(out_cmds, out_json);
ws.send(out_json);
};
std::thread input_thr(input_thread_func);
ws.open("ws://localhost:10001");
while (running.load()) std::this_thread::sleep_for(50ms);
チュートリアル 07 は SDK と一緒にローカルにもインストールされています。サービスのインストールディレクトリ配下の tutorials/07-haply-inverse-basis-and-mount/ を確認してください。
関連項目: 基底の並べ替え · マウントとワークスペース · デバイスの設定 · 制御コマンド(set_cursor_force) · 型(transform) · チュートリアル 04(Hello Floor)