-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathserver.py
More file actions
1400 lines (1239 loc) · 57.2 KB
/
Copy pathserver.py
File metadata and controls
1400 lines (1239 loc) · 57.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import hou
import json
import struct
import threading
import socket
import time
import difflib
import fnmatch
from itertools import islice
from contextlib import contextmanager
import requests
import tempfile
import traceback
import os
import shutil
import sys
# Try PySide6 first (Houdini 21.0+), fall back to PySide2 (older versions)
try:
from PySide6 import QtWidgets, QtCore
print("Using PySide6 (Houdini 21.0+)")
except ImportError:
try:
from PySide2 import QtWidgets, QtCore
print("Using PySide2 (Houdini 19.5-20.x)")
except ImportError:
print("Warning: Neither PySide6 nor PySide2 found. Some features may not work.")
# Create dummy classes to prevent import errors
class QtCore:
class QTimer:
pass
QtWidgets = None
import io
from contextlib import redirect_stdout, redirect_stderr
# Imports for OPUS import
import zipfile
from urllib.parse import urlparse
import uuid # For unique temp dirs and file processing
# --- NEW: Import render functions ---
# try:
from .HoudiniMCPRender import *
# HMCPLib = HoudiniMCPRender # Alias for easier use
print("HoudiniMCPRender module loaded successfully.")
# except ImportError:
# HMCPLib = None
# print("Warning: HoudiniMCPRender.py not found or failed to import. Rendering tools will be unavailable.")
# ----------------------------------
# Info about the extension (optional metadata)
EXTENSION_NAME = "Houdini MCP"
EXTENSION_VERSION = (0, 1)
EXTENSION_DESCRIPTION = "Connect Houdini to Claude via MCP"
class HoudiniMCPServer:
def __init__(self, host='127.0.0.1', port=9876):
self.host = host
self.port = port
self.running = False
self.server_socket = None
self.client = None
self.buffer = b''
self.timer = None
def start(self):
"""Begin listening on the given port; sets up a QTimer to poll for data."""
if self.running:
print(f"HoudiniMCP server is already running on {self.host}:{self.port}")
return
self._cleanup_client()
self._cleanup_socket()
self._cleanup_timer()
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
self.server_socket.bind((self.host, self.port))
self.server_socket.listen(4)
self.server_socket.setblocking(False)
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self._process_server)
self.timer.start(100)
self.running = True
print(f"HoudiniMCP server started on {self.host}:{self.port}")
except Exception as e:
print(f"Failed to start server: {str(e)}")
self.stop()
def stop(self):
"""Stop listening; close sockets and timers."""
self.running = False
self._cleanup_timer()
self._cleanup_client()
self._cleanup_socket()
print("HoudiniMCP server stopped")
def _cleanup_timer(self):
if self.timer is not None:
try:
self.timer.stop()
except Exception:
pass
self.timer = None
def _cleanup_client(self):
if self.client is not None:
try:
self.client.close()
except Exception:
pass
self.client = None
self.buffer = b''
def _cleanup_socket(self):
if self.server_socket is not None:
try:
self.server_socket.close()
except Exception:
pass
self.server_socket = None
def _process_server(self):
"""
Timer callback to accept connections and process any incoming data.
This runs in the main Houdini thread to avoid concurrency issues.
Protocol: each message is a 4-byte big-endian length prefix
followed by that many bytes of UTF-8 JSON.
"""
if not self.running:
return
try:
# Accept all pending connections; the newest client wins. A stale
# idle client (e.g. an abandoned bridge process) must never be able
# to hold the slot and lock new clients out of the server.
if self.server_socket:
while True:
try:
new_client, address = self.server_socket.accept()
except BlockingIOError:
break
except Exception as e:
print(f"Error accepting connection: {str(e)}")
break
if self.client is not None:
print(f"New connection from {address}; replacing existing client")
self._cleanup_client()
new_client.setblocking(False)
self.client = new_client
print(f"Connected to client: {address}")
if self.client:
try:
data = self.client.recv(8192)
if data:
self.buffer += data
while True:
if len(self.buffer) < 4:
break
msg_len = struct.unpack('>I', self.buffer[:4])[0]
MAX_MSG_LEN = 50 * 1024 * 1024
if msg_len > MAX_MSG_LEN:
print(f"Message too large ({msg_len} bytes), disconnecting client")
self._cleanup_client()
break
if len(self.buffer) < 4 + msg_len:
break
payload = self.buffer[4:4 + msg_len]
self.buffer = self.buffer[4 + msg_len:]
try:
command = json.loads(payload.decode('utf-8'))
response = self.execute_command(command)
response_bytes = json.dumps(response).encode('utf-8')
response_frame = struct.pack('>I', len(response_bytes)) + response_bytes
try:
self.client.sendall(response_frame)
except (BrokenPipeError, ConnectionResetError, OSError) as send_err:
print(f"Failed to send response (client likely disconnected): {send_err}")
self._cleanup_client()
break
except json.JSONDecodeError as e:
print(f"Invalid JSON in message: {e}")
else:
print("Client disconnected (empty recv)")
self._cleanup_client()
except BlockingIOError:
pass
except (ConnectionResetError, BrokenPipeError, OSError) as e:
print(f"Client connection lost: {str(e)}")
self._cleanup_client()
except Exception as e:
print(f"Server error: {str(e)}")
# -------------------------------------------------------------------------
# Command Handling
# -------------------------------------------------------------------------
def execute_command(self, command):
"""Entry point for executing a JSON command from the client."""
try:
return self._execute_command_internal(command)
except Exception as e:
print(f"Error executing command: {str(e)}")
traceback.print_exc()
return {"status": "error", "message": str(e)}
def _execute_command_internal(self, command):
"""
Internal dispatcher that looks up 'cmd_type' from the JSON,
calls the relevant function, and returns a JSON-friendly dict.
"""
cmd_type = command.get("type")
params = command.get("params", {})
# Always-available handlers
handlers = {
"get_scene_info": self.get_scene_info,
"create_node": self.create_node,
"modify_node": self.modify_node,
"delete_node": self.delete_node,
"get_node_info": self.get_node_info,
"execute_code": self.execute_code,
"set_material": self.set_material,
"get_asset_lib_status": self.get_asset_lib_status,
"import_opus_url": self.handle_import_opus_url,
# Graph editing & introspection
"connect_nodes": self.connect_nodes,
"disconnect_input": self.disconnect_input,
"set_parameters": self.set_parameters,
"get_parameter_schema": self.get_parameter_schema,
"set_node_flags": self.set_node_flags,
"layout_children": self.layout_children,
"find_error_nodes": self.find_error_nodes,
"cook_node": self.cook_node,
# VEX wrangles
"create_wrangle": self.create_wrangle,
"set_wrangle_code": self.set_wrangle_code,
# Geometry introspection
"get_geometry_info": self.get_geometry_info,
"get_geometry_data": self.get_geometry_data,
# Add new render handlers
"render_single_view": self.handle_render_single_view,
"render_quad_view": self.handle_render_quad_view,
"render_specific_camera": self.handle_render_specific_camera,
"ping": self._handle_ping,
}
# If user has toggled asset library usage
if getattr(hou.session, "houdinimcp_use_assetlib", False):
asset_handlers = {
"get_asset_categories": self.get_asset_categories,
"search_assets": self.search_assets,
"import_asset": self.import_asset,
}
handlers.update(asset_handlers)
handler = handlers.get(cmd_type)
if not handler:
return {"status": "error", "message": f"Unknown command type: {cmd_type}"}
print(f"Executing handler for {cmd_type}")
with self._undo_group(cmd_type):
result = handler(**params)
print(f"Handler execution complete for {cmd_type}")
return {"status": "success", "result": result}
# Commands that mutate the scene get wrapped in a single undo group so the
# artist can Ctrl+Z any agent action as one step.
MUTATING_COMMANDS = frozenset({
"create_node", "modify_node", "delete_node", "set_material",
"import_opus_url", "import_asset", "connect_nodes", "disconnect_input",
"set_parameters", "set_node_flags", "layout_children",
"create_wrangle", "set_wrangle_code",
})
@contextmanager
def _undo_group(self, cmd_type):
if cmd_type in self.MUTATING_COMMANDS and hasattr(hou, "undos"):
with hou.undos.group(f"MCP: {cmd_type}"):
yield
else:
yield
def _handle_ping(self):
return {"pong": True, "protocol": 1}
# -------------------------------------------------------------------------
# Basic Info & Node Operations
# -------------------------------------------------------------------------
def get_asset_lib_status(self):
"""Checks if the user toggled asset library usage in hou.session."""
use_assetlib = getattr(hou.session, "houdinimcp_use_assetlib", False)
msg = ("Asset library usage is enabled."
if use_assetlib
else "Asset library usage is disabled.")
return {"enabled": use_assetlib, "message": msg}
def get_scene_info(self):
"""Returns basic info about the current .hip file and top-level nodes per context."""
try:
hip_file = hou.hipFile.name()
scene_info = {
"name": os.path.basename(hip_file) if hip_file else "Untitled",
"filepath": hip_file or "",
"fps": hou.fps(),
"start_frame": hou.playbar.frameRange()[0],
"end_frame": hou.playbar.frameRange()[1],
"contexts": {},
}
# Collect per-context node summaries (avoids expensive allSubChildren traversal)
root = hou.node("/")
contexts = ["obj", "shop", "out", "ch", "vex", "stage"]
for ctx_name in contexts:
ctx_node = root.node(ctx_name)
if ctx_node:
children = ctx_node.children()
scene_info["contexts"][ctx_name] = {
"count": len(children),
"nodes": [
{
"name": node.name(),
"path": node.path(),
"type": node.type().name(),
}
for node in children[:20]
],
}
return scene_info
except Exception as e:
traceback.print_exc()
return {"error": str(e)}
def create_node(self, node_type, parent_path="/obj", name=None, position=None, parameters=None):
"""Creates a new node in the specified parent."""
try:
parent = hou.node(parent_path)
if not parent:
raise ValueError(f"Parent path not found: {parent_path}")
node = parent.createNode(node_type, node_name=name)
if position and len(position) >= 2:
node.setPosition([position[0], position[1]])
if parameters:
for p_name, p_val in parameters.items():
parm = node.parm(p_name)
if parm:
parm.set(p_val)
return {
"name": node.name(),
"path": node.path(),
"type": node.type().name(),
"position": list(node.position()),
}
except Exception as e:
raise Exception(f"Failed to create node: {str(e)}")
def modify_node(self, path, parameters=None, position=None, name=None):
"""Modifies an existing node."""
node = hou.node(path)
if not node:
raise ValueError(f"Node not found: {path}")
changes = []
old_name = node.name()
if name and name != old_name:
node.setName(name)
changes.append(f"Renamed from {old_name} to {name}")
if position and len(position) >= 2:
node.setPosition([position[0], position[1]])
changes.append(f"Position set to {position}")
if parameters:
for p_name, p_val in parameters.items():
parm = node.parm(p_name)
if parm:
old_val = parm.eval()
parm.set(p_val)
changes.append(f"Parameter {p_name} changed from {old_val} to {p_val}")
return {"path": node.path(), "changes": changes}
def delete_node(self, path):
"""Deletes a node from the scene."""
node = hou.node(path)
if not node:
raise ValueError(f"Node not found: {path}")
node_path = node.path()
node_name = node.name()
node.destroy()
return {"deleted": node_path, "name": node_name}
def get_node_info(self, path):
"""Returns detailed information about a single node."""
node = hou.node(path)
if not node:
raise ValueError(f"Node not found: {path}")
node_info = {
"name": node.name(),
"path": node.path(),
"type": node.type().name(),
"category": node.type().category().name(),
"position": [node.position()[0], node.position()[1]],
"color": list(node.color().rgb()) if node.color() else None,
"is_bypassed": getattr(node, "isBypassed", lambda: None)(),
"is_displayed": getattr(node, "isDisplayFlagSet", lambda: None)(),
"is_rendered": getattr(node, "isRenderFlagSet", lambda: None)(),
"parameters": [],
"inputs": [],
"outputs": []
}
# Limit to 20 parameters for brevity
for i, parm in enumerate(node.parms()):
if i >= 20:
break
node_info["parameters"].append({
"name": parm.name(),
"value": str(parm.eval()),
"type": parm.parmTemplate().type().name()
})
# Inputs
for i, in_node in enumerate(node.inputs()):
if in_node:
node_info["inputs"].append({
"index": i,
"name": in_node.name(),
"path": in_node.path(),
"type": in_node.type().name()
})
# Outputs
for i, out_conn in enumerate(node.outputConnections()):
out_node = out_conn.outputNode()
node_info["outputs"].append({
"index": i,
"name": out_node.name(),
"path": out_node.path(),
"type": out_node.type().name(),
"input_index": out_conn.inputIndex()
})
return node_info
def execute_code(self, code):
"""Executes arbitrary Python code within Houdini."""
stdout_capture = io.StringIO()
stderr_capture = io.StringIO()
try:
namespace = {"hou": hou}
# Capture stdout/stderr during exec
with redirect_stdout(stdout_capture), redirect_stderr(stderr_capture):
exec(code, namespace)
# Success case: return execution status and captured output
return {
"executed": True,
"stdout": stdout_capture.getvalue(),
"stderr": stderr_capture.getvalue()
}
except Exception as e:
# Failure case: print traceback to actual stderr for debugging in Houdini
print("--- Houdini MCP: execute_code Error ---", file=sys.stderr)
traceback.print_exc(file=sys.stderr)
print("--- End Error ---", file=sys.stderr)
# Re-raise the exception so it's caught by execute_command
# and reported back as a standard error message.
raise Exception(f"Code execution error: {str(e)}")
# -------------------------------------------------------------------------
# Graph Editing & Introspection
# -------------------------------------------------------------------------
def _resolve_node(self, path):
"""Return the hou.Node at 'path' or raise a clear error."""
node = hou.node(path)
if not node:
raise ValueError(f"Node not found: {path}")
return node
def _resolve_geometry_node(self, path):
"""
Resolve 'path' to a SOP node that owns geometry. Accepts a SOP path
directly, or a geometry container (OBJ node) whose display SOP is used.
"""
node = self._resolve_node(path)
if isinstance(node, hou.SopNode):
return node
display = getattr(node, "displayNode", lambda: None)()
if display is not None:
return display
raise ValueError(
f"{path} has no geometry. Pass a SOP path or a geometry container "
f"(got {node.type().category().name()} node '{node.type().name()}')."
)
@staticmethod
def _jsonable(value):
"""Convert HOM values (vectors, tuples, ...) to JSON-friendly types."""
if isinstance(value, (bool, int, float, str)) or value is None:
return value
if isinstance(value, (hou.Vector2, hou.Vector3, hou.Vector4, hou.Quaternion)):
return list(value)
if isinstance(value, (tuple, list)):
return [HoudiniMCPServer._jsonable(v) for v in value]
return str(value)
@staticmethod
def _parm_value(parm_tuple):
"""Evaluate a parm tuple; single-component parms come back as scalars."""
value = HoudiniMCPServer._jsonable(parm_tuple.eval())
if isinstance(value, list) and len(parm_tuple) == 1:
return value[0]
return value
def _cook_and_report(self, node):
"""Force-cook a node and return a structured pass/fail report."""
start = time.time()
cook_exception = None
try:
node.cook(force=True)
except hou.OperationFailed as e:
cook_exception = str(e)
elapsed_ms = round((time.time() - start) * 1000.0, 1)
errors = [e.strip() for e in node.errors() if e.strip()]
warnings = [w.strip() for w in node.warnings() if w.strip()]
if cook_exception and not errors:
errors.append(cook_exception)
return {
"node": node.path(),
"cooked": not errors,
"cook_time_ms": elapsed_ms,
"errors": errors,
"warnings": warnings,
}
def connect_nodes(self, from_path, to_path, input_index=0, output_index=0):
"""Wire from_path's output into to_path's input."""
src = self._resolve_node(from_path)
dst = self._resolve_node(to_path)
if src.parent() != dst.parent():
raise ValueError(
f"Nodes must share a parent network: {src.parent().path()} != {dst.parent().path()}"
)
dst.setInput(input_index, src, output_index)
return {
"from": src.path(),
"to": dst.path(),
"input_index": input_index,
"output_index": output_index,
}
def disconnect_input(self, path, input_index=0):
"""Disconnect one input of a node."""
node = self._resolve_node(path)
previous = None
for connection in node.inputConnections():
if connection.inputIndex() == input_index:
previous = connection.inputNode()
break
node.setInput(input_index, None)
return {
"node": node.path(),
"input_index": input_index,
"was_connected_to": previous.path() if previous else None,
}
def _set_one_parm(self, node, name, value):
"""
Set a single parameter (or parm tuple). Returns (previous, new).
Resolves menu tokens/labels for string values on menu parms, and
suggests close parameter names when the name doesn't exist.
"""
parm_tuple = node.parmTuple(name)
if parm_tuple is None:
candidates = [pt.name() for pt in node.parmTuples()]
close = difflib.get_close_matches(name, candidates, n=3, cutoff=0.5)
hint = f" Did you mean: {', '.join(close)}?" if close else ""
raise ValueError(f"Parameter '{name}' not found on {node.path()}.{hint}")
previous = self._parm_value(parm_tuple)
if isinstance(value, (list, tuple)):
if len(value) != len(parm_tuple):
raise ValueError(
f"'{name}' has {len(parm_tuple)} component(s), got {len(value)} values"
)
parm_tuple.set(tuple(value))
else:
if len(parm_tuple) != 1:
raise ValueError(
f"'{name}' has {len(parm_tuple)} components; pass a list of {len(parm_tuple)} values"
)
parm = parm_tuple[0]
try:
parm.set(value)
except (TypeError, hou.OperationFailed):
# A string that isn't a valid menu token: resolve label to index.
if not isinstance(value, str):
raise
try:
tokens = list(parm.menuItems())
labels = list(parm.menuLabels())
except hou.OperationFailed:
raise TypeError(
f"'{name}' does not accept a string value on {node.path()}"
)
if value in tokens:
parm.set(tokens.index(value))
elif value in labels:
parm.set(labels.index(value))
else:
raise ValueError(
f"'{value}' is not a menu token or label of '{name}'. "
f"Tokens: {tokens[:20]}"
)
return previous, self._parm_value(parm_tuple)
def set_parameters(self, path, parameters):
"""
Set multiple parameters on a node in one call.
Values: scalar for single parms, list for tuples (e.g. "t": [0, 1, 0]),
menu token/label strings for menu parms.
"""
node = self._resolve_node(path)
if not isinstance(parameters, dict) or not parameters:
raise ValueError("'parameters' must be a non-empty dict of {name: value}")
applied, failed = [], []
for name, value in parameters.items():
try:
previous, new = self._set_one_parm(node, name, value)
applied.append({"name": name, "previous": previous, "value": new})
except Exception as e:
failed.append({"name": name, "error": str(e)})
return {"node": node.path(), "set": applied, "failed": failed}
def get_parameter_schema(self, path, pattern=None, offset=0, limit=50):
"""
Describe a node's parameters: name, label, type, size, current value,
defaults, ranges and menu options. Filter with a glob 'pattern'
(matched against name and label), paginate with offset/limit.
"""
node = self._resolve_node(path)
limit = max(1, min(int(limit), 200))
offset = max(0, int(offset))
parm_tuples = node.parmTuples()
if pattern:
pat = pattern.lower()
parm_tuples = [
pt for pt in parm_tuples
if fnmatch.fnmatch(pt.name().lower(), pat)
or fnmatch.fnmatch(pt.parmTemplate().label().lower(), pat)
]
entries = []
for pt in parm_tuples[offset:offset + limit]:
template = pt.parmTemplate()
entry = {
"name": pt.name(),
"label": template.label(),
"type": template.type().name(),
"size": len(pt),
"value": self._parm_value(pt),
}
try:
default = self._jsonable(template.defaultValue())
if isinstance(default, list) and len(default) == 1:
default = default[0]
entry["default"] = default
except AttributeError:
pass
if isinstance(template, (hou.FloatParmTemplate, hou.IntParmTemplate)):
entry["min"] = template.minValue()
entry["max"] = template.maxValue()
menu_items = getattr(template, "menuItems", lambda: ())()
if menu_items:
menu_labels = template.menuLabels()
entry["menu"] = [
{"token": t, "label": l}
for t, l in islice(zip(menu_items, menu_labels), 30)
]
if len(menu_items) > 30:
entry["menu_truncated"] = len(menu_items)
entries.append(entry)
return {
"node": node.path(),
"node_type": node.type().name(),
"total": len(parm_tuples),
"offset": offset,
"parameters": entries,
}
def set_node_flags(self, path, display=None, render=None, bypass=None, template=None):
"""Set node flags; only the flags passed (non-None) are touched."""
node = self._resolve_node(path)
requested = {
"display": (display, "setDisplayFlag"),
"render": (render, "setRenderFlag"),
"bypass": (bypass, "bypass"),
"template": (template, "setTemplateFlag"),
}
applied, unsupported = {}, []
for flag, (value, method_name) in requested.items():
if value is None:
continue
method = getattr(node, method_name, None)
if method is None:
unsupported.append(flag)
continue
method(bool(value))
applied[flag] = bool(value)
return {"node": node.path(), "applied": applied, "unsupported": unsupported}
def layout_children(self, path):
"""Auto-layout all children of a network node."""
node = self._resolve_node(path)
node.layoutChildren()
return {"node": node.path(), "children_laid_out": len(node.children())}
def find_error_nodes(self, root_path="/obj", include_warnings=False,
max_nodes=2000, limit=50):
"""
Walk the network under root_path and report nodes whose last cook
produced errors (and optionally warnings). Does not force cooks.
"""
root = self._resolve_node(root_path)
found = []
scanned = 0
truncated = False
stack = [root]
while stack:
if scanned >= max_nodes or len(found) >= limit:
truncated = True
break
node = stack.pop()
scanned += 1
errors = [e.strip() for e in node.errors() if e.strip()]
warnings = []
if include_warnings:
warnings = [w.strip() for w in node.warnings() if w.strip()]
if errors or warnings:
entry = {"path": node.path(), "type": node.type().name(), "errors": errors}
if include_warnings:
entry["warnings"] = warnings
found.append(entry)
stack.extend(node.children())
return {
"root": root.path(),
"scanned": scanned,
"truncated": truncated,
"error_node_count": len(found),
"nodes": found,
}
def cook_node(self, path):
"""Force-cook a node and report errors, warnings and cook time."""
return self._cook_and_report(self._resolve_node(path))
# -------------------------------------------------------------------------
# VEX Wrangles
# -------------------------------------------------------------------------
def _set_run_over(self, node, run_over):
"""Match 'run_over' against the wrangle's class menu (token or label)."""
class_parm = node.parm("class")
if class_parm is None:
return None # e.g. volumewrangle has no class parm
want = run_over.lower().rstrip("s")
tokens = list(class_parm.menuItems())
labels = list(class_parm.menuLabels())
for index, (token, label) in enumerate(zip(tokens, labels)):
if want in (token.lower().rstrip("s"), label.lower().rstrip("s")):
class_parm.set(index)
return token
raise ValueError(
f"Unknown run_over '{run_over}'. Valid options: {tokens}"
)
def create_wrangle(self, parent_path, vex_code, name=None, run_over="points",
input_node=None, wrangle_type="attribwrangle"):
"""
Create a wrangle SOP, set its VEX snippet, optionally wire an input,
then cook it so VEX compile errors are reported immediately.
"""
parent = self._resolve_node(parent_path)
if parent.childTypeCategory() != hou.sopNodeTypeCategory():
raise ValueError(
f"{parent_path} is not a SOP network (cannot contain wrangles). "
f"Pass a geometry container or SOP subnet."
)
node = parent.createNode(wrangle_type, node_name=name)
try:
snippet = node.parm("snippet")
if snippet is None:
raise ValueError(f"'{wrangle_type}' has no 'snippet' parameter")
snippet.set(vex_code)
run_over_token = self._set_run_over(node, run_over)
if input_node:
node.setInput(0, self._resolve_node(input_node))
node.moveToGoodPosition()
except Exception:
node.destroy() # don't leave a half-configured node behind
raise
return {
"path": node.path(),
"type": wrangle_type,
"run_over": run_over_token,
"validation": self._cook_and_report(node),
}
def set_wrangle_code(self, path, vex_code, validate=True):
"""Replace the VEX snippet on an existing wrangle and re-validate."""
node = self._resolve_node(path)
snippet = node.parm("snippet")
if snippet is None:
raise ValueError(f"{path} has no 'snippet' parameter (not a wrangle)")
snippet.set(vex_code)
result = {"path": node.path(), "code_length": len(vex_code)}
if validate:
result["validation"] = self._cook_and_report(node)
return result
# -------------------------------------------------------------------------
# Geometry Introspection
# -------------------------------------------------------------------------
@staticmethod
def _attrib_summary(attribs):
return [
{"name": a.name(), "type": a.dataType().name(), "size": a.size()}
for a in attribs
]
def get_geometry_info(self, path):
"""
Summarize a node's geometry: element counts, bounding box, attributes
and group names. Accepts a SOP or a geometry container path.
"""
sop = self._resolve_geometry_node(path)
geo = sop.geometry()
if geo is None:
report = self._cook_and_report(sop)
raise ValueError(
f"{sop.path()} produced no geometry. Cook errors: {report['errors']}"
)
bbox = geo.boundingBox()
return {
"node": sop.path(),
"point_count": geo.intrinsicValue("pointcount"),
"primitive_count": geo.intrinsicValue("primitivecount"),
"vertex_count": geo.intrinsicValue("vertexcount"),
"bounding_box": {
"min": list(bbox.minvec()),
"max": list(bbox.maxvec()),
"size": list(bbox.sizevec()),
"center": list(bbox.center()),
},
"attributes": {
"point": self._attrib_summary(geo.pointAttribs()),
"primitive": self._attrib_summary(geo.primAttribs()),
"vertex": self._attrib_summary(geo.vertexAttribs()),
"detail": self._attrib_summary(geo.globalAttribs()),
},
"groups": {
"point": [g.name() for g in geo.pointGroups()],
"primitive": [g.name() for g in geo.primGroups()],
},
}
def get_geometry_data(self, path, element="points", attributes=None,
start=0, limit=100):
"""
Read actual attribute values from geometry, paginated.
element: 'points' or 'primitives'. attributes: list of names
(default: position for points, type info for prims).
"""
sop = self._resolve_geometry_node(path)
geo = sop.geometry()
if geo is None:
raise ValueError(f"{sop.path()} has no geometry (node may not cook)")
start = max(0, int(start))
limit = max(1, min(int(limit), 500))
if element == "points":
total = geo.intrinsicValue("pointcount")
available = {a.name(): a for a in geo.pointAttribs()}
iterator = geo.iterPoints()
elif element == "primitives":
total = geo.intrinsicValue("primitivecount")
available = {a.name(): a for a in geo.primAttribs()}
iterator = geo.iterPrims()
else:
raise ValueError(f"element must be 'points' or 'primitives', got '{element}'")
if attributes:
missing = [a for a in attributes if a not in available]
if missing:
raise ValueError(
f"Attribute(s) {missing} not found on {element}. "
f"Available: {sorted(available)}"
)
selected = [available[a] for a in attributes]
else:
selected = [available["P"]] if "P" in available else []
rows = []
for elem in islice(iterator, start, start + limit):
row = {"number": elem.number()}
if element == "primitives":
row["type"] = elem.type().name()
for attrib in selected:
row[attrib.name()] = self._jsonable(elem.attribValue(attrib))
rows.append(row)
return {
"node": sop.path(),
"element": element,
"total": total,
"start": start,
"count": len(rows),
"data": rows,
}
# -------------------------------------------------------------------------
# set_material (now completed)
# -------------------------------------------------------------------------
def set_material(self, node_path, material_type="principledshader", name=None, parameters=None):
"""
Creates or applies a material to an OBJ node.
For example, we can create a Principled Shader in /mat
and assign it to a geometry node or set the 'shop_materialpath'.
"""
try:
target_node = hou.node(node_path)
if not target_node:
raise ValueError(f"Node not found: {node_path}")
# Verify it's an OBJ node (i.e., category Object)
if target_node.type().category().name() != "Object":
raise ValueError(
f"Node {node_path} is not an OBJ-level node and cannot accept direct materials."
)
# Attempt to create/find a material in /mat (or /shop)
mat_context = hou.node("/mat")
if not mat_context:
# Fallback: try /shop if /mat doesn't exist
mat_context = hou.node("/shop")
if not mat_context:
raise RuntimeError("No /mat or /shop context found to create materials.")
mat_name = name or (f"{material_type}_auto")
mat_node = mat_context.node(mat_name)
if not mat_node:
# Create a new material node
mat_node = mat_context.createNode(material_type, mat_name)
# Apply any parameter overrides
if parameters:
for k, v in parameters.items():
p = mat_node.parm(k)
if p:
p.set(v)
# Now assign this material to the OBJ node
# Typically, you either set a "shop_materialpath" parameter
# or inside the geometry, you create a Material SOP.
mat_parm = target_node.parm("shop_materialpath")
if mat_parm:
mat_parm.set(mat_node.path())
else: