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):
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)