euv-cli 0.51.0

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
Documentation
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
"""Euv Live-Link Add-on for Blender 4.x / 5.x.

Streams 50ms-debounced scene deltas (transforms, cameras, lights, Principled
BSDF sliders, shape key morph weights) and selective binary .glb asset hot-swaps
over loopback HTTP to `euv blender live-sync` (default 127.0.0.1:9877, keeping
port 9876 reserved for Blender Lab MCP).
"""

bl_info = {
    "name": "Euv Live-Link",
    "author": "Euv Framework Contributors",
    "version": (1, 0, 0),
    "blender": (4, 0, 0),
    "location": "View3D > Sidebar > Euv",
    "description": "Real-time HTTP/SSE scene delta and selective GLB hot-swap bridge for euv",
    "category": "Import-Export",
}

import json
import os
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request

try:
    import bpy
    from bpy.props import BoolProperty, IntProperty, StringProperty
    from bpy.types import Operator, Panel, PropertyGroup
except ImportError:
    bpy = None


DEFAULT_LIVE_SYNC_HOST = "127.0.0.1"
DEFAULT_LIVE_SYNC_PORT = 9877
DEFAULT_DEBOUNCE_MS = 50


_STATE = {
    "connected": False,
    "timer_scheduled": False,
    "pending_delta": False,
    "pending_mesh_names": set(),
    "last_push_time": 0.0,
    "last_status": "Disconnected",
    "delta_seq": 0,
}


def _blender_vec3_to_yup(vec):
    return [float(vec[0]), float(vec[2]), float(-vec[1])]


def _blender_quat_to_yup(quat):
    # Blender quaternion is (w, x, y, z); glTF/euv quaternion is [x, y, z, w].
    return [float(quat[1]), float(quat[3]), float(-quat[2]), float(quat[0])]


def _blender_scale_to_yup(scale):
    return [float(scale[0]), float(scale[2]), float(scale[1])]


def _extract_principled_bsdf(mat):
    if mat is None or not mat.use_nodes or mat.node_tree is None:
        return None
    principled = None
    for node in mat.node_tree.nodes:
        if node.type == "BSDF_PRINCIPLED":
            principled = node
            break
    if principled is None:
        return None

    def _read_scalar(names, fallback):
        for name in names:
            sock = principled.inputs.get(name)
            if sock is not None and hasattr(sock, "default_value"):
                return float(sock.default_value)
        return float(fallback)

    def _read_color(names, fallback):
        for name in names:
            sock = principled.inputs.get(name)
            if sock is not None and hasattr(sock, "default_value"):
                val = sock.default_value
                return [float(val[0]), float(val[1]), float(val[2]), float(val[3]) if len(val) > 3 else 1.0]
        return list(fallback)

    emissive = _read_color(("Emission Color", "Emission"), [0.0, 0.0, 0.0, 1.0])
    sheen_tint = _read_color(("Sheen Tint",), [1.0, 1.0, 1.0, 1.0])
    return {
        "name": mat.name,
        "base_color": _read_color(("Base Color",), [0.8, 0.8, 0.8, 1.0]),
        "metallic": _read_scalar(("Metallic",), 0.0),
        "roughness": _read_scalar(("Roughness",), 0.5),
        "ior": _read_scalar(("IOR",), 1.5),
        "specular": _read_scalar(("Specular IOR Level", "Specular"), 0.5),
        "clearcoat": _read_scalar(("Coat Weight", "Clearcoat"), 0.0),
        "clearcoat_roughness": _read_scalar(("Coat Roughness", "Clearcoat Roughness"), 0.03),
        "transmission": _read_scalar(("Transmission Weight", "Transmission"), 0.0),
        "sheen": _read_scalar(("Sheen Weight", "Sheen"), 0.0),
        "sheen_roughness": _read_scalar(("Sheen Roughness",), 0.5),
        "sheen_color": sheen_tint[:3],
        "emissive": emissive[:3],
        "emissive_strength": _read_scalar(("Emission Strength",), 1.0),
    }


