{"TotalCount":7,"Files":[{"Ident":"kamishell.blender_bridge","Path":"Editor/BlenderBridge/BlenderBridgeWindow.cs","FileName":"BlenderBridgeWindow.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":337656,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Editor;\nusing Sandbox;\n\nnamespace BlenderBridge\n{\n\t/// \u003Csummary\u003E\n\t/// Editor dock for the Blender Bridge v2.\n\t/// Shows connection status, client indicator, manifest status, materials, and activity log.\n\t/// Summon from the editor\u0027s Window/Layout menu \u2014 the dock manager creates and parents the instance.\n\t/// \u003C/summary\u003E\n\t[Dock( \u0022Editor\u0022, \u0022Blender Bridge\u0022, \u0022sync_alt\u0022 )]\n\tpublic class BlenderBridgeWindow : Widget\n\t{\n\t\tprivate Label _statusLabel;\n\t\tprivate Label _portLabel;\n\t\tprivate Label _clientLabel;\n\t\tprivate Label _manifestLabel;\n\t\tprivate Button _toggleButton;\n\t\tprivate Widget _logCanvas;\n\t\tprivate Widget _materialsCanvas;\n\t\tprivate ToggleSwitch _autoStartToggle;\n\t\tprivate bool _lastRunningState = false;\n\t\tprivate readonly List\u003C(Button btn, BridgeLockFlags flag, string baseLabel)\u003E _lockButtons = new();\n\n\t\tprivate ScrollArea _logScroll;\n\t\tprivate bool _logCollapsed = false;\n\n\t\tprivate static readonly List\u003Cstring\u003E _logEntries = new();\n\t\tprivate const int MaxLogEntries = 200;\n\n\t\t// Auto-start lives in BlenderBridgeServer.AutoStartOnEditorLoad \u2014 a static\n\t\t// constructor here only runs if the dock is in the saved layout.\n\n\t\tpublic BlenderBridgeWindow( Widget parent ) : base( parent )\n\t\t{\n\t\t\tMinimumSize = new Vector2( 450, 400 );\n\t\t\tBuildUI();\n\t\t\t_pollTimer = new System.Threading.Timer( _ =\u003E RequestDrain(), null, 500, 500 );\n\t\t}\n\n\t\tprivate System.Threading.Timer _pollTimer;\n\t\tprivate volatile bool _needsDrain = false;\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Timer tick, on a threadpool thread. Setting the flag alone is not\n\t\t/// enough \u2014 _needsDrain is only consumed in OnPaint, and an unattended\n\t\t/// dock never repaints on its own, so status would sit stale (server\n\t\t/// stopped but \u0022\u25CF Running\u0022, Blender gone but \u00221 client connected\u0022)\n\t\t/// until a mouse-over forced a paint. Hop to the main thread and ask\n\t\t/// for one explicitly.\n\t\t/// \u003C/summary\u003E\n\t\tprivate void RequestDrain()\n\t\t{\n\t\t\t_needsDrain = true;\n\t\t\tGameTask.RunInThreadAsync( async () =\u003E\n\t\t\t{\n\t\t\t\tawait GameTask.MainThread();\n\t\t\t\tif ( IsValid )\n\t\t\t\t\tUpdate();\n\t\t\t} );\n\t\t}\n\n\t\tpublic override void OnDestroyed()\n\t\t{\n\t\t\t_pollTimer?.Dispose();\n\t\t\tbase.OnDestroyed();\n\t\t}\n\n\t\tprotected override void OnPaint()\n\t\t{\n\t\t\tbase.OnPaint();\n\t\t\t// Cheap state-refresh tied to redraw. Reads tags from the current\n\t\t\t// selection \u2014 both fast operations \u2014 so it\u0027s fine to do per-paint\n\t\t\t// rather than wiring up a SelectionChanged event.\n\t\t\tRefreshLockButtonStates();\n\t\t\tif ( !_needsDrain ) return;\n\t\t\t_needsDrain = false;\n\t\t\tDrainLogQueue();\n\t\t}\n\n\t\tprivate void DrainLogQueue()\n\t\t{\n\t\t\tif ( !IsValid || _logCanvas == null ) return;\n\n\t\t\t// Update status\n\t\t\tif ( BlenderBridgeServer.IsRunning != _lastRunningState )\n\t\t\t{\n\t\t\t\t_lastRunningState = BlenderBridgeServer.IsRunning;\n\t\t\t\tif ( _lastRunningState )\n\t\t\t\t{\n\t\t\t\t\t_statusLabel.Text = \u0022\u25CF Running\u0022;\n\t\t\t\t\t_statusLabel.SetStyles( \u0022font-size: 15px; font-weight: bold; color: #4ade80;\u0022 );\n\t\t\t\t\t_toggleButton.Text = \u0022Stop Bridge\u0022;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_statusLabel.Text = \u0022\u25CF Stopped\u0022;\n\t\t\t\t\t_statusLabel.SetStyles( \u0022font-size: 15px; font-weight: bold; color: #f87171;\u0022 );\n\t\t\t\t\t_toggleButton.Text = \u0022Start Bridge\u0022;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update client indicator\n\t\t\tif ( _clientLabel != null )\n\t\t\t{\n\t\t\t\tif ( BlenderBridgeServer.HasActiveClient )\n\t\t\t\t{\n\t\t\t\t\t_clientLabel.Text = \u00221 client connected\u0022;\n\t\t\t\t\t_clientLabel.SetStyles( \u0022font-size: 11px; color: #4ade80;\u0022 );\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_clientLabel.Text = \u0022No clients\u0022;\n\t\t\t\t\t_clientLabel.SetStyles( \u0022font-size: 11px; color: #9ca3af;\u0022 );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Update manifest status\n\t\t\tif ( _manifestLabel != null )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\t\t\tif ( scene != null \u0026\u0026 BridgePersistence.HasSavedState( scene ) )\n\t\t\t\t\t{\n\t\t\t\t\t\t_manifestLabel.Text = \u0022Bridge state saved\u0022;\n\t\t\t\t\t\t_manifestLabel.SetStyles( \u0022font-size: 11px; color: #4ade80;\u0022 );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t_manifestLabel.Text = \u0022No bridge state\u0022;\n\t\t\t\t\t\t_manifestLabel.SetStyles( \u0022font-size: 11px; color: #9ca3af;\u0022 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch\n\t\t\t\t{\n\t\t\t\t\t_manifestLabel.Text = \u0022No bridge state\u0022;\n\t\t\t\t\t_manifestLabel.SetStyles( \u0022font-size: 11px; color: #9ca3af;\u0022 );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Drain log queue. Cap check must come BEFORE TryDequeue: the other\n\t\t\t// order dequeues a 51st message and then discards it, silently losing\n\t\t\t// one line per over-full drain.\n\t\t\tint count = 0;\n\t\t\twhile ( count \u003C 50 \u0026\u0026 BlenderBridgeServer.LogQueue.TryDequeue( out var msg ) )\n\t\t\t{\n\t\t\t\tvar text = $\u0022[{DateTime.Now:HH:mm:ss}] {msg}\u0022;\n\t\t\t\t_logEntries.Add( text );\n\t\t\t\tAddLogLabel( text );\n\t\t\t\tcount\u002B\u002B;\n\n\t\t\t\tif ( _logEntries.Count \u003E MaxLogEntries )\n\t\t\t\t{\n\t\t\t\t\t_logEntries.RemoveAt( 0 );\n\t\t\t\t\tvar firstChild = _logCanvas?.Children?.FirstOrDefault();\n\t\t\t\t\tfirstChild?.Destroy();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprivate void BuildUI()\n\t\t{\n\t\t\tvar root = Layout.Column();\n\t\t\troot.Margin = 8;\n\t\t\troot.Spacing = 6;\n\n\t\t\t// \u2500\u2500 Status Row \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\t\t\tvar statusRow = Layout.Row();\n\t\t\tstatusRow.Spacing = 16;\n\n\t\t\tvar statusCol = Layout.Column();\n\t\t\tvar statusTitle = new Label( \u0022STATUS\u0022 );\n\t\t\tstatusTitle.SetStyles( \u0022font-size: 10px; color: #888;\u0022 );\n\t\t\tstatusCol.Add( statusTitle );\n\t\t\t_statusLabel = new Label( \u0022\u25CF Stopped\u0022 );\n\t\t\t_statusLabel.SetStyles( \u0022font-size: 15px; font-weight: bold; color: #f87171;\u0022 );\n\t\t\tstatusCol.Add( _statusLabel );\n\t\t\tstatusRow.Add( statusCol );\n\n\t\t\tvar portCol = Layout.Column();\n\t\t\tvar portTitle = new Label( \u0022PORT\u0022 );\n\t\t\tportTitle.SetStyles( \u0022font-size: 10px; color: #888;\u0022 );\n\t\t\tportCol.Add( portTitle );\n\t\t\t_portLabel = new Label( BlenderBridgeServer.Port.ToString() );\n\t\t\t_portLabel.SetStyles( \u0022font-size: 15px; font-weight: bold;\u0022 );\n\t\t\tportCol.Add( _portLabel );\n\t\t\tstatusRow.Add( portCol );\n\n\t\t\tstatusRow.AddStretchCell();\n\n\t\t\t_toggleButton = new Button( \u0022Start Bridge\u0022, \u0022play_arrow\u0022 );\n\t\t\t_toggleButton.Clicked \u002B= ToggleBridge;\n\t\t\tstatusRow.Add( _toggleButton );\n\n\t\t\troot.Add( statusRow );\n\n\t\t\t// \u2500\u2500 Client \u002B Manifest Indicators \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\t\t\tvar infoRow = Layout.Row();\n\t\t\tinfoRow.Spacing = 24;\n\n\t\t\tvar clientCol = Layout.Column();\n\t\t\tvar clientTitle = new Label( \u0022CLIENT\u0022 );\n\t\t\tclientTitle.SetStyles( \u0022font-size: 10px; color: #888;\u0022 );\n\t\t\tclientCol.Add( clientTitle );\n\t\t\t_clientLabel = new Label( \u0022No clients\u0022 );\n\t\t\t_clientLabel.SetStyles( \u0022font-size: 11px; color: #9ca3af;\u0022 );\n\t\t\tclientCol.Add( _clientLabel );\n\t\t\tinfoRow.Add( clientCol );\n\n\t\t\tvar manifestCol = Layout.Column();\n\t\t\tvar manifestTitle = new Label( \u0022PERSISTENCE\u0022 );\n\t\t\tmanifestTitle.SetStyles( \u0022font-size: 10px; color: #888;\u0022 );\n\t\t\tmanifestCol.Add( manifestTitle );\n\t\t\t_manifestLabel = new Label( \u0022No bridge state\u0022 );\n\t\t\t_manifestLabel.SetStyles( \u0022font-size: 11px; color: #9ca3af;\u0022 );\n\t\t\tmanifestCol.Add( _manifestLabel );\n\t\t\tinfoRow.Add( manifestCol );\n\n\t\t\troot.Add( infoRow );\n\t\t\troot.AddSeparator();\n\n\t\t\t// \u2500\u2500 Sync Controls \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\t\t\tvar syncBox = Layout.Column();\n\t\t\tsyncBox.Spacing = 4;\n\t\t\tvar syncTitle = new Label( \u0022Sync Controls\u0022 );\n\t\t\tsyncTitle.SetStyles( \u0022font-weight: bold; font-size: 13px;\u0022 );\n\t\t\tsyncBox.Add( syncTitle );\n\n\t\t\tvar syncBtnRow = Layout.Row();\n\t\t\tsyncBtnRow.Spacing = 4;\n\n\t\t\tvar sendToBlenderBtn = new Button( \u0022Send to Blender\u0022, \u0022upload\u0022 );\n\t\t\tsendToBlenderBtn.ToolTip = \u0022Push selected objects to Blender (adopts native MeshComponents if needed)\u0022;\n\t\t\tsendToBlenderBtn.Clicked \u002B= () =\u003E\n\t\t\t{\n\t\t\t\tif ( !BlenderBridgeServer.IsRunning ) return;\n\t\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\t\tif ( scene == null ) return;\n\n\t\t\t\t// Find selected objects in the editor\n\t\t\t\tvar session = SceneEditorSession.Active;\n\t\t\t\tif ( session == null ) return;\n\n\t\t\t\tint count = 0;\n\t\t\t\tforeach ( var sel in session.Selection )\n\t\t\t\t{\n\t\t\t\t\tif ( sel is not GameObject go ) continue;\n\n\t\t\t\t\t// Find existing bridge tag or adopt native MeshComponents.\n\t\t\t\t\t// Identity tags only \u2014 lock tags (bridge_lock_*) share the\n\t\t\t\t\t// prefix, and picking one up would broadcast the object\n\t\t\t\t\t// under a phantom id shared by every locked object.\n\t\t\t\t\tvar bridgeTag = go.Tags.TryGetAll().FirstOrDefault( BlenderBridgeDispatcher.IsBridgeIdentityTag );\n\t\t\t\t\tstring bridgeId;\n\n\t\t\t\t\tif ( bridgeTag != null )\n\t\t\t\t\t{\n\t\t\t\t\t\tbridgeId = bridgeTag.Substring( 7 );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\t// Adopt native MeshComponent or Terrain if present.\n\t\t\t\t\t\tvar meshComp = go.Components.Get\u003CMeshComponent\u003E();\n\t\t\t\t\t\tvar terrain = go.Components.Get\u003CTerrain\u003E();\n\t\t\t\t\t\tbool hasMesh = meshComp?.Mesh != null;\n\t\t\t\t\t\tbool hasTerrain = terrain?.Storage != null;\n\t\t\t\t\t\tif ( !hasMesh \u0026\u0026 !hasTerrain ) continue;\n\n\t\t\t\t\t\tbridgeId = \u0022b_\u0022 \u002B Guid.NewGuid().ToString( \u0022N\u0022 ).Substring( 0, 8 );\n\t\t\t\t\t\tgo.Tags.Add( $\u0022bridge_{bridgeId}\u0022 );\n\t\t\t\t\t\tvar kind = hasTerrain ? \u0022terrain\u0022 : \u0022mesh\u0022;\n\t\t\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Adopted \u0027{go.Name}\u0027 as {bridgeId} ({kind})\u0022 );\n\t\t\t\t\t}\n\n\t\t\t\t\t// Build and broadcast as an object_created message\n\t\t\t\t\tvar message = BlenderBridgeDispatcher.BuildObjectCreatedMessage( bridgeId, go );\n\t\t\t\t\tif ( message != null )\n\t\t\t\t\t{\n\t\t\t\t\t\tBlenderBridgeServer.BroadcastWithSeq( message );\n\t\t\t\t\t\tcount\u002B\u002B;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ( count \u003E 0 )\n\t\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Sent {count} object(s) to Blender\u0022 );\n\t\t\t\telse\n\t\t\t\t\tBlenderBridgeServer.LogInfo( \u0022No mesh objects selected\u0022 );\n\t\t\t};\n\t\t\tsyncBtnRow.Add( sendToBlenderBtn );\n\n\t\t\tvar requestFromBlenderBtn = new Button( \u0022Request from Blender\u0022, \u0022download\u0022 );\n\t\t\trequestFromBlenderBtn.ToolTip = \u0022Ask Blender to re-send mesh data for all bridge objects\u0022;\n\t\t\trequestFromBlenderBtn.Clicked \u002B= () =\u003E\n\t\t\t{\n\t\t\t\tif ( !BlenderBridgeServer.IsRunning ) return;\n\t\t\t\t// Trigger a full sync \u2014 Blender will send all its objects\n\t\t\t\tBlenderBridgeServer.BroadcastWithSeq( new { type = \u0022sync_response\u0022, objects = new object[0] } );\n\t\t\t\tBlenderBridgeServer.LogInfo( \u0022Requested resync from Blender\u0022 );\n\t\t\t};\n\t\t\tsyncBtnRow.Add( requestFromBlenderBtn );\n\n\t\t\tAddLockButton( syncBtnRow, \u0022Lock In\u0022, \u0022lock\u0022, BridgeLockFlags.Inbound,\n\t\t\t\t\u0022Toggle: block all Blender \u2192 s\u0026box updates for the selected object(s).\u0022 );\n\n\t\t\tAddLockButton( syncBtnRow, \u0022Lock Out\u0022, \u0022lock_outline\u0022, BridgeLockFlags.Outbound,\n\t\t\t\t\u0022Toggle: stop pushing s\u0026box-side changes for the selected object(s) to Blender.\u0022 );\n\n\t\t\tAddLockButton( syncBtnRow, \u0022Lock Mat\u0022, \u0022palette\u0022, BridgeLockFlags.Materials,\n\t\t\t\t\u0022Toggle: allow geometry/transform updates from Blender, but never overwrite materials. Use for objects with custom s\u0026box vmats (water shaders, etc).\u0022 );\n\n\t\t\troot.Add( syncBox );\n\t\t\troot.Add( syncBtnRow );\n\t\t\troot.AddSeparator();\n\n\t\t\t// \u2500\u2500 Materials Section \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\t\t\tvar matHeader = Layout.Row();\n\t\t\tvar matTitle = new Label( \u0022Generated Materials\u0022 );\n\t\t\tmatTitle.SetStyles( \u0022font-weight: bold; font-size: 13px;\u0022 );\n\t\t\tmatHeader.Add( matTitle );\n\t\t\tmatHeader.AddStretchCell();\n\n\t\t\tvar openFolderBtn = new Button( \u0022\u0022, \u0022folder_open\u0022 );\n\t\t\topenFolderBtn.ToolTip = \u0022Open materials folder\u0022;\n\t\t\topenFolderBtn.FixedWidth = 26;\n\t\t\topenFolderBtn.FixedHeight = 26;\n\t\t\topenFolderBtn.Clicked \u002B= OpenMaterialsFolder;\n\t\t\tmatHeader.Add( openFolderBtn );\n\n\t\t\tvar refreshBtn = new Button( \u0022\u0022, \u0022refresh\u0022 );\n\t\t\trefreshBtn.ToolTip = \u0022Refresh list\u0022;\n\t\t\trefreshBtn.FixedWidth = 26;\n\t\t\trefreshBtn.FixedHeight = 26;\n\t\t\trefreshBtn.Clicked \u002B= RefreshMaterialsList;\n\t\t\tmatHeader.Add( refreshBtn );\n\t\t\troot.Add( matHeader );\n\n\t\t\tvar matScroll = new ScrollArea( null );\n\t\t\tmatScroll.MaximumHeight = 150;\n\t\t\t_materialsCanvas = new Widget();\n\t\t\t_materialsCanvas.Layout = Layout.Column();\n\t\t\tmatScroll.Canvas = _materialsCanvas;\n\t\t\troot.Add( matScroll );\n\n\t\t\tRefreshMaterialsList();\n\t\t\troot.AddSeparator();\n\n\t\t\t// \u2500\u2500 Log Header \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\t\t\tvar logHeader = Layout.Row();\n\t\t\tvar logTitle = new Label( \u0022Activity Log\u0022 );\n\t\t\tlogTitle.SetStyles( \u0022font-weight: bold; font-size: 13px;\u0022 );\n\t\t\tlogHeader.Add( logTitle );\n\t\t\tlogHeader.AddStretchCell();\n\n\t\t\tvar collapseBtn = new Button( \u0022\u0022, \u0022unfold_less\u0022 );\n\t\t\tcollapseBtn.ToolTip = \u0022Hide / show log\u0022;\n\t\t\tcollapseBtn.FixedWidth = 26;\n\t\t\tcollapseBtn.FixedHeight = 26;\n\t\t\tcollapseBtn.Clicked \u002B= () =\u003E\n\t\t\t{\n\t\t\t\t_logCollapsed = !_logCollapsed;\n\t\t\t\tif ( _logScroll == null ) return;\n\t\t\t\tif ( _logCollapsed )\n\t\t\t\t{\n\t\t\t\t\t_logScroll.MinimumHeight = 0;\n\t\t\t\t\t_logScroll.MaximumHeight = 0;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t_logScroll.MinimumHeight = 250;\n\t\t\t\t\t_logScroll.MaximumHeight = int.MaxValue;\n\t\t\t\t}\n\t\t\t};\n\t\t\tlogHeader.Add( collapseBtn );\n\n\t\t\tvar clearBtn = new Button( \u0022\u0022, \u0022delete_sweep\u0022 );\n\t\t\tclearBtn.ToolTip = \u0022Clear Log\u0022;\n\t\t\tclearBtn.FixedWidth = 26;\n\t\t\tclearBtn.FixedHeight = 26;\n\t\t\tclearBtn.Clicked \u002B= () =\u003E { _logEntries.Clear(); _logCanvas.DestroyChildren(); };\n\t\t\tlogHeader.Add( clearBtn );\n\t\t\troot.Add( logHeader );\n\n\t\t\t// \u2500\u2500 Log Area \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\t\t\t_logScroll = new ScrollArea( null );\n\t\t\t_logScroll.MinimumHeight = 250;\n\t\t\t_logCanvas = new Widget();\n\t\t\t_logCanvas.Layout = Layout.Column();\n\t\t\t_logScroll.Canvas = _logCanvas;\n\n\t\t\tforeach ( var entry in _logEntries )\n\t\t\t\tAddLogLabel( entry );\n\n\t\t\troot.Add( _logScroll, 1 );\n\t\t\troot.AddSeparator();\n\n\t\t\t// \u2500\u2500 Footer: settings \u002B setup links \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\t\t\tvar footerRow = Layout.Row();\n\t\t\tfooterRow.Spacing = 8;\n\n\t\t\t_autoStartToggle = new ToggleSwitch( \u0022Auto-start on editor load\u0022 );\n\t\t\t_autoStartToggle.Value = BlenderBridgeServer.AutoStart;\n\t\t\t_autoStartToggle.MouseClick \u002B= () =\u003E\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.AutoStart = _autoStartToggle.Value;\n\t\t\t};\n\t\t\tfooterRow.Add( _autoStartToggle );\n\t\t\tfooterRow.AddStretchCell();\n\n\t\t\tvar addonUrl = \u0022https://github.com/SanicTehHedgehog/blender-sbox-bridge/releases\u0022;\n\t\t\tvar addonLink = new Button( \u0022Get Blender Addon\u0022, \u0022open_in_new\u0022 );\n\t\t\taddonLink.ToolTip = \u0022Open the Blender addon download page (companion v2.0\u002B required to connect).\u0022;\n\t\t\taddonLink.Clicked \u002B= () =\u003E\n\t\t\t{\n\t\t\t\tSystem.Diagnostics.Process.Start( new System.Diagnostics.ProcessStartInfo( addonUrl ) { UseShellExecute = true } );\n\t\t\t};\n\t\t\tfooterRow.Add( addonLink );\n\n\t\t\troot.Add( footerRow );\n\n\t\t\tLayout = root;\n\t\t}\n\n\t\tprivate void AddLogLabel( string text )\n\t\t{\n\t\t\tvar lbl = new Label( text );\n\t\t\tlbl.WordWrap = true;\n\n\t\t\tstring color = \u0022#e5e7eb\u0022;\n\t\t\tstring weight = \u0022normal\u0022;\n\n\t\t\tif ( text.Contains( \u0022[ERROR]\u0022 ) )\n\t\t\t{\n\t\t\t\tcolor = \u0022#f87171\u0022;\n\t\t\t\tweight = \u0022bold\u0022;\n\t\t\t}\n\t\t\telse if ( text.Contains( \u0022Created\u0022 ) || text.Contains( \u0022Sync\u0022 ) || text.Contains( \u0022Started\u0022 ) || text.Contains( \u0022Restored\u0022 ) )\n\t\t\t{\n\t\t\t\tcolor = \u0022#4ade80\u0022;\n\t\t\t}\n\t\t\telse if ( text.Contains( \u0022Deleted\u0022 ) || text.Contains( \u0022Stopped\u0022 ) )\n\t\t\t{\n\t\t\t\tcolor = \u0022#9ca3af\u0022;\n\t\t\t}\n\t\t\telse if ( text.Contains( \u0022mesh\u0022 ) || text.Contains( \u0022Model\u0022 ) || text.Contains( \u0022Chunked\u0022 ) )\n\t\t\t{\n\t\t\t\tcolor = \u0022#60a5fa\u0022;\n\t\t\t}\n\t\t\telse if ( text.Contains( \u0022light\u0022 ) || text.Contains( \u0022Light\u0022 ) )\n\t\t\t{\n\t\t\t\tcolor = \u0022#fbbf24\u0022;\n\t\t\t}\n\n\t\t\tlbl.SetStyles( $\u0022font-family: monospace; font-size: 11px; padding: 2px; color: {color}; font-weight: {weight};\u0022 );\n\t\t\t_logCanvas.Layout.Add( lbl );\n\t\t}\n\n\t\tprivate string FindBridgeMaterialsDir()\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\t// Must resolve to the SAME project the dispatcher writes materials\n\t\t\t\t// into (Project.Current). Scanning Documents\\s\u0026box projects\\* here\n\t\t\t\t// binds the panel \u2014 and its delete buttons \u2014 to whichever other\n\t\t\t\t// project happens to sort first.\n\t\t\t\tvar assetsDir = BlenderBridgeDispatcher.GetProjectAssetsDir();\n\t\t\t\tif ( assetsDir == null ) return null;\n\n\t\t\t\tvar candidate = System.IO.Path.Combine( assetsDir, \u0022materials\u0022, \u0022blender_bridge\u0022 );\n\t\t\t\tif ( System.IO.Directory.Exists( candidate ) )\n\t\t\t\t\treturn candidate;\n\t\t\t}\n\t\t\tcatch { }\n\t\t\treturn null;\n\t\t}\n\n\t\tprivate void RefreshMaterialsList()\n\t\t{\n\t\t\tif ( _materialsCanvas == null ) return;\n\t\t\t_materialsCanvas.DestroyChildren();\n\t\t\tMaterialThumb.PruneCache();\n\n\t\t\tvar dir = FindBridgeMaterialsDir();\n\t\t\tif ( dir == null || !System.IO.Directory.Exists( dir ) )\n\t\t\t{\n\t\t\t\tvar lbl = new Label( \u0022No materials generated yet\u0022 );\n\t\t\t\tlbl.SetStyles( \u0022font-size: 11px; color: #888; padding: 4px;\u0022 );\n\t\t\t\t_materialsCanvas.Layout.Add( lbl );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar vmats = System.IO.Directory.GetFiles( dir, \u0022*.vmat\u0022 );\n\t\t\tif ( vmats.Length == 0 )\n\t\t\t{\n\t\t\t\tvar lbl = new Label( \u0022No materials generated yet\u0022 );\n\t\t\t\tlbl.SetStyles( \u0022font-size: 11px; color: #888; padding: 4px;\u0022 );\n\t\t\t\t_materialsCanvas.Layout.Add( lbl );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tforeach ( var vmat in vmats.OrderBy( f =\u003E f ) )\n\t\t\t{\n\t\t\t\tvar fileName = System.IO.Path.GetFileNameWithoutExtension( vmat );\n\t\t\t\tvar filePath = vmat;\n\n\t\t\t\tvar row = Layout.Row();\n\t\t\t\trow.Spacing = 4;\n\n\t\t\t\trow.Add( new MaterialThumb( dir, fileName ) );\n\n\t\t\t\tvar nameLbl = new Label( fileName );\n\t\t\t\tnameLbl.SetStyles( \u0022font-family: monospace; font-size: 11px; color: #e5e7eb;\u0022 );\n\t\t\t\trow.Add( nameLbl );\n\n\t\t\t\trow.AddStretchCell();\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tvar info = new System.IO.FileInfo( filePath );\n\t\t\t\t\tvar sizeLbl = new Label( $\u0022{info.Length / 1024f:F1}kb\u0022 );\n\t\t\t\t\tsizeLbl.SetStyles( \u0022font-size: 10px; color: #666; padding-right: 4px;\u0022 );\n\t\t\t\t\trow.Add( sizeLbl );\n\t\t\t\t}\n\t\t\t\tcatch { }\n\n\t\t\t\tvar deleteBtn = new Button( \u0022\u0022, \u0022delete\u0022 );\n\t\t\t\tdeleteBtn.ToolTip = $\u0022Delete {fileName}\u0022;\n\t\t\t\tdeleteBtn.FixedWidth = 22;\n\t\t\t\tdeleteBtn.FixedHeight = 22;\n\t\t\t\tdeleteBtn.Clicked \u002B= () =\u003E\n\t\t\t\t{\n\t\t\t\t\ttry\n\t\t\t\t\t{\n\t\t\t\t\t\tDeleteMaterialFiles( dir, fileName );\n\t\t\t\t\t}\n\t\t\t\t\tcatch { }\n\t\t\t\t\tRefreshMaterialsList();\n\t\t\t\t};\n\t\t\t\trow.Add( deleteBtn );\n\n\t\t\t\tvar container = new Widget();\n\t\t\t\tcontainer.Layout = row;\n\t\t\t\tcontainer.SetStyles( \u0022padding: 1px 0;\u0022 );\n\t\t\t\t_materialsCanvas.Layout.Add( container );\n\t\t\t}\n\n\t\t\t// Delete All button\n\t\t\tvar deleteAllRow = Layout.Row();\n\t\t\tdeleteAllRow.AddStretchCell();\n\t\t\tvar deleteAllBtn = new Button( \u0022Delete All\u0022, \u0022delete_sweep\u0022 );\n\t\t\tdeleteAllBtn.ToolTip = \u0022Delete all generated bridge materials\u0022;\n\t\t\tdeleteAllBtn.Clicked \u002B= () =\u003E\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tforeach ( var f in System.IO.Directory.GetFiles( dir ) )\n\t\t\t\t\t\tSystem.IO.File.Delete( f );\n\t\t\t\t}\n\t\t\t\tcatch { }\n\t\t\t\tRefreshMaterialsList();\n\t\t\t};\n\t\t\tdeleteAllRow.Add( deleteAllBtn );\n\n\t\t\tvar allContainer = new Widget();\n\t\t\tallContainer.Layout = deleteAllRow;\n\t\t\t_materialsCanvas.Layout.Add( allContainer );\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Delete exactly one generated material\u0027s files. A bare \u0022{name}*\u0022 glob\n\t\t/// takes prefix-collided neighbours with it \u2014 deleting \u0022metal\u0022 would also\n\t\t/// remove metal_rough.vmat and metal_001.vmat, and those prefixes are\n\t\t/// normal Blender naming (\u0022Metal\u0022 / \u0022Metal Rough\u0022 / \u0022Metal.001\u0022). So:\n\t\t/// the vmat by exact name, textures only via the generator\u0027s four known\n\t\t/// suffixes, and never a .vmat/.vmat_c that merely shares a texture\u0027s\n\t\t/// name (\u0022metal\u0022\u0027s rough map metal_rough.png vs material metal_rough).\n\t\t/// \u003C/summary\u003E\n\t\tprivate static void DeleteMaterialFiles( string dir, string name )\n\t\t{\n\t\t\tforeach ( var ext in new[] { \u0022.vmat\u0022, \u0022.vmat_c\u0022 } )\n\t\t\t{\n\t\t\t\tvar path = System.IO.Path.Combine( dir, name \u002B ext );\n\t\t\t\tif ( System.IO.File.Exists( path ) )\n\t\t\t\t\tSystem.IO.File.Delete( path );\n\t\t\t}\n\n\t\t\tforeach ( var suffix in new[] { \u0022color\u0022, \u0022rough\u0022, \u0022metal\u0022, \u0022normal\u0022 } )\n\t\t\t{\n\t\t\t\tforeach ( var f in System.IO.Directory.GetFiles( dir, $\u0022{name}_{suffix}.*\u0022 ) )\n\t\t\t\t{\n\t\t\t\t\tif ( f.EndsWith( \u0022.vmat\u0022, StringComparison.OrdinalIgnoreCase ) ||\n\t\t\t\t\t\t f.EndsWith( \u0022.vmat_c\u0022, StringComparison.OrdinalIgnoreCase ) )\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\tSystem.IO.File.Delete( f );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Square preview for a generated material row: the copied color\n\t\t/// texture if one exists next to the .vmat, else a flat chip in the\n\t\t/// vmat\u0027s tint color.\n\t\t/// \u003C/summary\u003E\n\t\tprivate class MaterialThumb : Widget\n\t\t{\n\t\t\t// Pixmap has no Dispose, so loading the full-resolution source per\n\t\t\t// row on every list refresh abandons the previous set to\n\t\t\t// finalization. Cache one Pixmap per texture path instead; write\n\t\t\t// time invalidates when Blender regenerates the texture. Only ever\n\t\t\t// touched from the UI thread.\n\t\t\tprivate static readonly Dictionary\u003Cstring, (DateTime WriteTime, Pixmap Pix)\u003E _thumbCache = new();\n\n\t\t\t/// \u003Csummary\u003EDrop cache entries whose texture file was deleted.\u003C/summary\u003E\n\t\t\tinternal static void PruneCache()\n\t\t\t{\n\t\t\t\tforeach ( var key in _thumbCache.Keys.Where( k =\u003E !System.IO.File.Exists( k ) ).ToList() )\n\t\t\t\t\t_thumbCache.Remove( key );\n\t\t\t}\n\n\t\t\tprivate readonly Pixmap _pix;\n\t\t\tprivate readonly Color _tint = Color.Transparent;\n\n\t\t\tpublic MaterialThumb( string dir, string matName )\n\t\t\t{\n\t\t\t\tFixedWidth = 26;\n\t\t\t\tFixedHeight = 26;\n\t\t\t\tToolTip = matName;\n\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tvar tex = System.IO.Directory\n\t\t\t\t\t\t.GetFiles( dir, matName \u002B \u0022_color.*\u0022 )\n\t\t\t\t\t\t.FirstOrDefault( f =\u003E !f.EndsWith( \u0022.meta\u0022 ) );\n\t\t\t\t\tif ( tex != null )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar writeTime = System.IO.File.GetLastWriteTimeUtc( tex );\n\t\t\t\t\t\tif ( _thumbCache.TryGetValue( tex, out var cached ) \u0026\u0026 cached.WriteTime == writeTime )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t_pix = cached.Pix;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t_pix = Pixmap.FromFile( tex );\n\t\t\t\t\t\t_thumbCache[tex] = (writeTime, _pix);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// No color texture \u2014 parse the tint so untextured\n\t\t\t\t\t// materials still get a meaningful color chip.\n\t\t\t\t\tvar text = System.IO.File.ReadAllText(\n\t\t\t\t\t\tSystem.IO.Path.Combine( dir, matName \u002B \u0022.vmat\u0022 ) );\n\t\t\t\t\tvar m = System.Text.RegularExpressions.Regex.Match(\n\t\t\t\t\t\ttext, \u0022g_vColorTint\\\\s\u002B\\\u0022\\\\[([0-9.]\u002B) ([0-9.]\u002B) ([0-9.]\u002B)\u0022 );\n\t\t\t\t\tif ( m.Success )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar inv = System.Globalization.CultureInfo.InvariantCulture;\n\t\t\t\t\t\t_tint = new Color(\n\t\t\t\t\t\t\tfloat.Parse( m.Groups[1].Value, inv ),\n\t\t\t\t\t\t\tfloat.Parse( m.Groups[2].Value, inv ),\n\t\t\t\t\t\t\tfloat.Parse( m.Groups[3].Value, inv ) );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch { }\n\t\t\t}\n\n\t\t\tprotected override void OnPaint()\n\t\t\t{\n\t\t\t\tvar r = LocalRect.Shrink( 1 );\n\t\t\t\tif ( _pix != null )\n\t\t\t\t{\n\t\t\t\t\tPaint.Draw( r, _pix );\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tPaint.ClearPen();\n\t\t\t\tPaint.SetBrush( _tint );\n\t\t\t\tPaint.DrawRect( r, 3 );\n\t\t\t}\n\t\t}\n\n\t\tprivate void OpenMaterialsFolder()\n\t\t{\n\t\t\tvar dir = FindBridgeMaterialsDir();\n\t\t\tif ( dir != null \u0026\u0026 System.IO.Directory.Exists( dir ) )\n\t\t\t\tSystem.Diagnostics.Process.Start( \u0022explorer\u0022, $\u0022\\\u0022{dir}\\\u0022\u0022 );\n\t\t}\n\n\t\tprivate void AddLockButton( Layout row, string label, string icon, BridgeLockFlags flag, string tooltip )\n\t\t{\n\t\t\tvar btn = new Button( label, icon );\n\t\t\tbtn.ToolTip = tooltip;\n\t\t\tbtn.Clicked \u002B= () =\u003E\n\t\t\t{\n\t\t\t\tvar session = SceneEditorSession.Active;\n\t\t\t\tif ( session == null ) return;\n\t\t\t\tint set = 0, cleared = 0;\n\t\t\t\tforeach ( var sel in session.Selection )\n\t\t\t\t{\n\t\t\t\t\tif ( sel is not GameObject go ) continue;\n\t\t\t\t\tvar next = BridgeLockPolicy.ToggleExplicit( go, flag );\n\t\t\t\t\tif ( next.HasFlag( flag ) ) set\u002B\u002B; else cleared\u002B\u002B;\n\t\t\t\t}\n\t\t\t\tif ( set \u003E 0 )     BlenderBridgeServer.LogInfo( $\u0022Set {flag} on {set} object(s)\u0022 );\n\t\t\t\tif ( cleared \u003E 0 ) BlenderBridgeServer.LogInfo( $\u0022Cleared {flag} on {cleared} object(s)\u0022 );\n\t\t\t\tif ( set == 0 \u0026\u0026 cleared == 0 ) BlenderBridgeServer.LogInfo( \u0022No objects selected\u0022 );\n\t\t\t\tRefreshLockButtonStates();\n\t\t\t};\n\t\t\trow.Add( btn );\n\t\t\t_lockButtons.Add( (btn, flag, label) );\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Update each lock button\u0027s label to reflect whether the flag is set on\n\t\t/// the current selection. Three states: all-on -\u003E \u0022Label [ON]\u0022,\n\t\t/// none-on -\u003E \u0022Label\u0022, mixed -\u003E \u0022Label [~]\u0022. Tooltip stays static.\n\t\t///\n\t\t/// Called on every click and from the main OnPaint above, so selection\n\t\t/// changes surface the right state without explicit event subscription.\n\t\t/// \u003C/summary\u003E\n\t\tprivate void RefreshLockButtonStates()\n\t\t{\n\t\t\tvar session = SceneEditorSession.Active;\n\t\t\tvar selected = session?.Selection?.OfType\u003CGameObject\u003E().ToList();\n\n\t\t\tforeach ( var (btn, flag, baseLabel) in _lockButtons )\n\t\t\t{\n\t\t\t\tif ( selected == null || selected.Count == 0 )\n\t\t\t\t{\n\t\t\t\t\tbtn.Text = baseLabel;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tint onCount = selected.Count( g =\u003E BridgeLockPolicy.GetFlags( g ).HasFlag( flag ) );\n\t\t\t\tif ( onCount == selected.Count )\n\t\t\t\t\tbtn.Text = baseLabel \u002B \u0022 [ON]\u0022;\n\t\t\t\telse if ( onCount == 0 )\n\t\t\t\t\tbtn.Text = baseLabel;\n\t\t\t\telse\n\t\t\t\t\tbtn.Text = baseLabel \u002B \u0022 [~]\u0022;\n\t\t\t}\n\t\t}\n\n\t\tprivate void ToggleBridge()\n\t\t{\n\t\t\tif ( BlenderBridgeServer.IsRunning )\n\t\t\t\tBlenderBridgeServer.StopServer();\n\t\t\telse\n\t\t\t\tBlenderBridgeServer.StartServer();\n\t\t}\n\t}\n}\n"},{"Ident":"kamishell.blender_bridge","Path":"Editor/BlenderBridge/BridgeSceneHelper.cs","FileName":"BridgeSceneHelper.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":337656,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Editor;\nusing Sandbox;\n\nnamespace BlenderBridge;\n\n/// \u003Csummary\u003E\n/// Standalone scene helpers for the Blender Bridge \u2014 no MCP dependencies.\n/// \u003C/summary\u003E\ninternal static class BridgeSceneHelper\n{\n\t/// \u003Csummary\u003E\n\t/// Returns the best available scene:\n\t/// 1. Active SceneEditorSession.Scene (editor)\n\t/// 2. Any available editor session\n\t/// 3. Game.ActiveScene (play mode)\n\t/// \u003C/summary\u003E\n\tinternal static Scene ResolveScene()\n\t{\n\t\ttry\n\t\t{\n\t\t\tvar active = SceneEditorSession.Active;\n\t\t\tif ( active?.Scene != null ) return active.Scene;\n\t\t\tforeach ( var s in SceneEditorSession.All )\n\t\t\t\tif ( s?.Scene != null ) return s.Scene;\n\t\t}\n\t\tcatch { }\n\n\t\tif ( Game.ActiveScene != null ) return Game.ActiveScene;\n\t\treturn null;\n\t}\n\n\t/// \u003Csummary\u003EWalk all GameObjects in the scene, including children.\u003C/summary\u003E\n\tinternal static IEnumerable\u003CGameObject\u003E WalkAll( Scene scene, bool includeDisabled = true )\n\t{\n\t\tforeach ( var root in scene.Children )\n\t\t\tforeach ( var go in WalkSubtree( root, includeDisabled ) )\n\t\t\t\tyield return go;\n\t}\n\n\tprivate static IEnumerable\u003CGameObject\u003E WalkSubtree( GameObject root, bool includeDisabled )\n\t{\n\t\tif ( !includeDisabled \u0026\u0026 !root.Enabled ) yield break;\n\t\tyield return root;\n\t\tforeach ( var child in root.Children )\n\t\t\tforeach ( var go in WalkSubtree( child, includeDisabled ) )\n\t\t\t\tyield return go;\n\t}\n}\n"},{"Ident":"kamishell.blender_bridge","Path":"Editor/BlenderBridge/BridgeLockPolicy.cs","FileName":"BridgeLockPolicy.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":337656,"IsPrivate":false,"Code":"using System;\nusing System.Linq;\nusing Editor;\nusing Sandbox;\n\nnamespace BlenderBridge\n{\n\t/// \u003Csummary\u003E\n\t/// Per-object sync rules for the Blender bridge.\n\t/// \u003C/summary\u003E\n\t[Flags]\n\tpublic enum BridgeLockFlags\n\t{\n\t\tNone      = 0,\n\t\t/// \u003Csummary\u003EBlock all Blender \u2192 s\u0026amp;box updates for this object.\u003C/summary\u003E\n\t\tInbound   = 1 \u003C\u003C 0,\n\t\t/// \u003Csummary\u003EBlock all s\u0026amp;box \u2192 Blender pushes for this object.\u003C/summary\u003E\n\t\tOutbound  = 1 \u003C\u003C 1,\n\t\t/// \u003Csummary\u003EAllow geometry/transform updates from Blender, but never overwrite materials.\u003C/summary\u003E\n\t\tMaterials = 1 \u003C\u003C 2,\n\t\t/// \u003Csummary\u003EAllow material/transform updates from Blender, but never overwrite mesh geometry.\u003C/summary\u003E\n\t\tGeometry  = 1 \u003C\u003C 3,\n\t\t/// \u003Csummary\u003EAllow geometry/material updates from Blender, but never overwrite position/rotation.\u003C/summary\u003E\n\t\tTransform = 1 \u003C\u003C 4,\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// Resolves and mutates per-GameObject lock policy. Single source of truth for\n\t/// \u0022is this object syncing from Blender / to Blender / for materials / etc.\u0022\n\t///\n\t/// Storage: one tag of the form \u003Cc\u003Ebridge_lock_\u0026lt;int\u0026gt;\u003C/c\u003E on the GameObject,\n\t/// plus implicit auto-locks:\n\t///   - \u003Csee cref=\u0022Sandbox.Terrain\u0022/\u003E components imply Inbound | Geometry | Materials.\n\t///   - The legacy \u003Cc\u003Ebridge_locked\u003C/c\u003E tag (pre-flags) is treated as Inbound.\n\t///\n\t/// NOTE on the prefix: s\u0026amp;box GameTags accept only [a-zA-Z0-9._-] (32 chars max).\n\t/// An earlier iteration used a colon (\u0022bridge_lock:\u0022) which s\u0026amp;box silently\n\t/// rejected as invalid, leaving the lock state with nowhere to persist. The\n\t/// underscore form is what actually round-trips through the tag system.\n\t/// \u003C/summary\u003E\n\tinternal static class BridgeLockPolicy\n\t{\n\t\t/// \u003Csummary\u003EPre-flags lock tag, kept for backward compatibility.\u003C/summary\u003E\n\t\tinternal const string LegacyLockTag = \u0022bridge_locked\u0022;\n\t\tinternal const string FlagTagPrefix = \u0022bridge_lock_\u0022;\n\n\t\t/// \u003Csummary\u003ERead the effective lock flags for a GameObject \u2014 explicit \u002B implicit.\u003C/summary\u003E\n\t\tpublic static BridgeLockFlags GetFlags( GameObject go )\n\t\t{\n\t\t\tif ( go == null ) return BridgeLockFlags.None;\n\t\t\tvar flags = BridgeLockFlags.None;\n\n\t\t\t// Implicit: terrain components are read-only display from Blender.\n\t\t\tif ( go.Components.Get\u003CTerrain\u003E() != null )\n\t\t\t\tflags |= BridgeLockFlags.Inbound | BridgeLockFlags.Geometry | BridgeLockFlags.Materials;\n\n\t\t\t// Legacy tag = full inbound lock.\n\t\t\tif ( go.Tags.Has( LegacyLockTag ) )\n\t\t\t\tflags |= BridgeLockFlags.Inbound;\n\n\t\t\t// Explicit flag tag.\n\t\t\tforeach ( var tag in go.Tags.TryGetAll() )\n\t\t\t{\n\t\t\t\tif ( !tag.StartsWith( FlagTagPrefix, StringComparison.Ordinal ) ) continue;\n\t\t\t\tif ( int.TryParse( tag.Substring( FlagTagPrefix.Length ), out var v ) )\n\t\t\t\t\tflags |= (BridgeLockFlags)v;\n\t\t\t}\n\n\t\t\treturn flags;\n\t\t}\n\n\t\t/// \u003Csummary\u003EReplace the explicit flag tag on this GameObject. Implicit flags (Terrain) are unaffected.\u003C/summary\u003E\n\t\tpublic static void SetExplicitFlags( GameObject go, BridgeLockFlags flags )\n\t\t{\n\t\t\tif ( go == null ) return;\n\n\t\t\t// Remove any prior explicit flag tag(s).\n\t\t\tforeach ( var tag in go.Tags.TryGetAll().ToList() )\n\t\t\t{\n\t\t\t\tif ( tag.StartsWith( FlagTagPrefix, StringComparison.Ordinal ) )\n\t\t\t\t\tgo.Tags.Remove( tag );\n\t\t\t}\n\n\t\t\tif ( flags != BridgeLockFlags.None )\n\t\t\t\tgo.Tags.Add( FlagTagPrefix \u002B ((int)flags).ToString() );\n\t\t}\n\n\t\t/// \u003Csummary\u003ERead the explicit (user-set) flags only \u2014 excludes Terrain auto-lock and legacy tag.\u003C/summary\u003E\n\t\tpublic static BridgeLockFlags GetExplicitFlags( GameObject go )\n\t\t{\n\t\t\tif ( go == null ) return BridgeLockFlags.None;\n\t\t\tvar flags = BridgeLockFlags.None;\n\t\t\tforeach ( var tag in go.Tags.TryGetAll() )\n\t\t\t{\n\t\t\t\tif ( !tag.StartsWith( FlagTagPrefix, StringComparison.Ordinal ) ) continue;\n\t\t\t\tif ( int.TryParse( tag.Substring( FlagTagPrefix.Length ), out var v ) )\n\t\t\t\t\tflags |= (BridgeLockFlags)v;\n\t\t\t}\n\t\t\treturn flags;\n\t\t}\n\n\t\t/// \u003Csummary\u003EToggle a single flag on the explicit tag. Returns the new effective flag-set.\u003C/summary\u003E\n\t\tpublic static BridgeLockFlags ToggleExplicit( GameObject go, BridgeLockFlags flag )\n\t\t{\n\t\t\tvar current = GetExplicitFlags( go );\n\t\t\tvar next = current.HasFlag( flag ) ? (current \u0026 ~flag) : (current | flag);\n\t\t\tSetExplicitFlags( go, next );\n\t\t\treturn next;\n\t\t}\n\n\t\t// \u2500\u2500 Decision helpers \u2014 what each handler asks \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tpublic static bool AllowsInbound( GameObject go )\n\t\t\t=\u003E !GetFlags( go ).HasFlag( BridgeLockFlags.Inbound );\n\n\t\tpublic static bool AllowsOutbound( GameObject go )\n\t\t\t=\u003E !GetFlags( go ).HasFlag( BridgeLockFlags.Outbound );\n\n\t\tpublic static bool AllowsTransformChange( GameObject go )\n\t\t{\n\t\t\tvar f = GetFlags( go );\n\t\t\treturn !f.HasFlag( BridgeLockFlags.Inbound ) \u0026\u0026 !f.HasFlag( BridgeLockFlags.Transform );\n\t\t}\n\n\t\tpublic static bool AllowsGeometryChange( GameObject go )\n\t\t{\n\t\t\tvar f = GetFlags( go );\n\t\t\treturn !f.HasFlag( BridgeLockFlags.Inbound ) \u0026\u0026 !f.HasFlag( BridgeLockFlags.Geometry );\n\t\t}\n\n\t\tpublic static bool AllowsMaterialChange( GameObject go )\n\t\t{\n\t\t\tvar f = GetFlags( go );\n\t\t\treturn !f.HasFlag( BridgeLockFlags.Inbound ) \u0026\u0026 !f.HasFlag( BridgeLockFlags.Materials );\n\t\t}\n\t}\n}\n"},{"Ident":"kamishell.blender_bridge","Path":"Editor/BlenderBridge/BlenderBridgeDispatcher.cs","FileName":"BlenderBridgeDispatcher.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":337656,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.Json;\nusing System.Threading.Tasks;\nusing Editor;\nusing Editor.MeshEditor;\nusing HalfEdgeMesh;\nusing Sandbox;\n\nnamespace BlenderBridge\n{\n\t/// \u003Csummary\u003E\n\t/// Handles incoming bridge messages from Blender v2 and applies them to the s\u0026amp;box scene.\n\t/// Sequence-based echo prevention, idempotent creates, light support, chunked mesh, hierarchy grouping.\n\t/// \u003C/summary\u003E\n\tinternal static class BlenderBridgeDispatcher\n\t{\n\t\t// \u2500\u2500 Sequence state (echo prevention) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t/// \u003Csummary\u003EHighest Blender seq we have processed.\u003C/summary\u003E\n\t\tprivate static int _lastBlenderSeqProcessed = 0;\n\n\t\t/// \u003Csummary\u003EbridgeId -\u003E Blender seq that caused the last write. Used to suppress echo in PollForChanges.\u003C/summary\u003E\n\t\tprivate static Dictionary\u003Cstring, int\u003E _lastWriteSeq = new();\n\n\t\t// \u2500\u2500 Object caches \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t/// \u003Csummary\u003EO(1) lookup cache: bridgeId -\u003E GameObject. Rebuilt on cache miss via tree walk.\u003C/summary\u003E\n\t\tprivate static Dictionary\u003Cstring, GameObject\u003E _bridgeObjectCache = new();\n\n\t\t/// \u003Csummary\u003EIdempotency keys: key -\u003E bridgeId. Prevents duplicate creation on network retry.\u003C/summary\u003E\n\t\tprivate static Dictionary\u003Cstring, string\u003E _idempotencyKeys = new();\n\n\t\t/// \u003Csummary\u003ELast-known transforms for change detection.\u003C/summary\u003E\n\t\tprivate static Dictionary\u003Cstring, (Vector3 pos, Rotation rot)\u003E _lastKnown = new();\n\n\t\t/// \u003Csummary\u003ELast-known mesh hash for geometry change detection.\u003C/summary\u003E\n\t\tprivate static Dictionary\u003Cstring, int\u003E _lastMeshHash = new();\n\n\t\t/// \u003Csummary\u003ELast-known light property hash for change detection.\u003C/summary\u003E\n\t\tprivate static Dictionary\u003Cstring, int\u003E _lastLightHash = new();\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Last grid spacing we broadcast to Blender (in source units). Used to suppress\n\t\t/// the echo when Blender just pushed a grid_changed that we mirrored into\n\t\t/// Gizmo.Settings.GridSpacing \u2014 the poll loop would otherwise re-broadcast it.\n\t\t/// \u003C/summary\u003E\n\t\tprivate static float _lastBroadcastGridSpacing = -1f;\n\n\t\t// \u2500\u2500 Chunked mesh accumulator \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static Dictionary\u003Cstring, MeshAccumulator\u003E _pendingChunks = new();\n\n\t\tprivate struct MeshAccumulator\n\t\t{\n\t\t\tpublic List\u003Cfloat\u003E Vertices;\n\t\t\tpublic int TotalVertices;\n\t\t\tpublic int ChunksReceived;\n\t\t\tpublic int ChunkCount;\n\t\t\tpublic DateTime StartTime;\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Bridge IDs we\u0027ve told Blender to delete. If one reappears in a scan\n\t\t/// (Ctrl\u002BZ restores the GameObject with its tag intact), it must be\n\t\t/// re-announced as a creation \u2014 silently re-tracking it would leave the\n\t\t/// engine streaming updates for an id Blender no longer maps.\n\t\t/// \u003C/summary\u003E\n\t\tprivate static HashSet\u003Cstring\u003E _recentlyDeleted = new();\n\n\t\t// \u2500\u2500 Scan amortization \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate const int MeshHashBudget = 12;\n\t\tprivate static int _scanTick;\n\n\t\t// \u2500\u2500 Play mode \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static bool _wasPlaying = false;\n\n\t\t/// \u003Csummary\u003EReset all state. Called on server start and hot reload.\u003C/summary\u003E\n\t\tinternal static void ResetState()\n\t\t{\n\t\t\t_lastBlenderSeqProcessed = 0;\n\t\t\t_lastWriteSeq.Clear();\n\t\t\t_bridgeObjectCache.Clear();\n\t\t\t_idempotencyKeys.Clear();\n\t\t\t_lastKnown.Clear();\n\t\t\t_lastMeshHash.Clear();\n\t\t\t_lastLightHash.Clear();\n\t\t\t_pendingChunks.Clear();\n\t\t\t_recentlyDeleted.Clear();\n\t\t\t_wasPlaying = false;\n\t\t\t_lastBroadcastGridSpacing = -1f;\n\t\t\tBridgePersistence.ClearPendingSaves();\n\t\t}\n\n\t\t// \u2500\u2500 Dispatch \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t/// \u003Csummary\u003EHandle an incoming message. Returns a JSON response string. Must be called on main thread.\u003C/summary\u003E\n\t\tinternal static string Dispatch( JsonElement root )\n\t\t{\n\t\t\tvar type = root.TryGetProperty( \u0022type\u0022, out var t ) ? t.GetString() : null;\n\n\t\t\t// Extract and update sequence tracking\n\t\t\tif ( root.TryGetProperty( \u0022seq\u0022, out var seqEl ) \u0026\u0026 seqEl.ValueKind == JsonValueKind.Number )\n\t\t\t{\n\t\t\t\tvar seq = seqEl.GetInt32();\n\t\t\t\tif ( seq \u003E _lastBlenderSeqProcessed )\n\t\t\t\t\t_lastBlenderSeqProcessed = seq;\n\t\t\t}\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\treturn type switch\n\t\t\t\t{\n\t\t\t\t\t\u0022create\u0022 =\u003E HandleCreate( root ),\n\t\t\t\t\t\u0022update_transform\u0022 =\u003E HandleUpdateTransform( root ),\n\t\t\t\t\t\u0022update_mesh\u0022 =\u003E HandleUpdateMesh( root ),\n\t\t\t\t\t\u0022delete\u0022 =\u003E HandleDelete( root ),\n\t\t\t\t\t\u0022set_visibility\u0022 =\u003E HandleSetVisibility( root ),\n\t\t\t\t\t\u0022sync\u0022 =\u003E HandleSync( root ),\n\t\t\t\t\t\u0022update_scene_transform\u0022 =\u003E HandleUpdateSceneTransform( root ),\n\t\t\t\t\t\u0022create_light\u0022 =\u003E HandleCreateLight( root ),\n\t\t\t\t\t\u0022update_light\u0022 =\u003E HandleUpdateLight( root ),\n\t\t\t\t\t\u0022mesh_begin\u0022 =\u003E HandleMeshBegin( root ),\n\t\t\t\t\t\u0022mesh_chunk\u0022 =\u003E HandleMeshChunk( root ),\n\t\t\t\t\t\u0022mesh_end\u0022 =\u003E HandleMeshEnd( root ),\n\t\t\t\t\t\u0022get_project_info\u0022 =\u003E HandleGetProjectInfo( root ),\n\t\t\t\t\t\u0022grid_changed\u0022 =\u003E HandleGridChanged( root ),\n\t\t\t\t\t_ =\u003E \u0022{\\\u0022ok\\\u0022:true}\u0022\n\t\t\t\t};\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogError( $\u0022Dispatch error ({type}): {ex.Message}\u0022 );\n\t\t\t\t// Serialize \u2014 ex.Message often contains Windows paths whose\n\t\t\t\t// backslashes would otherwise produce invalid JSON, making\n\t\t\t\t// exactly these errors invisible to the addon\u0027s error surface.\n\t\t\t\treturn JsonSerializer.Serialize( new { error = ex.Message }, BlenderBridgeServer.JsonOptions );\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 create \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static string HandleCreate( JsonElement root )\n\t\t{\n\t\t\tvar name = GetString( root, \u0022name\u0022, \u0022Blender Object\u0022 );\n\t\t\tvar blenderSeq = GetInt( root, \u0022seq\u0022, 0 );\n\n\t\t\t// Idempotency check: if this key was already used, return existing bridgeId\n\t\t\tvar idemKey = GetString( root, \u0022idempotencyKey\u0022 );\n\t\t\tif ( !string.IsNullOrEmpty( idemKey ) \u0026\u0026 _idempotencyKeys.TryGetValue( idemKey, out var existingId ) )\n\t\t\t{\n\t\t\t\t// Verify the object still exists\n\t\t\t\tvar existingGo = FindByBridgeTag( existingId );\n\t\t\t\tif ( existingGo != null )\n\t\t\t\t{\n\t\t\t\t\tif ( BridgeLockPolicy.AllowsInbound( existingGo ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( BridgeLockPolicy.AllowsTransformChange( existingGo ) )\n\t\t\t\t\t\t\tApplyTransform( existingGo, root );\n\t\t\t\t\t\tif ( BridgeLockPolicy.AllowsGeometryChange( existingGo ) \u0026\u0026 root.TryGetProperty( \u0022meshData\u0022, out var md ) )\n\t\t\t\t\t\t\tApplyMeshData( existingGo, md );\n\t\t\t\t\t\t// Only arm the echo guard when something was actually\n\t\t\t\t\t\t// applied \u2014 a lock-rejected retry has no echo to suppress.\n\t\t\t\t\t\t_lastWriteSeq[existingId] = blenderSeq;\n\t\t\t\t\t\t_lastKnown[existingId] = (existingGo.WorldPosition, existingGo.WorldRotation);\n\t\t\t\t\t\tStampAppliedMeshHash( existingId, existingGo );\n\t\t\t\t\t}\n\t\t\t\t\treturn JsonSerializer.Serialize( new { bridgeId = existingId }, BlenderBridgeServer.JsonOptions );\n\t\t\t\t}\n\t\t\t\t_idempotencyKeys.Remove( idemKey );\n\t\t\t}\n\n\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\tif ( scene == null ) return \u0022{\\\u0022error\\\u0022:\\\u0022no scene\\\u0022}\u0022;\n\n\t\t\t// Anti-duplication guard: if a GameObject in this scene already\n\t\t\t// shares this name AND is locked from inbound Blender updates\n\t\t\t// (e.g. a Terrain that was sent as a one-way proxy), assume Blender\n\t\t\t// lost the bridge_id on round-trip and is trying to re-create it.\n\t\t\t// Quietly map the new request onto the existing object instead of\n\t\t\t// spawning a duplicate.\n\t\t\tvar nameClash = BridgeSceneHelper\n\t\t\t\t.WalkAll( scene )\n\t\t\t\t.FirstOrDefault( g =\u003E g.Name == name \u0026\u0026 !BridgeLockPolicy.AllowsInbound( g ) );\n\t\t\tif ( nameClash != null )\n\t\t\t{\n\t\t\t\tvar existingTag = nameClash.Tags.TryGetAll().FirstOrDefault( IsBridgeIdentityTag );\n\t\t\t\tvar resolvedId = existingTag != null ? existingTag.Substring( 7 ) : \u0022locked\u0022;\n\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Suppressed duplicate create for locked \u0027{name}\u0027 (re-binding to {resolvedId})\u0022 );\n\t\t\t\t// Locked object, nothing applied \u2014 no echo to suppress, so the\n\t\t\t\t// guard stays unarmed.\n\t\t\t\tif ( !string.IsNullOrEmpty( idemKey ) )\n\t\t\t\t\t_idempotencyKeys[idemKey] = resolvedId;\n\t\t\t\treturn JsonSerializer.Serialize( new { bridgeId = resolvedId, locked = true }, BlenderBridgeServer.JsonOptions );\n\t\t\t}\n\n\t\t\t// Honor a Blender-minted ID. The .blend is the durable side of the\n\t\t\t// bridge \u2014 engine-minted IDs died with every unsaved engine scene,\n\t\t\t// reissuing identity on each reconnect and orphaning mesh caches.\n\t\t\t// If the id already exists here, treat the create as an idempotent\n\t\t\t// upsert so re-sends after a session mismatch converge onto the\n\t\t\t// existing object instead of duplicating it.\n\t\t\tvar requestedId = GetString( root, \u0022bridgeId\u0022 );\n\t\t\tif ( IsValidClientBridgeId( requestedId ) )\n\t\t\t{\n\t\t\t\tvar existingByReq = FindByBridgeTag( requestedId );\n\t\t\t\tif ( existingByReq != null )\n\t\t\t\t{\n\t\t\t\t\tif ( BridgeLockPolicy.AllowsInbound( existingByReq ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( BridgeLockPolicy.AllowsTransformChange( existingByReq ) )\n\t\t\t\t\t\t\tApplyTransform( existingByReq, root );\n\t\t\t\t\t\tif ( BridgeLockPolicy.AllowsGeometryChange( existingByReq ) \u0026\u0026 root.TryGetProperty( \u0022meshData\u0022, out var upsertMd ) )\n\t\t\t\t\t\t\tApplyMeshData( existingByReq, upsertMd );\n\t\t\t\t\t\t_lastWriteSeq[requestedId] = blenderSeq;\n\t\t\t\t\t\t_lastKnown[requestedId] = (existingByReq.WorldPosition, existingByReq.WorldRotation);\n\t\t\t\t\t\tStampAppliedMeshHash( requestedId, existingByReq );\n\t\t\t\t\t\tBridgePersistence.SaveAfterChange( scene, requestedId, existingByReq );\n\t\t\t\t\t}\n\t\t\t\t\tif ( !string.IsNullOrEmpty( idemKey ) )\n\t\t\t\t\t\t_idempotencyKeys[idemKey] = requestedId;\n\t\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Upserted \u0027{name}\u0027 onto existing {requestedId}\u0022 );\n\t\t\t\t\treturn JsonSerializer.Serialize( new { bridgeId = requestedId }, BlenderBridgeServer.JsonOptions );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar bridgeId = IsValidClientBridgeId( requestedId )\n\t\t\t\t? requestedId\n\t\t\t\t: \u0022b_\u0022 \u002B Guid.NewGuid().ToString( \u0022N\u0022 ).Substring( 0, 8 );\n\n\t\t\t// Resolve hierarchy: Blender Bridge \u003E [collection path] \u003E object\n\t\t\tvar parent = GetOrCreateBridgeGroup( scene );\n\t\t\tif ( root.TryGetProperty( \u0022hierarchy\u0022, out var hierEl ) \u0026\u0026 hierEl.ValueKind == JsonValueKind.Array )\n\t\t\t{\n\t\t\t\tforeach ( var h in hierEl.EnumerateArray() )\n\t\t\t\t{\n\t\t\t\t\tvar hName = h.GetString();\n\t\t\t\t\tif ( !string.IsNullOrEmpty( hName ) )\n\t\t\t\t\t\tparent = GetOrCreateChild( parent, hName );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar go = scene.CreateObject();\n\t\t\tgo.Name = name;\n\t\t\tgo.Parent = parent;\n\t\t\tApplyTransform( go, root );\n\n\t\t\tif ( root.TryGetProperty( \u0022meshData\u0022, out var meshData ) )\n\t\t\t\tApplyMeshData( go, meshData );\n\n\t\t\tgo.Tags.Add( $\u0022bridge_{bridgeId}\u0022 );\n\t\t\t// A re-created id must not linger in the deleted set \u2014 the scan\n\t\t\t// would re-announce an object Blender just sent us.\n\t\t\t_recentlyDeleted.Remove( bridgeId );\n\t\t\t_bridgeObjectCache[bridgeId] = go;\n\t\t\t_lastWriteSeq[bridgeId] = blenderSeq;\n\t\t\t_lastKnown[bridgeId] = (go.WorldPosition, go.WorldRotation);\n\t\t\tStampAppliedMeshHash( bridgeId, go );\n\t\t\tif ( !string.IsNullOrEmpty( idemKey ) )\n\t\t\t\t_idempotencyKeys[idemKey] = bridgeId;\n\n\t\t\tBlenderBridgeServer.LogInfo( $\u0022Created \u0027{name}\u0027 as {bridgeId}\u0022 );\n\t\t\tBridgePersistence.SaveAfterChange( scene, bridgeId, go );\n\t\t\treturn JsonSerializer.Serialize( new { bridgeId }, BlenderBridgeServer.JsonOptions );\n\t\t}\n\n\t\t// \u2500\u2500 update_transform \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static string HandleUpdateTransform( JsonElement root )\n\t\t{\n\t\t\tvar bridgeId = GetString( root, \u0022bridgeId\u0022 );\n\t\t\tif ( string.IsNullOrEmpty( bridgeId ) ) return \u0022{\\\u0022error\\\u0022:\\\u0022missing bridgeId\\\u0022}\u0022;\n\t\t\tvar blenderSeq = GetInt( root, \u0022seq\u0022, 0 );\n\n\t\t\tvar go = FindByBridgeTag( bridgeId );\n\t\t\tif ( go == null ) return \u0022{\\\u0022error\\\u0022:\\\u0022not found\\\u0022}\u0022;\n\n\t\t\t// Lock-rejected: nothing was applied, so there is no echo to\n\t\t\t// suppress \u2014 arming the guard here would swallow the next real\n\t\t\t// s\u0026box-side edit instead.\n\t\t\tif ( !BridgeLockPolicy.AllowsTransformChange( go ) )\n\t\t\t\treturn \u0022{\\\u0022ok\\\u0022:true,\\\u0022locked\\\u0022:true}\u0022;\n\n\t\t\tApplyTransform( go, root );\n\t\t\t_lastWriteSeq[bridgeId] = blenderSeq;\n\t\t\t_lastKnown[bridgeId] = (go.WorldPosition, go.WorldRotation);\n\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\t// \u2500\u2500 update_mesh \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t// All lock decisions go through BridgeLockPolicy. The legacy bridge_locked\n\t\t// tag is still recognized there for backward compatibility, and Terrain\n\t\t// components are auto-locked (Inbound | Geometry | Materials) so the\n\t\t// one-way proxy mesh never clobbers the heightmap-driven terrain.\n\t\tinternal const string LockTag = BridgeLockPolicy.LegacyLockTag;\n\n\t\tinternal static bool IsLockedFromBlender( GameObject go )\n\t\t\t=\u003E !BridgeLockPolicy.AllowsInbound( go );\n\n\t\tprivate static string HandleUpdateMesh( JsonElement root )\n\t\t{\n\t\t\tvar bridgeId = GetString( root, \u0022bridgeId\u0022 );\n\t\t\tif ( string.IsNullOrEmpty( bridgeId ) ) return \u0022{\\\u0022error\\\u0022:\\\u0022missing bridgeId\\\u0022}\u0022;\n\t\t\tvar blenderSeq = GetInt( root, \u0022seq\u0022, 0 );\n\n\t\t\tvar go = FindByBridgeTag( bridgeId );\n\t\t\tif ( go == null ) return \u0022{\\\u0022error\\\u0022:\\\u0022not found\\\u0022}\u0022;\n\n\t\t\t// Lock-rejected: nothing applied, no echo to suppress \u2014 do not arm\n\t\t\t// the guard (see HandleUpdateTransform).\n\t\t\tif ( !BridgeLockPolicy.AllowsInbound( go ) )\n\t\t\t\treturn \u0022{\\\u0022ok\\\u0022:true,\\\u0022locked\\\u0022:true}\u0022;\n\n\t\t\tif ( BridgeLockPolicy.AllowsTransformChange( go ) )\n\t\t\t\tApplyTransform( go, root );\n\n\t\t\tif ( BridgeLockPolicy.AllowsGeometryChange( go ) \u0026\u0026 root.TryGetProperty( \u0022meshData\u0022, out var meshData ) )\n\t\t\t\tApplyMeshData( go, meshData );\n\n\t\t\t_lastWriteSeq[bridgeId] = blenderSeq;\n\t\t\t_lastKnown[bridgeId] = (go.WorldPosition, go.WorldRotation);\n\t\t\tStampAppliedMeshHash( bridgeId, go );\n\n\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\tif ( scene != null )\n\t\t\t\tBridgePersistence.SaveAfterChange( scene, bridgeId, go );\n\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Record the hash of a mesh we JUST applied from a Blender write.\n\t\t/// Mandatory with amortized scanning: the round-robin check may not\n\t\t/// reach this object until many ticks after the echo guard was\n\t\t/// consumed, and without the stamp our own write would read as a\n\t\t/// user edit and get broadcast back to Blender.\n\t\t/// \u003C/summary\u003E\n\t\tprivate static void StampAppliedMeshHash( string bridgeId, GameObject go )\n\t\t{\n\t\t\tvar mesh = go?.Components.Get\u003CMeshComponent\u003E()?.Mesh;\n\t\t\tif ( mesh != null )\n\t\t\t\t_lastMeshHash[bridgeId] = ComputeMeshGeometryHash( mesh );\n\t\t}\n\n\t\t// \u2500\u2500 delete \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static string HandleDelete( JsonElement root )\n\t\t{\n\t\t\tvar bridgeId = GetString( root, \u0022bridgeId\u0022 );\n\t\t\tif ( string.IsNullOrEmpty( bridgeId ) ) return \u0022{\\\u0022error\\\u0022:\\\u0022missing bridgeId\\\u0022}\u0022;\n\n\t\t\tvar go = FindByBridgeTag( bridgeId );\n\t\t\tif ( go != null )\n\t\t\t{\n\t\t\t\tgo.Destroy();\n\t\t\t\t// If Ctrl\u002BZ later restores this GameObject, the scan must\n\t\t\t\t// re-announce it \u2014 Blender no longer maps this id.\n\t\t\t\t_recentlyDeleted.Add( bridgeId );\n\t\t\t}\n\n\t\t\t_bridgeObjectCache.Remove( bridgeId );\n\t\t\t_lastKnown.Remove( bridgeId );\n\t\t\t_lastWriteSeq.Remove( bridgeId );\n\t\t\t_lastMeshHash.Remove( bridgeId );\n\t\t\t_idempotencyKeys.Where( kv =\u003E kv.Value == bridgeId ).Select( kv =\u003E kv.Key ).ToList()\n\t\t\t\t.ForEach( k =\u003E _idempotencyKeys.Remove( k ) );\n\n\t\t\tBridgePersistence.RemoveFromCache( bridgeId );\n\t\t\tBlenderBridgeServer.LogInfo( $\u0022Deleted {bridgeId}\u0022 );\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\t// \u2500\u2500 set_visibility \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t/// \u003Csummary\u003EBlender hid/unhid an object \u2014 toggle Enabled instead of\n\t\t/// destroying, so the GameObject keeps its components and materials.\u003C/summary\u003E\n\t\tprivate static string HandleSetVisibility( JsonElement root )\n\t\t{\n\t\t\tvar bridgeId = GetString( root, \u0022bridgeId\u0022 );\n\t\t\tif ( string.IsNullOrEmpty( bridgeId ) ) return \u0022{\\\u0022error\\\u0022:\\\u0022missing bridgeId\\\u0022}\u0022;\n\n\t\t\tvar go = FindByBridgeTag( bridgeId );\n\t\t\tif ( go == null ) return JsonSerializer.Serialize( new { error = $\u0022\u0027{bridgeId}\u0027 not found\u0022 }, BlenderBridgeServer.JsonOptions );\n\n\t\t\tif ( !BridgeLockPolicy.AllowsInbound( go ) )\n\t\t\t\treturn \u0022{\\\u0022ok\\\u0022:true,\\\u0022locked\\\u0022:true}\u0022;\n\n\t\t\tvar visible = !root.TryGetProperty( \u0022visible\u0022, out var v ) || v.ValueKind != JsonValueKind.False;\n\t\t\tgo.Enabled = visible;\n\t\t\tBlenderBridgeServer.LogInfo( $\u0022{(visible ? \u0022Enabled\u0022 : \u0022Disabled\u0022)} {bridgeId}\u0022 );\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\t// \u2500\u2500 create_light \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static string HandleCreateLight( JsonElement root )\n\t\t{\n\t\t\tvar name = GetString( root, \u0022name\u0022, \u0022Blender Light\u0022 );\n\t\t\tvar lightType = GetString( root, \u0022lightType\u0022, \u0022point\u0022 );\n\t\t\tvar blenderSeq = GetInt( root, \u0022seq\u0022, 0 );\n\n\t\t\t// Idempotency\n\t\t\tvar idemKey = GetString( root, \u0022idempotencyKey\u0022 );\n\t\t\tif ( !string.IsNullOrEmpty( idemKey ) \u0026\u0026 _idempotencyKeys.TryGetValue( idemKey, out var existingId ) )\n\t\t\t{\n\t\t\t\tvar existingGo = FindByBridgeTag( existingId );\n\t\t\t\tif ( existingGo != null )\n\t\t\t\t{\n\t\t\t\t\t// Same lock policy as the mesh handlers \u2014 the idempotent\n\t\t\t\t\t// re-apply must not be a side door around \u0022Lock In\u0022.\n\t\t\t\t\tif ( BridgeLockPolicy.AllowsInbound( existingGo ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( BridgeLockPolicy.AllowsTransformChange( existingGo ) )\n\t\t\t\t\t\t\tApplyTransform( existingGo, root );\n\t\t\t\t\t\tApplyLightProperties( existingGo, root );\n\t\t\t\t\t\t_lastWriteSeq[existingId] = blenderSeq;\n\t\t\t\t\t\t_lastKnown[existingId] = (existingGo.WorldPosition, existingGo.WorldRotation);\n\t\t\t\t\t}\n\t\t\t\t\treturn JsonSerializer.Serialize( new { bridgeId = existingId }, BlenderBridgeServer.JsonOptions );\n\t\t\t\t}\n\t\t\t\t_idempotencyKeys.Remove( idemKey );\n\t\t\t}\n\n\t\t\t// Honor a Blender-minted ID; upsert if the id already exists here\n\t\t\t// (same rationale as HandleCreate).\n\t\t\tvar requestedId = GetString( root, \u0022bridgeId\u0022 );\n\t\t\tif ( IsValidClientBridgeId( requestedId ) )\n\t\t\t{\n\t\t\t\tvar existingByReq = FindByBridgeTag( requestedId );\n\t\t\t\tif ( existingByReq != null )\n\t\t\t\t{\n\t\t\t\t\tif ( BridgeLockPolicy.AllowsInbound( existingByReq ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( BridgeLockPolicy.AllowsTransformChange( existingByReq ) )\n\t\t\t\t\t\t\tApplyTransform( existingByReq, root );\n\t\t\t\t\t\tApplyLightProperties( existingByReq, root );\n\t\t\t\t\t\t_lastWriteSeq[requestedId] = blenderSeq;\n\t\t\t\t\t\t_lastKnown[requestedId] = (existingByReq.WorldPosition, existingByReq.WorldRotation);\n\t\t\t\t\t}\n\t\t\t\t\tif ( !string.IsNullOrEmpty( idemKey ) )\n\t\t\t\t\t\t_idempotencyKeys[idemKey] = requestedId;\n\t\t\t\t\treturn JsonSerializer.Serialize( new { bridgeId = requestedId }, BlenderBridgeServer.JsonOptions );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar bridgeId = IsValidClientBridgeId( requestedId )\n\t\t\t\t? requestedId\n\t\t\t\t: \u0022b_\u0022 \u002B Guid.NewGuid().ToString( \u0022N\u0022 ).Substring( 0, 8 );\n\n\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\tif ( scene == null ) return \u0022{\\\u0022error\\\u0022:\\\u0022no scene\\\u0022}\u0022;\n\n\t\t\tvar parent = GetOrCreateBridgeGroup( scene );\n\t\t\tvar go = scene.CreateObject();\n\t\t\tgo.Name = name;\n\t\t\tgo.Parent = parent;\n\t\t\tApplyTransform( go, root );\n\n\t\t\t// Create appropriate light component\n\t\t\tswitch ( lightType )\n\t\t\t{\n\t\t\t\tcase \u0022spot\u0022:\n\t\t\t\t\tgo.Components.Create\u003CSpotLight\u003E();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \u0022directional\u0022:\n\t\t\t\t\tgo.Components.Create\u003CDirectionalLight\u003E();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tgo.Components.Create\u003CPointLight\u003E();\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tApplyLightProperties( go, root );\n\n\t\t\tgo.Tags.Add( $\u0022bridge_{bridgeId}\u0022 );\n\t\t\t_recentlyDeleted.Remove( bridgeId );\n\t\t\t_bridgeObjectCache[bridgeId] = go;\n\t\t\t_lastWriteSeq[bridgeId] = blenderSeq;\n\t\t\t_lastKnown[bridgeId] = (go.WorldPosition, go.WorldRotation);\n\t\t\tif ( !string.IsNullOrEmpty( idemKey ) )\n\t\t\t\t_idempotencyKeys[idemKey] = bridgeId;\n\n\t\t\tBlenderBridgeServer.LogInfo( $\u0022Created light \u0027{name}\u0027 as {bridgeId} ({lightType})\u0022 );\n\t\t\treturn JsonSerializer.Serialize( new { bridgeId }, BlenderBridgeServer.JsonOptions );\n\t\t}\n\n\t\t// \u2500\u2500 update_light \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static string HandleUpdateLight( JsonElement root )\n\t\t{\n\t\t\tvar bridgeId = GetString( root, \u0022bridgeId\u0022 );\n\t\t\tif ( string.IsNullOrEmpty( bridgeId ) ) return \u0022{\\\u0022error\\\u0022:\\\u0022missing bridgeId\\\u0022}\u0022;\n\t\t\tvar blenderSeq = GetInt( root, \u0022seq\u0022, 0 );\n\n\t\t\tvar go = FindByBridgeTag( bridgeId );\n\t\t\tif ( go == null ) return \u0022{\\\u0022error\\\u0022:\\\u0022not found\\\u0022}\u0022;\n\n\t\t\t// Same lock policy as every other mutation handler \u2014 \u0022Lock In\u0022\n\t\t\t// must cover lights too. Nothing applied, so the echo guard\n\t\t\t// stays unarmed.\n\t\t\tif ( !BridgeLockPolicy.AllowsInbound( go ) )\n\t\t\t\treturn \u0022{\\\u0022ok\\\u0022:true,\\\u0022locked\\\u0022:true}\u0022;\n\n\t\t\tif ( BridgeLockPolicy.AllowsTransformChange( go ) )\n\t\t\t\tApplyTransform( go, root );\n\t\t\tApplyLightProperties( go, root );\n\t\t\t_lastWriteSeq[bridgeId] = blenderSeq;\n\t\t\t_lastKnown[bridgeId] = (go.WorldPosition, go.WorldRotation);\n\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\t// \u2500\u2500 Chunked mesh handlers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static string HandleMeshBegin( JsonElement root )\n\t\t{\n\t\t\tvar bridgeId = GetString( root, \u0022bridgeId\u0022 );\n\t\t\tif ( string.IsNullOrEmpty( bridgeId ) ) return \u0022{\\\u0022error\\\u0022:\\\u0022missing bridgeId\\\u0022}\u0022;\n\n\t\t\tvar totalVerts = GetInt( root, \u0022totalVertices\u0022, 0 );\n\t\t\tvar chunkCount = GetInt( root, \u0022chunkCount\u0022, 0 );\n\n\t\t\t_pendingChunks[bridgeId] = new MeshAccumulator\n\t\t\t{\n\t\t\t\tVertices = new List\u003Cfloat\u003E( totalVerts * 3 ),\n\t\t\t\tTotalVertices = totalVerts,\n\t\t\t\tChunksReceived = 0,\n\t\t\t\tChunkCount = chunkCount,\n\t\t\t\tStartTime = DateTime.UtcNow,\n\t\t\t};\n\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\tprivate static string HandleMeshChunk( JsonElement root )\n\t\t{\n\t\t\tvar bridgeId = GetString( root, \u0022bridgeId\u0022 );\n\t\t\tif ( string.IsNullOrEmpty( bridgeId ) ) return \u0022{\\\u0022error\\\u0022:\\\u0022missing bridgeId\\\u0022}\u0022;\n\n\t\t\tif ( !_pendingChunks.TryGetValue( bridgeId, out var accum ) )\n\t\t\t\treturn \u0022{\\\u0022error\\\u0022:\\\u0022no pending mesh_begin\\\u0022}\u0022;\n\n\t\t\tif ( root.TryGetProperty( \u0022vertices\u0022, out var vertsEl ) )\n\t\t\t{\n\t\t\t\tforeach ( var v in vertsEl.EnumerateArray() )\n\t\t\t\t\taccum.Vertices.Add( v.GetSingle() );\n\t\t\t}\n\n\t\t\taccum.ChunksReceived\u002B\u002B;\n\t\t\t_pendingChunks[bridgeId] = accum;\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\tprivate static string HandleMeshEnd( JsonElement root )\n\t\t{\n\t\t\tvar bridgeId = GetString( root, \u0022bridgeId\u0022 );\n\t\t\tif ( string.IsNullOrEmpty( bridgeId ) ) return \u0022{\\\u0022error\\\u0022:\\\u0022missing bridgeId\\\u0022}\u0022;\n\t\t\tvar blenderSeq = GetInt( root, \u0022seq\u0022, 0 );\n\n\t\t\tif ( !_pendingChunks.TryGetValue( bridgeId, out var accum ) )\n\t\t\t\treturn \u0022{\\\u0022error\\\u0022:\\\u0022no pending mesh_begin\\\u0022}\u0022;\n\n\t\t\t_pendingChunks.Remove( bridgeId );\n\n\t\t\t// Validate stream completeness before applying. A dropped chunk\n\t\t\t// shifts every later vertex \u2014 faces then resolve to the wrong\n\t\t\t// vertices and the scrambled mesh would be persisted to the mesh\n\t\t\t// cache while Blender, having stored the geometry hash at stream\n\t\t\t// start, considers it synced and never resends.\n\t\t\tvar receivedVerts = accum.Vertices.Count / 3;\n\t\t\tif ( (accum.ChunkCount \u003E 0 \u0026\u0026 accum.ChunksReceived != accum.ChunkCount)\n\t\t\t\t|| (accum.TotalVertices \u003E 0 \u0026\u0026 receivedVerts != accum.TotalVertices) )\n\t\t\t{\n\t\t\t\tvar detail = $\u0022incomplete mesh stream for {bridgeId}: \u0022\n\t\t\t\t\t\u002B $\u0022{accum.ChunksReceived}/{accum.ChunkCount} chunks, \u0022\n\t\t\t\t\t\u002B $\u0022{receivedVerts}/{accum.TotalVertices} vertices\u0022;\n\t\t\t\tBlenderBridgeServer.LogError( detail );\n\t\t\t\treturn JsonSerializer.Serialize( new { error = detail }, BlenderBridgeServer.JsonOptions );\n\t\t\t}\n\n\t\t\t// Build a complete meshData JsonElement from accumulated vertices \u002B face data from this message\n\t\t\tvar vertArray = accum.Vertices;\n\n\t\t\t// Parse faces from this message\n\t\t\tvar faces = new List\u003Cint\u003E();\n\t\t\tif ( root.TryGetProperty( \u0022faces\u0022, out var facesEl ) )\n\t\t\t\tforeach ( var f in facesEl.EnumerateArray() )\n\t\t\t\t\tfaces.Add( f.GetInt32() );\n\n\t\t\tint[] faceMaterials = null;\n\t\t\tif ( root.TryGetProperty( \u0022faceMaterials\u0022, out var fmEl ) )\n\t\t\t{\n\t\t\t\tvar fmList = new List\u003Cint\u003E();\n\t\t\t\tforeach ( var fm in fmEl.EnumerateArray() )\n\t\t\t\t\tfmList.Add( fm.GetInt32() );\n\t\t\t\tfaceMaterials = fmList.ToArray();\n\t\t\t}\n\n\t\t\tList\u003CMaterialDef\u003E materials = null;\n\t\t\tif ( root.TryGetProperty( \u0022materials\u0022, out var matsEl ) )\n\t\t\t\tmaterials = ParseMaterialDefs( matsEl );\n\n\t\t\t// Build ParsedMesh\n\t\t\tvar vertCount = vertArray.Count / 3;\n\t\t\tvar vertices = new Vector3[vertCount];\n\t\t\tfor ( int i = 0; i \u003C vertCount; i\u002B\u002B )\n\t\t\t\tvertices[i] = new Vector3( vertArray[i * 3], vertArray[i * 3 \u002B 1], vertArray[i * 3 \u002B 2] );\n\n\t\t\tvar faceGroups = new List\u003Cint[]\u003E();\n\t\t\tint idx = 0;\n\t\t\twhile ( idx \u003C faces.Count )\n\t\t\t{\n\t\t\t\tint fvc = faces[idx\u002B\u002B];\n\t\t\t\tif ( idx \u002B fvc \u003E faces.Count ) break;\n\t\t\t\tvar face = new int[fvc];\n\t\t\t\tfor ( int i = 0; i \u003C fvc; i\u002B\u002B )\n\t\t\t\t\tface[i] = faces[idx\u002B\u002B];\n\t\t\t\tfaceGroups.Add( face );\n\t\t\t}\n\n\t\t\t// Blender-authored UVs ride on mesh_end in the same flat format as\n\t\t\t// update_mesh. Without parsing them here, every chunked (20k\u002B vertex)\n\t\t\t// mesh silently loses its UV layout to the grid-align fallback.\n\t\t\tList\u003CVector2[]\u003E faceUVs = null;\n\t\t\tif ( root.TryGetProperty( \u0022faceUVs\u0022, out var uvEl ) )\n\t\t\t\tfaceUVs = ParseFaceUVs( uvEl, faceGroups );\n\n\t\t\tvar parsed = new ParsedMesh\n\t\t\t{\n\t\t\t\tVertices = vertices,\n\t\t\t\tFaceGroups = faceGroups,\n\t\t\t\tFaceMaterials = faceMaterials,\n\t\t\t\tMaterials = materials,\n\t\t\t\tFaceUVs = faceUVs\n\t\t\t};\n\n\t\t\t// Find the object and apply mesh\n\t\t\tvar go = FindByBridgeTag( bridgeId );\n\t\t\tif ( go == null )\n\t\t\t\treturn \u0022{\\\u0022error\\\u0022:\\\u0022not found\\\u0022}\u0022;\n\n\t\t\t// Same lock policy as update_mesh \u2014 the chunked path must not be a\n\t\t\t// side door around per-object locks. Nothing applied, so do not arm\n\t\t\t// the echo guard.\n\t\t\tif ( !BridgeLockPolicy.AllowsInbound( go ) )\n\t\t\t\treturn \u0022{\\\u0022ok\\\u0022:true,\\\u0022locked\\\u0022:true}\u0022;\n\n\t\t\tif ( BridgeLockPolicy.AllowsTransformChange( go ) )\n\t\t\t\tApplyTransform( go, root );\n\n\t\t\tif ( BridgeLockPolicy.AllowsGeometryChange( go ) )\n\t\t\t\tApplyParsedMeshData( go, parsed );\n\n\t\t\t_lastWriteSeq[bridgeId] = blenderSeq;\n\t\t\t_lastKnown[bridgeId] = (go.WorldPosition, go.WorldRotation);\n\t\t\tStampAppliedMeshHash( bridgeId, go );\n\n\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\tif ( scene != null )\n\t\t\t\tBridgePersistence.SaveAfterChange( scene, bridgeId, go );\n\n\t\t\tBlenderBridgeServer.LogInfo( $\u0022Chunked mesh assembled for {bridgeId} ({vertCount} verts)\u0022 );\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\t// \u2500\u2500 update_scene_transform \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static string HandleUpdateSceneTransform( JsonElement root )\n\t\t{\n\t\t\tvar sceneId = GetString( root, \u0022sceneId\u0022 );\n\t\t\tif ( string.IsNullOrEmpty( sceneId ) ) return \u0022{\\\u0022error\\\u0022:\\\u0022missing sceneId\\\u0022}\u0022;\n\t\t\tvar blenderSeq = GetInt( root, \u0022seq\u0022, 0 );\n\n\t\t\tif ( !Guid.TryParse( sceneId, out var guid ) ) return \u0022{\\\u0022error\\\u0022:\\\u0022invalid sceneId\\\u0022}\u0022;\n\n\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\tif ( scene == null ) return \u0022{\\\u0022error\\\u0022:\\\u0022no scene\\\u0022}\u0022;\n\n\t\t\tGameObject go = null;\n\t\t\tforeach ( var root2 in scene.Children )\n\t\t\t{\n\t\t\t\tgo = SearchTree( root2, g =\u003E g.Id == guid );\n\t\t\t\tif ( go != null ) break;\n\t\t\t}\n\t\t\tif ( go == null ) return \u0022{\\\u0022error\\\u0022:\\\u0022not found\\\u0022}\u0022;\n\n\t\t\tApplyTransform( go, root );\n\n\t\t\tvar key = $\u0022scene_{sceneId}\u0022;\n\t\t\t_lastWriteSeq[key] = blenderSeq;\n\t\t\t_lastKnown[key] = (go.WorldPosition, go.WorldRotation);\n\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\t// \u2500\u2500 grid_changed \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static string HandleGridChanged( JsonElement root )\n\t\t{\n\t\t\tvar gridSize = GetInt( root, \u0022gridSize\u0022, 0 );\n\t\t\tif ( gridSize \u003C= 0 ) return \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\n\t\t\t// GridSpacing range is [0.125, 128]. Bridge range is [1, 256].\n\t\t\t// Clamp at the engine ceiling; the bridge property keeps the original value\n\t\t\t// so users see what they asked for, but the engine grid can\u0027t go above 128.\n\t\t\tfloat spacing = gridSize \u003E 128 ? 128f : gridSize;\n\t\t\t_lastBroadcastGridSpacing = spacing;\n\t\t\ttry\n\t\t\t{\n\t\t\t\t// EditorScene.GizmoSettings is the editor\u0027s live settings object \u2014 the\n\t\t\t\t// scene viewport assigns this exact instance into its GizmoInstance, and\n\t\t\t\t// the editor\u0027s own grid menu/[ ]/snap widgets read and write it.\n\t\t\t\t// Gizmo.Settings must NOT be used here: it resolves Active?.Settings,\n\t\t\t\t// and Gizmo.Active only exists inside a gizmo scope \u2014 from the\n\t\t\t\t// dispatcher it is null, so writes through it silently do nothing.\n\t\t\t\tEditorScene.GizmoSettings.GridSpacing = spacing;\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022grid_changed apply skipped: {ex.Message}\u0022 );\n\t\t\t}\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Broadcast the editor\u0027s grid spacing to Blender as grid_updated and stamp\n\t\t/// the echo guard so the poll loop doesn\u0027t re-send the same value.\n\t\t/// \u003C/summary\u003E\n\t\tprivate static void BroadcastGridSpacing( float spacing )\n\t\t{\n\t\t\t_lastBroadcastGridSpacing = spacing;\n\t\t\tint gridSize = (int)MathF.Round( spacing );\n\t\t\tif ( gridSize \u003C 1 ) gridSize = 1;\n\t\t\tif ( gridSize \u003E 256 ) gridSize = 256;\n\t\t\tBlenderBridgeServer.BroadcastWithSeq( new\n\t\t\t{\n\t\t\t\ttype = \u0022grid_updated\u0022,\n\t\t\t\tgridSize\n\t\t\t} );\n\t\t}\n\n\t\t// \u2500\u2500 sync \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static string HandleSync( JsonElement root )\n\t\t{\n\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\tif ( scene == null ) return \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\n\t\t\t// Parse what Blender knows about\n\t\t\tvar blenderKnown = new HashSet\u003Cstring\u003E();\n\t\t\tif ( root.TryGetProperty( \u0022knownObjects\u0022, out var known ) )\n\t\t\t{\n\t\t\t\tforeach ( var item in known.EnumerateArray() )\n\t\t\t\t{\n\t\t\t\t\tvar bid = item.TryGetProperty( \u0022bridgeId\u0022, out var b ) ? b.GetString() : null;\n\t\t\t\t\tif ( bid != null ) blenderKnown.Add( bid );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar bridgeObjects = FindAllBridgeObjects( scene );\n\t\t\tvar sboxIds = new HashSet\u003Cstring\u003E( bridgeObjects.Select( x =\u003E x.bridgeId ) );\n\t\t\tvar objects = new List\u003Cobject\u003E();\n\n\t\t\t// Sync re-baselines _lastKnown to the objects\u0027 current state below,\n\t\t\t// so any armed echo guard is stale \u2014 clearing here means the first\n\t\t\t// edit after a manual sync always broadcasts instead of being\n\t\t\t// swallowed by a leftover guard.\n\t\t\t_lastWriteSeq.Clear();\n\n\t\t\tforeach ( var (bridgeId, go) in bridgeObjects )\n\t\t\t{\n\t\t\t\t_lastKnown[bridgeId] = (go.WorldPosition, go.WorldRotation);\n\t\t\t\tif ( !BridgeLockPolicy.AllowsOutbound( go ) ) continue;\n\t\t\t\tobjects.Add( BuildObjectPayload( bridgeId, go ) );\n\t\t\t}\n\n\t\t\t// Include scene lights, models, and native MeshComponents\n\t\t\tforeach ( var go in BridgeSceneHelper.WalkAll( scene, true ) )\n\t\t\t{\n\t\t\t\tif ( go.Tags.TryGetAll().Any( tag =\u003E tag.StartsWith( \u0022bridge_\u0022 ) ) )\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvar light = go.Components.GetAll().FirstOrDefault( c =\u003E c is Light ) as Light;\n\t\t\t\tif ( light != null )\n\t\t\t\t{\n\t\t\t\t\tobjects.Add( BuildLightPayload( go, light ) );\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Native MeshComponents placed in s\u0026box \u2014 adopt as bridge objects\n\t\t\t\tvar meshComp = go.Components.Get\u003CMeshComponent\u003E();\n\t\t\t\tif ( meshComp?.Mesh != null )\n\t\t\t\t{\n\t\t\t\t\tvar adoptId = \u0022b_\u0022 \u002B Guid.NewGuid().ToString( \u0022N\u0022 ).Substring( 0, 8 );\n\t\t\t\t\tgo.Tags.Add( $\u0022bridge_{adoptId}\u0022 );\n\t\t\t\t\t_bridgeObjectCache[adoptId] = go;\n\t\t\t\t\t_lastKnown[adoptId] = (go.WorldPosition, go.WorldRotation);\n\t\t\t\t\tobjects.Add( BuildObjectPayload( adoptId, go ) );\n\t\t\t\t\tsboxIds.Add( adoptId );\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tvar anyModel = go.Components.GetAll()\n\t\t\t\t\t.FirstOrDefault( c =\u003E c.GetType().Name.Contains( \u0022ModelRenderer\u0022 ) );\n\t\t\t\tif ( anyModel != null )\n\t\t\t\t\tobjects.Add( BuildModelPayload( go, anyModel ) );\n\t\t\t}\n\n\t\t\t// Tell Blender to remove objects it has that s\u0026box doesn\u0027t.\n\t\t\t// Only when the resolved scene is the one the change-scanner has\n\t\t\t// settled on \u2014 during a tab switch Blender\u0027s list reflects another\n\t\t\t// scene, and emitting deletes here would wipe the Blender side.\n\t\t\tif ( ReferenceEquals( scene, _lastScannedScene ) )\n\t\t\t{\n\t\t\t\tvar staleInBlender = blenderKnown.Except( sboxIds );\n\t\t\t\tforeach ( var staleId in staleInBlender )\n\t\t\t\t\tobjects.Add( new { type = \u0022deleted\u0022, bridgeId = staleId } );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogInfo( \u0022Sync: scene not settled \u2014 skipped stale-object reconciliation\u0022 );\n\t\t\t}\n\n\t\t\tBlenderBridgeServer.BroadcastWithSeq( new { type = \u0022sync_response\u0022, objects } );\n\n\t\t\t// Grid handshake: Blender requests sync on connect, reconnect, and session\n\t\t\t// change. Push the editor\u0027s current grid spacing alongside the response so\n\t\t\t// both sides start aligned \u2014 change-detection alone never fires for a\n\t\t\t// client that reconnected after the last change.\n\t\t\ttry\n\t\t\t{\n\t\t\t\tBroadcastGridSpacing( EditorScene.GizmoSettings.GridSpacing );\n\t\t\t}\n\t\t\tcatch { }\n\n\t\t\tBlenderBridgeServer.LogInfo( $\u0022Sync: {bridgeObjects.Count} bridge, {objects.Count} total\u0022 );\n\t\t\treturn \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t}\n\n\t\t// \u2500\u2500 Poll for s\u0026box-side changes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tinternal static void PollForChanges()\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tPollForChangesInternal();\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Poll cycle skipped: {ex.Message}\u0022 );\n\t\t\t}\n\t\t}\n\n\t\t// Last observed Game.IsPlaying, stamped on the main thread each scan tick.\n\t\t// Read by HandlePoll (background thread) so every poll response carries\n\t\t// play-mode ground truth \u2014 Blender syncs its play flag level-triggered\n\t\t// instead of trusting edge-triggered messages that can be missed.\n\t\tinternal static bool IsPlayingSnapshot;\n\n\t\t// Scene the change-scanner ran against last tick. ResolveScene() follows\n\t\t// the ACTIVE editor tab \u2014 with multiple scenes open, a tab switch makes\n\t\t// every tracked object \u0022vanish\u0022 from the scan and the deletion detector\n\t\t// would broadcast deletes for all of them (Blender then wipes its side).\n\t\tprivate static Scene _lastScannedScene;\n\n\t\tprivate static void PollForChangesInternal()\n\t\t{\n\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\tif ( scene == null ) return;\n\n\t\t\tif ( !ReferenceEquals( scene, _lastScannedScene ) )\n\t\t\t{\n\t\t\t\tbool firstScan = _lastScannedScene == null;\n\t\t\t\t_lastScannedScene = scene;\n\t\t\t\tif ( !firstScan )\n\t\t\t\t{\n\t\t\t\t\t_lastKnown.Clear();\n\t\t\t\t\t_lastMeshHash.Clear();\n\t\t\t\t\t_bridgeObjectCache.Clear();\n\t\t\t\t\t// Echo guards belong to the old scene\u0027s write history \u2014 a\n\t\t\t\t\t// stale armed key would swallow the first real edit made to\n\t\t\t\t\t// a same-ID object after switching back.\n\t\t\t\t\t_lastWriteSeq.Clear();\n\t\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Scene changed to \u0027{scene.Name}\u0027 \u2014 bridge tracking reset, deletes suppressed this tick\u0022 );\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Play mode detection\n\t\t\tbool isPlaying = Game.IsPlaying;\n\t\t\tIsPlayingSnapshot = isPlaying;\n\t\t\tif ( isPlaying != _wasPlaying )\n\t\t\t{\n\t\t\t\t_wasPlaying = isPlaying;\n\t\t\t\tBlenderBridgeServer.BroadcastWithSeq( new\n\t\t\t\t{\n\t\t\t\t\ttype = \u0022play_mode\u0022,\n\t\t\t\t\tstate = isPlaying ? \u0022started\u0022 : \u0022stopped\u0022\n\t\t\t\t} );\n\n\t\t\t\tif ( isPlaying )\n\t\t\t\t{\n\t\t\t\t\t// Entering play mode wipes editor meshes \u2014 everything\n\t\t\t\t\t// queued must hit disk NOW or the restore has stale data.\n\t\t\t\t\ttry { BridgePersistence.FlushPendingSaves( scene, force: true ); }\n\t\t\t\t\tcatch { }\n\t\t\t\t}\n\n\t\t\t\tif ( !isPlaying )\n\t\t\t\t{\n\t\t\t\t\t// Exiting play mode \u2014 restore cached meshes\n\t\t\t\t\ttry { BridgePersistence.RestoreFromCache( scene ); }\n\t\t\t\t\tcatch { }\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Clean up timed-out chunk accumulators\n\t\t\tvar timedOut = _pendingChunks\n\t\t\t\t.Where( kv =\u003E (DateTime.UtcNow - kv.Value.StartTime).TotalSeconds \u003E 30 )\n\t\t\t\t.Select( kv =\u003E kv.Key ).ToList();\n\t\t\tforeach ( var key in timedOut )\n\t\t\t\t_pendingChunks.Remove( key );\n\n\t\t\t// Grid-spacing change detection: if the editor user changed the grid spacing\n\t\t\t// (menu, [ ] shortcuts, snap widget), broadcast it to Blender.\n\t\t\t// _lastBroadcastGridSpacing is stamped on inbound grid_changed too, so a\n\t\t\t// bridge-driven write doesn\u0027t echo back. Read EditorScene.GizmoSettings \u2014\n\t\t\t// NOT Gizmo.Settings, which is null outside a gizmo scope.\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfloat spacing = EditorScene.GizmoSettings.GridSpacing;\n\t\t\t\tif ( MathF.Abs( spacing - _lastBroadcastGridSpacing ) \u003E 0.001f )\n\t\t\t\t\tBroadcastGridSpacing( spacing );\n\t\t\t}\n\t\t\tcatch { }\n\n\t\t\tvar bridgeObjects = FindAllBridgeObjects( scene );\n\t\t\tvar currentIds = new HashSet\u003Cstring\u003E();\n\n\t\t\t// Mesh-hash amortization: hashing every mesh every tick is\n\t\t\t// per-vertex work \u00D7 object count \u00D7 5Hz on the editor main thread \u2014\n\t\t\t// the scan\u0027s scale cliff. Round-robin so at most MeshHashBudget\n\t\t\t// objects hash per tick; each object is still checked every\n\t\t\t// ceil(n/budget) ticks (~1s at 60 objects). Safe because every\n\t\t\t// mesh-apply handler stamps _lastMeshHash itself, so a delayed\n\t\t\t// check can never mistake our own write for a user edit after the\n\t\t\t// echo guard was consumed.\n\t\t\t_scanTick\u002B\u002B;\n\t\t\tint hashSlices = Math.Max( 1, (bridgeObjects.Count \u002B MeshHashBudget - 1) / MeshHashBudget );\n\t\t\tint objIdx = -1;\n\n\t\t\tforeach ( var (bridgeId, go) in bridgeObjects )\n\t\t\t{\n\t\t\t\tobjIdx\u002B\u002B;\n\t\t\t\tif ( go == null || !go.IsValid ) continue;\n\n\t\t\t\t// Editor-side duplication (shift-drag, Ctrl\u002BD) copies the GameObject\n\t\t\t\t// together with its bridge tag, leaving two objects claiming one ID.\n\t\t\t\t// The scan then flip-flops _lastKnown between their transforms and\n\t\t\t\t// broadcasts an \u0022updated\u0022 storm every tick \u2014 which also keeps\n\t\t\t\t// Blender\u0027s echo-suppression window open so Blender-\u003Eengine moves\n\t\t\t\t// stop applying. Re-tag the copy with a fresh ID and announce it\n\t\t\t\t// to Blender as a new object.\n\t\t\t\tif ( !currentIds.Add( bridgeId ) )\n\t\t\t\t{\n\t\t\t\t\tgo.Tags.Remove( $\u0022bridge_{bridgeId}\u0022 );\n\t\t\t\t\tvar dupId = \u0022b_\u0022 \u002B Guid.NewGuid().ToString( \u0022N\u0022 ).Substring( 0, 8 );\n\t\t\t\t\tgo.Tags.Add( $\u0022bridge_{dupId}\u0022 );\n\t\t\t\t\tcurrentIds.Add( dupId );\n\t\t\t\t\t_bridgeObjectCache.Remove( bridgeId ); // may point at the re-tagged copy\n\t\t\t\t\t_bridgeObjectCache[dupId] = go;\n\t\t\t\t\t_lastKnown[dupId] = (go.WorldPosition, go.WorldRotation);\n\n\t\t\t\t\tvar dupMeshComp = go.Components.Get\u003CMeshComponent\u003E();\n\t\t\t\t\tif ( dupMeshComp?.Mesh != null )\n\t\t\t\t\t{\n\t\t\t\t\t\t_lastMeshHash[dupId] = ComputeMeshGeometryHash( dupMeshComp.Mesh );\n\t\t\t\t\t\tvar dupExtracted = ExtractMeshData( dupMeshComp.Mesh );\n\t\t\t\t\t\tobject dupMd = null;\n\t\t\t\t\t\tif ( dupExtracted != null )\n\t\t\t\t\t\t\tdupMd = new { vertices = dupExtracted.Value.Vertices, faces = dupExtracted.Value.Faces };\n\t\t\t\t\t\tvar dupPos = go.WorldPosition;\n\t\t\t\t\t\tvar dupRot = go.WorldRotation.Angles();\n\t\t\t\t\t\t// sourceBridgeId: the wire meshData is geometry-only, so\n\t\t\t\t\t\t// Blender clones materials/UVs from its own copy of the\n\t\t\t\t\t\t// source object instead of creating the dup bare \u2014 a bare\n\t\t\t\t\t\t// dup used to echo a material-less mesh update back and\n\t\t\t\t\t\t// wipe THIS object\u0027s textures.\n\t\t\t\t\t\tBlenderBridgeServer.BroadcastWithSeq( new\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype = \u0022object_created\u0022,\n\t\t\t\t\t\t\tbridgeId = dupId,\n\t\t\t\t\t\t\tsourceBridgeId = bridgeId,\n\t\t\t\t\t\t\tname = go.Name,\n\t\t\t\t\t\t\tposition = new { x = dupPos.x, y = dupPos.y, z = dupPos.z },\n\t\t\t\t\t\t\trotation = new { pitch = dupRot.pitch, yaw = dupRot.yaw, roll = dupRot.roll },\n\t\t\t\t\t\t\tmeshData = dupMd\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\t\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Duplicated {bridgeId} re-tagged as {dupId}\u0022 );\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Undo of a delete restores the GameObject with its bridge tag\n\t\t\t\t// intact \u2014 Blender was already told to delete this id, so\n\t\t\t\t// re-announce it as a creation instead of silently re-tracking.\n\t\t\t\tif ( _recentlyDeleted.Remove( bridgeId ) )\n\t\t\t\t{\n\t\t\t\t\t_bridgeObjectCache[bridgeId] = go;\n\t\t\t\t\t_lastKnown[bridgeId] = (go.WorldPosition, go.WorldRotation);\n\t\t\t\t\tvar undoMesh = go.Components.Get\u003CMeshComponent\u003E();\n\t\t\t\t\tif ( undoMesh?.Mesh != null )\n\t\t\t\t\t\t_lastMeshHash[bridgeId] = ComputeMeshGeometryHash( undoMesh.Mesh );\n\t\t\t\t\tBlenderBridgeServer.BroadcastWithSeq( BuildObjectCreatedMessage( bridgeId, go ) );\n\t\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Restored {bridgeId} (\u0027{go.Name}\u0027) \u2014 re-announced to Blender\u0022 );\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Outbound lock: skip pushing changes to Blender for this object,\n\t\t\t\t// but keep tracking it (so deletes still propagate, etc).\n\t\t\t\tif ( !BridgeLockPolicy.AllowsOutbound( go ) )\n\t\t\t\t{\n\t\t\t\t\t_lastKnown[bridgeId] = (go.WorldPosition, go.WorldRotation);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tvar pos = go.WorldPosition;\n\t\t\t\tvar rot = go.WorldRotation;\n\n\t\t\t\tbool posChanged = false;\n\t\t\t\tbool rotChanged = false;\n\n\t\t\t\tif ( _lastKnown.TryGetValue( bridgeId, out var prev ) )\n\t\t\t\t{\n\t\t\t\t\tposChanged = MathF.Abs( pos.x - prev.pos.x ) \u003E 0.01f\n\t\t\t\t\t\t|| MathF.Abs( pos.y - prev.pos.y ) \u003E 0.01f\n\t\t\t\t\t\t|| MathF.Abs( pos.z - prev.pos.z ) \u003E 0.01f;\n\t\t\t\t\trotChanged = !rot.Equals( prev.rot );\n\t\t\t\t}\n\n\t\t\t\t// Check mesh changes \u2014 hash vertex positions so moves/pulls are\n\t\t\t\t// detected. Only this object\u0027s round-robin slice hashes this tick.\n\t\t\t\tbool meshChanged = false;\n\t\t\t\tvar meshComp = go.Components.Get\u003CMeshComponent\u003E();\n\t\t\t\tif ( meshComp?.Mesh != null \u0026\u0026 (objIdx % hashSlices) == (_scanTick % hashSlices) )\n\t\t\t\t{\n\t\t\t\t\tvar meshHash = ComputeMeshGeometryHash( meshComp.Mesh );\n\t\t\t\t\tif ( _lastMeshHash.TryGetValue( bridgeId, out var prevHash ) \u0026\u0026 prevHash != meshHash )\n\t\t\t\t\t\tmeshChanged = true;\n\t\t\t\t\t_lastMeshHash[bridgeId] = meshHash;\n\t\t\t\t}\n\n\t\t\t\t// Echo suppression: consume the guard every tick, delta or not.\n\t\t\t\t// Handlers stamp _lastKnown from the object AFTER applying a\n\t\t\t\t// Blender write, so the echo usually produces no delta here \u2014\n\t\t\t\t// consuming only inside the delta branch leaves the key armed\n\t\t\t\t// indefinitely, where it silently swallows the user\u0027s next\n\t\t\t\t// genuine s\u0026box edit (undo, typed coordinate, snap). Dispatch\n\t\t\t\t// and poll are serialized on the main thread, so any echo delta\n\t\t\t\t// that does surface (mesh hash, transform quantization) is\n\t\t\t\t// visible by the tick right after the write \u2014 a one-tick\n\t\t\t\t// lifetime is enough.\n\t\t\t\tbool suppressEcho = _lastWriteSeq.Remove( bridgeId );\n\n\t\t\t\tif ( (posChanged || rotChanged || meshChanged) \u0026\u0026 !suppressEcho )\n\t\t\t\t{\n\t\t\t\t\tvar angles = rot.Angles();\n\t\t\t\t\tif ( meshChanged )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar extracted = ExtractMeshData( meshComp.Mesh );\n\t\t\t\t\t\tobject md = null;\n\t\t\t\t\t\tif ( extracted != null )\n\t\t\t\t\t\t\tmd = new { vertices = extracted.Value.Vertices, faces = extracted.Value.Faces };\n\n\t\t\t\t\t\tBlenderBridgeServer.BroadcastWithSeq( new\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype = \u0022mesh_updated\u0022,\n\t\t\t\t\t\t\tbridgeId,\n\t\t\t\t\t\t\tposition = new { x = pos.x, y = pos.y, z = pos.z },\n\t\t\t\t\t\t\trotation = new { pitch = angles.pitch, yaw = angles.yaw, roll = angles.roll },\n\t\t\t\t\t\t\tmeshData = md\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tBlenderBridgeServer.BroadcastWithSeq( new\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype = \u0022updated\u0022,\n\t\t\t\t\t\t\tbridgeId,\n\t\t\t\t\t\t\tposition = new { x = pos.x, y = pos.y, z = pos.z },\n\t\t\t\t\t\t\trotation = new { pitch = angles.pitch, yaw = angles.yaw, roll = angles.roll }\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t_lastKnown[bridgeId] = (pos, rot);\n\t\t\t}\n\n\t\t\t// Detect deletions\n\t\t\tforeach ( var oldId in _lastKnown.Keys.ToList() )\n\t\t\t{\n\t\t\t\tif ( oldId.StartsWith( \u0022scene_\u0022 ) ) continue;\n\t\t\t\tif ( !currentIds.Contains( oldId ) )\n\t\t\t\t{\n\t\t\t\t\t_lastKnown.Remove( oldId );\n\t\t\t\t\t_lastWriteSeq.Remove( oldId );\n\t\t\t\t\t_lastMeshHash.Remove( oldId );\n\t\t\t\t\t_bridgeObjectCache.Remove( oldId );\n\t\t\t\t\t_recentlyDeleted.Add( oldId );\n\t\t\t\t\tBlenderBridgeServer.BroadcastWithSeq( new { type = \u0022deleted\u0022, bridgeId = oldId } );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Track scene objects (models/lights) and auto-adopt native MeshComponents\n\t\t\tforeach ( var go in BridgeSceneHelper.WalkAll( scene, true ) )\n\t\t\t{\n\t\t\t\tif ( go == null || !go.IsValid ) continue;\n\t\t\t\tif ( go.Tags.TryGetAll().Any( tag =\u003E tag.StartsWith( \u0022bridge_\u0022 ) ) )\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// Auto-adopt native MeshComponents that aren\u0027t bridge-tagged yet\n\t\t\t\tvar nativeMesh = go.Components.Get\u003CMeshComponent\u003E();\n\t\t\t\tif ( nativeMesh?.Mesh != null )\n\t\t\t\t{\n\t\t\t\t\tvar adoptId = \u0022b_\u0022 \u002B Guid.NewGuid().ToString( \u0022N\u0022 ).Substring( 0, 8 );\n\t\t\t\t\tgo.Tags.Add( $\u0022bridge_{adoptId}\u0022 );\n\t\t\t\t\t_bridgeObjectCache[adoptId] = go;\n\t\t\t\t\t_lastKnown[adoptId] = (go.WorldPosition, go.WorldRotation);\n\t\t\t\t\t_lastMeshHash[adoptId] = ComputeMeshGeometryHash( nativeMesh.Mesh );\n\n\t\t\t\t\t// Broadcast the new object to Blender as a creation event\n\t\t\t\t\tvar adoptPos = go.WorldPosition;\n\t\t\t\t\tvar adoptRot = go.WorldRotation.Angles();\n\t\t\t\t\tvar extracted = ExtractMeshData( nativeMesh.Mesh );\n\t\t\t\t\tobject meshData = null;\n\t\t\t\t\tif ( extracted != null )\n\t\t\t\t\t\tmeshData = new { vertices = extracted.Value.Vertices, faces = extracted.Value.Faces };\n\n\t\t\t\t\tBlenderBridgeServer.BroadcastWithSeq( new\n\t\t\t\t\t{\n\t\t\t\t\t\ttype = \u0022object_created\u0022,\n\t\t\t\t\t\tbridgeId = adoptId,\n\t\t\t\t\t\tname = go.Name,\n\t\t\t\t\t\tposition = new { x = adoptPos.x, y = adoptPos.y, z = adoptPos.z },\n\t\t\t\t\t\trotation = new { pitch = adoptRot.pitch, yaw = adoptRot.yaw, roll = adoptRot.roll },\n\t\t\t\t\t\tmeshData\n\t\t\t\t\t} );\n\t\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Auto-adopted native mesh \u0027{go.Name}\u0027 as {adoptId}\u0022 );\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tvar hasModel = go.Components.GetAll().Any( c =\u003E c.GetType().Name.Contains( \u0022ModelRenderer\u0022 ) );\n\t\t\t\tvar hasLight = go.Components.GetAll().Any( c =\u003E c is Light );\n\t\t\t\tif ( !hasModel \u0026\u0026 !hasLight ) continue;\n\n\t\t\t\tvar key = $\u0022scene_{go.Id}\u0022;\n\t\t\t\tvar pos = go.WorldPosition;\n\t\t\t\tvar rot = go.WorldRotation;\n\n\t\t\t\tif ( _lastKnown.TryGetValue( key, out var prevScene ) )\n\t\t\t\t{\n\t\t\t\t\tbool sceneChanged = MathF.Abs( pos.x - prevScene.pos.x ) \u003E 0.01f\n\t\t\t\t\t\t|| MathF.Abs( pos.y - prevScene.pos.y ) \u003E 0.01f\n\t\t\t\t\t\t|| MathF.Abs( pos.z - prevScene.pos.z ) \u003E 0.01f;\n\n\t\t\t\t\tif ( sceneChanged \u0026\u0026 !_lastWriteSeq.ContainsKey( key ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar angles = rot.Angles();\n\t\t\t\t\t\tBlenderBridgeServer.BroadcastWithSeq( new\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype = \u0022scene_updated\u0022,\n\t\t\t\t\t\t\tsceneId = go.Id.ToString(),\n\t\t\t\t\t\t\tposition = new { x = pos.x, y = pos.y, z = pos.z },\n\t\t\t\t\t\t\trotation = new { pitch = angles.pitch, yaw = angles.yaw, roll = angles.roll }\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\t\t\t\t\telse if ( _lastWriteSeq.ContainsKey( key ) )\n\t\t\t\t\t{\n\t\t\t\t\t\t_lastWriteSeq.Remove( key );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t_lastKnown[key] = (pos, rot);\n\t\t\t}\n\n\t\t\t// Write out queued mesh caches \u002B manifest once things go quiet.\n\t\t\tBridgePersistence.FlushPendingSaves( scene );\n\t\t}\n\n\t\t// \u2500\u2500 Hierarchy grouping \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t/// \u003Csummary\u003EFind or create the \u0022Blender Bridge\u0022 parent object identified by tag.\u003C/summary\u003E\n\t\tprivate static GameObject GetOrCreateBridgeGroup( Scene scene )\n\t\t{\n\t\t\t// Search by tag (survives renames)\n\t\t\tforeach ( var root in scene.Children )\n\t\t\t{\n\t\t\t\tvar found = SearchTree( root, g =\u003E g.Tags.Has( \u0022bridge_group\u0022 ) );\n\t\t\t\tif ( found != null ) return found;\n\t\t\t}\n\n\t\t\t// Create new group\n\t\t\tvar go = scene.CreateObject();\n\t\t\tgo.Name = \u0022Blender Bridge\u0022;\n\t\t\tgo.Tags.Add( \u0022bridge_group\u0022 );\n\t\t\treturn go;\n\t\t}\n\n\t\t/// \u003Csummary\u003EFind or create a child GameObject by name under a parent.\n\t\t/// Used to build hierarchy from Blender collection paths.\u003C/summary\u003E\n\t\tprivate static GameObject GetOrCreateChild( GameObject parent, string name )\n\t\t{\n\t\t\t// Search existing children\n\t\t\tforeach ( var child in parent.Children )\n\t\t\t{\n\t\t\t\tif ( child.Name == name )\n\t\t\t\t\treturn child;\n\t\t\t}\n\n\t\t\t// Create new empty child\n\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\tif ( scene == null ) return parent;\n\n\t\t\tvar go = scene.CreateObject();\n\t\t\tgo.Name = name;\n\t\t\tgo.Parent = parent;\n\t\t\treturn go;\n\t\t}\n\n\t\t// \u2500\u2500 Object finders \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t/// \u003Csummary\u003ETrue if this tag carries a bridge identity (bridge_\u0026lt;id\u0026gt;).\n\t\t/// The group marker and the lock tags (bridge_locked, bridge_lock_\u0026lt;flags\u0026gt;)\n\t\t/// share the prefix but are not identity \u2014 treating them as one yields\n\t\t/// phantom ids like \u0022lock_4\u0022 shared by every object with the same flags.\u003C/summary\u003E\n\t\tinternal static bool IsBridgeIdentityTag( string tag )\n\t\t\t=\u003E tag.StartsWith( \u0022bridge_\u0022 ) \u0026\u0026 tag != \u0022bridge_group\u0022\n\t\t\t\t\u0026\u0026 tag != BridgeLockPolicy.LegacyLockTag\n\t\t\t\t\u0026\u0026 !tag.StartsWith( BridgeLockPolicy.FlagTagPrefix );\n\n\t\t/// \u003Csummary\u003EClient-supplied bridge IDs become GameObject tags \u2014 accept\n\t\t/// only the addon\u0027s own \u0022b_\u0022 \u002B lowercase-hex format so a malformed\n\t\t/// value can\u0027t smuggle arbitrary tag content (or collide with the\n\t\t/// group/lock tag namespace).\u003C/summary\u003E\n\t\tprivate static bool IsValidClientBridgeId( string id )\n\t\t{\n\t\t\tif ( string.IsNullOrEmpty( id ) || id.Length \u003C 4 || id.Length \u003E 40 ) return false;\n\t\t\tif ( !id.StartsWith( \u0022b_\u0022 ) ) return false;\n\t\t\tfor ( int i = 2; i \u003C id.Length; i\u002B\u002B )\n\t\t\t{\n\t\t\t\tvar c = id[i];\n\t\t\t\tif ( !((c \u003E= \u00270\u0027 \u0026\u0026 c \u003C= \u00279\u0027) || (c \u003E= \u0027a\u0027 \u0026\u0026 c \u003C= \u0027f\u0027)) ) return false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\t/// \u003Csummary\u003EFind a bridge object by ID. Uses cache, falls back to tree walk.\u003C/summary\u003E\n\t\tprivate static GameObject FindByBridgeTag( string bridgeId )\n\t\t{\n\t\t\t// Cache hit\n\t\t\tif ( _bridgeObjectCache.TryGetValue( bridgeId, out var cached ) \u0026\u0026 cached != null \u0026\u0026 cached.IsValid )\n\t\t\t\treturn cached;\n\n\t\t\t// Cache miss \u2014 walk the scene\n\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\tif ( scene == null ) return null;\n\n\t\t\tvar tag = $\u0022bridge_{bridgeId}\u0022;\n\t\t\tforeach ( var root in scene.Children )\n\t\t\t{\n\t\t\t\tvar found = SearchTree( root, tag );\n\t\t\t\tif ( found != null )\n\t\t\t\t{\n\t\t\t\t\t_bridgeObjectCache[bridgeId] = found;\n\t\t\t\t\treturn found;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\tprivate static GameObject SearchTree( GameObject node, string tag )\n\t\t{\n\t\t\tif ( node.Tags.Has( tag ) ) return node;\n\t\t\tforeach ( var child in node.Children )\n\t\t\t{\n\t\t\t\tvar found = SearchTree( child, tag );\n\t\t\t\tif ( found != null ) return found;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\tprivate static GameObject SearchTree( GameObject node, Func\u003CGameObject, bool\u003E predicate )\n\t\t{\n\t\t\tif ( predicate( node ) ) return node;\n\t\t\tforeach ( var child in node.Children )\n\t\t\t{\n\t\t\t\tvar found = SearchTree( child, predicate );\n\t\t\t\tif ( found != null ) return found;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\tprivate static List\u003C(string bridgeId, GameObject go)\u003E FindAllBridgeObjects( Scene scene )\n\t\t{\n\t\t\tvar result = new List\u003C(string, GameObject)\u003E();\n\t\t\tforeach ( var root in scene.Children )\n\t\t\t\tCollectBridgeObjects( root, result );\n\t\t\treturn result;\n\t\t}\n\n\t\tprivate static void CollectBridgeObjects( GameObject node, List\u003C(string, GameObject)\u003E result )\n\t\t{\n\t\t\tforeach ( var tag in node.Tags.TryGetAll() )\n\t\t\t{\n\t\t\t\tif ( IsBridgeIdentityTag( tag ) )\n\t\t\t\t{\n\t\t\t\t\tvar bridgeId = tag.Substring( 7 );\n\t\t\t\t\tresult.Add( (bridgeId, node) );\n\t\t\t\t\t_bridgeObjectCache[bridgeId] = node; // Keep cache warm\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tforeach ( var child in node.Children )\n\t\t\t\tCollectBridgeObjects( child, result );\n\t\t}\n\n\t\t/// \u003Csummary\u003ERead-only diagnostic snapshot for GET /debug.\u003C/summary\u003E\n\t\tinternal static string DumpDebugState()\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\t\tvar objs = new List\u003Cobject\u003E();\n\t\t\t\tif ( scene != null )\n\t\t\t\t{\n\t\t\t\t\tforeach ( var go in BridgeSceneHelper.WalkAll( scene, true ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tif ( go == null || !go.IsValid ) continue;\n\t\t\t\t\t\tvar bridgeTags = go.Tags.TryGetAll()\n\t\t\t\t\t\t\t.Where( t =\u003E t.StartsWith( \u0022bridge_\u0022 ) ).ToList();\n\t\t\t\t\t\tif ( bridgeTags.Count == 0 ) continue;\n\t\t\t\t\t\tvar p = go.WorldPosition;\n\t\t\t\t\t\tobjs.Add( new\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tname = go.Name,\n\t\t\t\t\t\t\ttags = bridgeTags,\n\t\t\t\t\t\t\tposition = new { x = p.x, y = p.y, z = p.z }\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn JsonSerializer.Serialize( new\n\t\t\t\t{\n\t\t\t\t\tscene = scene?.Name,\n\t\t\t\t\tplaying = Game.IsPlaying,\n\t\t\t\t\tobjects = objs,\n\t\t\t\t\tlastKnown = _lastKnown.Keys.ToList(),\n\t\t\t\t\tlastWriteSeq = _lastWriteSeq.Keys.ToList(),\n\t\t\t\t\tlastMeshHash = _lastMeshHash.Keys.ToList(),\n\t\t\t\t\tidempotencyKeys = _idempotencyKeys.Count,\n\t\t\t\t}, BlenderBridgeServer.JsonOptions );\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\treturn JsonSerializer.Serialize( new { error = ex.Message }, BlenderBridgeServer.JsonOptions );\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 Light properties \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static void ApplyLightProperties( GameObject go, JsonElement root )\n\t\t{\n\t\t\tif ( !root.TryGetProperty( \u0022properties\u0022, out var propsEl ) )\n\t\t\t\treturn;\n\n\t\t\tvar light = go.Components.GetAll().FirstOrDefault( c =\u003E c is Light ) as Light;\n\t\t\tif ( light == null ) return;\n\n\t\t\tif ( propsEl.TryGetProperty( \u0022color\u0022, out var colorEl ) )\n\t\t\t{\n\t\t\t\tvar r = GetFloat( colorEl, \u0022r\u0022, 1f );\n\t\t\t\tvar g = GetFloat( colorEl, \u0022g\u0022, 1f );\n\t\t\t\tvar b = GetFloat( colorEl, \u0022b\u0022, 1f );\n\t\t\t\tlight.LightColor = new Color( r, g, b );\n\t\t\t}\n\n\t\t\tif ( light is PointLight point )\n\t\t\t{\n\t\t\t\tif ( propsEl.TryGetProperty( \u0022radius\u0022, out var radiusEl ) )\n\t\t\t\t\tpoint.Radius = radiusEl.GetSingle();\n\t\t\t}\n\t\t\telse if ( light is SpotLight spot )\n\t\t\t{\n\t\t\t\tif ( propsEl.TryGetProperty( \u0022radius\u0022, out var radiusEl ) )\n\t\t\t\t\tspot.Radius = radiusEl.GetSingle();\n\t\t\t\tif ( propsEl.TryGetProperty( \u0022coneOuter\u0022, out var outerEl ) )\n\t\t\t\t\tspot.ConeOuter = outerEl.GetSingle();\n\t\t\t\tif ( propsEl.TryGetProperty( \u0022coneInner\u0022, out var innerEl ) )\n\t\t\t\t\tspot.ConeInner = innerEl.GetSingle();\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 Mesh handling \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate struct ParsedMesh\n\t\t{\n\t\t\tpublic Vector3[] Vertices;\n\t\t\tpublic List\u003Cint[]\u003E FaceGroups;\n\t\t\tpublic int[] FaceMaterials;\n\t\t\tpublic List\u003CMaterialDef\u003E Materials;\n\t\t\t/// \u003Csummary\u003EPer-face Blender-authored UVs, parallel to FaceGroups.\n\t\t\t/// Each entry has one Vector2 per face vertex. Null when Blender\n\t\t\t/// didn\u0027t send a UV layer; the apply path falls back to grid-align.\u003C/summary\u003E\n\t\t\tpublic List\u003CVector2[]\u003E FaceUVs;\n\t\t}\n\n\t\tprivate struct MaterialDef\n\t\t{\n\t\t\tpublic string Name;\n\t\t\tpublic float[] BaseColor;\n\t\t\tpublic float Metallic;\n\t\t\tpublic float Roughness;\n\t\t\tpublic string BaseColorTexture;\n\t\t\tpublic string RoughnessTexture;\n\t\t\tpublic string MetallicTexture;\n\t\t\tpublic string NormalTexture;\n\t\t\tpublic float NormalStrength;\n\t\t\tpublic float[] EmissionColor;\n\t\t\tpublic float EmissionStrength;\n\t\t\tpublic string VmatPath;\n\t\t}\n\n\t\tprivate static void ApplyMeshData( GameObject go, JsonElement meshData )\n\t\t{\n\t\t\tvar parsed = ParseMeshData( meshData );\n\t\t\tif ( parsed == null ) return;\n\t\t\tApplyParsedMeshData( go, parsed.Value );\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Pulls the material off the first face of the GameObject\u0027s existing\n\t\t/// mesh. Used to preserve manually-authored materials (water shaders,\n\t\t/// custom vmats) when Blender resyncs without supplying material info.\n\t\t/// Returns null if there\u0027s no mesh, no faces, or only the dev default\n\t\t/// material is present (in which case the caller\u0027s fallback is fine).\n\t\t/// \u003C/summary\u003E\n\t\tprivate static Material TryGetExistingDominantMaterial( GameObject go )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar mesh = go?.Components.Get\u003CMeshComponent\u003E()?.Mesh;\n\t\t\t\tif ( mesh == null ) return null;\n\n\t\t\t\tvar getFaceMatMeth = mesh.GetType().GetMethod( \u0022GetFaceMaterial\u0022, new[] { typeof( FaceHandle ) } );\n\t\t\t\tif ( getFaceMatMeth == null ) return null;\n\n\t\t\t\tforeach ( var fh in mesh.FaceHandles )\n\t\t\t\t{\n\t\t\t\t\tvar result = getFaceMatMeth.Invoke( mesh, new object[] { fh } );\n\t\t\t\t\tif ( result is Material m \u0026\u0026 m != null )\n\t\t\t\t\t{\n\t\t\t\t\t\t// Skip the dev placeholder \u2014 using it as the \u0022preserve\u0022\n\t\t\t\t\t\t// fallback means we\u0027d never escape it once it\u0027s been set.\n\t\t\t\t\t\tvar path = m.ResourcePath ?? \u0022\u0022;\n\t\t\t\t\t\tif ( path.EndsWith( \u0022reflectivity_30.vmat\u0022, StringComparison.OrdinalIgnoreCase ) ||\n\t\t\t\t\t\t\t path.EndsWith( \u0022reflectivity_30.vmat_c\u0022, StringComparison.OrdinalIgnoreCase ) )\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\treturn m;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch { }\n\t\t\treturn null;\n\t\t}\n\n\t\tprivate static void ApplyParsedMeshData( GameObject go, ParsedMesh parsed )\n\t\t{\n\t\t\tvar faceMaterials = new Material[parsed.FaceGroups.Count];\n\t\t\tvar defaultMaterial = LoadMaterialSafe( \u0022materials/dev/reflectivity_30.vmat\u0022 );\n\n\t\t\t// Materials lock: preserve whatever\u0027s already on the object regardless\n\t\t\t// of what Blender supplied. Skips the entire material-resolution path\n\t\t\t// and falls through to the existing-material preservation branch.\n\t\t\tbool forceMaterialPreserve = !BridgeLockPolicy.AllowsMaterialChange( go );\n\n\t\t\tif ( !forceMaterialPreserve \u0026\u0026 parsed.Materials != null \u0026\u0026 parsed.FaceMaterials != null )\n\t\t\t{\n\t\t\t\tvar materialCache = new Dictionary\u003Cint, Material\u003E();\n\t\t\t\tfor ( int fi = 0; fi \u003C parsed.FaceGroups.Count \u0026\u0026 fi \u003C parsed.FaceMaterials.Length; fi\u002B\u002B )\n\t\t\t\t{\n\t\t\t\t\tvar matIdx = parsed.FaceMaterials[fi];\n\t\t\t\t\tif ( !materialCache.ContainsKey( matIdx ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tMaterial mat = null;\n\t\t\t\t\t\tif ( matIdx \u003C parsed.Materials.Count )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar vmatPath = parsed.Materials[matIdx].VmatPath;\n\t\t\t\t\t\t\tif ( !string.IsNullOrEmpty( vmatPath ) )\n\t\t\t\t\t\t\t\tmat = LoadMaterialSafe( vmatPath );\n\t\t\t\t\t\t\tif ( mat == null )\n\t\t\t\t\t\t\t\tmat = GenerateOrLoadMaterial( parsed.Materials[matIdx] );\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmaterialCache[matIdx] = mat ?? defaultMaterial;\n\t\t\t\t\t}\n\t\t\t\t\tfaceMaterials[fi] = materialCache[matIdx];\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// Blender sent geometry but no material info. Before stamping\n\t\t\t\t// the dev placeholder over every face, try to preserve whatever\n\t\t\t\t// material is already on this GameObject\u0027s mesh \u2014 water shaders,\n\t\t\t\t// custom vmats, anything authored on the s\u0026box side.\n\t\t\t\tvar preserved = TryGetExistingDominantMaterial( go );\n\t\t\t\tvar fallback = preserved ?? defaultMaterial;\n\t\t\t\tfor ( int i = 0; i \u003C faceMaterials.Length; i\u002B\u002B )\n\t\t\t\t\tfaceMaterials[i] = fallback;\n\t\t\t\tif ( preserved != null )\n\t\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Preserved existing material on \u0027{go.Name}\u0027 (Blender sent no materials)\u0022 );\n\t\t\t}\n\n\t\t\tvar mesh = new PolygonMesh();\n\t\t\tvar hVertices = mesh.AddVertices( parsed.Vertices );\n\n\t\t\tbool hasBlenderUVs = parsed.FaceUVs != null \u0026\u0026 parsed.FaceUVs.Count == parsed.FaceGroups.Count;\n\n\t\t\tint faceIdx = 0;\n\t\t\tforeach ( var faceGroup in parsed.FaceGroups )\n\t\t\t{\n\t\t\t\tvar faceVerts = faceGroup\n\t\t\t\t\t.Where( fi =\u003E fi \u003E= 0 \u0026\u0026 fi \u003C hVertices.Length )\n\t\t\t\t\t.Select( fi =\u003E hVertices[fi] )\n\t\t\t\t\t.ToArray();\n\t\t\t\tif ( faceVerts.Length \u003E= 3 )\n\t\t\t\t{\n\t\t\t\t\tvar hFace = mesh.AddFace( faceVerts );\n\t\t\t\t\tmesh.SetFaceMaterial( hFace, faceIdx \u003C faceMaterials.Length ? faceMaterials[faceIdx] : defaultMaterial );\n\t\t\t\t\tif ( hasBlenderUVs \u0026\u0026 faceIdx \u003C parsed.FaceUVs.Count )\n\t\t\t\t\t{\n\t\t\t\t\t\t// Use Blender-authored UVs verbatim. SetFaceTextureCoords\n\t\t\t\t\t\t// also recomputes the face\u0027s texture parameters from the\n\t\t\t\t\t\t// new coords, so the planar projection follows the UV\n\t\t\t\t\t\t// layout instead of fighting it.\n\t\t\t\t\t\tmesh.SetFaceTextureCoords( hFace, parsed.FaceUVs[faceIdx] );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfaceIdx\u002B\u002B;\n\t\t\t}\n\n\t\t\t// Only fall back to grid-aligned auto-UVs if Blender didn\u0027t send a\n\t\t\t// UV layer. Calling TextureAlignToGrid when we have real UVs would\n\t\t\t// stomp them.\n\t\t\tif ( !hasBlenderUVs )\n\t\t\t\tmesh.TextureAlignToGrid( mesh.Transform );\n\t\t\tmesh.SetSmoothingAngle( 40.0f );\n\n\t\t\t// Defense in depth: never replace a Terrain component with a\n\t\t\t// MeshComponent. If the lock check earlier in the dispatch flow was\n\t\t\t// bypassed (e.g. an addon bug, a missing tag), this still blocks the\n\t\t\t// destructive path.\n\t\t\tif ( go.Components.Get\u003CTerrain\u003E() != null )\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Skipped ApplyMeshData on \u0027{go.Name}\u0027 \u2014 has Terrain component\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tvar existingMr = go.Components.Get\u003CModelRenderer\u003E();\n\t\t\tif ( existingMr != null )\n\t\t\t\texistingMr.Destroy();\n\n\t\t\tvar meshComp = go.Components.Get\u003CMeshComponent\u003E();\n\t\t\tif ( meshComp == null )\n\t\t\t\tmeshComp = go.Components.Create\u003CMeshComponent\u003E();\n\n\t\t\tmeshComp.Mesh = mesh;\n\t\t}\n\n\t\t// \u2500\u2500 Material generation \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static Material GenerateOrLoadMaterial( MaterialDef def )\n\t\t{\n\t\t\tvar safeName = System.Text.RegularExpressions.Regex.Replace(\n\t\t\t\tdef.Name ?? \u0022default\u0022, @\u0022[^a-zA-Z0-9_\\-]\u0022, \u0022_\u0022 ).ToLower();\n\t\t\tvar vmatRelPath = $\u0022materials/blender_bridge/{safeName}.vmat\u0022;\n\n\t\t\tvar assetsDir = GetProjectAssetsDir();\n\t\t\tif ( assetsDir == null ) return null;\n\n\t\t\tvar bridgeMatDir = System.IO.Path.Combine( assetsDir, \u0022materials\u0022, \u0022blender_bridge\u0022 );\n\t\t\tSystem.IO.Directory.CreateDirectory( bridgeMatDir );\n\n\t\t\tvar colorTexRef = CopyTextureToAssets( def.BaseColorTexture, safeName, \u0022color\u0022, assetsDir );\n\t\t\tvar roughTexRef = CopyTextureToAssets( def.RoughnessTexture, safeName, \u0022rough\u0022, assetsDir );\n\t\t\tvar metalTexRef = CopyTextureToAssets( def.MetallicTexture, safeName, \u0022metal\u0022, assetsDir );\n\t\t\tvar normalTexRef = CopyTextureToAssets( def.NormalTexture, safeName, \u0022normal\u0022, assetsDir );\n\n\t\t\tvar sb = new System.Text.StringBuilder();\n\t\t\tsb.AppendLine( \u0022// AUTO-GENERATED BY BLENDER BRIDGE\u0022 );\n\t\t\tsb.AppendLine();\n\t\t\tsb.AppendLine( \u0022Layer0\u0022 );\n\t\t\tsb.AppendLine( \u0022{\u0022 );\n\t\t\tsb.AppendLine( \u0022\\tshader \\\u0022shaders/complex.shader\\\u0022\u0022 );\n\t\t\tsb.AppendLine();\n\t\t\tif ( metalTexRef != null ) sb.AppendLine( \u0022\\tF_METALNESS_TEXTURE 1\u0022 );\n\t\t\tsb.AppendLine( \u0022\\tF_SPECULAR 1\u0022 );\n\t\t\tsb.AppendLine();\n\n\t\t\tvar r = def.BaseColor?.Length \u003E= 3 ? def.BaseColor[0] : 0.8f;\n\t\t\tvar g = def.BaseColor?.Length \u003E= 3 ? def.BaseColor[1] : 0.8f;\n\t\t\tvar b = def.BaseColor?.Length \u003E= 3 ? def.BaseColor[2] : 0.8f;\n\t\t\t// A color texture drives albedo \u2014 Blender\u0027s Base Color value is\n\t\t\t// whatever was set before the texture was linked, and tinting by\n\t\t\t// it multiplies the texture by that stale color.\n\t\t\tif ( colorTexRef != null ) { r = 1f; g = 1f; b = 1f; }\n\t\t\tsb.AppendLine( $\u0022\\tg_flModelTintAmount \\\u00221.000\\\u0022\u0022 );\n\t\t\tsb.AppendLine( $\u0022\\tg_vColorTint \\\u0022[{r:F6} {g:F6} {b:F6} 0.000000]\\\u0022\u0022 );\n\t\t\tif ( colorTexRef != null ) sb.AppendLine( $\u0022\\tTextureColor \\\u0022{colorTexRef}\\\u0022\u0022 );\n\t\t\tsb.AppendLine();\n\t\t\tsb.AppendLine( $\u0022\\tg_flMetalness \\\u0022{def.Metallic:F3}\\\u0022\u0022 );\n\t\t\tif ( metalTexRef != null ) sb.AppendLine( $\u0022\\tTextureMetalness \\\u0022{metalTexRef}\\\u0022\u0022 );\n\t\t\tsb.AppendLine();\n\t\t\tsb.AppendLine( $\u0022\\tg_flRoughnessScaleFactor \\\u0022{def.Roughness:F3}\\\u0022\u0022 );\n\t\t\tif ( roughTexRef != null ) sb.AppendLine( $\u0022\\tTextureRoughness \\\u0022{roughTexRef}\\\u0022\u0022 );\n\t\t\tsb.AppendLine();\n\t\t\tif ( normalTexRef != null ) { sb.AppendLine( $\u0022\\tTextureNormal \\\u0022{normalTexRef}\\\u0022\u0022 ); sb.AppendLine(); }\n\t\t\tif ( def.EmissionStrength \u003E 0.001f )\n\t\t\t{\n\t\t\t\tvar er = def.EmissionColor?.Length \u003E= 3 ? def.EmissionColor[0] : 0f;\n\t\t\t\tvar eg = def.EmissionColor?.Length \u003E= 3 ? def.EmissionColor[1] : 0f;\n\t\t\t\tvar eb = def.EmissionColor?.Length \u003E= 3 ? def.EmissionColor[2] : 0f;\n\t\t\t\tsb.AppendLine( $\u0022\\tg_vSelfIllumTint \\\u0022[{er:F6} {eg:F6} {eb:F6} 0.000000]\\\u0022\u0022 );\n\t\t\t\tsb.AppendLine( $\u0022\\tg_flSelfIllumScale \\\u0022{def.EmissionStrength:F3}\\\u0022\u0022 );\n\t\t\t\tsb.AppendLine();\n\t\t\t}\n\t\t\tsb.AppendLine( \u0022\\tg_vTexCoordScale \\\u0022[1.000 1.000]\\\u0022\u0022 );\n\t\t\tsb.AppendLine( \u0022\\tg_vTexCoordOffset \\\u0022[0.000 0.000]\\\u0022\u0022 );\n\t\t\tsb.AppendLine( \u0022}\u0022 );\n\n\t\t\tvar vmatPath = System.IO.Path.Combine( assetsDir, vmatRelPath.Replace( \u0022/\u0022, \u0022\\\\\u0022 ) );\n\t\t\tSystem.IO.File.WriteAllText( vmatPath, sb.ToString() );\n\n\t\t\t// Register AND compile, otherwise Material.Load returns null on the\n\t\t\t// first call (no .vmat_c on disk yet) and we silently fall through\n\t\t\t// to the dev placeholder. Compile(false) is incremental and\n\t\t\t// synchronous \u2014 by the time it returns, the compiled resource\n\t\t\t// exists and Material.Load can resolve it. Re-registering an\n\t\t\t// already-known path is a no-op.\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar asset = AssetSystem.RegisterFile( vmatPath );\n\t\t\t\tasset?.Compile( full: false );\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Vmat register/compile failed for {vmatPath}: {ex.Message}\u0022 );\n\t\t\t}\n\n\t\t\treturn LoadMaterialSafe( vmatRelPath ) ?? LoadMaterialSafe( \u0022materials/dev/reflectivity_30.vmat\u0022 );\n\t\t}\n\n\t\tprivate static string GenerateVmatPath( MaterialDef def )\n\t\t{\n\t\t\tvar safeName = System.Text.RegularExpressions.Regex.Replace(\n\t\t\t\tdef.Name ?? \u0022default\u0022, @\u0022[^a-zA-Z0-9_\\-]\u0022, \u0022_\u0022 ).ToLower();\n\t\t\treturn $\u0022materials/blender_bridge/{safeName}.vmat\u0022;\n\t\t}\n\n\t\tprivate static string CopyTextureToAssets( string srcPath, string matName, string suffix, string assetsDir )\n\t\t{\n\t\t\tif ( string.IsNullOrEmpty( srcPath ) || !System.IO.File.Exists( srcPath ) )\n\t\t\t\treturn null;\n\t\t\tvar ext = System.IO.Path.GetExtension( srcPath );\n\t\t\tvar destName = $\u0022{matName}_{suffix}{ext}\u0022;\n\t\t\tvar destRelPath = $\u0022materials/blender_bridge/{destName}\u0022;\n\t\t\tvar destAbsPath = System.IO.Path.Combine( assetsDir, destRelPath.Replace( \u0022/\u0022, \u0022\\\\\u0022 ) );\n\t\t\ttry\n\t\t\t{\n\t\t\t\tSystem.IO.File.Copy( srcPath, destAbsPath, overwrite: true );\n\t\t\t\t// Register \u002B compile so the vmat that references this texture\n\t\t\t\t// can find a resolved .vtex_c on disk. Without compile, the\n\t\t\t\t// material loads but renders untextured.\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tvar asset = AssetSystem.RegisterFile( destAbsPath );\n\t\t\t\t\tasset?.Compile( full: false );\n\t\t\t\t}\n\t\t\t\tcatch ( Exception cex )\n\t\t\t\t{\n\t\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Texture register/compile failed for {destAbsPath}: {cex.Message}\u0022 );\n\t\t\t\t}\n\t\t\t\treturn destRelPath;\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Texture copy failed ({srcPath}): {ex.Message}\u0022 );\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 Mesh parsing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static ParsedMesh? ParseMeshData( JsonElement meshData )\n\t\t{\n\t\t\tif ( !meshData.TryGetProperty( \u0022vertices\u0022, out var vertsEl ) ) return null;\n\t\t\tif ( !meshData.TryGetProperty( \u0022faces\u0022, out var facesEl ) ) return null;\n\n\t\t\tvar vertFloats = new List\u003Cfloat\u003E();\n\t\t\tforeach ( var v in vertsEl.EnumerateArray() ) vertFloats.Add( v.GetSingle() );\n\t\t\tif ( vertFloats.Count \u003C 9 ) return null;\n\n\t\t\tvar vertCount = vertFloats.Count / 3;\n\t\t\tvar vertices = new Vector3[vertCount];\n\t\t\tfor ( int i = 0; i \u003C vertCount; i\u002B\u002B )\n\t\t\t\tvertices[i] = new Vector3( vertFloats[i * 3], vertFloats[i * 3 \u002B 1], vertFloats[i * 3 \u002B 2] );\n\n\t\t\tvar rawFaces = new List\u003Cint\u003E();\n\t\t\tforeach ( var f in facesEl.EnumerateArray() ) rawFaces.Add( f.GetInt32() );\n\n\t\t\tvar faceGroups = new List\u003Cint[]\u003E();\n\t\t\tint idx = 0;\n\t\t\twhile ( idx \u003C rawFaces.Count )\n\t\t\t{\n\t\t\t\tint faceVertCount = rawFaces[idx\u002B\u002B];\n\t\t\t\tif ( idx \u002B faceVertCount \u003E rawFaces.Count ) break;\n\t\t\t\tvar face = new int[faceVertCount];\n\t\t\t\tfor ( int i = 0; i \u003C faceVertCount; i\u002B\u002B ) face[i] = rawFaces[idx\u002B\u002B];\n\t\t\t\tfaceGroups.Add( face );\n\t\t\t}\n\n\t\t\tint[] faceMaterials = null;\n\t\t\tif ( meshData.TryGetProperty( \u0022faceMaterials\u0022, out var fmEl ) )\n\t\t\t{\n\t\t\t\tvar fmList = new List\u003Cint\u003E();\n\t\t\t\tforeach ( var fm in fmEl.EnumerateArray() ) fmList.Add( fm.GetInt32() );\n\t\t\t\tfaceMaterials = fmList.ToArray();\n\t\t\t}\n\n\t\t\tList\u003CMaterialDef\u003E materials = null;\n\t\t\tif ( meshData.TryGetProperty( \u0022materials\u0022, out var matsEl ) )\n\t\t\t\tmaterials = ParseMaterialDefs( matsEl );\n\n\t\t\t// Optional per-face-corner UVs. Flat [u,v,u,v,...] aligned with\n\t\t\t// faceGroups: face N\u0027s UVs are the next (face.Length) pairs.\n\t\t\tList\u003CVector2[]\u003E faceUVs = null;\n\t\t\tif ( meshData.TryGetProperty( \u0022faceUVs\u0022, out var uvEl ) )\n\t\t\t\tfaceUVs = ParseFaceUVs( uvEl, faceGroups );\n\n\t\t\treturn new ParsedMesh\n\t\t\t{\n\t\t\t\tVertices = vertices,\n\t\t\t\tFaceGroups = faceGroups,\n\t\t\t\tFaceMaterials = faceMaterials,\n\t\t\t\tMaterials = materials,\n\t\t\t\tFaceUVs = faceUVs\n\t\t\t};\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Parse a flat [u,v,u,v,...] array into per-face UV sets aligned with\n\t\t/// faceGroups: face N\u0027s UVs are the next (face.Length) pairs.\n\t\t/// \u003C/summary\u003E\n\t\tprivate static List\u003CVector2[]\u003E ParseFaceUVs( JsonElement uvEl, List\u003Cint[]\u003E faceGroups )\n\t\t{\n\t\t\tvar uvFloats = new List\u003Cfloat\u003E();\n\t\t\tforeach ( var u in uvEl.EnumerateArray() ) uvFloats.Add( u.GetSingle() );\n\t\t\tvar faceUVs = new List\u003CVector2[]\u003E( faceGroups.Count );\n\t\t\tint uvIdx = 0;\n\t\t\tforeach ( var face in faceGroups )\n\t\t\t{\n\t\t\t\tvar uvs = new Vector2[face.Length];\n\t\t\t\tfor ( int i = 0; i \u003C face.Length \u0026\u0026 uvIdx \u002B 1 \u003C uvFloats.Count; i\u002B\u002B )\n\t\t\t\t{\n\t\t\t\t\tuvs[i] = new Vector2( uvFloats[uvIdx], uvFloats[uvIdx \u002B 1] );\n\t\t\t\t\tuvIdx \u002B= 2;\n\t\t\t\t}\n\t\t\t\tfaceUVs.Add( uvs );\n\t\t\t}\n\t\t\treturn faceUVs;\n\t\t}\n\n\t\tprivate static List\u003CMaterialDef\u003E ParseMaterialDefs( JsonElement matsEl )\n\t\t{\n\t\t\tvar materials = new List\u003CMaterialDef\u003E();\n\t\t\tforeach ( var matEl in matsEl.EnumerateArray() )\n\t\t\t{\n\t\t\t\tvar def = new MaterialDef\n\t\t\t\t{\n\t\t\t\t\tName = matEl.TryGetProperty( \u0022name\u0022, out var n ) ? n.GetString() : \u0022default\u0022,\n\t\t\t\t\tMetallic = matEl.TryGetProperty( \u0022metallic\u0022, out var met ) ? met.GetSingle() : 0f,\n\t\t\t\t\tRoughness = matEl.TryGetProperty( \u0022roughness\u0022, out var rough ) ? rough.GetSingle() : 0.5f,\n\t\t\t\t\tNormalStrength = matEl.TryGetProperty( \u0022normalStrength\u0022, out var ns ) ? ns.GetSingle() : 1f,\n\t\t\t\t\tEmissionStrength = matEl.TryGetProperty( \u0022emissionStrength\u0022, out var es ) ? es.GetSingle() : 0f,\n\t\t\t\t\tBaseColorTexture = matEl.TryGetProperty( \u0022baseColorTexture\u0022, out var bct ) \u0026\u0026 bct.ValueKind == JsonValueKind.String ? bct.GetString() : null,\n\t\t\t\t\tRoughnessTexture = matEl.TryGetProperty( \u0022roughnessTexture\u0022, out var rt ) \u0026\u0026 rt.ValueKind == JsonValueKind.String ? rt.GetString() : null,\n\t\t\t\t\tMetallicTexture = matEl.TryGetProperty( \u0022metallicTexture\u0022, out var mt ) \u0026\u0026 mt.ValueKind == JsonValueKind.String ? mt.GetString() : null,\n\t\t\t\t\tNormalTexture = matEl.TryGetProperty( \u0022normalTexture\u0022, out var nt ) \u0026\u0026 nt.ValueKind == JsonValueKind.String ? nt.GetString() : null,\n\t\t\t\t\tVmatPath = matEl.TryGetProperty( \u0022vmatPath\u0022, out var vp ) \u0026\u0026 vp.ValueKind == JsonValueKind.String ? vp.GetString() : null,\n\t\t\t\t};\n\n\t\t\t\tif ( matEl.TryGetProperty( \u0022baseColor\u0022, out var bcEl ) \u0026\u0026 bcEl.ValueKind == JsonValueKind.Array )\n\t\t\t\t{\n\t\t\t\t\tvar arr = new List\u003Cfloat\u003E();\n\t\t\t\t\tforeach ( var c in bcEl.EnumerateArray() ) arr.Add( c.GetSingle() );\n\t\t\t\t\tdef.BaseColor = arr.ToArray();\n\t\t\t\t}\n\n\t\t\t\tif ( matEl.TryGetProperty( \u0022emissionColor\u0022, out var ecEl ) \u0026\u0026 ecEl.ValueKind == JsonValueKind.Array )\n\t\t\t\t{\n\t\t\t\t\tvar arr = new List\u003Cfloat\u003E();\n\t\t\t\t\tforeach ( var c in ecEl.EnumerateArray() ) arr.Add( c.GetSingle() );\n\t\t\t\t\tdef.EmissionColor = arr.ToArray();\n\t\t\t\t}\n\n\t\t\t\tmaterials.Add( def );\n\t\t\t}\n\t\t\treturn materials;\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Compute a geometry hash that includes vertex positions,\n\t\t/// so moving/pulling vertices is detected as a change.\n\t\t/// \u003C/summary\u003E\n\t\t// Reflection hot-path cache. GetMethod \u002B Invoke PER VERTEX (boxing every\n\t\t// argument and return) was fine at small scenes but became the \u0022editor\n\t\t// lags on everything\u0022 stall once the scan ran it thousands of times per\n\t\t// tick. Resolve once into an open instance delegate \u2014 a direct call\n\t\t// thereafter.\n\t\tprivate static Func\u003CPolygonMesh, VertexHandle, Vector3\u003E _getVertexPositionFn;\n\t\tprivate static bool _getVertexPositionTried;\n\n\t\tprivate static Func\u003CPolygonMesh, VertexHandle, Vector3\u003E ResolveGetVertexPosition( PolygonMesh mesh )\n\t\t{\n\t\t\tif ( !_getVertexPositionTried )\n\t\t\t{\n\t\t\t\t_getVertexPositionTried = true;\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tvar m = mesh.GetType().GetMethod( \u0022GetVertexPosition\u0022, new[] { typeof( VertexHandle ) } );\n\t\t\t\t\tif ( m != null \u0026\u0026 m.ReturnType == typeof( Vector3 ) \u0026\u0026 !m.IsStatic )\n\t\t\t\t\t\t_getVertexPositionFn = (Func\u003CPolygonMesh, VertexHandle, Vector3\u003E)Delegate.CreateDelegate(\n\t\t\t\t\t\t\ttypeof( Func\u003CPolygonMesh, VertexHandle, Vector3\u003E ), m );\n\t\t\t\t}\n\t\t\t\tcatch { }\n\t\t\t}\n\t\t\treturn _getVertexPositionFn;\n\t\t}\n\n\t\tprivate static int ComputeMeshGeometryHash( PolygonMesh mesh )\n\t\t{\n\t\t\tunchecked\n\t\t\t{\n\t\t\t\tint hash = 17;\n\t\t\t\tvar vertHandles = mesh.VertexHandles;\n\t\t\t\tif ( vertHandles == null ) return 0;\n\n\t\t\t\thash = hash * 31 \u002B vertHandles.Count();\n\n\t\t\t\tvar getPos = ResolveGetVertexPosition( mesh );\n\t\t\t\tif ( getPos != null )\n\t\t\t\t{\n\t\t\t\t\tforeach ( var vh in vertHandles )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar pos = getPos( mesh, vh );\n\t\t\t\t\t\t// Quantize to 0.001 precision to avoid float noise\n\t\t\t\t\t\thash = hash * 31 \u002B (int)( pos.x * 1000 );\n\t\t\t\t\t\thash = hash * 31 \u002B (int)( pos.y * 1000 );\n\t\t\t\t\t\thash = hash * 31 \u002B (int)( pos.z * 1000 );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvar getPosMeth = mesh.GetType().GetMethod( \u0022GetVertexPosition\u0022, new[] { typeof( VertexHandle ) } );\n\t\t\t\t\tif ( getPosMeth != null )\n\t\t\t\t\t{\n\t\t\t\t\t\tforeach ( var vh in vertHandles )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttry\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar result = getPosMeth.Invoke( mesh, new object[] { vh } );\n\t\t\t\t\t\t\t\tif ( result is Vector3 pos )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\thash = hash * 31 \u002B (int)( pos.x * 1000 );\n\t\t\t\t\t\t\t\t\thash = hash * 31 \u002B (int)( pos.y * 1000 );\n\t\t\t\t\t\t\t\t\thash = hash * 31 \u002B (int)( pos.z * 1000 );\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch { break; }\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tvar faceHandles = mesh.FaceHandles;\n\t\t\t\tif ( faceHandles != null )\n\t\t\t\t\thash = hash * 31 \u002B faceHandles.Count();\n\n\t\t\t\treturn hash;\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 Mesh extraction (s\u0026box -\u003E Blender) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tinternal struct ExtractedMesh\n\t\t{\n\t\t\tpublic float[] Vertices;\n\t\t\tpublic int[] Faces;\n\t\t}\n\n\t\tinternal static ExtractedMesh? ExtractMeshData( PolygonMesh mesh )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar vertHandles = mesh.VertexHandles.ToList();\n\t\t\t\tif ( vertHandles.Count \u003C 3 ) return null;\n\n\t\t\t\tvar vertMap = new Dictionary\u003CVertexHandle, int\u003E();\n\t\t\t\tint vertIdx = 0;\n\t\t\t\tforeach ( var vh in vertHandles ) vertMap[vh] = vertIdx\u002B\u002B;\n\n\t\t\t\tvar verts = new List\u003Cfloat\u003E();\n\t\t\t\tvar getPos = ResolveGetVertexPosition( mesh );\n\t\t\t\tif ( getPos != null )\n\t\t\t\t{\n\t\t\t\t\tforeach ( var vh in vertHandles )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar pos = getPos( mesh, vh );\n\t\t\t\t\t\tverts.Add( pos.x );\n\t\t\t\t\t\tverts.Add( pos.y );\n\t\t\t\t\t\tverts.Add( pos.z );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvar getPosMeth = mesh.GetType().GetMethod( \u0022GetVertexPosition\u0022, new[] { typeof( VertexHandle ) } );\n\t\t\t\t\tif ( getPosMeth != null )\n\t\t\t\t\t{\n\t\t\t\t\t\tforeach ( var vh in vertHandles )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttry\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar result = getPosMeth.Invoke( mesh, new object[] { vh } );\n\t\t\t\t\t\t\t\tif ( result is Vector3 pos )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tverts.Add( pos.x );\n\t\t\t\t\t\t\t\t\tverts.Add( pos.y );\n\t\t\t\t\t\t\t\t\tverts.Add( pos.z );\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcatch { break; }\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ( verts.Count \u003C 9 ) return null;\n\n\t\t\t\tvar faces = new List\u003Cint\u003E();\n\t\t\t\tvar getFaceVertsMeth = mesh.GetType().GetMethod( \u0022GetFaceVertices\u0022, new[] { typeof( FaceHandle ) } );\n\t\t\t\tif ( getFaceVertsMeth != null )\n\t\t\t\t{\n\t\t\t\t\tforeach ( var fh in mesh.FaceHandles )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar result = getFaceVertsMeth.Invoke( mesh, new object[] { fh } );\n\t\t\t\t\t\tif ( result is VertexHandle[] faceVerts )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tfaces.Add( faceVerts.Length );\n\t\t\t\t\t\t\tforeach ( var fv in faceVerts )\n\t\t\t\t\t\t\t\tfaces.Add( vertMap.TryGetValue( fv, out var i ) ? i : 0 );\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if ( result is IEnumerable\u003CVertexHandle\u003E faceVertsEnum )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar fvList = faceVertsEnum.ToList();\n\t\t\t\t\t\t\tfaces.Add( fvList.Count );\n\t\t\t\t\t\t\tforeach ( var fv in fvList )\n\t\t\t\t\t\t\t\tfaces.Add( vertMap.TryGetValue( fv, out var i ) ? i : 0 );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif ( faces.Count == 0 ) return null;\n\t\t\t\treturn new ExtractedMesh { Vertices = verts.ToArray(), Faces = faces.ToArray() };\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogError( $\u0022ExtractMeshData failed: {ex.Message}\u0022 );\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 Terrain proxy extraction (s\u0026box -\u003E Blender) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\t\t//\n\t\t// The Sandbox.Terrain component isn\u0027t a PolygonMesh \u2014 its data lives in\n\t\t// a TerrainStorage with a Resolution\u00B2 ushort[] heightmap. Sending the\n\t\t// full heightmap to Blender is impractical (a 1024\u00B2 terrain = 1M verts),\n\t\t// so we downsample to a fixed PROXY_RESOLUTION grid for a low-poly\n\t\t// reference mesh in mesh-local space. Triangulation: each cell is a\n\t\t// quad face (the wire format already supports n-gons).\n\n\t\tprivate const int TerrainProxyResolution = 128;\n\n\t\tinternal static ExtractedMesh? ExtractTerrainProxyMesh( Terrain terrain )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar storage = terrain?.Storage;\n\t\t\t\tif ( storage == null ) return null;\n\t\t\t\tif ( storage.HeightMap == null || storage.HeightMap.Length == 0 ) return null;\n\n\t\t\t\tint srcRes = storage.Resolution;\n\t\t\t\tif ( srcRes \u003C= 0 || storage.HeightMap.Length \u003C srcRes * srcRes ) return null;\n\n\t\t\t\tint proxyRes = Math.Min( TerrainProxyResolution, srcRes );\n\t\t\t\tint vertsPerSide = proxyRes \u002B 1;\n\n\t\t\t\tfloat terrainSize = storage.TerrainSize;\n\t\t\t\tfloat terrainHeight = storage.TerrainHeight;\n\t\t\t\tfloat cellSize = terrainSize / proxyRes;\n\t\t\t\tfloat invMaxHeight = 1.0f / 65535f;\n\n\t\t\t\tvar verts = new float[vertsPerSide * vertsPerSide * 3];\n\t\t\t\tfor ( int gy = 0; gy \u003C vertsPerSide; gy\u002B\u002B )\n\t\t\t\t{\n\t\t\t\t\tint srcY = (int)((long)gy * (srcRes - 1) / proxyRes);\n\t\t\t\t\tfor ( int gx = 0; gx \u003C vertsPerSide; gx\u002B\u002B )\n\t\t\t\t\t{\n\t\t\t\t\t\tint srcX = (int)((long)gx * (srcRes - 1) / proxyRes);\n\t\t\t\t\t\tushort h = storage.HeightMap[srcY * srcRes \u002B srcX];\n\n\t\t\t\t\t\tint vi = (gy * vertsPerSide \u002B gx) * 3;\n\t\t\t\t\t\tverts[vi \u002B 0] = gx * cellSize;\n\t\t\t\t\t\tverts[vi \u002B 1] = gy * cellSize;\n\t\t\t\t\t\tverts[vi \u002B 2] = h * invMaxHeight * terrainHeight;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Faces: one quad per cell, [4, v00, v10, v11, v01].\n\t\t\t\tvar faces = new int[proxyRes * proxyRes * 5];\n\t\t\t\tint fi = 0;\n\t\t\t\tfor ( int gy = 0; gy \u003C proxyRes; gy\u002B\u002B )\n\t\t\t\t{\n\t\t\t\t\tint row0 = gy * vertsPerSide;\n\t\t\t\t\tint row1 = (gy \u002B 1) * vertsPerSide;\n\t\t\t\t\tfor ( int gx = 0; gx \u003C proxyRes; gx\u002B\u002B )\n\t\t\t\t\t{\n\t\t\t\t\t\tfaces[fi\u002B\u002B] = 4;\n\t\t\t\t\t\tfaces[fi\u002B\u002B] = row0 \u002B gx;\n\t\t\t\t\t\tfaces[fi\u002B\u002B] = row0 \u002B gx \u002B 1;\n\t\t\t\t\t\tfaces[fi\u002B\u002B] = row1 \u002B gx \u002B 1;\n\t\t\t\t\t\tfaces[fi\u002B\u002B] = row1 \u002B gx;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn new ExtractedMesh { Vertices = verts, Faces = faces };\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogError( $\u0022ExtractTerrainProxyMesh failed: {ex.Message}\u0022 );\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Pulls mesh data out of either a MeshComponent or (as a downsampled\n\t\t/// proxy) a Terrain. Used by the payload builders so terrain shows up\n\t\t/// in Blender alongside regular meshes.\n\t\t/// \u003C/summary\u003E\n\t\tprivate static object TryBuildMeshData( GameObject go )\n\t\t{\n\t\t\tvar meshComp = go.Components.Get\u003CMeshComponent\u003E();\n\t\t\tif ( meshComp?.Mesh != null )\n\t\t\t{\n\t\t\t\tvar extracted = ExtractMeshData( meshComp.Mesh );\n\t\t\t\tif ( extracted != null )\n\t\t\t\t\treturn new { vertices = extracted.Value.Vertices, faces = extracted.Value.Faces };\n\t\t\t}\n\n\t\t\tvar terrain = go.Components.Get\u003CTerrain\u003E();\n\t\t\tif ( terrain?.Storage != null )\n\t\t\t{\n\t\t\t\tvar extracted = ExtractTerrainProxyMesh( terrain );\n\t\t\t\tif ( extracted != null )\n\t\t\t\t\treturn new { vertices = extracted.Value.Vertices, faces = extracted.Value.Faces };\n\t\t\t}\n\n\t\t\treturn null;\n\t\t}\n\n\t\t// \u2500\u2500 Payload builders \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t/// \u003Csummary\u003EPublic access to BuildObjectPayload for the editor window\u0027s Send to Blender button.\u003C/summary\u003E\n\t\tinternal static object BuildObjectPayloadPublic( string bridgeId, GameObject go )\n\t\t{\n\t\t\treturn BuildObjectPayload( bridgeId, go );\n\t\t}\n\n\t\t/// \u003Csummary\u003EBuild a complete object_created message with type field for broadcasting.\u003C/summary\u003E\n\t\tinternal static object BuildObjectCreatedMessage( string bridgeId, GameObject go )\n\t\t{\n\t\t\tvar pos = go.WorldPosition;\n\t\t\tvar rot = go.WorldRotation.Angles();\n\t\t\tvar meshData = TryBuildMeshData( go );\n\n\t\t\treturn new\n\t\t\t{\n\t\t\t\ttype = \u0022object_created\u0022,\n\t\t\t\tbridgeId,\n\t\t\t\tname = go.Name,\n\t\t\t\tposition = new { x = pos.x, y = pos.y, z = pos.z },\n\t\t\t\trotation = new { pitch = rot.pitch, yaw = rot.yaw, roll = rot.roll },\n\t\t\t\tmeshData\n\t\t\t};\n\t\t}\n\n\t\tprivate static object BuildObjectPayload( string bridgeId, GameObject go )\n\t\t{\n\t\t\tvar pos = go.WorldPosition;\n\t\t\tvar rot = go.WorldRotation.Angles();\n\t\t\tvar meshData = TryBuildMeshData( go );\n\n\t\t\t// Build hierarchy path from parent chain (excluding bridge group root)\n\t\t\tvar hierarchy = new List\u003Cstring\u003E();\n\t\t\tvar parent = go.Parent;\n\t\t\twhile ( parent != null \u0026\u0026 !parent.Tags.Has( \u0022bridge_group\u0022 ) )\n\t\t\t{\n\t\t\t\thierarchy.Insert( 0, parent.Name );\n\t\t\t\tparent = parent.Parent;\n\t\t\t}\n\n\t\t\treturn new\n\t\t\t{\n\t\t\t\tbridgeId,\n\t\t\t\tname = go.Name,\n\t\t\t\tposition = new { x = pos.x, y = pos.y, z = pos.z },\n\t\t\t\trotation = new { pitch = rot.pitch, yaw = rot.yaw, roll = rot.roll },\n\t\t\t\tmeshData,\n\t\t\t\thierarchy\n\t\t\t};\n\t\t}\n\n\t\tprivate static object BuildLightPayload( GameObject go, Light light )\n\t\t{\n\t\t\tvar pos = go.WorldPosition;\n\t\t\tvar rot = go.WorldRotation.Angles();\n\t\t\tstring lightType = \u0022point\u0022;\n\t\t\tif ( light is SpotLight ) lightType = \u0022spot\u0022;\n\t\t\telse if ( light is DirectionalLight ) lightType = \u0022directional\u0022;\n\n\t\t\tfloat radius = 0f;\n\t\t\tfloat coneOuter = 0f;\n\t\t\tfloat coneInner = 0f;\n\t\t\tif ( light is PointLight pl ) radius = pl.Radius;\n\t\t\tif ( light is SpotLight spl ) { radius = spl.Radius; coneOuter = spl.ConeOuter; coneInner = spl.ConeInner; }\n\n\t\t\tobject properties = new\n\t\t\t{\n\t\t\t\tcolor = new { r = light.LightColor.r, g = light.LightColor.g, b = light.LightColor.b },\n\t\t\t\tradius,\n\t\t\t\tconeOuter,\n\t\t\t\tconeInner,\n\t\t\t};\n\n\t\t\treturn new\n\t\t\t{\n\t\t\t\tobjectType = \u0022light\u0022,\n\t\t\t\tlightType,\n\t\t\t\tname = go.Name,\n\t\t\t\tsceneId = go.Id.ToString(),\n\t\t\t\tposition = new { x = pos.x, y = pos.y, z = pos.z },\n\t\t\t\trotation = new { pitch = rot.pitch, yaw = rot.yaw, roll = rot.roll },\n\t\t\t\tproperties\n\t\t\t};\n\t\t}\n\n\t\tprivate static object BuildModelPayload( GameObject go, Component modelComp )\n\t\t{\n\t\t\tvar pos = go.WorldPosition;\n\t\t\tvar rot = go.WorldRotation.Angles();\n\t\t\tvar modelProp = modelComp.GetType().GetProperty( \u0022Model\u0022 );\n\t\t\tvar model = modelProp?.GetValue( modelComp ) as Model;\n\t\t\tvar modelPath = model?.ResourcePath ?? \u0022unknown\u0022;\n\n\t\t\tobject bounds = null;\n\t\t\tif ( model != null )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tbounds = new\n\t\t\t\t\t{\n\t\t\t\t\t\tmins = new { x = model.Bounds.Mins.x, y = model.Bounds.Mins.y, z = model.Bounds.Mins.z },\n\t\t\t\t\t\tmaxs = new { x = model.Bounds.Maxs.x, y = model.Bounds.Maxs.y, z = model.Bounds.Maxs.z }\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tcatch { }\n\t\t\t}\n\n\t\t\tstring fbxSourcePath = null;\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif ( modelPath != \u0022unknown\u0022 )\n\t\t\t\t\tfbxSourcePath = ResolveFbxPath( modelPath );\n\t\t\t}\n\t\t\tcatch { }\n\n\t\t\treturn new\n\t\t\t{\n\t\t\t\tobjectType = \u0022model\u0022,\n\t\t\t\tname = go.Name,\n\t\t\t\tsceneId = go.Id.ToString(),\n\t\t\t\tmodelPath,\n\t\t\t\tfbxSourcePath,\n\t\t\t\tbounds,\n\t\t\t\tposition = new { x = pos.x, y = pos.y, z = pos.z },\n\t\t\t\trotation = new { pitch = rot.pitch, yaw = rot.yaw, roll = rot.roll }\n\t\t\t};\n\t\t}\n\n\t\tprivate static string ResolveFbxPath( string modelPath )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar assetsDir = GetProjectAssetsDir();\n\t\t\t\tif ( assetsDir == null ) return null;\n\t\t\t\tvar projectRoot = System.IO.Path.GetDirectoryName( assetsDir );\n\t\t\t\tvar basePaths = new List\u003Cstring\u003E { assetsDir, projectRoot };\n\t\t\t\tvar relativePath = modelPath.Replace( \u0022\\\\\u0022, \u0022/\u0022 );\n\t\t\t\tforeach ( var prefix in new[] { \u0022assets/\u0022, \u0022models/\u0022 } )\n\t\t\t\t\tif ( relativePath.StartsWith( prefix, StringComparison.OrdinalIgnoreCase ) )\n\t\t\t\t\t{ relativePath = relativePath.Substring( prefix.Length ); break; }\n\n\t\t\t\tstring vmdlPath = null;\n\t\t\t\tstring vmdlDir = null;\n\t\t\t\tforeach ( var basePath in basePaths )\n\t\t\t\t{\n\t\t\t\t\tif ( string.IsNullOrEmpty( basePath ) ) continue;\n\t\t\t\t\tvar candidate = System.IO.Path.Combine( basePath, relativePath );\n\t\t\t\t\tif ( System.IO.File.Exists( candidate ) ) { vmdlPath = candidate; vmdlDir = System.IO.Path.GetDirectoryName( candidate ); break; }\n\t\t\t\t\tcandidate = System.IO.Path.Combine( basePath, modelPath.Replace( \u0022/\u0022, \u0022\\\\\u0022 ) );\n\t\t\t\t\tif ( System.IO.File.Exists( candidate ) ) { vmdlPath = candidate; vmdlDir = System.IO.Path.GetDirectoryName( candidate ); break; }\n\t\t\t\t}\n\t\t\t\tif ( vmdlPath == null ) return null;\n\n\t\t\t\tvar content = System.IO.File.ReadAllText( vmdlPath );\n\t\t\t\tvar match = System.Text.RegularExpressions.Regex.Match( content,\n\t\t\t\t\t@\u0022_class\\s*=\\s*\u0022\u0022RenderMeshFile\u0022\u0022[\\s\\S]*?filename\\s*=\\s*\u0022\u0022([^\u0022\u0022]\u002B)\u0022\u0022\u0022 );\n\t\t\t\tif ( !match.Success ) return null;\n\n\t\t\t\tvar fbxRelative = match.Groups[1].Value.Replace( \u0022\\\\\u0022, \u0022/\u0022 );\n\t\t\t\tvar fbxPath = System.IO.Path.GetFullPath( System.IO.Path.Combine( vmdlDir, fbxRelative ) );\n\t\t\t\tif ( System.IO.File.Exists( fbxPath ) ) return fbxPath;\n\t\t\t\tforeach ( var basePath in basePaths )\n\t\t\t\t{\n\t\t\t\t\tif ( string.IsNullOrEmpty( basePath ) ) continue;\n\t\t\t\t\tfbxPath = System.IO.Path.GetFullPath( System.IO.Path.Combine( basePath, fbxRelative ) );\n\t\t\t\t\tif ( System.IO.File.Exists( fbxPath ) ) return fbxPath;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tcatch { return null; }\n\t\t}\n\n\t\t// \u2500\u2500 Helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static void ApplyTransform( GameObject go, JsonElement root )\n\t\t{\n\t\t\tif ( root.TryGetProperty( \u0022position\u0022, out var pos ) )\n\t\t\t{\n\t\t\t\tgo.WorldPosition = new Vector3(\n\t\t\t\t\tGetFloat( pos, \u0022x\u0022, 0f ),\n\t\t\t\t\tGetFloat( pos, \u0022y\u0022, 0f ),\n\t\t\t\t\tGetFloat( pos, \u0022z\u0022, 0f )\n\t\t\t\t);\n\t\t\t}\n\t\t\tif ( root.TryGetProperty( \u0022rotation\u0022, out var rot ) )\n\t\t\t{\n\t\t\t\tgo.WorldRotation = Rotation.From(\n\t\t\t\t\tGetFloat( rot, \u0022pitch\u0022, 0f ),\n\t\t\t\t\tGetFloat( rot, \u0022yaw\u0022, 0f ),\n\t\t\t\t\tGetFloat( rot, \u0022roll\u0022, 0f )\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\tprivate static string GetString( JsonElement el, string prop, string fallback = null )\n\t\t{\n\t\t\treturn el.TryGetProperty( prop, out var v ) \u0026\u0026 v.ValueKind == JsonValueKind.String ? v.GetString() : fallback;\n\t\t}\n\n\t\tprivate static float GetFloat( JsonElement el, string prop, float fallback )\n\t\t{\n\t\t\tif ( el.TryGetProperty( prop, out var v ) \u0026\u0026 v.ValueKind == JsonValueKind.Number ) return v.GetSingle();\n\t\t\treturn fallback;\n\t\t}\n\n\t\tprivate static int GetInt( JsonElement el, string prop, int fallback )\n\t\t{\n\t\t\tif ( el.TryGetProperty( prop, out var v ) \u0026\u0026 v.ValueKind == JsonValueKind.Number ) return v.GetInt32();\n\t\t\treturn fallback;\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Reply with this s\u0026box project\u0027s Assets folder so Blender can\n\t\t/// auto-populate its addon path on connect. Carries diagnostic\n\t\t/// fields too so the Blender side can log what failed when\n\t\t/// assetsDir comes back null.\n\t\t/// \u003C/summary\u003E\n\t\tprivate static string HandleGetProjectInfo( JsonElement root )\n\t\t{\n\t\t\tstring discoveryMethod = \u0022none\u0022;\n\t\t\tstring projectCurrentName = null;\n\t\t\tstring projectCurrentRoot = null;\n\t\t\tstring sessionState = \u0022missing\u0022;\n\t\t\tstring sceneState = \u0022missing\u0022;\n\t\t\tstring sceneResourcePath = null;\n\t\t\tstring fullScenePath = null;\n\t\t\tstring discoveryError = null;\n\t\t\tstring assetsDir = null;\n\n\t\t\t// Primary: Project.Current \u2014 scene-independent.\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif ( Sandbox.Project.Current != null )\n\t\t\t\t{\n\t\t\t\t\tprojectCurrentName = Sandbox.Project.Current.Config?.Title;\n\t\t\t\t\tprojectCurrentRoot = Sandbox.Project.Current.GetRootPath();\n\t\t\t\t\tif ( Sandbox.Project.Current.HasAssetsPath() )\n\t\t\t\t\t{\n\t\t\t\t\t\tassetsDir = Sandbox.Project.Current.GetAssetsPath();\n\t\t\t\t\t\tdiscoveryMethod = \u0022Project.Current\u0022;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tdiscoveryError = \u0022Project.Current: \u0022 \u002B ex.GetType().Name \u002B \u0022: \u0022 \u002B ex.Message;\n\t\t\t}\n\n\t\t\t// Fallback: scene-walk (only if Project.Current didn\u0027t resolve).\n\t\t\tif ( assetsDir == null )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tvar session = SceneEditorSession.Active;\n\t\t\t\t\tif ( session != null )\n\t\t\t\t\t{\n\t\t\t\t\t\tsessionState = \u0022active\u0022;\n\t\t\t\t\t\tif ( session.Scene != null )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tsceneState = \u0022active\u0022;\n\t\t\t\t\t\t\tsceneResourcePath = session.Scene.Source?.ResourcePath;\n\t\t\t\t\t\t\tif ( !string.IsNullOrEmpty( sceneResourcePath ) )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tfullScenePath = Sandbox.FileSystem.Mounted.GetFullPath( sceneResourcePath );\n\t\t\t\t\t\t\t\tif ( !string.IsNullOrEmpty( fullScenePath ) )\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tvar dir = System.IO.Path.GetDirectoryName( fullScenePath );\n\t\t\t\t\t\t\t\t\twhile ( dir != null )\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tvar candidate = System.IO.Path.Combine( dir, \u0022Assets\u0022 );\n\t\t\t\t\t\t\t\t\t\tif ( System.IO.Directory.Exists( candidate ) )\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tassetsDir = candidate;\n\t\t\t\t\t\t\t\t\t\t\tdiscoveryMethod = \u0022scene-walk\u0022;\n\t\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\tdir = System.IO.Path.GetDirectoryName( dir );\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch ( Exception ex )\n\t\t\t\t{\n\t\t\t\t\tdiscoveryError = (discoveryError == null ? \u0022\u0022 : discoveryError \u002B \u0022; \u0022)\n\t\t\t\t\t\t\u002B \u0022scene-walk: \u0022 \u002B ex.GetType().Name \u002B \u0022: \u0022 \u002B ex.Message;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tstring projectName = projectCurrentName;\n\t\t\tif ( projectName == null \u0026\u0026 !string.IsNullOrEmpty( assetsDir ) )\n\t\t\t{\n\t\t\t\tvar projectDir = System.IO.Path.GetDirectoryName( assetsDir );\n\t\t\t\tif ( !string.IsNullOrEmpty( projectDir ) )\n\t\t\t\t\tprojectName = System.IO.Path.GetFileName( projectDir );\n\t\t\t}\n\n\t\t\tstatic string J( string s ) =\u003E s == null ? \u0022null\u0022 : System.Text.Json.JsonSerializer.Serialize( s );\n\n\t\t\tvar sb = new System.Text.StringBuilder();\n\t\t\tsb.Append( \u0022{\\\u0022ok\\\u0022:true\u0022 );\n\t\t\tsb.Append( \u0022,\\\u0022assetsDir\\\u0022:\u0022 ).Append( J( assetsDir ) );\n\t\t\tsb.Append( \u0022,\\\u0022projectName\\\u0022:\u0022 ).Append( J( projectName ) );\n\t\t\tsb.Append( \u0022,\\\u0022diag\\\u0022:{\u0022 );\n\t\t\tsb.Append( \u0022\\\u0022discoveryMethod\\\u0022:\u0022 ).Append( J( discoveryMethod ) );\n\t\t\tsb.Append( \u0022,\\\u0022projectCurrentRoot\\\u0022:\u0022 ).Append( J( projectCurrentRoot ) );\n\t\t\tsb.Append( \u0022,\\\u0022sessionState\\\u0022:\u0022 ).Append( J( sessionState ) );\n\t\t\tsb.Append( \u0022,\\\u0022sceneState\\\u0022:\u0022 ).Append( J( sceneState ) );\n\t\t\tsb.Append( \u0022,\\\u0022sceneResourcePath\\\u0022:\u0022 ).Append( J( sceneResourcePath ) );\n\t\t\tsb.Append( \u0022,\\\u0022fullScenePath\\\u0022:\u0022 ).Append( J( fullScenePath ) );\n\t\t\tsb.Append( \u0022,\\\u0022discoveryError\\\u0022:\u0022 ).Append( J( discoveryError ) );\n\t\t\tsb.Append( \u0022}}\u0022 );\n\t\t\treturn sb.ToString();\n\t\t}\n\n\t\tinternal static string GetProjectAssetsDir()\n\t\t{\n\t\t\t// Primary: Project.Current \u2014 works regardless of whether a scene is\n\t\t\t// loaded or saved. The editor sets this when the project opens.\n\t\t\ttry\n\t\t\t{\n\t\t\t\tif ( Sandbox.Project.Current != null \u0026\u0026 Sandbox.Project.Current.HasAssetsPath() )\n\t\t\t\t\treturn Sandbox.Project.Current.GetAssetsPath();\n\t\t\t}\n\t\t\tcatch { }\n\n\t\t\t// Fallback: walk up from the active scene\u0027s resource path. Useful in\n\t\t\t// edge cases where Project.Current isn\u0027t set but a scene is.\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar session = SceneEditorSession.Active;\n\t\t\t\tif ( session?.Scene != null )\n\t\t\t\t{\n\t\t\t\t\tvar scenePath = session.Scene.Source?.ResourcePath;\n\t\t\t\t\tif ( !string.IsNullOrEmpty( scenePath ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar fullScenePath = Sandbox.FileSystem.Mounted.GetFullPath( scenePath );\n\t\t\t\t\t\tif ( !string.IsNullOrEmpty( fullScenePath ) )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar dir = System.IO.Path.GetDirectoryName( fullScenePath );\n\t\t\t\t\t\t\twhile ( dir != null )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tvar candidate = System.IO.Path.Combine( dir, \u0022Assets\u0022 );\n\t\t\t\t\t\t\t\tif ( System.IO.Directory.Exists( candidate ) ) return candidate;\n\t\t\t\t\t\t\t\tdir = System.IO.Path.GetDirectoryName( dir );\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch { }\n\n\t\t\treturn null;\n\t\t}\n\n\t\tprivate static Material LoadMaterialSafe( string path )\n\t\t{\n\t\t\tif ( string.IsNullOrEmpty( path ) ) return null;\n\t\t\ttry\n\t\t\t{\n\t\t\t\t// The addon rewrites generated vmats IN PLACE (same path) when a\n\t\t\t\t// material is edited. Material.Load can win the race against the\n\t\t\t\t// asset watcher and return the stale compiled version \u2014 live\n\t\t\t\t// material edits then only show up on the NEXT load (a dup, a\n\t\t\t\t// restart). Nudge the compile first; no-op when up to date.\n\t\t\t\ttry { AssetSystem.FindByPath( path )?.Compile( false ); }\n\t\t\t\tcatch { }\n\t\t\t\treturn Material.Load( path );\n\t\t\t}\n\t\t\tcatch { return null; }\n\t\t}\n\t}\n}\n"},{"Ident":"kamishell.blender_bridge","Path":"Editor/BlenderBridge/BridgeStatusDot.cs","FileName":"BridgeStatusDot.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":337656,"IsPrivate":false,"Code":"using System;\nusing Editor;\nusing Sandbox;\n\nnamespace BlenderBridge\n{\n\t/// \u003Csummary\u003E\n\t/// Small colored dot that mirrors BlenderBridgeServer state.\n\t/// Red = stopped. Yellow = running, no client. Green = client connected.\n\t/// Designed to be embedded next to a title label; functionality (click, tooltip, popover) can grow on this class.\n\t/// \u003C/summary\u003E\n\tpublic class BridgeStatusDot : Widget\n\t{\n\t\tprivate Label _dot;\n\t\tprivate System.Threading.Timer _pollTimer;\n\t\tprivate volatile bool _needsRefresh = true;\n\n\t\tprivate bool _lastRunning;\n\t\tprivate bool _lastClient;\n\n\t\tpublic BridgeStatusDot() : base( null )\n\t\t{\n\t\t\tToolTip = \u0022Bridge status\u0022;\n\t\t\tFixedWidth = 16;\n\t\t\tFixedHeight = 16;\n\n\t\t\t_dot = new Label( \u0022\u25CF\u0022 );\n\t\t\t_dot.SetStyles( \u0022color: #f87171; font-size: 14px;\u0022 );\n\n\t\t\tvar row = Layout.Row();\n\t\t\trow.Add( _dot );\n\t\t\tLayout = row;\n\n\t\t\t_pollTimer = new System.Threading.Timer( _ =\u003E RequestRefresh(), null, 500, 500 );\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Timer tick, on a threadpool thread. _needsRefresh is only consumed\n\t\t/// in OnPaint and nothing else ever requests a repaint, so an\n\t\t/// unattended dot would show stale state indefinitely. Hop to the main\n\t\t/// thread and ask for one explicitly.\n\t\t/// \u003C/summary\u003E\n\t\tprivate void RequestRefresh()\n\t\t{\n\t\t\t_needsRefresh = true;\n\t\t\tGameTask.RunInThreadAsync( async () =\u003E\n\t\t\t{\n\t\t\t\tawait GameTask.MainThread();\n\t\t\t\tif ( IsValid )\n\t\t\t\t\tUpdate();\n\t\t\t} );\n\t\t}\n\n\t\tpublic override void OnDestroyed()\n\t\t{\n\t\t\t_pollTimer?.Dispose();\n\t\t\t_pollTimer = null;\n\t\t\tbase.OnDestroyed();\n\t\t}\n\n\t\tprotected override void OnPaint()\n\t\t{\n\t\t\tbase.OnPaint();\n\t\t\tif ( !_needsRefresh ) return;\n\t\t\t_needsRefresh = false;\n\t\t\tRefresh();\n\t\t}\n\n\t\tprivate void Refresh()\n\t\t{\n\t\t\tif ( _dot == null ) return;\n\n\t\t\tvar running = BlenderBridgeServer.IsRunning;\n\t\t\tvar client = BlenderBridgeServer.HasActiveClient;\n\n\t\t\tif ( running == _lastRunning \u0026\u0026 client == _lastClient ) return;\n\t\t\t_lastRunning = running;\n\t\t\t_lastClient = client;\n\n\t\t\tstring color;\n\t\t\tstring tip;\n\t\t\tif ( !running )      { color = \u0022#f87171\u0022; tip = \u0022Bridge: stopped\u0022; }\n\t\t\telse if ( client )   { color = \u0022#4ade80\u0022; tip = $\u0022Bridge: 1 client connected \u00B7 port {BlenderBridgeServer.Port}\u0022; }\n\t\t\telse                 { color = \u0022#fbbf24\u0022; tip = $\u0022Bridge: idle \u00B7 port {BlenderBridgeServer.Port}\u0022; }\n\n\t\t\t_dot.SetStyles( $\u0022color: {color}; font-size: 14px;\u0022 );\n\t\t\tToolTip = tip;\n\t\t}\n\t}\n}\n"},{"Ident":"kamishell.blender_bridge","Path":"Editor/BlenderBridge/BridgePersistence.cs","FileName":"BridgePersistence.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":337656,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Text.Json;\nusing Editor;\nusing HalfEdgeMesh;\nusing Sandbox;\n\nnamespace BlenderBridge\n{\n\t/// \u003Csummary\u003E\n\t/// Persistence layer for bridge mesh data.\n\t/// Writes a sidecar manifest (.bridge.json) alongside the scene file\n\t/// and binary mesh cache files so geometry survives play mode without\n\t/// bloating the scene JSON.\n\t/// \u003C/summary\u003E\n\tinternal static class BridgePersistence\n\t{\n\t\tprivate const string CacheDirName = \u0022.sbox_bridge_cache\u0022;\n\t\tprivate const int ManifestVersion = 1;\n\n\t\t// \u2500\u2500 Public API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t// Deferred saves. Writing cache \u002B manifest synchronously on every\n\t\t// inbound message made each Blender edit an editor hitch: the mesh\n\t\t// extraction \u002B per-face attribute reflection is per-object work, and\n\t\t// SaveManifest re-walks the WHOLE scene (counting every mesh\u0027s\n\t\t// handles) \u2014 during a full resync that\u0027s O(n\u00B2). Queue instead; the\n\t\t// poll tick flushes after a quiet period, and play-mode entry /\n\t\t// server stop flush immediately so nothing is lost where it matters.\n\t\tprivate static readonly Dictionary\u003Cstring, GameObject\u003E _pendingSaves = new();\n\t\tprivate static DateTime _lastQueueTime = DateTime.MinValue;\n\t\tprivate const double SaveQuietSeconds = 1.5;\n\n\t\t/// \u003Csummary\u003EQueue a cache\u002Bmanifest save after a create or mesh update.\u003C/summary\u003E\n\t\tinternal static void SaveAfterChange( Scene scene, string bridgeId, GameObject go )\n\t\t{\n\t\t\tif ( scene == null || go == null ) return;\n\t\t\t_pendingSaves[bridgeId] = go;\n\t\t\t_lastQueueTime = DateTime.UtcNow;\n\t\t}\n\n\t\t/// \u003Csummary\u003EDrop all queued saves (server restart \u2014 stale GameObjects).\u003C/summary\u003E\n\t\tinternal static void ClearPendingSaves()\n\t\t{\n\t\t\t_pendingSaves.Clear();\n\t\t}\n\n\t\t/// \u003Csummary\u003EWrite queued caches \u002B one manifest. Called every poll tick\n\t\t/// (respects the quiet period) and with force=true on play-mode entry\n\t\t/// and server stop.\u003C/summary\u003E\n\t\tinternal static void FlushPendingSaves( Scene scene, bool force = false )\n\t\t{\n\t\t\tif ( scene == null || _pendingSaves.Count == 0 ) return;\n\t\t\tif ( !force \u0026\u0026 (DateTime.UtcNow - _lastQueueTime).TotalSeconds \u003C SaveQuietSeconds ) return;\n\n\t\t\tforeach ( var (bridgeId, go) in _pendingSaves )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tif ( go == null || !go.IsValid ) continue;\n\t\t\t\t\tvar meshComp = go.Components.Get\u003CMeshComponent\u003E();\n\t\t\t\t\tif ( meshComp?.Mesh == null ) continue;\n\n\t\t\t\t\tvar extracted = BlenderBridgeDispatcher.ExtractMeshData( meshComp.Mesh );\n\t\t\t\t\tif ( extracted == null ) continue;\n\n\t\t\t\t\tvar cachePath = GetCachePath( scene, bridgeId );\n\t\t\t\t\tif ( cachePath != null )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar (faceMats, faceUVs) = ExtractFaceAttributes( meshComp.Mesh );\n\t\t\t\t\t\tSaveMeshCache( cachePath, extracted.Value.Vertices, extracted.Value.Faces, faceMats, faceUVs );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcatch ( Exception ex )\n\t\t\t\t{\n\t\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Persistence save error ({bridgeId}): {ex.Message}\u0022 );\n\t\t\t\t}\n\t\t\t}\n\t\t\t_pendingSaves.Clear();\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tSaveManifest( scene );\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Manifest save error: {ex.Message}\u0022 );\n\t\t\t}\n\t\t}\n\n\t\t/// \u003Csummary\u003ERemove cache file for a deleted bridge object.\u003C/summary\u003E\n\t\tinternal static void RemoveFromCache( string bridgeId )\n\t\t{\n\t\t\t// A queued save for a deleted object must not resurrect its cache.\n\t\t\t_pendingSaves.Remove( bridgeId );\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar scene = BridgeSceneHelper.ResolveScene();\n\t\t\t\tif ( scene == null ) return;\n\n\t\t\t\tvar cachePath = GetCachePath( scene, bridgeId );\n\t\t\t\tif ( cachePath != null \u0026\u0026 File.Exists( cachePath ) )\n\t\t\t\t\tFile.Delete( cachePath );\n\n\t\t\t\tSaveManifest( scene );\n\t\t\t}\n\t\t\tcatch { }\n\t\t}\n\n\t\t/// \u003Csummary\u003ERestore mesh data from cache for bridge objects missing geometry.\n\t\t/// Called on server start and after exiting play mode.\u003C/summary\u003E\n\t\tinternal static void RestoreFromCache( Scene scene )\n\t\t{\n\t\t\tif ( scene == null ) return;\n\n\t\t\tvar cacheDir = GetCacheDir( scene );\n\t\t\tif ( cacheDir == null || !Directory.Exists( cacheDir ) ) return;\n\n\t\t\tint restored = 0;\n\n\t\t\tforeach ( var root in scene.Children )\n\t\t\t{\n\t\t\t\tRestoreSubtree( root, cacheDir, ref restored );\n\t\t\t}\n\n\t\t\tif ( restored \u003E 0 )\n\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Restored {restored} mesh(es) from cache\u0022 );\n\t\t}\n\n\t\t/// \u003Csummary\u003ECheck if any bridge state has been saved.\u003C/summary\u003E\n\t\tinternal static bool HasSavedState( Scene scene )\n\t\t{\n\t\t\tif ( scene == null ) return false;\n\t\t\tvar manifestPath = GetManifestPath( scene );\n\t\t\treturn manifestPath != null \u0026\u0026 File.Exists( manifestPath );\n\t\t}\n\n\t\t// \u2500\u2500 Manifest \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static void SaveManifest( Scene scene )\n\t\t{\n\t\t\tvar manifestPath = GetManifestPath( scene );\n\t\t\tif ( manifestPath == null ) return;\n\n\t\t\tvar objects = new Dictionary\u003Cstring, object\u003E();\n\n\t\t\tforeach ( var root in scene.Children )\n\t\t\t\tCollectManifestEntries( root, objects );\n\n\t\t\tvar manifest = new\n\t\t\t{\n\t\t\t\tversion = ManifestVersion,\n\t\t\t\tsavedAt = DateTime.UtcNow.ToString( \u0022o\u0022 ),\n\t\t\t\tobjects\n\t\t\t};\n\n\t\t\tvar json = JsonSerializer.Serialize( manifest, new JsonSerializerOptions\n\t\t\t{\n\t\t\t\tWriteIndented = true,\n\t\t\t\tPropertyNamingPolicy = JsonNamingPolicy.CamelCase\n\t\t\t} );\n\n\t\t\t// Write-to-temp \u002B rename: truncating in place leaves a corrupt\n\t\t\t// manifest behind if a crash or full disk interrupts the write,\n\t\t\t// which then fails restore silently on every cycle.\n\t\t\tvar tmpPath = manifestPath \u002B \u0022.tmp\u0022;\n\t\t\tFile.WriteAllText( tmpPath, json );\n\t\t\tFile.Move( tmpPath, manifestPath, overwrite: true );\n\t\t}\n\n\t\tprivate static void CollectManifestEntries( GameObject node, Dictionary\u003Cstring, object\u003E entries )\n\t\t{\n\t\t\tforeach ( var tag in node.Tags.TryGetAll() )\n\t\t\t{\n\t\t\t\tif ( tag.StartsWith( \u0022bridge_\u0022 ) \u0026\u0026 tag != \u0022bridge_group\u0022 )\n\t\t\t\t{\n\t\t\t\t\tvar bridgeId = tag.Substring( 7 );\n\t\t\t\t\tvar pos = node.WorldPosition;\n\t\t\t\t\tvar rot = node.WorldRotation.Angles();\n\n\t\t\t\t\tvar meshComp = node.Components.Get\u003CMeshComponent\u003E();\n\t\t\t\t\tint vertCount = 0, faceCount = 0;\n\t\t\t\t\tif ( meshComp?.Mesh != null )\n\t\t\t\t\t{\n\t\t\t\t\t\tvertCount = meshComp.Mesh.VertexHandles?.Count() ?? 0;\n\t\t\t\t\t\tfaceCount = meshComp.Mesh.FaceHandles?.Count() ?? 0;\n\t\t\t\t\t}\n\n\t\t\t\t\tentries[bridgeId] = new\n\t\t\t\t\t{\n\t\t\t\t\t\tname = node.Name,\n\t\t\t\t\t\tvertexCount = vertCount,\n\t\t\t\t\t\tfaceCount = faceCount,\n\t\t\t\t\t\tposition = new { x = pos.x, y = pos.y, z = pos.z },\n\t\t\t\t\t\trotation = new { pitch = rot.pitch, yaw = rot.yaw, roll = rot.roll }\n\t\t\t\t\t};\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tforeach ( var child in node.Children )\n\t\t\t\tCollectManifestEntries( child, entries );\n\t\t}\n\n\t\t// \u2500\u2500 Binary Cache \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t// v2 cache layout, magic-prefixed (\u0022BMC2\u0022). v1 files start with the raw\n\t\t// vert count instead \u2014 no real mesh reaches ~845M verts, so the first\n\t\t// uint32 disambiguates and old geometry-only caches keep restoring.\n\t\t//   [uint32 magic][uint32 vertCount][uint32 faceDataLen]\n\t\t//   [float32[] verts][int32[] faces]\n\t\t//   [int32 matCount][string[] matPaths]           \u2014 indexed table\n\t\t//   [int32 faceCount][int32[] perFaceMatIdx]      \u2014 -1 = no material\n\t\t//   [bool hasUVs][per face: int32 n, float32 u,v * n]\n\t\tprivate const uint CacheMagicV2 = 0x32434D42; // \u0022BMC2\u0022\n\n\t\t/// \u003Csummary\u003EWrite binary mesh cache including per-face materials and UVs,\n\t\t/// so a restore doesn\u0027t silently downgrade everything to the dev\n\t\t/// checkerboard with grid UVs.\u003C/summary\u003E\n\t\tprivate static void SaveMeshCache( string path, float[] vertices, int[] faces, string[] faceMaterials, Vector2[][] faceUVs )\n\t\t{\n\t\t\tvar dir = Path.GetDirectoryName( path );\n\t\t\tif ( dir != null )\n\t\t\t\tDirectory.CreateDirectory( dir );\n\n\t\t\t// Write-to-temp \u002B rename so a crash or full disk mid-write can\u0027t\n\t\t\t// leave a truncated cache that fails restore on every cycle.\n\t\t\tvar tmpPath = path \u002B \u0022.tmp\u0022;\n\t\t\tusing ( var fs = new FileStream( tmpPath, FileMode.Create ) )\n\t\t\tusing ( var bw = new BinaryWriter( fs ) )\n\t\t\t{\n\t\t\t\tbw.Write( CacheMagicV2 );\n\t\t\t\tbw.Write( (uint)(vertices.Length / 3) );\n\t\t\t\tbw.Write( (uint)faces.Length );\n\n\t\t\t\tforeach ( var v in vertices )\n\t\t\t\t\tbw.Write( v );\n\n\t\t\t\tforeach ( var f in faces )\n\t\t\t\t\tbw.Write( f );\n\n\t\t\t\t// Per-face materials as an indexed string table.\n\t\t\t\tvar matTable = new List\u003Cstring\u003E();\n\t\t\t\tvar matLookup = new Dictionary\u003Cstring, int\u003E();\n\t\t\t\tvar faceMatIdx = new int[faceMaterials?.Length ?? 0];\n\t\t\t\tfor ( int i = 0; i \u003C faceMatIdx.Length; i\u002B\u002B )\n\t\t\t\t{\n\t\t\t\t\tvar matPath = faceMaterials[i];\n\t\t\t\t\tif ( string.IsNullOrEmpty( matPath ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tfaceMatIdx[i] = -1;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif ( !matLookup.TryGetValue( matPath, out var mi ) )\n\t\t\t\t\t{\n\t\t\t\t\t\tmi = matTable.Count;\n\t\t\t\t\t\tmatTable.Add( matPath );\n\t\t\t\t\t\tmatLookup[matPath] = mi;\n\t\t\t\t\t}\n\t\t\t\t\tfaceMatIdx[i] = mi;\n\t\t\t\t}\n\n\t\t\t\tbw.Write( matTable.Count );\n\t\t\t\tforeach ( var m in matTable )\n\t\t\t\t\tbw.Write( m );\n\t\t\t\tbw.Write( faceMatIdx.Length );\n\t\t\t\tforeach ( var mi in faceMatIdx )\n\t\t\t\t\tbw.Write( mi );\n\n\t\t\t\tbw.Write( faceUVs != null );\n\t\t\t\tif ( faceUVs != null )\n\t\t\t\t{\n\t\t\t\t\tbw.Write( faceUVs.Length );\n\t\t\t\t\tforeach ( var uv in faceUVs )\n\t\t\t\t\t{\n\t\t\t\t\t\tbw.Write( uv?.Length ?? 0 );\n\t\t\t\t\t\tif ( uv == null ) continue;\n\t\t\t\t\t\tforeach ( var p in uv )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbw.Write( p.x );\n\t\t\t\t\t\t\tbw.Write( p.y );\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tFile.Move( tmpPath, path, overwrite: true );\n\t\t}\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Pull per-face material paths and texture coords off a live mesh so a\n\t\t/// cache restore can rebuild more than bare geometry. Face order matches\n\t\t/// ExtractMeshData \u2014 both enumerate FaceHandles. Either result may be\n\t\t/// null (engine API unavailable via reflection); the cache format and\n\t\t/// restore path tolerate that by falling back to current behavior.\n\t\t/// \u003C/summary\u003E\n\t\tprivate static (string[] MatPaths, Vector2[][] FaceUVs) ExtractFaceAttributes( PolygonMesh mesh )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar faceHandles = mesh.FaceHandles.ToList();\n\t\t\t\t// The handle type isn\u0027t directly nameable from here \u2014 derive it\n\t\t\t\t// from the list\u0027s generic argument for the reflection lookups.\n\t\t\t\tvar handleType = faceHandles.GetType().GetGenericArguments()[0];\n\t\t\t\tvar getMat = mesh.GetType().GetMethod( \u0022GetFaceMaterial\u0022, new[] { handleType } );\n\t\t\t\tvar getUVs = mesh.GetType().GetMethod( \u0022GetFaceTextureCoords\u0022, new[] { handleType } );\n\n\t\t\t\tvar mats = getMat != null ? new string[faceHandles.Count] : null;\n\t\t\t\tvar uvs = getUVs != null ? new Vector2[faceHandles.Count][] : null;\n\t\t\t\tbool anyUV = false;\n\n\t\t\t\tfor ( int i = 0; i \u003C faceHandles.Count; i\u002B\u002B )\n\t\t\t\t{\n\t\t\t\t\tif ( mats != null )\n\t\t\t\t\t{\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar m = getMat.Invoke( mesh, new object[] { faceHandles[i] } ) as Material;\n\t\t\t\t\t\t\tvar matPath = m?.ResourcePath;\n\t\t\t\t\t\t\t// Compiled path -\u003E source path, so Material.Load\n\t\t\t\t\t\t\t// resolves it on restore.\n\t\t\t\t\t\t\tif ( matPath != null \u0026\u0026 matPath.EndsWith( \u0022_c\u0022, StringComparison.OrdinalIgnoreCase ) )\n\t\t\t\t\t\t\t\tmatPath = matPath.Substring( 0, matPath.Length - 2 );\n\t\t\t\t\t\t\tmats[i] = matPath;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch { mats = null; }\n\t\t\t\t\t}\n\n\t\t\t\t\tif ( uvs != null )\n\t\t\t\t\t{\n\t\t\t\t\t\ttry\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tif ( getUVs.Invoke( mesh, new object[] { faceHandles[i] } ) is Vector2[] coords \u0026\u0026 coords.Length \u003E 0 )\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tuvs[i] = coords;\n\t\t\t\t\t\t\t\tanyUV = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcatch { uvs = null; }\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn (mats, anyUV ? uvs : null);\n\t\t\t}\n\t\t\tcatch\n\t\t\t{\n\t\t\t\treturn (null, null);\n\t\t\t}\n\t\t}\n\n\t\t/// \u003Csummary\u003ERead binary mesh cache and rebuild PolygonMesh on a GameObject.\u003C/summary\u003E\n\t\tprivate static bool RestoreMeshFromCache( string cachePath, GameObject go )\n\t\t{\n\t\t\tif ( !File.Exists( cachePath ) ) return false;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tusing var fs = new FileStream( cachePath, FileMode.Open );\n\t\t\t\tusing var br = new BinaryReader( fs );\n\n\t\t\t\t// v1 files have no magic \u2014 the first uint32 is the vert count.\n\t\t\t\tvar first = br.ReadUInt32();\n\t\t\t\tbool isV2 = first == CacheMagicV2;\n\t\t\t\tvar vertCount = isV2 ? br.ReadUInt32() : first;\n\t\t\t\tvar faceDataLen = br.ReadUInt32();\n\n\t\t\t\tvar vertices = new Vector3[vertCount];\n\t\t\t\tfor ( int i = 0; i \u003C vertCount; i\u002B\u002B )\n\t\t\t\t{\n\t\t\t\t\tfloat x = br.ReadSingle();\n\t\t\t\t\tfloat y = br.ReadSingle();\n\t\t\t\t\tfloat z = br.ReadSingle();\n\t\t\t\t\tvertices[i] = new Vector3( x, y, z );\n\t\t\t\t}\n\n\t\t\t\tvar faceData = new int[faceDataLen];\n\t\t\t\tfor ( int i = 0; i \u003C faceDataLen; i\u002B\u002B )\n\t\t\t\t\tfaceData[i] = br.ReadInt32();\n\n\t\t\t\t// v2 trailer: material table, per-face material indices, UVs.\n\t\t\t\tstring[] matTable = null;\n\t\t\t\tint[] faceMatIdx = null;\n\t\t\t\tVector2[][] faceUVs = null;\n\t\t\t\tif ( isV2 )\n\t\t\t\t{\n\t\t\t\t\tint matCount = br.ReadInt32();\n\t\t\t\t\tmatTable = new string[matCount];\n\t\t\t\t\tfor ( int i = 0; i \u003C matCount; i\u002B\u002B )\n\t\t\t\t\t\tmatTable[i] = br.ReadString();\n\n\t\t\t\t\tint faceCount = br.ReadInt32();\n\t\t\t\t\tfaceMatIdx = new int[faceCount];\n\t\t\t\t\tfor ( int i = 0; i \u003C faceCount; i\u002B\u002B )\n\t\t\t\t\t\tfaceMatIdx[i] = br.ReadInt32();\n\n\t\t\t\t\tif ( br.ReadBoolean() )\n\t\t\t\t\t{\n\t\t\t\t\t\tint uvFaceCount = br.ReadInt32();\n\t\t\t\t\t\tfaceUVs = new Vector2[uvFaceCount][];\n\t\t\t\t\t\tfor ( int i = 0; i \u003C uvFaceCount; i\u002B\u002B )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint n = br.ReadInt32();\n\t\t\t\t\t\t\tvar uv = new Vector2[n];\n\t\t\t\t\t\t\tfor ( int j = 0; j \u003C n; j\u002B\u002B )\n\t\t\t\t\t\t\t\tuv[j] = new Vector2( br.ReadSingle(), br.ReadSingle() );\n\t\t\t\t\t\t\tfaceUVs[i] = uv;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Parse face groups\n\t\t\t\tvar faceGroups = new List\u003Cint[]\u003E();\n\t\t\t\tint idx = 0;\n\t\t\t\twhile ( idx \u003C faceData.Length )\n\t\t\t\t{\n\t\t\t\t\tint fvc = faceData[idx\u002B\u002B];\n\t\t\t\t\tif ( idx \u002B fvc \u003E faceData.Length ) break;\n\t\t\t\t\tvar face = new int[fvc];\n\t\t\t\t\tfor ( int i = 0; i \u003C fvc; i\u002B\u002B )\n\t\t\t\t\t\tface[i] = faceData[idx\u002B\u002B];\n\t\t\t\t\tfaceGroups.Add( face );\n\t\t\t\t}\n\n\t\t\t\t// Build PolygonMesh\n\t\t\t\tvar mesh = new PolygonMesh();\n\t\t\t\tvar hVertices = mesh.AddVertices( vertices );\n\n\t\t\t\tvar defaultMat = Material.Load( \u0022materials/dev/reflectivity_30.vmat\u0022 );\n\n\t\t\t\t// Attribute arrays are only trusted when they line up with the\n\t\t\t\t// parsed faces \u2014 a mismatch (partial extraction at save time)\n\t\t\t\t// degrades to the old geometry-only behavior.\n\t\t\t\tMaterial[] mats = null;\n\t\t\t\tif ( matTable != null )\n\t\t\t\t{\n\t\t\t\t\tmats = new Material[matTable.Length];\n\t\t\t\t\tfor ( int i = 0; i \u003C matTable.Length; i\u002B\u002B )\n\t\t\t\t\t\tmats[i] = TryLoadMaterial( matTable[i] ) ?? defaultMat;\n\t\t\t\t}\n\t\t\t\tbool hasMats = mats != null \u0026\u0026 faceMatIdx != null \u0026\u0026 faceMatIdx.Length == faceGroups.Count;\n\t\t\t\tbool hasUVs = faceUVs != null \u0026\u0026 faceUVs.Length == faceGroups.Count;\n\n\t\t\t\tint faceIdx = 0;\n\t\t\t\tforeach ( var faceGroup in faceGroups )\n\t\t\t\t{\n\t\t\t\t\tvar faceVerts = faceGroup\n\t\t\t\t\t\t.Where( fi =\u003E fi \u003E= 0 \u0026\u0026 fi \u003C hVertices.Length )\n\t\t\t\t\t\t.Select( fi =\u003E hVertices[fi] )\n\t\t\t\t\t\t.ToArray();\n\t\t\t\t\tif ( faceVerts.Length \u003E= 3 )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar hFace = mesh.AddFace( faceVerts );\n\n\t\t\t\t\t\tvar mat = defaultMat;\n\t\t\t\t\t\tif ( hasMats )\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tvar mi = faceMatIdx[faceIdx];\n\t\t\t\t\t\t\tif ( mi \u003E= 0 \u0026\u0026 mi \u003C mats.Length )\n\t\t\t\t\t\t\t\tmat = mats[mi];\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmesh.SetFaceMaterial( hFace, mat );\n\n\t\t\t\t\t\tif ( hasUVs \u0026\u0026 faceUVs[faceIdx]?.Length == faceVerts.Length )\n\t\t\t\t\t\t\tmesh.SetFaceTextureCoords( hFace, faceUVs[faceIdx] );\n\t\t\t\t\t}\n\t\t\t\t\tfaceIdx\u002B\u002B;\n\t\t\t\t}\n\n\t\t\t\t// Grid-align only when no authored UVs were cached \u2014 running it\n\t\t\t\t// over restored UVs would stomp them, which is the exact bug\n\t\t\t\t// this format exists to fix.\n\t\t\t\tif ( !hasUVs )\n\t\t\t\t\tmesh.TextureAlignToGrid( mesh.Transform );\n\t\t\t\tmesh.SetSmoothingAngle( 40.0f );\n\n\t\t\t\tvar existingMr = go.Components.Get\u003CModelRenderer\u003E();\n\t\t\t\tif ( existingMr != null )\n\t\t\t\t\texistingMr.Destroy();\n\n\t\t\t\tvar meshComp = go.Components.Get\u003CMeshComponent\u003E();\n\t\t\t\tif ( meshComp == null )\n\t\t\t\t\tmeshComp = go.Components.Create\u003CMeshComponent\u003E();\n\n\t\t\t\tmeshComp.Mesh = mesh;\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tBlenderBridgeServer.LogInfo( $\u0022Cache restore failed for {cachePath}: {ex.Message}\u0022 );\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tprivate static Material TryLoadMaterial( string path )\n\t\t{\n\t\t\tif ( string.IsNullOrEmpty( path ) ) return null;\n\t\t\ttry { return Material.Load( path ); }\n\t\t\tcatch { return null; }\n\t\t}\n\n\t\tprivate static void RestoreSubtree( GameObject node, string cacheDir, ref int restored )\n\t\t{\n\t\t\tforeach ( var tag in node.Tags.TryGetAll() )\n\t\t\t{\n\t\t\t\tif ( tag.StartsWith( \u0022bridge_\u0022 ) \u0026\u0026 tag != \u0022bridge_group\u0022 )\n\t\t\t\t{\n\t\t\t\t\tvar bridgeId = tag.Substring( 7 );\n\n\t\t\t\t\t// Only restore if the object has no mesh currently\n\t\t\t\t\tvar meshComp = node.Components.Get\u003CMeshComponent\u003E();\n\t\t\t\t\tif ( meshComp?.Mesh == null || (meshComp.Mesh.VertexHandles?.Count() ?? 0) == 0 )\n\t\t\t\t\t{\n\t\t\t\t\t\tvar cachePath = Path.Combine( cacheDir, $\u0022{bridgeId}.meshcache\u0022 );\n\t\t\t\t\t\tif ( RestoreMeshFromCache( cachePath, node ) )\n\t\t\t\t\t\t\trestored\u002B\u002B;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tforeach ( var child in node.Children )\n\t\t\t\tRestoreSubtree( child, cacheDir, ref restored );\n\t\t}\n\n\t\t// \u2500\u2500 Path helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static string GetManifestPath( Scene scene )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar scenePath = scene.Source?.ResourcePath;\n\t\t\t\tif ( string.IsNullOrEmpty( scenePath ) ) return null;\n\n\t\t\t\tvar fullPath = Sandbox.FileSystem.Mounted.GetFullPath( scenePath );\n\t\t\t\tif ( string.IsNullOrEmpty( fullPath ) ) return null;\n\n\t\t\t\tvar dir = Path.GetDirectoryName( fullPath );\n\t\t\t\tvar name = Path.GetFileNameWithoutExtension( fullPath );\n\t\t\t\treturn Path.Combine( dir, $\u0022{name}.bridge.json\u0022 );\n\t\t\t}\n\t\t\tcatch\n\t\t\t{\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tprivate static string GetCacheDir( Scene scene )\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar assetsDir = BlenderBridgeDispatcher.GetProjectAssetsDir();\n\t\t\t\tif ( assetsDir == null ) return null;\n\n\t\t\t\tvar projectRoot = Path.GetDirectoryName( assetsDir );\n\t\t\t\tif ( projectRoot == null ) return null;\n\n\t\t\t\treturn Path.Combine( projectRoot, CacheDirName );\n\t\t\t}\n\t\t\tcatch\n\t\t\t{\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\n\t\tprivate static string GetCachePath( Scene scene, string bridgeId )\n\t\t{\n\t\t\tvar dir = GetCacheDir( scene );\n\t\t\tif ( dir == null ) return null;\n\t\t\treturn Path.Combine( dir, $\u0022{bridgeId}.meshcache\u0022 );\n\t\t}\n\t}\n}\n"},{"Ident":"kamishell.blender_bridge","Path":"Editor/BlenderBridge/BlenderBridgeServer.cs","FileName":"BlenderBridgeServer.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":337656,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Concurrent;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\nusing System.Net;\nusing System.Text;\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing Editor;\nusing Sandbox;\n\nnamespace BlenderBridge\n{\n\t/// \u003Csummary\u003E\n\t/// HTTP server for bidirectional scene sync with Blender (v2).\n\t/// Sequence-based echo prevention, session tracking, play mode detection.\n\t///\n\t/// Routes:\n\t///   POST /message \u2014 Blender sends scene changes to s\u0026amp;box\n\t///   GET  /poll    \u2014 Blender polls for scene changes (returns {sessionId, sboxSeq, messages})\n\t///   GET  /status  \u2014 Health check with session info\n\t/// \u003C/summary\u003E\n\tpublic static class BlenderBridgeServer\n\t{\n\t\t[ConVar( \u0022bridge_port\u0022, ConVarFlags.Saved )]\n\t\tpublic static int Port { get; set; } = 8099;\n\n\t\t[ConVar( \u0022bridge_autostart\u0022, ConVarFlags.Saved )]\n\t\tpublic static bool AutoStart { get; set; } = true;\n\n\t\t[ConCmd( \u0022bridge_start\u0022 )]\n\t\tpublic static void CmdStart() =\u003E StartServer();\n\n\t\t[ConCmd( \u0022bridge_stop\u0022 )]\n\t\tpublic static void CmdStop() =\u003E StopServer();\n\n\t\t[ConCmd( \u0022bridge_status\u0022 )]\n\t\tpublic static void CmdStatus()\n\t\t{\n\t\t\tif ( IsRunning )\n\t\t\t\tLog.Info( $\u0022[BlenderBridge] Running on port {Port}, session={SessionId}, seq={SboxSeq}, {_outbox.Count} queued\u0022 );\n\t\t\telse\n\t\t\t\tLog.Info( \u0022[BlenderBridge] Not running. Type bridge_start to start.\u0022 );\n\t\t}\n\n\t\t// \u2500\u2500 Public state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\t\tpublic static bool IsRunning =\u003E _listener != null \u0026\u0026 _listener.IsListening;\n\n\t\t/// \u003Csummary\u003ESession ID \u2014 changes on every server start, enables Blender reconnection detection.\u003C/summary\u003E\n\t\tpublic static string SessionId { get; private set; } = \u0022\u0022;\n\n\t\t/// \u003Csummary\u003EMonotonic sequence counter for outgoing messages.\u003C/summary\u003E\n\t\tpublic static int SboxSeq { get; internal set; } = 0;\n\n\t\t/// \u003Csummary\u003ETrue if a Blender client has polled within the last 5 seconds.\u003C/summary\u003E\n\t\tpublic static bool HasActiveClient =\u003E (DateTime.UtcNow - _lastPollTime).TotalSeconds \u003C 5.0;\n\n\t\tinternal static readonly JsonSerializerOptions JsonOptions = new()\n\t\t{\n\t\t\tPropertyNamingPolicy = JsonNamingPolicy.CamelCase,\n\t\t\tDefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,\n\t\t\tWriteIndented = false\n\t\t};\n\n\t\t// \u2500\u2500 Internal state \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\t\tprivate static HttpListener _listener;\n\t\tprivate static CancellationTokenSource _cts;\n\t\tprivate static readonly ConcurrentQueue\u003Cstring\u003E _outbox = new();\n\t\tprivate static DateTime _lastPollTime = DateTime.MinValue;\n\n\t\t/// \u003Csummary\u003ESerializes /poll handlers so concurrent pollers can\u0027t interleave outbox drains.\u003C/summary\u003E\n\t\tprivate static readonly SemaphoreSlim _pollGate = new( 1, 1 );\n\n\t\t/// \u003Csummary\u003EMessages drained from the outbox but whose response write failed \u2014\n\t\t/// redelivered (oldest first) on the next poll instead of being lost. Guarded by _pollGate.\u003C/summary\u003E\n\t\tprivate static readonly List\u003Cstring\u003E _undelivered = new();\n\n\t\t// \u2500\u2500 Lifecycle \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static bool _autoStartAttempted;\n\n\t\t/// \u003Csummary\u003E\n\t\t/// Auto-start hook that fires whether or not the dock is in the saved\n\t\t/// layout. Previously this lived in the dock\u0027s static constructor, so a\n\t\t/// layout without the dock silently disabled auto-start \u2014 and opening\n\t\t/// the dock to investigate started the server, masking the failure.\n\t\t/// Runs on the editor main thread; one-shot.\n\t\t/// \u003C/summary\u003E\n\t\t[EditorEvent.Frame]\n\t\tprivate static void AutoStartOnEditorLoad()\n\t\t{\n\t\t\tif ( _autoStartAttempted ) return;\n\t\t\t_autoStartAttempted = true;\n\n\t\t\tif ( AutoStart \u0026\u0026 !IsRunning )\n\t\t\t\tStartServer();\n\t\t}\n\n\t\tpublic static void StartServer()\n\t\t{\n\t\t\tif ( _listener != null \u0026\u0026 _listener.IsListening )\n\t\t\t{\n\t\t\t\tLogInfo( \u0022Blender Bridge is already running.\u0022 );\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\t// Generate new session ID (Blender detects this change and resyncs)\n\t\t\t\tSessionId = Guid.NewGuid().ToString( \u0022N\u0022 ).Substring( 0, 8 );\n\t\t\t\tSboxSeq = 0;\n\t\t\t\tBlenderBridgeDispatcher.ResetState();\n\n\t\t\t\t// Drop any undelivered messages from a previous session \u2014 Blender\n\t\t\t\t// resyncs on session change, so replaying stale deletes/updates\n\t\t\t\t// into the new session would only cause harm.\n\t\t\t\t_pollGate.Wait();\n\t\t\t\ttry { _undelivered.Clear(); }\n\t\t\t\tfinally { _pollGate.Release(); }\n\n\t\t\t\t_listener = new HttpListener();\n\t\t\t\t_listener.Prefixes.Add( $\u0022http://localhost:{Port}/\u0022 );\n\t\t\t\t_listener.Prefixes.Add( $\u0022http://127.0.0.1:{Port}/\u0022 );\n\t\t\t\t_listener.Start();\n\n\t\t\t\t_cts = new CancellationTokenSource();\n\t\t\t\tTask.Run( () =\u003E ListenLoop( _cts.Token ) );\n\t\t\t\tTask.Run( () =\u003E PollLoop( _cts.Token ) );\n\n\t\t\t\tLogInfo( $\u0022Blender Bridge started on port {Port} (session={SessionId})\u0022 );\n\n\t\t\t\t// Restore cached meshes if available\n\t\t\t\ttry { BridgePersistence.RestoreFromCache( BridgeSceneHelper.ResolveScene() ); }\n\t\t\t\tcatch ( Exception ex ) { LogInfo( $\u0022Cache restore skipped: {ex.Message}\u0022 ); }\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tLogError( $\u0022Failed to start Blender Bridge: {ex.Message}\u0022 );\n\t\t\t}\n\t\t}\n\n\t\tpublic static void StopServer()\n\t\t{\n\t\t\t// Queued mesh-cache saves must land before shutdown \u2014 the next\n\t\t\t// session\u0027s restore reads them.\n\t\t\ttry { BridgePersistence.FlushPendingSaves( BridgeSceneHelper.ResolveScene(), force: true ); }\n\t\t\tcatch { }\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\t_cts?.Cancel();\n\t\t\t\ttry { _listener?.Stop(); } catch { }\n\t\t\t\ttry { _listener?.Close(); } catch { }\n\t\t\t\t_listener = null;\n\t\t\t\twhile ( _outbox.TryDequeue( out _ ) ) { }\n\t\t\t\tLogInfo( \u0022Blender Bridge stopped.\u0022 );\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\ttry { LogError( $\u0022Error stopping Blender Bridge: {ex.Message}\u0022 ); } catch { }\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 HTTP listen loop \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static async Task ListenLoop( CancellationToken token )\n\t\t{\n\t\t\twhile ( !token.IsCancellationRequested \u0026\u0026 _listener != null \u0026\u0026 _listener.IsListening )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tvar context = await _listener.GetContextAsync();\n\t\t\t\t\t_ = Task.Run( () =\u003E HandleRequest( context, token ), token );\n\t\t\t\t}\n\t\t\t\tcatch ( Exception ex ) when ( ex is not ObjectDisposedException )\n\t\t\t\t{\n\t\t\t\t\tif ( !token.IsCancellationRequested )\n\t\t\t\t\t\tLogError( $\u0022Bridge listen loop error: {ex.Message}\u0022 );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tprivate static async Task HandleRequest( HttpListenerContext context, CancellationToken token )\n\t\t{\n\t\t\tvar req = context.Request;\n\t\t\tvar res = context.Response;\n\n\t\t\tres.Headers.Add( \u0022Access-Control-Allow-Origin\u0022, \u0022*\u0022 );\n\t\t\tres.Headers.Add( \u0022Access-Control-Allow-Methods\u0022, \u0022GET, POST, OPTIONS\u0022 );\n\t\t\tres.Headers.Add( \u0022Access-Control-Allow-Headers\u0022, \u0022*\u0022 );\n\t\t\t// Browsers may cache GET responses (/debug, /status) and show stale\n\t\t\t// state during diagnosis \u2014 forbid caching outright.\n\t\t\tres.Headers.Add( \u0022Cache-Control\u0022, \u0022no-store\u0022 );\n\n\t\t\tif ( req.HttpMethod == \u0022OPTIONS\u0022 ) { res.StatusCode = 200; res.Close(); return; }\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tvar path = req.Url.AbsolutePath.TrimEnd( \u0027/\u0027 );\n\n\t\t\t\tswitch ( path )\n\t\t\t\t{\n\t\t\t\t\tcase \u0022/message\u0022 when req.HttpMethod == \u0022POST\u0022:\n\t\t\t\t\t\tawait HandleIncomingMessage( req, res );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \u0022/poll\u0022 when req.HttpMethod == \u0022GET\u0022:\n\t\t\t\t\t\tawait HandlePoll( res );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tcase \u0022/debug\u0022 when req.HttpMethod == \u0022GET\u0022:\n\t\t\t\t\t\tawait HandleDebug( res );\n\t\t\t\t\t\tbreak;\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tawait HandleStatus( res );\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tLogError( $\u0022Request error: {ex.Message}\u0022 );\n\t\t\t\ttry { res.StatusCode = 500; res.Close(); } catch { }\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 POST /message \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static async Task HandleIncomingMessage( HttpListenerRequest req, HttpListenerResponse res )\n\t\t{\n\t\t\tusing var reader = new StreamReader( req.InputStream, Encoding.UTF8 );\n\t\t\tvar body = await reader.ReadToEndAsync();\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tusing var doc = JsonDocument.Parse( body );\n\t\t\t\tvar root = doc.RootElement;\n\n\t\t\t\t// Reject echoed messages from s\u0026box itself\n\t\t\t\tvar origin = root.TryGetProperty( \u0022origin\u0022, out var o ) ? o.GetString() : null;\n\t\t\t\tif ( origin == \u0022sbox\u0022 )\n\t\t\t\t{\n\t\t\t\t\tres.StatusCode = 200;\n\t\t\t\t\tres.Close();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Dispatch on the main thread and capture response\n\t\t\t\tstring responseJson = \u0022{\\\u0022ok\\\u0022:true}\u0022;\n\t\t\t\tawait GameTask.RunInThreadAsync( async () =\u003E\n\t\t\t\t{\n\t\t\t\t\tawait GameTask.MainThread();\n\t\t\t\t\tresponseJson = BlenderBridgeDispatcher.Dispatch( root );\n\t\t\t\t} );\n\n\t\t\t\tres.StatusCode = 200;\n\t\t\t\tres.ContentType = \u0022application/json\u0022;\n\t\t\t\tvar responseBytes = Encoding.UTF8.GetBytes( responseJson );\n\t\t\t\tawait res.OutputStream.WriteAsync( responseBytes, 0, responseBytes.Length );\n\t\t\t\tres.Close();\n\t\t\t}\n\t\t\tcatch ( Exception ex )\n\t\t\t{\n\t\t\t\tLogError( $\u0022Error handling message: {ex.Message}\u0022 );\n\t\t\t\tres.StatusCode = 400;\n\t\t\t\t// Serialize \u2014 ex.Message often contains Windows paths whose\n\t\t\t\t// backslashes would otherwise produce invalid JSON.\n\t\t\t\tvar err = Encoding.UTF8.GetBytes( JsonSerializer.Serialize( new { error = ex.Message }, JsonOptions ) );\n\t\t\t\tawait res.OutputStream.WriteAsync( err, 0, err.Length );\n\t\t\t\tres.Close();\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 GET /poll \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static async Task HandlePoll( HttpListenerResponse res )\n\t\t{\n\t\t\t_lastPollTime = DateTime.UtcNow;\n\n\t\t\t// Serialize pollers so a concurrent /poll (e.g. a debug probe racing\n\t\t\t// the addon) can\u0027t interleave a drain, and hold drained messages in\n\t\t\t// _undelivered until the response write succeeds \u2014 a failed write\n\t\t\t// otherwise loses deleted/object_created/mesh_updated messages\n\t\t\t// permanently, since state was already updated at broadcast time.\n\t\t\tawait _pollGate.WaitAsync();\n\t\t\ttry\n\t\t\t{\n\t\t\t\t// Snapshot seq BEFORE draining: a broadcast landing between the\n\t\t\t\t// drain and response serialization would otherwise make this\n\t\t\t\t// response claim a seq whose message it doesn\u0027t contain, misfiring\n\t\t\t\t// client-side gap detection. Under-claiming (message included, seq\n\t\t\t\t// not yet claimed) is the safe direction.\n\t\t\t\tvar seqSnapshot = SboxSeq;\n\n\t\t\t\t// Oldest first: redeliveries from a failed write, then new messages.\n\t\t\t\tvar messages = new List\u003Cstring\u003E( _undelivered );\n\t\t\t\t_undelivered.Clear();\n\t\t\t\twhile ( _outbox.TryDequeue( out var msg ) )\n\t\t\t\t\tmessages.Add( msg );\n\n\t\t\t\tres.StatusCode = 200;\n\t\t\t\tres.ContentType = \u0022application/json\u0022;\n\n\t\t\t\t// New v2 format: {sessionId, sboxSeq, messages}\n\t\t\t\tstring messagesJson = messages.Count == 0\n\t\t\t\t\t? \u0022[]\u0022\n\t\t\t\t\t: \u0022[\u0022 \u002B string.Join( \u0022,\u0022, messages ) \u002B \u0022]\u0022;\n\n\t\t\t\tvar playing = BlenderBridgeDispatcher.IsPlayingSnapshot ? \u0022true\u0022 : \u0022false\u0022;\n\t\t\t\tvar json = $\u0022{{\\\u0022sessionId\\\u0022:\\\u0022{SessionId}\\\u0022,\\\u0022sboxSeq\\\u0022:{seqSnapshot},\\\u0022playing\\\u0022:{playing},\\\u0022messages\\\u0022:{messagesJson}}}\u0022;\n\n\t\t\t\tvar bytes = Encoding.UTF8.GetBytes( json );\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tawait res.OutputStream.WriteAsync( bytes, 0, bytes.Length );\n\t\t\t\t\tres.Close();\n\t\t\t\t}\n\t\t\t\tcatch\n\t\t\t\t{\n\t\t\t\t\t// The poller never received these \u2014 keep them for the next poll.\n\t\t\t\t\t_undelivered.AddRange( messages );\n\t\t\t\t\tthrow;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\t_pollGate.Release();\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 GET /debug \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t/// \u003Csummary\u003ERead-only diagnostic dump: scene, bridge objects with their\n\t\t/// full tag lists, and tracking-dictionary keys. Never mutates state.\u003C/summary\u003E\n\t\tprivate static async Task HandleDebug( HttpListenerResponse res )\n\t\t{\n\t\t\tstring json = \u0022{\\\u0022error\\\u0022:\\\u0022debug dump failed\\\u0022}\u0022;\n\t\t\tawait GameTask.RunInThreadAsync( async () =\u003E\n\t\t\t{\n\t\t\t\tawait GameTask.MainThread();\n\t\t\t\tjson = BlenderBridgeDispatcher.DumpDebugState();\n\t\t\t} );\n\n\t\t\tres.ContentType = \u0022application/json\u0022;\n\t\t\tres.StatusCode = 200;\n\t\t\tvar bytes = Encoding.UTF8.GetBytes( json );\n\t\t\tawait res.OutputStream.WriteAsync( bytes, 0, bytes.Length );\n\t\t\tres.Close();\n\t\t}\n\n\t\t// \u2500\u2500 GET /status \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static async Task HandleStatus( HttpListenerResponse res )\n\t\t{\n\t\t\tres.ContentType = \u0022application/json\u0022;\n\t\t\tres.StatusCode = 200;\n\t\t\tvar status = JsonSerializer.Serialize( new\n\t\t\t{\n\t\t\t\tservice = \u0022BlenderBridge\u0022,\n\t\t\t\trunning = true,\n\t\t\t\tsessionId = SessionId,\n\t\t\t\tsboxSeq = SboxSeq\n\t\t\t}, JsonOptions );\n\t\t\tvar bytes = Encoding.UTF8.GetBytes( status );\n\t\t\tawait res.OutputStream.WriteAsync( bytes, 0, bytes.Length );\n\t\t\tres.Close();\n\t\t}\n\n\t\t// \u2500\u2500 Poll loop: detect s\u0026box-side changes \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tprivate static async Task PollLoop( CancellationToken token )\n\t\t{\n\t\t\twhile ( !token.IsCancellationRequested )\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tawait Task.Delay( 200, token );\n\t\t\t\t\tif ( !HasActiveClient ) continue;\n\n\t\t\t\t\tawait GameTask.RunInThreadAsync( async () =\u003E\n\t\t\t\t\t{\n\t\t\t\t\t\tawait GameTask.MainThread();\n\t\t\t\t\t\tBlenderBridgeDispatcher.PollForChanges();\n\t\t\t\t\t} );\n\t\t\t\t}\n\t\t\t\tcatch ( OperationCanceledException ) { break; }\n\t\t\t\tcatch ( Exception ex )\n\t\t\t\t{\n\t\t\t\t\tLogError( $\u0022Poll error: {ex.Message}\u0022 );\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// \u2500\u2500 Outbox \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\t/// \u003Csummary\u003EQueue a raw JSON message for Blender to pick up on next poll.\u003C/summary\u003E\n\t\tinternal static void SendToAll( string json )\n\t\t{\n\t\t\t_outbox.Enqueue( json );\n\t\t}\n\n\t\t/// \u003Csummary\u003ESerialize an object with auto-incrementing seq and queue it.\u003C/summary\u003E\n\t\tinternal static void Broadcast( object message )\n\t\t{\n\t\t\tvar json = JsonSerializer.Serialize( message, JsonOptions );\n\t\t\tSendToAll( json );\n\t\t}\n\n\t\t/// \u003Csummary\u003EBroadcast with explicit seq increment.\u003C/summary\u003E\n\t\tinternal static void BroadcastWithSeq( object message )\n\t\t{\n\t\t\tSboxSeq\u002B\u002B;\n\t\t\tBroadcast( message );\n\t\t}\n\n\t\t// \u2500\u2500 Logging \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n\t\tinternal static readonly ConcurrentQueue\u003Cstring\u003E LogQueue = new();\n\n\t\tinternal static void LogInfo( string msg )\n\t\t{\n\t\t\tLogQueue.Enqueue( msg );\n\t\t}\n\n\t\tinternal static void LogError( string msg )\n\t\t{\n\t\t\tLog.Error( $\u0022[BlenderBridge] {msg}\u0022 );\n\t\t\tLogQueue.Enqueue( $\u0022[ERROR] {msg}\u0022 );\n\t\t}\n\t}\n}\n"}]}