Repository navigation
Expand file tree
/
Copy pathcombinedBackend.txt
More file actions
1654 lines (1371 loc) · 64.7 KB
/
Copy pathcombinedBackend.txt
File metadata and controls
1654 lines (1371 loc) · 64.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
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 cadquery as cq
def create_circular_sketch_on_face(workplane, face, circle_diameter):
# Select the face
face_workplane = workplane.workplane(offset=0).face(face)
# Create the circular sketch
sketch = face_workplane.circle(circle_diameter / 2)
return sketch
def perform_extrude_cut(workplane, sketch, cut_depth):
# Perform the cut
result = workplane.cut(sketch.extrude(-cut_depth))
return result
def circular_cut_on_face(workplane, face_selector, circle_diameter, cut_depth):
# Create the circular sketch
sketch = create_circular_sketch_on_face(workplane, face_selector, circle_diameter)
# Perform the cut
result = perform_extrude_cut(workplane, sketch, cut_depth)
return result
def create_concentric_circles_sketch(workplane, face, outer_diameter, inner_diameter):
if outer_diameter <= inner_diameter:
raise ValueError("Outer diameter must be greater than inner diameter")
# Select the face
face_workplane = workplane.workplane(offset=0).face(face)
# Create the outer circle
sketch = face_workplane.circle(outer_diameter / 2)
# Create the inner circle
sketch = sketch.circle(inner_diameter / 2)
return sketch
def extrude_between_circles(workplane, face, outer_diameter, inner_diameter, extrude_height):
# Create the sketch
sketch = create_concentric_circles_sketch(workplane, face, outer_diameter, inner_diameter)
# Extrude the area between circles
result = sketch.extrude(extrude_height)
return result
/* ================================================================================ */
import cadquery as cq
import numpy as np
def mirror_feature(workplane, feature, mirror_plane):
# Assume feature is a CadQuery object
mirrored = feature.mirror(mirror_plane.origin, mirror_plane.normal)
return workplane.union(mirrored)
def mirror_body(workplane, body, mirror_plane):
# Assume body is a CadQuery Workplane object
mirrored = body.mirror(mirror_plane.origin, mirror_plane.normal)
return workplane.union(mirrored)
def mirror_sketch(sketch, mirror_line):
# Assume sketch is a list of points
mirrored_points = []
for point in sketch:
mirrored_point = mirror_point(point, mirror_line)
mirrored_points.append(mirrored_point)
return mirrored_points
def mirror_point(point, mirror_line):
# Mirror a point across a line
x1, y1 = mirror_line[0]
x2, y2 = mirror_line[1]
x, y = point
dx = x2 - x1
dy = y2 - y1
a = (dx * dx - dy * dy) / (dx * dx + dy * dy)
b = 2 * dx * dy / (dx * dx + dy * dy)
x_new = a * (x - x1) + b * (y - y1) + x1
y_new = b * (x - x1) - a * (y - y1) + y1
return (x_new, y_new)
def create_mirror_plane(origin, normal):
return cq.Plane(origin, normal)
def apply_mirror_operation(model, mirror_type, object_to_mirror, mirror_plane):
if mirror_type == 'feature':
return mirror_feature(model, object_to_mirror, mirror_plane)
elif mirror_type == 'body':
return mirror_body(model, object_to_mirror, mirror_plane)
elif mirror_type == 'sketch':
mirror_line = (mirror_plane.origin[:2], (mirror_plane.origin + mirror_plane.normal)[:2])
return mirror_sketch(object_to_mirror, mirror_line)
else:
raise ValueError(f"Unknown mirror type: {mirror_type}")
/* ================================================================================ */
import json
import uuid
from cadquery import Workplane, Sketch
class ModelManager:
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
self.models = {}
self.history = {}
def create_new_model(self):
from ..models.parametric_model import ParametricModel
model_id = str(uuid.uuid4())
self.models[model_id] = ParametricModel()
self.history[model_id] = []
return model_id
def get_model(self, model_id):
return self.models.get(model_id)
def add_parameter(self, model_id, name, value):
model = self.get_model(model_id)
if model:
model.add_parameter(name, value)
self._add_to_history(model_id, 'add_parameter', {'name': name, 'value': value})
def update_parameter(self, model_id, name, value):
model = self.get_model(model_id)
if model:
old_value = model.parameters.get(name)
model.update_parameter(name, value)
self._add_to_history(model_id, 'update_parameter', {'name': name, 'old_value': old_value, 'new_value': value})
def add_feature(self, model_id, feature_type, *args, **kwargs):
model = self.get_model(model_id)
if model:
feature_id = model.add_feature(feature_type, *args, **kwargs)
self._add_to_history(model_id, 'add_feature', {'feature_type': feature_type, 'args': args, 'kwargs': kwargs})
return feature_id
def remove_feature(self, model_id, feature_id):
model = self.get_model(model_id)
if model:
removed_feature = model.remove_feature(feature_id)
self._add_to_history(model_id, 'remove_feature', {'feature_id': feature_id, 'feature_data': removed_feature})
def perform_circular_cut(self, model_id, face_selector, radius, depth):
model = self.get_model(model_id)
if model:
result = model.circular_cut(face_selector, radius, depth)
self._add_to_history(model_id, 'circular_cut', {'face_selector': face_selector, 'radius': radius, 'depth': depth})
return result
def perform_concentric_extrude(self, model_id, face_selector, outer_radius, inner_radius, height):
model = self.get_model(model_id)
if model:
result = model.concentric_extrude(face_selector, outer_radius, inner_radius, height)
self._add_to_history(model_id, 'concentric_extrude', {
'face_selector': face_selector,
'outer_radius': outer_radius,
'inner_radius': inner_radius,
'height': height
})
return result
def perform_mirror(self, model_id, mirror_plane, keep_original=True):
model = self.get_model(model_id)
if model:
result = model.mirror(mirror_plane, keep_original)
self._add_to_history(model_id, 'mirror', {'mirror_plane': mirror_plane, 'keep_original': keep_original})
return result
def perform_structural_analysis(self, model_id, material_properties, loads, constraints):
from ..routes.structural_analysis import StructuralAnalysis
model = self.get_model(model_id)
if model:
analyzer = StructuralAnalysis(model)
results, failure_points = analyzer.perform_analysis(material_properties, loads, constraints)
self._add_to_history(model_id, 'structural_analysis', {
'material_properties': material_properties,
'loads': loads,
'constraints': constraints
})
return results, failure_points
def undo(self, model_id):
if self.history[model_id]:
action = self.history[model_id].pop()
self._reverse_action(model_id, action)
def redo(self, model_id):
# Implementation depends on how you store redo information
pass
def _add_to_history(self, model_id, action_type, action_data):
self.history[model_id].append({'type': action_type, 'data': action_data})
def _reverse_action(self, model_id, action):
model = self.get_model(model_id)
if model:
if action['type'] == 'add_parameter':
model.remove_parameter(action['data']['name'])
elif action['type'] == 'update_parameter':
model.update_parameter(action['data']['name'], action['data']['old_value'])
elif action['type'] == 'add_feature':
model.remove_last_feature()
elif action['type'] == 'remove_feature':
model.add_feature(action['data']['feature_data'])
# Add more reverse actions for other operation types
def export_model(self, model_id):
model = self.get_model(model_id)
if model:
export_data = {
"modelId": model_id,
"parameters": model.parameters,
"features": [
{
"id": feature['id'],
"type": feature['type'],
"args": feature['args'],
"kwargs": feature['kwargs']
} for feature in model.features
],
"structuralAnalysis": {
"results": model.analysis_results if hasattr(model, 'analysis_results') else None,
"failurePoints": model.failure_points if hasattr(model, 'failure_points') else None
}
}
return json.dumps(export_data, indent=2)
def import_model(self, json_data):
import_data = json.loads(json_data)
model_id = self.create_new_model()
model = self.get_model(model_id)
for name, value in import_data["parameters"].items():
model.add_parameter(name, value)
for feature in import_data["features"]:
model.add_feature(feature["type"], *feature["args"], **feature["kwargs"])
if "structuralAnalysis" in import_data:
model.analysis_results = import_data["structuralAnalysis"]["results"]
model.failure_points = import_data["structuralAnalysis"]["failurePoints"]
model.rebuild()
return model_id
def get_model_data(self, model_id):
model = self.get_model(model_id)
if model:
return {
"id": model_id,
"parameters": model.parameters,
"features": [
{
"id": feature['id'],
"type": feature['type'],
"args": feature['args'],
"kwargs": feature['kwargs']
} for feature in model.features
],
"boundingBox": model.bounding_box(),
"vertices": model.vertices(),
"edges": model.edges(),
"faces": model.faces()
}
/* ================================================================================ */
import cadquery as cq
def create_cylinder(workplane, radius, height):
return workplane.cylinder(height, radius)
def circular_cut(workplane, radius, depth):
return workplane.faces(">Z").circle(radius).cutBlind(-depth)
def concentric_extrude(workplane, outer_radius, inner_radius, height):
return workplane.faces(">Z").circle(outer_radius).circle(inner_radius).extrude(height)
def mirror_feature(workplane, mirror_plane):
return workplane.mirror(mirror_plane.origin, mirror_plane.normal)
# Add more parametric feature functions as needed
/* ================================================================================ */
from flask import Blueprint
main = Blueprint('main', __name__)
@main.route('/api/test')
def test():
return {'message': 'Test route is working!'}
# Import other route files here
# from . import cad_operations, structural_analysis, etc.
/* ================================================================================ */
import cadquery as cq
class ParametricModel:
def __init__(self):
self.parameters = {}
self.features = []
self.workplane = cq.Workplane("XY")
def add_parameter(self, name, value):
self.parameters[name] = value
def update_parameter(self, name, value):
if name in self.parameters:
self.parameters[name] = value
self.rebuild()
else:
raise ValueError(f"Parameter {name} does not exist")
def add_feature(self, feature_func, *args, **kwargs):
feature_id = len(self.features)
self.features.append({
'id': feature_id,
'func': feature_func,
'args': args,
'kwargs': kwargs,
'visible': True,
'color': (0.7, 0.7, 0.7) # Default color (light gray)
})
return feature_id
def set_feature_visibility(self, feature_id, visible):
if 0 <= feature_id < len(self.features):
self.features[feature_id]['visible'] = visible
self.rebuild()
else:
raise ValueError(f"Invalid feature ID: {feature_id}")
def set_feature_color(self, feature_id, color):
if 0 <= feature_id < len(self.features):
self.features[feature_id]['color'] = color
self.rebuild()
else:
raise ValueError(f"Invalid feature ID: {feature_id}")
def rebuild(self):
self.workplane = cq.Workplane("XY")
for feature in self.features:
if feature['visible']:
func = feature['func']
args = [self.parameters.get(arg, arg) for arg in feature['args']]
kwargs = {k: self.parameters.get(v, v) for k, v in feature['kwargs'].items()}
self.workplane = func(self.workplane, *args, **kwargs)
def get_model(self):
return self.workplane
def get_features(self):
return [{'id': f['id'], 'visible': f['visible'], 'color': f['color']} for f in self.features]
/* ================================================================================ */
from flask import Blueprint
main = Blueprint('main', __name__)
@main.route('/api/test')
def test():
return {'message': 'Test route is working!'}
# Import other route files here
# from . import cad_operations, structural_analysis, etc.
/* ================================================================================ */
from flask import request, jsonify
from .model_manager import ModelManager
from .parametric_feature_functions import circular_cut, concentric_extrude, mirror_feature
@app.route('/api/add_feature', methods=['POST'])
def add_feature():
data = request.json
model_id = data.get('modelId')
feature_type = data.get('featureType')
parameters = data.get('parameters', {})
if not all([model_id, feature_type]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager = ModelManager.get_instance()
if feature_type == 'circular_cut':
model_manager.add_feature(model_id, circular_cut, parameters['radius'], parameters['depth'])
elif feature_type == 'concentric_extrude':
model_manager.add_feature(model_id, concentric_extrude, parameters['outerRadius'], parameters['innerRadius'], parameters['height'])
elif feature_type == 'mirror':
model_manager.add_feature(model_id, mirror_feature, parameters['mirrorPlane'])
else:
return jsonify({"success": False, "error": f"Unknown feature type: {feature_type}"}), 400
model_manager.rebuild_model(model_id)
updated_model_data = model_manager.get_model_data(model_id)
return jsonify({"success": True, "updatedModel": updated_model_data})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
/* ================================================================================ */
from flask import Blueprint, request, jsonify
from .structural_analysis import StructuralAnalysis
structural_analysis = Blueprint('structural_analysis', __name__)
@structural_analysis.route('/analyze', methods=['POST'])
def analyze():
data = request.json
model_id = data.get('modelId')
material_properties = data.get('materialProperties')
loads = data.get('loads')
constraints = data.get('constraints')
if not all([model_id, material_properties, loads, constraints]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
analysis = StructuralAnalysis(model_id)
results = analysis.perform_analysis(material_properties, loads, constraints)
return jsonify({"success": True, "results": results})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 500
/* ================================================================================ */
import cadquery as cq
from flask import Blueprint, request, jsonify
from ..cad.model_manager import ModelManager
from ..cad.parametric_feature_functions import circular_cut, concentric_extrude, mirror_feature
# Create a Blueprint
cad_operations = Blueprint('cad_operations', __name__)
# Initialize the ModelManager singleton
model_manager = ModelManager.get_instance()
# Route to create a new model
@cad_operations.route('/create_new_model', methods=['POST'])
def create_new_model():
try:
model_id = model_manager.create_new_model()
return jsonify({"success": True, "modelId": model_id})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
# Route to perform a circular cut on a model
@cad_operations.route('/circular_cut', methods=['POST'])
def circular_cut():
data = request.json
model_id = data.get('modelId')
face_selector = data.get('faceSelector')
radius = data.get('radius')
depth = data.get('depth')
if not all([model_id, face_selector, radius, depth]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager.add_feature(model_id, circular_cut, radius, depth)
model_manager.rebuild_model(model_id)
updated_model_data = model_manager.get_model_data(model_id)
return jsonify({"success": True, "updatedModel": updated_model_data})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
# Route to perform a concentric extrude on a model
@cad_operations.route('/concentric_extrude', methods=['POST'])
def concentric_extrude():
data = request.json
model_id = data.get('modelId')
face_selector = data.get('faceSelector')
outer_radius = data.get('outerRadius')
inner_radius = data.get('innerRadius')
height = data.get('height')
if not all([model_id, face_selector, outer_radius, inner_radius, height]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager.add_feature(model_id, concentric_extrude, outer_radius, inner_radius, height)
model_manager.rebuild_model(model_id)
updated_model_data = model_manager.get_model_data(model_id)
return jsonify({"success": True, "updatedModel": updated_model_data})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
# Route to mirror features of a model
@cad_operations.route('/mirror', methods=['POST'])
def mirror():
data = request.json
model_id = data.get('modelId')
mirror_plane = data.get('mirrorPlane')
keep_original = data.get('keepOriginal', True)
align_to_axis = data.get('alignToAxis')
partial_features = data.get('partialFeatures', {})
if not all([model_id, mirror_plane]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager.add_feature(model_id, mirror_feature, mirror_plane)
model_manager.rebuild_model(model_id)
updated_model_data = model_manager.get_model_data(model_id)
return jsonify({"success": True, "updatedModel": updated_model_data})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
# Route to update a parameter in the model
@cad_operations.route('/update_parameter', methods=['POST'])
def update_parameter():
data = request.json
model_id = data.get('modelId')
parameter_name = data.get('parameterName')
new_value = data.get('newValue')
if not all([model_id, parameter_name, new_value]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager.update_parameter(model_id, parameter_name, new_value)
model_manager.rebuild_model(model_id)
updated_model_data = model_manager.get_model_data(model_id)
return jsonify({"success": True, "updatedModel": updated_model_data})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
# Route to get parameters of the model
@cad_operations.route('/get_parameters/<int:model_id>', methods=['GET'])
def get_parameters(model_id):
try:
model = model_manager.parametric_models[model_id]
return jsonify({"success": True, "parameters": model.parameters})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
# Route to get features of the model
@cad_operations.route('/get_features/<int:model_id>', methods=['GET'])
def get_features(model_id):
try:
model = model_manager.parametric_models[model_id]
return jsonify({"success": True, "features": model.get_features()})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
/* ================================================================================ */
from flask import request, jsonify
from .model_manager import ModelManager
from .cad_exceptions import CADOperationError
@app.route('/api/circular_cut', methods=['POST'])
def circular_cut():
data = request.json
object_id = data.get('objectId')
face_selector = data.get('faceSelector')
circle_diameter = data.get('circleDiameter')
cut_depth = data.get('cutDepth')
if not all([object_id, face_selector, circle_diameter, cut_depth]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager = ModelManager.get_instance()
updated_model_data = model_manager.apply_circular_cut(object_id, face_selector, circle_diameter, cut_depth)
return jsonify({"success": True, "updatedModel": updated_model_data})
except CADOperationError as e:
return jsonify({"success": False, "error": str(e)}), 400
except Exception as e:
app.logger.error(f"An unexpected error occurred: {str(e)}")
return jsonify({"success": False, "error": "An unexpected error occurred. Please try again later."}), 500
/* ================================================================================ */
from flask import request, jsonify
from .model_manager import ModelManager
from .cad_exceptions import CADOperationError
@app.route('/api/concentric_extrude', methods=['POST'])
def concentric_extrude():
data = request.json
object_id = data.get('objectId')
face_selector = data.get('faceSelector')
outer_diameter = data.get('outerDiameter')
inner_diameter = data.get('innerDiameter')
extrude_height = data.get('extrudeHeight')
if not all([object_id, face_selector, outer_diameter, inner_diameter, extrude_height]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager = ModelManager.get_instance()
updated_model_data = model_manager.apply_concentric_extrude(
object_id, face_selector, outer_diameter, inner_diameter, extrude_height
)
return jsonify({"success": True, "updatedModel": updated_model_data})
except CADOperationError as e:
return jsonify({"success": False, "error": str(e)}), 400
except Exception as e:
app.logger.error(f"An unexpected error occurred: {str(e)}")
return jsonify({"success": False, "error": "An unexpected error occurred. Please try again later."}), 500
/* ================================================================================ */
from flask import Blueprint, request, jsonify, send_file
from .model_manager import ModelManager
import io
import json
export_import = Blueprint('export_import', __name__)
@export_import.route('/export_model/<int:model_id>', methods=['GET'])
def export_model(model_id):
try:
model_manager = ModelManager.get_instance()
export_data = model_manager.export_model(model_id)
# Create a BytesIO object
bytes_io = io.BytesIO(export_data.encode('utf-8'))
# Send the file
return send_file(
bytes_io,
mimetype='application/json',
as_attachment=True,
attachment_filename=f'model_{model_id}.json'
)
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
@export_import.route('/import_model', methods=['POST'])
def import_model():
if 'file' not in request.files:
return jsonify({"success": False, "error": "No file part"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"success": False, "error": "No selected file"}), 400
if file:
try:
json_data = file.read().decode('utf-8')
# Validate JSON structure
json.loads(json_data) # This will raise an exception if JSON is invalid
model_manager = ModelManager.get_instance()
model_id = model_manager.import_model(json_data)
model_data = model_manager.get_model_data(model_id)
return jsonify({"success": True, "modelId": model_id, "modelData": model_data})
except json.JSONDecodeError:
return jsonify({"success": False, "error": "Invalid JSON format"}), 400
except ValueError as e:
return jsonify({"success": False, "error": str(e)}), 400
except Exception as e:
return jsonify({"success": False, "error": f"An unexpected error occurred: {str(e)}"}), 500
/* ================================================================================ */
from flask import Blueprint, request, jsonify
from .model_manager import ModelManager
feature_management = Blueprint('feature_management', __name__)
@feature_management.route('/get_features/<int:model_id>', methods=['GET'])
def get_features(model_id):
try:
model_manager = ModelManager.get_instance()
features = model_manager.get_features(model_id)
return jsonify({"success": True, "features": features})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
@feature_management.route('/set_feature_visibility', methods=['POST'])
def set_feature_visibility():
data = request.json
model_id = data.get('modelId')
feature_id = data.get('featureId')
visible = data.get('visible')
if not all([model_id, feature_id is not None, visible is not None]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager = ModelManager.get_instance()
model_manager.set_feature_visibility(model_id, feature_id, visible)
updated_model_data = model_manager.get_model_data(model_id)
return jsonify({"success": True, "updatedModel": updated_model_data})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
@feature_management.route('/set_feature_color', methods=['POST'])
def set_feature_color():
data = request.json
model_id = data.get('modelId')
feature_id = data.get('featureId')
color = data.get('color')
if not all([model_id, feature_id is not None, color]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager = ModelManager.get_instance()
model_manager.set_feature_color(model_id, feature_id, color)
updated_model_data = model_manager.get_model_data(model_id)
return jsonify({"success": True, "updatedModel": updated_model_data})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
/* ================================================================================ */
from flask import Blueprint, request, jsonify
from .model_manager import ModelManager
import json
export_import = Blueprint('export_import', __name__)
@export_import.route('/import_model', methods=['POST'])
def import_model():
if 'file' not in request.files:
return jsonify({"success": False, "error": "No file part"}), 400
file = request.files['file']
if file.filename == '':
return jsonify({"success": False, "error": "No selected file"}), 400
if file:
try:
json_data = file.read().decode('utf-8')
# Validate JSON structure
json.loads(json_data) # This will raise an exception if JSON is invalid
model_manager = ModelManager.get_instance()
model_id = model_manager.import_model(json_data)
model_data = model_manager.get_model_data(model_id)
return jsonify({"success": True, "modelId": model_id, "modelData": model_data})
except json.JSONDecodeError:
return jsonify({"success": False, "error": "Invalid JSON format"}), 400
except ValueError as e:
return jsonify({"success": False, "error": str(e)}), 400
except Exception as e:
return jsonify({"success": False, "error": f"An unexpected error occurred: {str(e)}"}), 500
/* ================================================================================ */
from flask import request, jsonify
from .model_manager import ModelManager
from .mirror_operation import MirrorOperation
from .cad_exceptions import CADOperationError
@app.route('/api/mirror', methods=['POST'])
def mirror():
data = request.json
object_ids = data.get('objectIds')
mirror_plane = data.get('mirrorPlane')
keep_original = data.get('keepOriginal', True)
align_to_axis = data.get('alignToAxis')
partial_features = data.get('partialFeatures', {})
if not all([object_ids, mirror_plane]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager = ModelManager.get_instance()
objects_to_mirror = [model_manager.get_object(obj_id) for obj_id in object_ids]
mirror_op = MirrorOperation(
'complex', # Use 'complex' type for objects that might include circular cuts or concentric extrudes
objects_to_mirror,
mirror_plane,
keep_original,
align_to_axis,
partial_features
)
updated_model_data = model_manager.apply_mirror_operation(mirror_op)
return jsonify({"success": True, "updatedModel": updated_model_data})
except CADOperationError as e:
return jsonify({"success": False, "error": str(e)}), 400
except Exception as e:
app.logger.error(f"An unexpected error occurred: {str(e)}")
return jsonify({"success": False, "error": "An unexpected error occurred. Please try again later."}), 500
/* ================================================================================ */
import numpy as np
from ..cad.model_manager import ModelManager
class StructuralAnalysis:
def __init__(self, model_id):
self.model_manager = ModelManager.get_instance()
self.model = self.model_manager.get_model(model_id)
def prepare_inp_file(self, material_properties, loads, constraints):
# Convert our model to CalculiX input format
# This is a simplified version and would need to be expanded
inp_content = "*NODE\n"
for i, vertex in enumerate(self.model.vertices().vals(), 1):
inp_content += f"{i}, {vertex.X}, {vertex.Y}, {vertex.Z}\n"
inp_content += "*ELEMENT, TYPE=C3D8R\n"
# Add element definitions here
inp_content += "*MATERIAL, NAME=MATERIAL1\n"
inp_content += f"*ELASTIC\n{material_properties['young_modulus']}, {material_properties['poisson_ratio']}\n"
inp_content += "*BOUNDARY\n"
for constraint in constraints:
inp_content += f"{constraint['node']}, {constraint['dof']}, {constraint['value']}\n"
inp_content += "*STEP\n*STATIC\n"
inp_content += "*CLOAD\n"
for load in loads:
inp_content += f"{load['node']}, {load['direction']}, {load['magnitude']}\n"
inp_content += "*NODE PRINT, NSET=NALL\nU\n*EL PRINT, ELSET=EALL\nS\n*END STEP"
with open('model.inp', 'w') as f:
f.write(inp_content)
def run_analysis(self):
# Run CalculiX
subprocess.run(["ccx", "model"])
def process_results(self):
# Process the .frd file generated by CalculiX
# This is a simplified version and would need to be expanded
results = {}
with open('model.frd', 'r') as f:
lines = f.readlines()
for i, line in enumerate(lines):
if line.strip().startswith('1PSTRESS'):
# Extract stress values
stress_values = [float(val) for val in lines[i+1].split()]
results[f'node_{i}'] = {
'stress': max(stress_values)
}
return results
def perform_analysis(self, material_properties, loads, constraints):
self.prepare_inp_file(material_properties, loads, constraints)
self.run_analysis()
return self.process_results()
def generate_recommendations(self, failure_point, material_properties):
recommendations = []
# Recommendation based on safety factor
if failure_point['safety_factor'] < 1:
recommendations.append("Critical: Immediate redesign required. The part is likely to fail under the given load.")
elif failure_point['safety_factor'] < 1.5:
recommendations.append("Increase the thickness or change the geometry of this area to improve the safety factor.")
# Recommendation based on stress concentration
if failure_point['stress'] > 0.8 * material_properties['yield_strength']:
recommendations.append("Consider adding fillets or chamfers to reduce stress concentration in this area.")
# Recommendation based on material
if failure_point['stress'] > 0.5 * material_properties['yield_strength']:
recommendations.append("Consider using a stronger material with a higher yield strength in this area.")
# Recommendation for load redistribution
recommendations.append("Analyze the load path and consider redistributing the load to reduce stress in this area.")
return recommendations
def identify_failure_points(self, results, material_properties):
failure_points = []
for node, data in results.items():
safety_factor = material_properties['yield_strength'] / data['stress']
if safety_factor < 2: # Consider points with safety factor < 2 as potential failure points
severity = 1 - (safety_factor / 2) # Normalize severity between 0 and 1
failure_point = {
'node': node,
'position': data['position'],
'stress': data['stress'],
'safety_factor': safety_factor,
'severity': severity
}
failure_point['recommendations'] = self.generate_recommendations(failure_point, material_properties)
failure_points.append(failure_point)
# Sort failure points by severity (highest to lowest)
failure_points.sort(key=lambda x: x['severity'], reverse=True)
return failure_points[:5] # Return top 5 most severe points
def perform_analysis(self, material_properties, loads, constraints):
self.prepare_inp_file(material_properties, loads, constraints)
self.run_analysis()
results = self.process_results()
failure_points = self.identify_failure_points(results, material_properties)
return results, failure_points
/* ================================================================================ */
from flask import request, jsonify
from .model_manager import ModelManager
@app.route('/api/update_parameter', methods=['POST'])
def update_parameter():
data = request.json
model_id = data.get('modelId')
parameter_name = data.get('parameterName')
new_value = data.get('newValue')
if not all([model_id, parameter_name, new_value]):
return jsonify({"success": False, "error": "Missing required parameters"}), 400
try:
model_manager = ModelManager.get_instance()
model_manager.update_parameter(model_id, parameter_name, new_value)
model_manager.rebuild_model(model_id)
updated_model_data = model_manager.get_model_data(model_id)
return jsonify({"success": True, "updatedModel": updated_model_data})
except Exception as e:
return jsonify({"success": False, "error": str(e)}), 400
/* ================================================================================ */
from flask import Blueprint
main = Blueprint('main', __name__)
@main.route('/api/test')
def test():
return {'message': 'Test route is working!'}
/* ================================================================================ */
class ReversedCircularCutOperation:
def __init__(self, object_id):
self.object_id = object_id
def apply(self, model_manager):
# In a real system, you'd restore the cut volume here
print(f"Reversed circular cut on object {self.object_id}")
return model_manager.get_object(self.object_id)
class CircularCutOperation:
def __init__(self, object_id, face_selector, circle_diameter, cut_depth):
self.object_id = object_id
self.face_selector = face_selector
self.circle_diameter = circle_diameter
self.cut_depth = cut_depth
def apply(self, model_manager):
return model_manager.apply_circular_cut(self.object_id, self.face_selector, self.circle_diameter, self.cut_depth)
def reverse(self):
# Reversing a cut is complex and might require storing the cut volume
# For simplicity, we'll just note that this operation was reversed
# In a real CAD system, you'd need to implement proper reversal
return ReversedCircularCutOperation(self.object_id)
/* ================================================================================ */
class ConcentricExtrudeOperation:
def __init__(self, object_id, face_selector, outer_diameter, inner_diameter, extrude_height):
self.object_id = object_id
self.face_selector = face_selector
self.outer_diameter = outer_diameter
self.inner_diameter = inner_diameter
self.extrude_height = extrude_height
def apply(self, model_manager):
return model_manager.apply_concentric_extrude(
self.object_id, self.face_selector, self.outer_diameter, self.inner_diameter, self.extrude_height
)
def reverse(self):
# Reversing an extrude operation would require cutting the extruded volume
# For simplicity, we'll just note that this operation was reversed
# In a real CAD system, you'd need to implement proper reversal
return ReversedConcentricExtrudeOperation(self.object_id)
class ReversedConcentricExtrudeOperation:
def __init__(self, object_id):
self.object_id = object_id
def apply(self, model_manager):
# In a real system, you'd remove the extruded volume here
print(f"Reversed concentric extrude on object {self.object_id}")
return model_manager.get_object(self.object_id)
/* ================================================================================ */
import cadquery as cq
from flask import request, jsonify, send_file
import tempfile
import os
@app.route('/api/export_step', methods=['POST'])
def export_step():
data = request.json
model_data = data['model']
try:
# Recreate the model from the data
# This is a placeholder - you'll need to implement the actual model recreation
model = recreate_model(model_data)
# Export the model to a STEP file
with tempfile.NamedTemporaryFile(delete=False, suffix='.step') as temp_file:
model.exportStep(temp_file.name)
temp_filename = temp_file.name
# Send the file to the client
return send_file(temp_filename, as_attachment=True, attachment_filename='export.step')
except Exception as e:
return jsonify({"error": str(e)}), 500
finally:
# Clean up the temporary file
if 'temp_filename' in locals():
os.unlink(temp_filename)
/* ================================================================================ */
import cadquery as cq
from flask import request, jsonify
@app.route('/api/extrude', methods=['POST'])
def extrude():
data = request.json
sketch_data = data['sketch']
extrusion_distance = data['distance']