def collect_scene_delta_payload(scene):
    transforms = []
    cameras = []
    lights = []
    morph_weights = []
    seen_materials = {}

    for obj in scene.objects:
        loc, rot, scale = obj.matrix_world.decompose()
        transforms.append(
            {
                "name": obj.name,
                "translation": _blender_vec3_to_yup(loc),
                "rotation": _blender_quat_to_yup(rot),
                "scale": _blender_scale_to_yup(scale),
                "visible": not obj.hide_viewport,
                "collections": [coll.name for coll in obj.users_collection],
            }
        )
        if obj.type == "CAMERA" and obj.data is not None:
            cam = obj.data
            cameras.append(
                {
                    "name": obj.name,
                    "is_perspective": cam.type == "PERSP",
                    "fov_deg": float(getattr(cam, "angle", 0.85)) * 57.2957795,
                    "ortho_scale": float(getattr(cam, "ortho_scale", 6.0)),
                    "clip_start": float(cam.clip_start),
                    "clip_end": float(cam.clip_end),
                    "translation": _blender_vec3_to_yup(loc),
                    "rotation": _blender_quat_to_yup(rot),
                }
            )
        elif obj.type == "LIGHT" and obj.data is not None:
            light = obj.data
            light_entry = {
                "name": obj.name,
                "kind": str(light.type).lower(),
                "color": [float(light.color[0]), float(light.color[1]), float(light.color[2])],
                "intensity": float(light.energy),
                "translation": _blender_vec3_to_yup(loc),
                "rotation": _blender_quat_to_yup(rot),
            }
            if light.type == "AREA":
                width = float(getattr(light, "size", 1.0))
                shape = str(getattr(light, "shape", "SQUARE"))
                height = float(getattr(light, "size_y", width)) if shape in ("RECTANGLE", "ELLIPSE") else width
                light_entry["width"] = width
                light_entry["height"] = height
            lights.append(light_entry)
        elif obj.type == "MESH" and obj.data is not None:
            mesh = obj.data
            if mesh.shape_keys is not None and mesh.shape_keys.key_blocks:
                weights = [float(kb.value) for kb in mesh.shape_keys.key_blocks[1:]]
                if weights:
                    morph_weights.append({"name": obj.name, "weights": weights})
            for slot in obj.material_slots:
                mat = slot.material
                if mat is not None and mat.name not in seen_materials:
                    parsed = _extract_principled_bsdf(mat)
                    if parsed is not None:
                        seen_materials[mat.name] = parsed

    _STATE["delta_seq"] += 1
    return {
        "scene_name": scene.name,
        "blender_version": ".".join(str(part) for part in bpy.app.version),
        "frame": int(scene.frame_current),
        "client_seq": _STATE["delta_seq"],
        "timestamp_ms": int(time.time() * 1000),
        "transforms": transforms,
        "cameras": cameras,
        "lights": lights,
        "materials": list(seen_materials.values()),
        "morph_weights": morph_weights,
    }


def _http_post_async(url, payload_bytes, content_type):
    def _worker():
        req = urllib.request.Request(
            url,
            data=payload_bytes,
            method="POST",
            headers={"Content-Type": content_type},
        )
        try:
            with urllib.request.urlopen(req, timeout=2.0) as resp:
                _STATE["last_status"] = f"Synced ({resp.status})"
        except urllib.error.URLError as exc:
            _STATE["last_status"] = f"Sync error: {exc.reason}"
        except Exception as exc:
            _STATE["last_status"] = f"Sync error: {exc}"

    thread = threading.Thread(target=_worker, daemon=True)
    thread.start()


def _base_url(scene):
    settings = scene.euv_live_link
    host = settings.host.strip() or DEFAULT_LIVE_SYNC_HOST
    port = int(settings.port)
    return f"http://{host}:{port}"


