-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path__init__.py
More file actions
847 lines (692 loc) · 34.7 KB
/
__init__.py
File metadata and controls
847 lines (692 loc) · 34.7 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
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTIBILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import bpy
from bpy.types import Operator, Panel
from bpy.props import StringProperty, BoolProperty
from bpy.app.handlers import persistent
import traceback
import os
import tempfile
from pathlib import Path
print("\n[eLCA] Initializing eLCA Bonsai integration...")
# First, ensure dependencies are installed
from . import dependencies
dependencies_installed = dependencies.ensure_dependencies()
# Only import our modules if dependencies are installed
if dependencies_installed:
# Import our modules
from . import elca_parser
from . import ifc_library_creator
from . import material_sets
else:
# Create dummy modules for graceful failure
class DummyModule:
pass
elca_parser = DummyModule()
elca_parser.ELCAComponentExtractor = lambda *args, **kwargs: None
ifc_library_creator = DummyModule()
ifc_library_creator.create_ifc_library_from_bauteil_elements = lambda *args, **kwargs: None
ifc_library_creator.attach_library_to_project = lambda *args, **kwargs: None
material_sets = DummyModule()
material_sets.add_material_sets_to_project = lambda *args, **kwargs: None
material_sets.add_material_sets_from_library_file = lambda *args, **kwargs: None
material_sets.get_material_sets_summary = lambda *args, **kwargs: {}
material_sets.remove_material_sets_from_project = lambda *args, **kwargs: None
material_sets.validate_material_sets = lambda *args, **kwargs: []
material_sets.sync_material_sets_with_ifc = lambda *args, **kwargs: False
bl_info = {
"name": "Elca Bonsai",
"author": "Jakob Beetz",
"description": "Integration of eLCA data into Blender Bonsai",
"blender": (2, 80, 0),
"version": (0, 2, 0),
"location": "Bonsai > GEOMETRY tab > eLCA",
"warning": "",
"category": "Generic",
}
class ELCA_OT_LoadResults(Operator):
"""Load eLCA results from HTML file"""
bl_idname = "elca.load_results"
bl_label = "Load eLCA Results (HTML)"
bl_options = {'REGISTER', 'UNDO'}
filepath: StringProperty(
name="File Path",
description="Path to eLCA results HTML file",
default="",
subtype='FILE_PATH'
)
filter_glob: StringProperty(
default="*.html;*.htm",
options={'HIDDEN'}
)
def execute(self, context):
if not dependencies_installed:
self.report({'ERROR'}, "Required dependencies are not installed. Check the console for details.")
return {'CANCELLED'}
try:
print(f"[eLCA] Loading eLCA results : {self.filepath}")
# Extract components from HTML file only (no XML yet)
extractor = elca_parser.ELCAComponentExtractor(self.filepath)
bauteil_elements = extractor.extract_bauteil_elements()
# Store HTML data for later use
context.scene["elca_html_path"] = self.filepath
context.scene["elca_html_data"] = str(len(bauteil_elements)) # Simple count for now
# Report the number of elements found
num_elements = len(bauteil_elements)
num_components = sum(len(element.components) for element in bauteil_elements)
self.report({'INFO'}, f"Loaded HTML with {num_elements} building elements and {num_components} components")
print(f"[eLCA] Loaded HTML with {num_elements} building elements and {num_components} components")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error loading eLCA HTML results: {str(e)}")
print(f"[eLCA] Error loading eLCA HTML results: {str(e)}")
print(traceback.format_exc())
return {'CANCELLED'}
def invoke(self, context, event):
print("[eLCA] Opening file browser for eLCA HTML results selection")
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class ELCA_OT_LoadProject(Operator):
"""Load eLCA project XML file and match with HTML data"""
bl_idname = "elca.load_project"
bl_label = "Load eLCA Project (XML)"
bl_options = {'REGISTER', 'UNDO'}
filepath: StringProperty(
name="File Path",
description="Path to eLCA project XML file",
default="",
subtype='FILE_PATH'
)
filter_glob: StringProperty(
default="*.xml",
options={'HIDDEN'}
)
def execute(self, context):
if not dependencies_installed:
self.report({'ERROR'}, "Required dependencies are not installed. Check the console for details.")
return {'CANCELLED'}
try:
print(f"[eLCA] Loading eLCA project XML from: {self.filepath}")
# Check if HTML has been loaded first
html_path = context.scene.get("elca_html_path", None)
if not html_path or not Path(html_path).exists():
self.report({'ERROR'}, "Please load the HTML results file first!")
return {'CANCELLED'}
# Store the XML file path
context.scene["elca_xml_path"] = self.filepath
# Now create extractor with both HTML and XML files
print(f"[eLCA] Processing both HTML ({html_path}) and XML ({self.filepath}) files")
extractor = elca_parser.ELCAComponentExtractor(html_path, self.filepath)
# Extract building elements with matched layer thicknesses
bauteil_elements = extractor.extract_bauteil_elements()
# Get layer thickness summary from XML
layer_summary = extractor.get_layer_thickness_summary()
# Report results
num_elements = len(bauteil_elements)
num_components = sum(len(element.components) for element in bauteil_elements)
num_layers_with_thickness = 0
print(f"Calculating number of layers with thickness > 0...")
for element in bauteil_elements:
print(f" Processing Bauteil: {element.name} (Category: {element.category_code})")
for comp in element.components:
thickness = comp.get('layer_thickness')
print(f" Checking Component: {comp.get('name', 'Unnamed Component')} (Thickness: {thickness})")
if thickness is not None and thickness > 0:
num_layers_with_thickness += 1
print(f" Found layer with thickness > 0. Current count: {num_layers_with_thickness}")
print(f"Finished calculating. Total layers with thickness > 0: {num_layers_with_thickness}")
if layer_summary.get('total_layers', 0) > 0:
self.report({'INFO'}, f"Matched {num_layers_with_thickness} components with layer thicknesses from {layer_summary['total_elements']} XML elements")
print(f"[eLCA] Matched {num_layers_with_thickness} components with layer thicknesses")
# # Store the matched data
context.scene["elca_matched_data"] = "true"
context.scene["elca_layer_data"] = str(layer_summary)
else:
self.report({'WARNING'}, "No layer thickness data found in XML file")
print("[eLCA] No layer thickness data found in XML file")
context.scene["elca_matched_data"] = "false"
# Store the processed bauteil elements for IFC creation
# We'll serialize this data for the IFC creation step
try:
import pickle
import base64
serialized_data = base64.b64encode(pickle.dumps(bauteil_elements)).decode('utf-8')
context.scene["elca_bauteil_elements"] = serialized_data
print(f"[eLCA] Stored {num_elements} bauteil elements for IFC creation")
except Exception as e:
print(f"[eLCA] Could not serialize bauteil elements: {e}")
context.scene["elca_bauteil_elements"] = ""
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error processing eLCA project: {str(e)}")
print(f"[eLCA] Error processing eLCA project: {str(e)}")
print(traceback.format_exc())
return {'CANCELLED'}
def invoke(self, context, event):
print("[eLCA] Opening file browser for eLCA project XML selection")
context.window_manager.fileselect_add(self)
return {'RUNNING_MODAL'}
class ELCA_OT_ResetData(Operator):
"""Reset all loaded eLCA data"""
bl_idname = "elca.reset_data"
bl_label = "Reset eLCA Data"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
try:
# Clear all stored eLCA data from scene
elca_properties = [
"elca_html_path",
"elca_xml_path",
"elca_html_data",
"elca_matched_data",
"elca_layer_data",
"elca_xml_layer_data",
"elca_bauteil_elements"
]
cleared_count = 0
for prop in elca_properties:
if prop in context.scene:
del context.scene[prop]
cleared_count += 1
print(f"[eLCA] Reset complete - cleared {cleared_count} properties")
self.report({'INFO'}, f"Reset eLCA data - cleared {cleared_count} stored properties")
# Force UI refresh
for area in bpy.context.screen.areas:
if area.type == 'PROPERTIES':
area.tag_redraw()
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error resetting eLCA data: {str(e)}")
print(f"[eLCA] Error resetting eLCA data: {str(e)}")
print(traceback.format_exc())
return {'CANCELLED'}
class ELCA_OT_CreateIFCLibrary(Operator):
"""Create IFC material library from loaded eLCA data"""
bl_idname = "elca.create_ifc_library"
bl_label = "Create IFC Library"
bl_options = {'REGISTER', 'UNDO'}
attach_to_project: BoolProperty(
name="Attach to Project",
description="Attach the created library to the current IFC project",
default=False
)
def execute(self, context):
if not dependencies_installed:
self.report({'ERROR'}, "Required dependencies are not installed. Check the console for details.")
return {'CANCELLED'}
try:
# Check if both HTML and XML have been loaded
html_path = context.scene.get("elca_html_path", None)
xml_path = context.scene.get("elca_xml_path", None)
matched_data = context.scene.get("elca_matched_data", "false")
if not html_path:
self.report({'ERROR'}, "No HTML file loaded. Please load HTML results first.")
return {'CANCELLED'}
if not xml_path:
self.report({'ERROR'}, "No XML file loaded. Please load XML project file first.")
return {'CANCELLED'}
if matched_data != "true":
self.report({'WARNING'}, "Data matching may not be complete. Proceeding anyway...")
# Retrieve stored bauteil elements
serialized_data = context.scene.get("elca_bauteil_elements", "")
if not serialized_data:
self.report({'ERROR'}, "No processed bauteil elements found. Please reload the XML file.")
return {'CANCELLED'}
try:
import pickle
import base64
bauteil_elements = pickle.loads(base64.b64decode(serialized_data.encode('utf-8')))
print(f"[eLCA] Retrieved {len(bauteil_elements)} bauteil elements for IFC creation")
except Exception as e:
self.report({'ERROR'}, f"Could not retrieve bauteil elements: {str(e)}")
return {'CANCELLED'}
# Create output path based on HTML file location
html_file_path = Path(html_path)
output_path = html_file_path.with_suffix('.ifc')
# Create the IFC library with layer thickness data
print(f"[eLCA] Creating IFC library at: {output_path}")
ifc_file = ifc_library_creator.create_ifc_library_from_bauteil_elements(
bauteil_elements, str(output_path))
# Count elements with layer thicknesses
num_elements = len(bauteil_elements)
num_layers_with_thickness = sum(
sum(1 for comp in element.components if comp.get('layer_thickness', 0) > 0)
for element in bauteil_elements
)
self.report({'INFO'}, f"Created IFC library with {num_elements} elements ({num_layers_with_thickness} with layer thicknesses) at {output_path}")
print(f"[eLCA] Created IFC library with {num_elements} elements ({num_layers_with_thickness} with layer thicknesses)")
# Attach to project if requested
if self.attach_to_project:
try:
project_path = context.scene.BIMProperties.ifc_file if hasattr(context.scene, 'BIMProperties') else None
if project_path:
# Attach the library to the project
ifc_library_creator.attach_library_to_project(project_path, str(output_path))
self.report({'INFO'}, f"Attached library to project at {project_path}")
print(f"[eLCA] Attached library to project at {project_path}")
else:
self.report({'WARNING'}, "No active IFC project found to attach library to")
except Exception as e:
self.report({'WARNING'}, f"Could not attach to project: {str(e)}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error creating IFC library: {str(e)}")
print(f"[eLCA] Error creating IFC library: {str(e)}")
print(traceback.format_exc())
return {'CANCELLED'}
class ELCA_OT_InstallDependencies(Operator):
"""Install required dependencies for eLCA integration"""
bl_idname = "elca.install_dependencies"
bl_label = "Install Dependencies"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
try:
success = dependencies.ensure_dependencies()
if success:
self.report({'INFO'}, "All dependencies successfully installed")
return {'FINISHED'}
else:
self.report({'ERROR'}, "Failed to install some dependencies. Check the console for details.")
return {'CANCELLED'}
except Exception as e:
self.report({'ERROR'}, f"Error installing dependencies: {str(e)}")
print(f"[eLCA] Error installing dependencies: {str(e)}")
print(traceback.format_exc())
return {'CANCELLED'}
class ELCA_OT_ShowMaterialSets(Operator):
"""Show summary of material sets in the project"""
bl_idname = "elca.show_material_sets"
bl_label = "Show Material Sets"
bl_options = {'REGISTER'}
def execute(self, context):
if not dependencies_installed:
self.report({'ERROR'}, "Required dependencies are not installed.")
return {'CANCELLED'}
try:
summary = material_sets.get_material_sets_summary()
if summary:
layer_count = summary.get('total_layer_sets', 0)
constituent_count = summary.get('total_constituent_sets', 0)
message = f"Found {layer_count} layer sets and {constituent_count} constituent sets"
self.report({'INFO'}, message)
print(f"[eLCA] {message}")
# Print detailed info to console
if layer_count > 0:
print("[eLCA] Material Layer Sets:")
for layer_set in summary.get('layer_sets', []):
print(f" - {layer_set['name']} ({layer_set['layer_count']} layers, {layer_set['total_thickness']}mm thick)")
if constituent_count > 0:
print("[eLCA] Material Constituent Sets:")
for const_set in summary.get('constituent_sets', []):
print(f" - {const_set['name']} ({const_set['constituent_count']} constituents)")
else:
self.report({'INFO'}, "No material sets found in project")
print("[eLCA] No material sets found in project")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error getting material sets summary: {str(e)}")
print(f"[eLCA] Error getting material sets summary: {str(e)}")
return {'CANCELLED'}
class ELCA_OT_RemoveMaterialSets(Operator):
"""Remove material sets from the project"""
bl_idname = "elca.remove_material_sets"
bl_label = "Remove Material Sets"
bl_options = {'REGISTER', 'UNDO'}
material_type: StringProperty(
name="Material Type",
description="Type of material sets to remove",
default="ALL"
)
def execute(self, context):
if not dependencies_installed:
self.report({'ERROR'}, "Required dependencies are not installed.")
return {'CANCELLED'}
try:
material_type_filter = None if self.material_type == "ALL" else self.material_type
material_sets.remove_material_sets_from_project(material_type_filter)
self.report({'INFO'}, f"Removed material sets from project")
print(f"[eLCA] Removed material sets from project")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error removing material sets: {str(e)}")
print(f"[eLCA] Error removing material sets: {str(e)}")
return {'CANCELLED'}
def invoke(self, context, event):
return context.window_manager.invoke_confirm(self, event)
class ELCA_OT_ValidateMaterialSets(Operator):
"""Validate material sets in the project"""
bl_idname = "elca.validate_material_sets"
bl_label = "Validate Material Sets"
bl_options = {'REGISTER'}
def execute(self, context):
if not dependencies_installed:
self.report({'ERROR'}, "Required dependencies are not installed.")
return {'CANCELLED'}
try:
issues = material_sets.validate_material_sets()
if not issues:
self.report({'INFO'}, "All material sets are valid")
print("[eLCA] All material sets are valid")
else:
self.report({'WARNING'}, f"Found {len(issues)} material sets with issues")
print(f"[eLCA] Found {len(issues)} material sets with issues:")
for issue in issues:
if 'error' in issue:
print(f" Error: {issue['error']}")
else:
print(f" - {issue['material_name']} ({issue['material_type']}):")
for problem in issue['issues']:
print(f" * {problem}")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error validating material sets: {str(e)}")
print(f"[eLCA] Error validating material sets: {str(e)}")
return {'CANCELLED'}
class ELCA_OT_SyncMaterialSets(Operator):
"""Synchronize material sets with the active IFC file"""
bl_idname = "elca.sync_material_sets"
bl_label = "Sync with IFC"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
if not dependencies_installed:
self.report({'ERROR'}, "Required dependencies are not installed.")
return {'CANCELLED'}
try:
success = material_sets.sync_material_sets_with_ifc()
if success:
self.report({'INFO'}, "Successfully synchronized material sets with IFC file")
print("[eLCA] Successfully synchronized material sets with IFC file")
else:
self.report({'WARNING'}, "Could not synchronize material sets. Check console for details.")
print("[eLCA] Could not synchronize material sets")
return {'FINISHED'}
except Exception as e:
self.report({'ERROR'}, f"Error synchronizing material sets: {str(e)}")
print(f"[eLCA] Error synchronizing material sets: {str(e)}")
return {'CANCELLED'}
# Create our own panel as a fallback
class ELCA_PT_Panel(Panel):
"""eLCA Panel"""
bl_label = "eLCA Integration"
bl_idname = "ELCA_PT_Panel"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "material"
def draw(self, context):
layout = self.layout
box = layout.box()
box.label(text="eLCA Integration", icon='FILE_REFRESH')
# Show dependency status
if not dependencies_installed:
box.label(text="Dependencies not installed", icon='ERROR')
box.operator("elca.install_dependencies", icon='PACKAGE')
else:
box.label(text="Load eLCA project and results files:")
row = box.row()
row.operator("elca.load_results", text="1. Load Results (.html / .htm file) (do this first)", icon='SPREADSHEET')
row = box.row()
row.operator("elca.load_project", text="2. Load Project (.xml File)", icon='IMPORT')
# Material Sets section
box.separator()
box.label(text="Material Sets Management:")
row = box.row()
row.operator("elca.show_material_sets", text="Show Sets", icon='INFO')
row = box.row()
row.operator("elca.validate_material_sets", text="Validate", icon='CHECKMARK')
row = box.row()
row.operator("elca.sync_material_sets", text="Sync with IFC", icon='FILE_REFRESH')
row = box.row()
row.operator("elca.remove_material_sets", text="Remove All", icon='TRASH')
# Store original draw functions
_original_draw_functions = {}
# Draw function for the BIM panel
def draw_elca_ui(self, context):
try:
layout = self.layout
box = layout.box()
box.label(text="eLCA Integration", icon='FILE_REFRESH')
# Show dependency status
if not dependencies_installed:
box.label(text="Dependencies not installed", icon='ERROR')
box.operator("elca.install_dependencies", icon='PACKAGE')
else:
# Show file loading status
html_path = context.scene.get("elca_html_path", None)
xml_path = context.scene.get("elca_xml_path", None)
matched_data = context.scene.get("elca_matched_data", "false")
has_layer_data = context.scene.get("elca_layer_data", None)
# Step 1: HTML Status
if html_path:
html_file = Path(html_path).name
box.label(text=f"✓ HTML loaded: {html_file}", icon='CHECKMARK')
else:
box.label(text="1. Load HTML results file", icon='RADIOBUT_OFF')
# Step 2: XML Status
if xml_path:
xml_file = Path(xml_path).name
if matched_data == "true" and has_layer_data:
box.label(text=f"✓ XML loaded: {xml_file}", icon='CHECKMARK')
# Try to show layer count
try:
layer_summary = eval(has_layer_data)
layer_count = layer_summary.get('total_layers', 0)
element_count = layer_summary.get('total_elements', 0)
box.label(text=f" {element_count} elements, {layer_count} layers matched")
except:
pass
else:
box.label(text=f"⚠ XML loaded: {xml_file} (no matching)", icon='ERROR')
else:
if html_path:
box.label(text="2. Load XML project file", icon='RADIOBUT_OFF')
else:
box.label(text="2. Load XML project file", icon='RADIOBUT_OFF')
# File loading buttons
col = box.column(align=True)
# Step 1: Load HTML
row = col.row(align=True)
if html_path:
row.enabled = False
row.operator("elca.load_results", text="✓ HTML Loaded", icon='CHECKMARK')
else:
row.operator("elca.load_results", text="1. Load Results (HTML)", icon='IMPORT')
# Step 2: Load XML (only enabled after HTML)
row = col.row(align=True)
if not html_path:
row.enabled = False
row.operator("elca.load_project", text="2. Load Project (XML)", icon='IMPORT')
elif xml_path and matched_data == "true":
row.enabled = False
row.operator("elca.load_project", text="✓ XML Loaded & Matched", icon='CHECKMARK')
else:
row.operator("elca.load_project", text="2. Load Project (XML)", icon='IMPORT')
# Step 3: Create IFC Library (only enabled after both files loaded)
if html_path and xml_path and matched_data == "true":
col.separator()
col.label(text="3. Create IFC Library:")
ifc_row = col.row(align=True)
create_op = ifc_row.operator("elca.create_ifc_library", text="Create IFC Library", icon='PACKAGE')
# Add checkbox for attaching to project
attach_row = col.row(align=True)
attach_row.prop(context.scene, "elca_attach_to_project", text="Attach to active project")
# Reset button
if html_path or xml_path:
col.separator()
col.operator("elca.reset_data", text="Reset All Data", icon='X')
except Exception as e:
print(f"[eLCA] Error in draw_elca_ui: {e}")
print(traceback.format_exc())
# Function to monkey patch a panel's draw method
def monkey_patch_panel(panel_class, panel_name):
if panel_name not in _original_draw_functions:
print(f"[eLCA] Storing original draw function for {panel_name}")
_original_draw_functions[panel_name] = panel_class.draw
def new_draw(self, context):
try:
# Draw our UI first
draw_elca_ui(self, context)
# Then call the original draw function
if panel_name in _original_draw_functions:
_original_draw_functions[panel_name](self, context)
except Exception as e:
print(f"[eLCA] Error in monkey-patched draw function for {panel_name}: {e}")
print(traceback.format_exc())
# Fallback to original draw if our addition fails
if panel_name in _original_draw_functions:
_original_draw_functions[panel_name](self, context)
print(f"[eLCA] Setting new draw function for {panel_name}")
panel_class.draw = new_draw
# Persistent handler to add our UI elements after file load
@persistent
def load_handler(dummy):
print("\n[eLCA] Load handler triggered")
# List all panel classes for debugging
print("[eLCA] Available Panel classes:")
# for i, cls in enumerate(bpy.types.Panel.__subclasses__()):
# if hasattr(cls, '__module__'):
# print(f" {i+1}. {cls.__module__}.{cls.__name__}")
# Target panel classes to try
target_panel_classes = [
"bonsai.bim.module.material.ui.BIM_PT_materials",
"bonsai.bim.module.material.ui.BIM_PT_object_material",
]
found_panel = False
for target_panel_name in target_panel_classes:
try:
panel_class = None
for cls in bpy.types.Panel.__subclasses__():
if hasattr(cls, '__module__') and f"{cls.__module__}.{cls.__name__}" == target_panel_name:
panel_class = cls
break
if panel_class:
print(f"[eLCA] Found panel: {target_panel_name}")
monkey_patch_panel(panel_class, target_panel_name)
print(f"[eLCA] Added eLCA UI to {target_panel_name} panel")
found_panel = True
break # Stop after finding one panel
else:
print(f"[eLCA] Panel not found: {target_panel_name}")
except Exception as e:
print(f"[eLCA] Error processing panel {target_panel_name}: {e}")
print(traceback.format_exc())
if not found_panel:
print("[eLCA] Could not find any target panels. Using fallback panel.")
def register():
print("\n[eLCA] Registering eLCA Bonsai integration...")
try:
bpy.utils.register_class(ELCA_OT_LoadResults)
print("[eLCA] Registered ELCA_OT_LoadResults")
except Exception as e:
print(f"[eLCA] Error registering ELCA_OT_LoadResults: {e}")
try:
bpy.utils.register_class(ELCA_OT_LoadProject)
print("[eLCA] Registered ELCA_OT_LoadProject")
except Exception as e:
print(f"[eLCA] Error registering ELCA_OT_LoadProject: {e}")
try:
bpy.utils.register_class(ELCA_OT_CreateIFCLibrary)
print("[eLCA] Registered ELCA_OT_CreateIFCLibrary")
except Exception as e:
print(f"[eLCA] Error registering ELCA_OT_CreateIFCLibrary: {e}")
try:
bpy.utils.register_class(ELCA_OT_ResetData)
print("[eLCA] Registered ELCA_OT_ResetData")
except Exception as e:
print(f"[eLCA] Error registering ELCA_OT_ResetData: {e}")
try:
bpy.utils.register_class(ELCA_OT_InstallDependencies)
print("[eLCA] Registered ELCA_OT_InstallDependencies")
except Exception as e:
print(f"[eLCA] Error registering ELCA_OT_InstallDependencies: {e}")
try:
bpy.utils.register_class(ELCA_PT_Panel)
print("[eLCA] Registered ELCA_PT_Panel (fallback panel)")
except Exception as e:
print(f"[eLCA] Error registering ELCA_PT_Panel: {e}")
# Add scene properties for UI state
try:
from bpy.props import BoolProperty
bpy.types.Scene.elca_attach_to_project = BoolProperty(
name="Attach to Project",
description="Attach the created IFC library to the current project",
default=False
)
print("[eLCA] Added scene properties")
except Exception as e:
print(f"[eLCA] Error adding scene properties: {e}")
# Add our load handler
if load_handler not in bpy.app.handlers.load_post:
bpy.app.handlers.load_post.append(load_handler)
print("[eLCA] Added load_handler to load_post")
# Run the load handler immediately
load_handler(None)
print("[eLCA] Registration complete")
def unregister():
print("\n[eLCA] Unregistering eLCA Bonsai integration...")
# Restore original draw functions
for panel_name, original_draw in _original_draw_functions.items():
try:
panel_class = None
for cls in bpy.types.Panel.__subclasses__():
if hasattr(cls, '__module__') and f"{cls.__module__}.{cls.__name__}" == panel_name:
panel_class = cls
break
if panel_class:
panel_class.draw = original_draw
print(f"[eLCA] Restored original draw function for {panel_name}")
except Exception as e:
print(f"[eLCA] Error restoring draw function for {panel_name}: {e}")
# Remove load handler
if load_handler in bpy.app.handlers.load_post:
bpy.app.handlers.load_post.remove(load_handler)
print("[eLCA] Removed load_handler from load_post")
# Remove scene properties
try:
del bpy.types.Scene.elca_attach_to_project
print("[eLCA] Removed scene properties")
except Exception as e:
print(f"[eLCA] Error removing scene properties: {e}")
try:
bpy.utils.unregister_class(ELCA_PT_Panel)
print("[eLCA] Unregistered ELCA_PT_Panel")
except Exception as e:
print(f"[eLCA] Error unregistering ELCA_PT_Panel: {e}")
try:
bpy.utils.unregister_class(ELCA_OT_InstallDependencies)
print("[eLCA] Unregistered ELCA_OT_InstallDependencies")
except Exception as e:
print(f"[eLCA] Error unregistering ELCA_OT_InstallDependencies: {e}")
try:
bpy.utils.unregister_class(ELCA_OT_ResetData)
print("[eLCA] Unregistered ELCA_OT_ResetData")
except Exception as e:
print(f"[eLCA] Error unregistering ELCA_OT_ResetData: {e}")
try:
bpy.utils.unregister_class(ELCA_OT_CreateIFCLibrary)
print("[eLCA] Unregistered ELCA_OT_CreateIFCLibrary")
except Exception as e:
print(f"[eLCA] Error unregistering ELCA_OT_CreateIFCLibrary: {e}")
try:
bpy.utils.unregister_class(ELCA_OT_LoadProject)
print("[eLCA] Unregistered ELCA_OT_LoadProject")
except Exception as e:
print(f"[eLCA] Error unregistering ELCA_OT_LoadProject: {e}")
try:
bpy.utils.unregister_class(ELCA_OT_LoadResults)
print("[eLCA] Unregistered ELCA_OT_LoadResults")
except Exception as e:
print(f"[eLCA] Error unregistering ELCA_OT_LoadResults: {e}")
print("[eLCA] Unregistration complete")
if __name__ == "__main__":
print("[eLCA] Running as main script")
register()