def push_delta_now(scene):
    payload = collect_scene_delta_payload(scene)
    encoded = json.dumps(payload).encode("utf-8")
    _http_post_async(f"{_base_url(scene)}/blender/delta", encoded, "application/json")
    _STATE["last_push_time"] = time.monotonic()


def push_glb_asset_now(scene, asset_id="scene", selected_only=False):
    safe_id = "".join(ch if (ch.isalnum() or ch in ("-", "_", ".")) else "_" for ch in asset_id)
    if not safe_id:
        safe_id = "scene"
    with tempfile.TemporaryDirectory(prefix="euv_live_link_") as tmp_dir:
        glb_path = os.path.join(tmp_dir, f"{safe_id}.glb")
        rna_props = set(bpy.ops.export_scene.gltf.get_rna_type().properties.keys())
        desired = {
            "filepath": glb_path,
            "export_format": "GLB",
            "use_selection": selected_only,
            "export_yup": True,
            "export_apply": True,
            "export_texcoords": True,
            "export_normals": True,
            "export_tangents": True,
            "export_materials": "EXPORT",
            "export_cameras": True,
            "export_lights": True,
            "export_extras": True,
            "export_skins": True,
            "export_morph": True,
            "export_animations": True,
        }
        kwargs = {key: value for key, value in desired.items() if key in rna_props}
        bpy.ops.export_scene.gltf(**kwargs)
        if os.path.isfile(glb_path):
            with open(glb_path, "rb") as handle:
                glb_bytes = handle.read()
            quoted_id = urllib.parse.quote(safe_id, safe="")
            _http_post_async(
                f"{_base_url(scene)}/blender/asset/{quoted_id}",
                glb_bytes,
                "model/gltf-binary",
            )


def _debounced_flush_timer():
    _STATE["timer_scheduled"] = False
    if bpy is None or not _STATE["connected"]:
        return None
    scene = bpy.context.scene
    if scene is None:
        return None
    if _STATE["pending_delta"]:
        _STATE["pending_delta"] = False
        push_delta_now(scene)
    if _STATE["pending_mesh_names"]:
        mesh_names = list(_STATE["pending_mesh_names"])
        _STATE["pending_mesh_names"].clear()
        if scene.euv_live_link.auto_export_geometry and mesh_names:
            push_glb_asset_now(scene, asset_id=mesh_names[0], selected_only=False)
    return None


def _on_depsgraph_update(scene, depsgraph):
    if not _STATE["connected"] or not scene.euv_live_link.auto_sync:
        return
    if depsgraph is None:
        return
    for update in depsgraph.updates:
        if update.is_updated_transform or update.is_updated_shading:
            _STATE["pending_delta"] = True
        if update.is_updated_geometry:
            _STATE["pending_delta"] = True
            id_obj = getattr(update, "id", None)
            if id_obj is not None and hasattr(id_obj, "name"):
                _STATE["pending_mesh_names"].add(str(id_obj.name))
    if (_STATE["pending_delta"] or _STATE["pending_mesh_names"]) and not _STATE["timer_scheduled"]:
        _STATE["timer_scheduled"] = True
        delay_sec = max(0.01, float(scene.euv_live_link.debounce_ms) / 1000.0)
        bpy.app.timers.register(_debounced_flush_timer, first_interval=delay_sec)


if bpy is not None:

    class EuvLiveLinkSettings(PropertyGroup):
        host: StringProperty(
            name="Host",
            description="Euv Live-Link daemon host",
            default=DEFAULT_LIVE_SYNC_HOST,
        )
        port: IntProperty(
            name="Port",
            description="Euv Live-Link daemon HTTP/SSE port (avoids Blender MCP 9876)",
            default=DEFAULT_LIVE_SYNC_PORT,
            min=1,
            max=65535,
        )
        debounce_ms: IntProperty(
            name="Debounce (ms)",
            description="Depsgraph update debounce window in milliseconds",
            default=DEFAULT_DEBOUNCE_MS,
            min=10,
            max=1000,
        )
        auto_sync: BoolProperty(
            name="Auto-Sync Deltas",
            description="Stream transforms, cameras, lights, and Principled BSDF edits live",
            default=True,
        )
        auto_export_geometry: BoolProperty(
            name="Hot-Swap Mesh GLB",
            description="Automatically push binary .glb updates on mesh geometry edits",
            default=False,
        )

    class EUV_OT_toggle_live_link(Operator):
        bl_idname = "euv.toggle_live_link"
        bl_label = "Toggle Euv Live-Link"
        bl_description = "Connect or disconnect Euv Live-Link depsgraph sync"

        def execute(self, context):
            _STATE["connected"] = not _STATE["connected"]
            if _STATE["connected"]:
                if _on_depsgraph_update not in bpy.app.handlers.depsgraph_update_post:
                    bpy.app.handlers.depsgraph_update_post.append(_on_depsgraph_update)
                _STATE["last_status"] = "Connected"
                push_delta_now(context.scene)
            else:
                if _on_depsgraph_update in bpy.app.handlers.depsgraph_update_post:
                    bpy.app.handlers.depsgraph_update_post.remove(_on_depsgraph_update)
                _STATE["last_status"] = "Disconnected"
            return {"FINISHED"}

    class EUV_OT_push_delta(Operator):
        bl_idname = "euv.push_delta"
        bl_label = "Push Delta Now"
        bl_description = "Send an immediate JSON scene delta to Euv Live-Link"

        def execute(self, context):
            push_delta_now(context.scene)
            return {"FINISHED"}

    class EUV_OT_push_glb(Operator):
        bl_idname = "euv.push_glb"
        bl_label = "Push GLB Asset"
        bl_description = "Export binary .glb and hot-swap into connected Euv viewports"

        def execute(self, context):
            active = context.active_object
            asset_id = active.name if active is not None else context.scene.name
            push_glb_asset_now(context.scene, asset_id=asset_id, selected_only=False)
            return {"FINISHED"}

    class EUV_PT_live_link_panel(Panel):
        bl_label = "Euv Live-Link"
        bl_idname = "EUV_PT_live_link_panel"
        bl_space_type = "VIEW_3D"
        bl_region_type = "UI"
        bl_category = "Euv"

        def draw(self, context):
            layout = self.layout
            settings = context.scene.euv_live_link
            layout.prop(settings, "host")
            layout.prop(settings, "port")
            layout.prop(settings, "debounce_ms")
            layout.prop(settings, "auto_sync")
            layout.prop(settings, "auto_export_geometry")
            row = layout.row()
            toggle_label = "Disconnect" if _STATE["connected"] else "Connect Live-Link"
            row.operator("euv.toggle_live_link", text=toggle_label)
            layout.operator("euv.push_delta")
            layout.operator("euv.push_glb")
            layout.label(text=f"Status: {_STATE['last_status']}")

    _CLASSES = (
        EuvLiveLinkSettings,
        EUV_OT_toggle_live_link,
        EUV_OT_push_delta,
        EUV_OT_push_glb,
        EUV_PT_live_link_panel,
    )

    def register():
        for cls in _CLASSES:
            bpy.utils.register_class(cls)
        bpy.types.Scene.euv_live_link = bpy.props.PointerProperty(type=EuvLiveLinkSettings)

    def unregister():
        _STATE["connected"] = False
        if _on_depsgraph_update in bpy.app.handlers.depsgraph_update_post:
            bpy.app.handlers.depsgraph_update_post.remove(_on_depsgraph_update)
        if hasattr(bpy.types.Scene, "euv_live_link"):
            del bpy.types.Scene.euv_live_link
        for cls in reversed(_CLASSES):
            bpy.utils.unregister_class(cls)