-
Notifications
You must be signed in to change notification settings - Fork 17
/
Acis2Step.py
1815 lines (1594 loc) · 67.7 KB
/
Acis2Step.py
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
# -*- coding: utf-8 -*-
'''
Acis2Step.py:
'''
import traceback, os, sys, math, io
import Part
import Acis
from datetime import datetime
from importerUtils import isEqual, getDumpFolder
from FreeCAD import Vector as VEC, Rotation as ROT, Placement as PLC, Matrix as MAT
from importerUtils import logInfo, logWarning, logError, logAlways, isEqual1D, getColorDefault, getDumpFolder, getAuthor, getDescription
from importerConstants import CENTER, DIR_X, DIR_Y, DIR_Z, EPS
if (sys.version_info.major > 2):
long = int
unicode = str
#############################################################
# private variables
#############################################################
_pointsVertex = {}
_pointsCartesian = {}
_directions = {}
_edgeCurves = {}
_lines = {}
_ellipses = {}
_vectors = {}
_cones = {}
_cylinders = {}
_planes = {}
_spheres = {}
_curveBSplines = {}
_assignments = {}
_entities = []
_colorPalette = {}
TRANSFORM_NONE = PLC()
#############################################################
# private functions
#############################################################
def _isIdentity(transf):
return transf.Base.distanceToPoint(CENTER) < EPS and transf.Rotation.Axis.getAngle(DIR_Z) < EPS
def _getE(o):
if (o is None): return None
if (isinstance(o, E)): return o
return E(o)
def _dbl2str(d):
if (d == 0.0):
return u"0."
if (math.fabs(d) > 5e5):
s = ('%E' % d).split('E')
return s[0].rstrip('0') + 'E+' + s[1][1:].lstrip('0')
if (math.fabs(d) < 5e-5):
s = ('%E' % d).split('E')
return s[0].rstrip('0') + 'E-' + s[1][1:].lstrip('0')
s = u"%r" %(d)
return s.rstrip('0')
def _bool2str(v):
return u".T." if v else u".F."
def _str2str(s):
if (s is None): return '$'
return u"'%s'" %(s)
def _entity2str(e):
if (isinstance(e, AnonymEntity)):
return u"%s" %(e.__str__())
return '*'
def _lst2str(l):
return u"(%s)" %(",".join([_obj2str(i) for i in l]))
def _obj2str(o):
if (o is None): return _str2str(o)
if (type(o) == int): return u"%d" %(o)
if (sys.version_info.major < 3):
if (type(o) == long): return u"%d" %(o)
if (type(o) == unicode): return _str2str(o)
if (type(o) == float): return _dbl2str(o)
if (type(o) == bool): return _bool2str(o)
if (type(o) == str): return _str2str(o)
if (isinstance(o, AnyEntity)): return "*"
if (isinstance(o, E)): return u"%r" %(o)
if (isinstance(o, AnonymEntity)): return _entity2str(o)
if (type(o) == list): return _lst2str(o)
if (type(o) == tuple): return _lst2str(o)
raise Exception("Don't know how to convert '%s' into a string!" %(o.__class__.__name__))
def _values3D(v):
return [v.x, v.y, v.z]
def rotation_matrix(axis, angle):
axis.normalize()
a = math.cos(angle / 2.0)
aa = a * a
v = axis * math.sin(angle / -2.0)
b = v.x
c = v.y
d = v.z
aa, bb, cc, dd = a * a, b * b, c * c, d * d
bc, ad, ac, ab, bd, cd = b * c, a * d, a * c, a * b, b * d, c * d
m11 = aa + bb - cc - dd
m12 = 2 * (bc + ad)
m13 = 2 * (bd - ac)
m21 = 2 * (bc - ad)
m22 = aa + cc - bb - dd
m23 = 2 * (cd + ab)
m31 = 2 * (bd + ac)
m32 = 2 * (cd - ab)
m33 = aa + dd - bb - cc
return MAT(m11, m12, m13, 0.0, m21, m22, m23, 0.0, m31, m32, m33, 0.0, 0.0, 0.0, 0.0, 0.0)
def _rotate(vec, rotation):
return rotation_matrix(rotation.Axis, rotation.Angle) * vec
def getColor(entity):
global _colorPalette
r = g = b = None
color = entity.getColor()
if (color):
r, g, b = color.red, color.green, color.blue
else:
color = getColorDefault()
if (color):
r, g, b = color
else:
return None
key = "#%02X%02X%02X" %(int(r*255.0), int(g*255.0), int(b*255.0))
try:
rgb = _colorPalette[key]
except:
rgb = COLOUR_RGB('', r, g, b)
_colorPalette[key] = rgb
return rgb
def assignColor(color, item, context):
global _assignments
if (color):
keyRGB = "%g,%g,%g" %(color.red, color.green, color.blue)
representation = MECHANICAL_DESIGN_GEOMETRIC_PRESENTATION_REPRESENTATION('', [], context)
style = STYLED_ITEM('color', [], item)
representation.items.append(style)
try:
assignment = _assignments[keyRGB]
except:
assignment = PRESENTATION_STYLE_ASSIGNMENT(color);
_assignments[keyRGB] = assignment
style.styles = [assignment]
def _createTransformation(ref1, ref2, idt):
return ListEntity(REPRESENTATION_RELATIONSHIP(None, ref1, ref2), REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(idt), SHAPE_REPRESENTATION_RELATIONSHIP())
def _createUnit(tolerance):
unit = UNIT()
uncr_ctx = GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT()
glob_ctx = GLOBAL_UNIT_ASSIGNED_CONTEXT()
repr_ctx = REPRESENTATION_CONTEXT()
length = ListEntity(LENGTH_UNIT(None), NAMED_UNIT(AnyEntity()), SI_UNIT('MILLI', 'METRE'))
angle1 = ListEntity(NAMED_UNIT(AnyEntity()), PLANE_ANGLE_UNIT(None), SI_UNIT(None, 'RADIAN'))
angle2 = ListEntity(NAMED_UNIT(AnyEntity()), SI_UNIT(None, 'STERADIAN'), SOLID_ANGLE_UNIT(None))
uncertainty = UNCERTAINTY_MEASURE_WITH_UNIT(tolerance, length)
uncr_ctx.units = (uncertainty,)
glob_ctx.assignments = (length, angle1, angle2)
unit.entities = _createGeometricRepresentationList(uncr_ctx, glob_ctx, repr_ctx)
return unit
def _createCartesianPoint(fcVec, name = ''):
global _pointsCartesian
key = "%s,'%s'" %(fcVec, name)
try:
cp = _pointsCartesian[key]
except:
cp = CARTESIAN_POINT(name, _values3D(fcVec))
_pointsCartesian[key] = cp
return cp
def _createVertexPoint(fcVec, name = ''):
global _pointsVertex
key = "%s,'%s'" %(fcVec, name)
try:
vp = _pointsVertex[key]
except:
vp = VERTEX_POINT('', None)
vp.point = _createCartesianPoint(fcVec)
_pointsVertex[key] = vp
return vp
def _createDirection(fcVec, name = ''):
global _directions
v = VEC(fcVec).normalize()
key = "%s,'%s'" %(v, name)
try:
dir = _directions[key]
except:
dir = DIRECTION(name, _values3D(v))
_directions[key] = dir
return dir
def _createVector(fcVec, name = ''):
global _vectors
global _scale
key = "%s,'%s'" %(fcVec, name)
try:
vec = _vectors[key]
except:
vec = VECTOR('', None, _scale)
vec.orientation = _createDirection(fcVec)
_vectors[key] = vec
return vec
def _createAxis1Placement(name, aPt, aName, bPt, bName):
plc = AXIS1_PLACEMENT(name, None, None)
plc.location = _createCartesianPoint(aPt, aName)
plc.axis = _createDirection(bPt, bName)
return plc
def _createAxis2Placement3D(name, aPt, aName, bPt, bName, cPt, cName):
plc = AXIS2_PLACEMENT_3D(name, None, None, None)
plc.location = _createCartesianPoint(aPt, aName)
plc.axis = _createDirection(bPt, bName)
plc.direction = _createDirection(cPt, cName)
return plc
def _createEdgeCurve(p1, p2, curve, sense):
global _edgeCurves
key = "#%d,#%d,#%d,%s" %(p1.id, p2.id, curve.id, _bool2str(sense))
try:
ec = _edgeCurves[key]
except:
ec = EDGE_CURVE('', p1, p2, curve, sense)
_edgeCurves[key] = ec
return ec
def _exportInternalList_(a):
step = ''
for i in a:
if (isinstance(i, ExportEntity)):
step += i.exportSTEP()
elif (type(i) == list):
step += _exportInternalList_(i)
elif (type(i) == tuple):
step += _exportInternalList_(i)
return step
def _createCurveComp(acisCurve):
# TODO
return None
def _createCurveDegenerate(acisCurve):
# TODO
return None
def _createCurveEllipse(acisCurve):
global _ellipses
key = '%s,%s,%s,%s' %(acisCurve.center, acisCurve.axis, acisCurve.major, acisCurve.ratio)
try:
circle = _ellipses[key]
except:
if (isEqual1D(acisCurve.ratio, 1.0)):
circle = CIRCLE('', None, acisCurve.major.Length)
else:
axis1 = acisCurve.major.Length
circle = ELLIPSE('', None, axis1, axis1 * acisCurve.ratio)
circle.placement = _createAxis2Placement3D('', acisCurve.center, 'Origin', acisCurve.axis, 'center_axis', acisCurve.major, 'ref_axis')
_ellipses[key] = circle
return circle
def __create_b_spline_curve(spline):
if (spline):
points = [_createCartesianPoint(pole, 'Ctrl Pts') for pole in spline.poles]
k1 = ",".join(["#%d"%(point.id) for point in points])
k2 = ""
mults = spline.uMults
if (mults):
k2 = ",".join(["%d" %(mult) for mult in mults])
k3 = ""
knots = spline.uKnots
if (knots):
k3 = ",".join(["%r" %(knot) for knot in knots])
key = "(%s),(%s),(%s)" %(k1, k2, k3)
try:
curve = _curveBSplines[key]
except:
degree = spline.uDegree
closed = (spline.poles[0] == spline.poles[-1])
if (spline.rational):
p0 = BOUNDED_CURVE()
p1 = B_SPLINE_CURVE(name=None, degree=degree, points=points, form='UNSPECIFIED', closed=closed, selfIntersecting=False)
p2 = B_SPLINE_CURVE_WITH_KNOTS(name='', mults=mults, knots=knots, form2='UNSPECIFIED', closed=closed)
p3 = CURVE()
p4 = GEOMETRIC_REPRESENTATION_ITEM()
p5 = RATIONAL_B_SPLINE_CURVE(spline.weights)
p6 = REPRESENTATION_ITEM('')
curve = ListEntity(p0, p1, p2, p3, p4, p5, p6)
else:
curve = B_SPLINE_CURVE_WITH_KNOTS(name='', degree=degree, points=points, form='UNSPECIFIED', closed=closed, selfIntersecting=False, mults=spline.uMults, knots=spline.uKnots, form2='UNSPECIFIED')
_curveBSplines[key] = curve
return curve
return None
def _createCurveIntExact(acisCurve):
# acisCurve.spline
# acisCurve.singularity
# acisCurve.surface1# readSurface(chunks, i)
# acisCurve.surface2# readSurface(chunks, i)
# acisCurve.pcurve1 # readBS2Curve(chunks, i)
# acisCurve.pcurve2 # readBS2Curve(chunks, i)
#
curve = __create_b_spline_curve(acisCurve.spline)
return curve
def _createCurveIntBlend(acisCurve):
# TODO
return None
def _createCurveIntBlendSpring(acisCurve):
# TODO
return None
def _createCurveIntLaw(acisCurve):
# TODO
return None
def _createCurveIntOff(acisCurve):
# TODO
return None
def _createCurveIntOffset(acisCurve):
# TODO
return None
def _createCurveIntOffsetSurface(acisCurve):
# TODO
return None
def _createCurveIntSilhouetteParameter(acisCurve):
# TODO
return None
def _createCurveIntParameter(acisCurve):
# TODO
return None
def _createCurveIntProject(acisCurve):
# TODO
return None
def _createCurveIntSurface(acisCurve):
# TODO
return None
def _createCurveIntSilhouetteTaper(acisCurve):
# TODO
return None
def _createCurveIntComp(acisCurve):
# TODO
return None
def _createCurveIntDefm(acisCurve):
# TODO
return None
def _createCurveIntHelix(acisCurve):
# TODO
return None
def _createCurveIntSSS(acisCurve):
# TODO
return None
def _createCurveIntInt(acisCurve):
# TODO
return None
CREATE_CURVE_INT ={
'bldcur': _createCurveIntBlend,
'blend_int_cur': _createCurveIntBlend,
'blndsprngcur': _createCurveIntBlendSpring,
'spring_int_cur': _createCurveIntBlendSpring,
'exactcur': _createCurveIntExact,
'exact_int_cur': _createCurveIntExact,
'lawintcur': _createCurveIntLaw,
'law_int_cur': _createCurveIntLaw,
'offintcur': _createCurveIntOff,
'off_int_cur': _createCurveIntOff,
'offsetintcur': _createCurveIntOffset,
'offset_int_cur': _createCurveIntOffset,
'offsurfintcur': _createCurveIntOffsetSurface,
'off_surf_int_cur': _createCurveIntOffsetSurface,
'parasil': _createCurveIntSilhouetteParameter,
'para_silh_int_cur': _createCurveIntSilhouetteParameter,
'parcur': _createCurveIntParameter,
'par_int_cur': _createCurveIntParameter,
'projcur': _createCurveIntProject,
'proj_int_cur': _createCurveIntProject,
# 'd5c2_cur': _createCurveIntSkin, # !!!No examples available!!!
# 'skin_int_cur': _createCurveIntSkin, # !!!No examples available!!!
# 'subsetintcur': _createCurveIntSubset, # !!!No examples available!!!
# 'subset_int_cur': _createCurveIntSubset, # !!!No examples available!!!
'surfcur': _createCurveIntSurface,
'surf_int_cur': _createCurveIntSurface,
'surfintcur': _createCurveIntInt,
'int_int_cur': _createCurveIntInt,
# 'tapersil': _createCurveIntSilhouetteTaper, # !!!No examples available!!!
# 'taper_silh_int_cur': _createCurveIntSilhouetteTaper, # !!!No examples available!!!
## ASM Extensions ##
'comp_int_cur': _createCurveIntComp,
'defm_int_cur': _createCurveIntDefm,
'helix_int_cur': _createCurveIntHelix,
'sss_int_cur': _createCurveIntSSS,
}
def _createCurveInt(acisCurve):
spline = acisCurve.spline
if (spline):
curve = __create_b_spline_curve(spline)
return curve
else:
try:
create = CREATE_CURVE_INT[acisCurve.subtype]
return create(acisCurve)
except Exception as ex:
logError("Don't know how how to create INT_CURVE %s - %s" %(acisCurve.subtype, ex))
return None
def _createCurveP(acisCurve):
# TODO
return None
def _createCurveStraight(acisCurve):
global _lines
key = "%s,%s" %(acisCurve.root, acisCurve.dir)
try:
line = _lines[key]
except:
line = LINE('', None, None)
line.pnt = _createCartesianPoint(acisCurve.root)
line.dir = _createVector(acisCurve.dir)
_lines[key] = line
return line
def _createCurve(acisCurve):
if (acisCurve is None):
return None
if (isinstance(acisCurve, Acis.CurveComp)):
return _createCurveComp(acisCurve)
if (isinstance(acisCurve, Acis.CurveDegenerate)):
return _createCurveDegenerate(acisCurve)
if (isinstance(acisCurve, Acis.CurveEllipse)):
return _createCurveEllipse(acisCurve)
if (isinstance(acisCurve, Acis.CurveInt)):
return _createCurveInt(acisCurve)
if (isinstance(acisCurve, Acis.CurveIntInt)):
return _createCurveIntInt(acisCurve)
if (isinstance(acisCurve, Acis.CurveP)):
return _createCurveP(acisCurve)
if (isinstance(acisCurve, Acis.CurveStraight)):
return _createCurveStraight(acisCurve)
return None
def _createCoEdge(acisCoEdge):
acisEdge = acisCoEdge.getEdge()
acisCurve = acisEdge.getCurve()
curve = _createCurve(acisCurve)
if (curve):
oe = ORIENTED_EDGE((acisCoEdge.sense == 'forward'))
p1 = _createVertexPoint(acisEdge.getStart())
p2 = _createVertexPoint(acisEdge.getEnd())
e = _createEdgeCurve(p1, p2, curve, (acisEdge.sense == 'forward'))
oe.edge = e
return oe
return None
def _createBoundaries(acisLoops):
boundaries = []
isouter = True
for acisLoop in acisLoops:
coedges = acisLoop.getCoEdges()
edges = []
for acisCoEdge in coedges:
edge = _createCoEdge(acisCoEdge)
if (edge):
edges.append(edge)
if (len(edges) > 0):
face = FACE_BOUND('', True)
loop = EDGE_LOOP('', edges)
face.wire = loop
boundaries.append(face)
return boundaries
def _calculateRef(axis):
if (isEqual1D(axis.x, 1.0)): return DIR_Y
if (isEqual1D(axis.x, -1.0)): return -DIR_Y
return DIR_X.cross(axis) # any perpendicular vector to normal?!?
def _createSurfaceBSpline(bss, acisSurface, sense):
points = []
for u in bss.getPoles():
p = [_createCartesianPoint(v, 'Ctrl Pts') for v in u]
points.append(p)
if (bss.isURational()):
p0 = BOUNDED_SURFACE()
p1 = B_SPLINE_SURFACE(bss.UDegree, bss.VDegree, points, 'UNSPECIFIED', bss.isUClosed(), bss.isVClosed(), False)
p2 = B_SPLINE_SURFACE_WITH_KNOTS(uMults=bss.getUMultiplicities(), vMults=bss.getVMultiplicities(), uKnots=bss.getUKnots(), vKnots=bss.getVKnots(), form2='UNSPECIFIED')
p3 = GEOMETRIC_REPRESENTATION_ITEM()
p4 = RATIONAL_B_SPLINE_SURFACE(bss.getWeights())
p5 = REPRESENTATION_ITEM('')
p6 = SURFACE()
spline = ListEntity(p0, p1, p2, p3, p4, p5, p6)
else:
spline = B_SPLINE_SURFACE_WITH_KNOTS(name='', uDegree=bss.UDegree, vDegree=bss.VDegree, points=points, form='UNSPECIFIED', uClosed=bss.isUClosed(), vClosed=bss.isVClosed(), selfIntersecting=False, uMults=bss.getUMultiplicities(), vMults=bss.getVMultiplicities(), uKnots=bss.getUKnots(), vKnots=bss.getVKnots(), form2='UNSPECIFIED')
spline.__acis__ = acisSurface
return spline, sense == 'forward'
def _createSurfaceCone(center, axis, cosine, sine, major, sense):
global _cones
key = "%s,%s,%s,%s,%s,%s" %(center, axis, major, cosine, sine, major)
try:
cone = _cones[key]
except:
if (cosine * sine < 0):
plc = _createAxis2Placement3D('', center, 'Origin', axis.negative(), 'center_axis', major, 'ref_axis')
else:
plc = _createAxis2Placement3D('', center, 'Origin', axis, 'center_axis', major, 'ref_axis')
radius = major.Length
if (isEqual1D(sine, 0.0)):
cone = CYLINDRICAL_SURFACE('', plc, radius)
else:
angle = math.fabs(math.asin(sine))
cone = CONICAL_SURFACE('', plc, radius, angle)
_cones[key] = cone
if( cosine < 0.0):
return cone, (sense != 'forward')
return cone, (sense == 'forward')
def _createSurfaceCylinder(center, axis, radius, sense):
global _cylinders
key = "%s,%s,%s" %(center, axis, radius)
try:
cylinder = _cylinders[key]
except:
ref = _calculateRef(axis)
plc = _createAxis2Placement3D('', center, 'Origin', axis, 'center_axis', ref, 'ref_axis')
cylinder = CYLINDRICAL_SURFACE('', plc, radius)
_cylinders[key] = cylinder
return cylinder, (sense == 'forward')
def _createSurfacePlane(center, axis, sense):
global _planes
key = "%s,%s" %(center, axis)
try:
plane = _planes[key]
except:
ref = _calculateRef(axis)
plane = PLANE('', None)
plane.placement = _createAxis2Placement3D('', center, 'Origin', axis, 'center_axis', ref, 'ref_axis')
_planes[key] = plane
return plane, sense == 'forward'
def _createSurfaceRevolution(curve, center, axis, sense):
ref = _calculateRef(axis)
revolution = SURFACE_OF_REVOLUTION('', None, None)
revolution.curve = _createCurve(curve)
revolution.placement = _createAxis2Placement3D('', center, 'Origin', axis, 'center_axis', ref, 'ref_axis')
return revolution, (sense == 'forward')
def _createSurfaceSphere(center, radius, pole, sense):
global _spheres
key = "%s,%r" %(center, radius)
try:
sphere = _spheres[key]
except:
sphere = SPHERICAL_SURFACE('', None, radius)
ref = _calculateRef(pole)
sphere.placement = _createAxis2Placement3D('', center, 'Origin', pole, 'center_axis', ref, 'ref_axis')
_spheres[key] = sphere
return sphere, (sense == 'forward')
def _createSurfaceBS(acisSurface, sense):
spline = acisSurface.spline
points = []
for u in spline.poles:
p = [_createCartesianPoint(v, 'Ctrl Pts') for v in u]
points.append(p)
if (spline.rational):
p0 = BOUNDED_SURFACE()
p1 = B_SPLINE_SURFACE(spline.uDegree, spline.vDegree, points, 'UNSPECIFIED', spline.uPeriodic, spline.vPeriodic, False)
p2 = B_SPLINE_SURFACE_WITH_KNOTS(uMults=spline.uMults, vMults=spline.vMults, uKnots=spline.uKnots, vKnots=spline.vKnots, form2='UNSPECIFIED')
p3 = GEOMETRIC_REPRESENTATION_ITEM()
p4 = RATIONAL_B_SPLINE_SURFACE(spline.weights)
p5 = REPRESENTATION_ITEM('')
p6 = SURFACE()
spline = ListEntity(p0, p1, p2, p3, p4, p5, p6)
else:
spline = B_SPLINE_SURFACE_WITH_KNOTS(name='', uDegree=spline.uDegree, vDegree=spline.vDegree, points=points, form='UNSPECIFIED', uClosed=spline.uPeriodic, vClosed=spline.vPeriodic, selfIntersecting=False, uMults=spline.uMults, vMults=spline.vMults, uKnots=spline.uKnots, vKnots=spline.vKnots, form2='UNSPECIFIED')
spline.__acis__ = acisSurface
return spline, sense == 'forward'
def _createSurfaceSpline(acisFace):
surface = acisFace.getSurface()
if (surface.subtype == 'ref'): surface = surface.getSurface()
if (surface.spline):
return _createSurfaceBS(surface, acisFace.sense)
shape = acisFace.build()
if (isinstance(shape, Part.BSplineSurface)):
return _createSurfaceBSpline(shape, surface, acisFace.sense)
# if (isinstance(shape, Part.Mesh)):
# return _createSurfaceMesh(shape, acisFace.sense)
if (isinstance(shape, Part.Cone)):
return _createSurfaceCone(surface.center, surface.axis, surface.cosine, surface.sine, surface.major, acisFace.sense)
if (isinstance(shape, Part.Cylinder)):
return _createSurfaceCylinder(shape.Center, shape.Axis, shape.Radius, acisFace.sense)
if (isinstance(shape, Part.Plane)):
return _createSurfacePlane(shape.Position, shape.Axis, acisFace.sense)
if (isinstance(shape, Part.Sphere)):
return _createSurfaceSphere(surface.center, surface.radius, surface.pole, acisFace.sense)
if (isinstance(shape, Part.SurfaceOfRevolution)):
return _createSurfaceRevolution(surface.profile, surface.center, surface.axis, acisFace.sense)
if (isinstance(shape, Part.Toroid)):
return _createSurfaceToroid(shape.MajorRadius, shape.MinorRadius, shape.Center, shape.Axis, acisFace.sense)
return None, acisFace.sense == 'forwared'
def _createSurfaceToroid(major, minor, center, axis, sense):
torus = TOROIDAL_SURFACE('', None, major, math.fabs(minor))
ref = _calculateRef(axis)
torus.placement = _createAxis2Placement3D('', center, 'Origin', axis, 'center_axis', ref, 'ref_axis')
if (minor < 0.0): return torus, (sense != 'forward')
return torus, (sense == 'forward')
def _createSurfaceFaceShape(acisFace):
surface = acisFace.getSurface()
if (isinstance(surface, Acis.SurfaceCone)):
return _createSurfaceCone(surface.center, surface.axis, surface.cosine, surface.sine, surface.major, acisFace.sense)
# if (isinstance(surface, Acis.SurfaceMesh)):
# return _createSurfaceMesh(surface, acisFace.sense)
if (isinstance(surface, Acis.SurfacePlane)):
return _createSurfacePlane(surface.root, surface.normal, acisFace.sense)
if (isinstance(surface, Acis.SurfaceSphere)):
return _createSurfaceSphere(surface.center, surface.radius, surface.pole, acisFace.sense)
if (isinstance(surface, Acis.SurfaceSpline)):
return _createSurfaceSpline(acisFace)
if (isinstance(surface, Acis.SurfaceTorus)):
return _createSurfaceToroid(surface.major, surface.minor, surface.center, surface.axis, acisFace.sense)
logWarning("Can't export surface '%s.%s'!" %(surface.__class__.__module__, surface.__class__.__name__))
return None, (acisFace.sense == 'forward')
def _convertFace(acisFace, parentColor, context):
color = getColor(acisFace)
if (color is None): color = parentColor
try:
surface, sense = _createSurfaceFaceShape(acisFace)
if (surface):
face = ADVANCED_FACE('', surface, sense)
face.bounds = _createBoundaries(acisFace.getLoops())
assignColor(color, face, context)
return face
except:
logError('Fatal forr acisFace= %s', acisFace.getSurface().getSurface())
return None
def _convertShell(acisShell, representation, parentColor):
# FIXME how to distinguish between open or closed shell?
# MC: vedi OPEN_SHELL e CLOSED_SHELL, ma alla fine non le usa
faces = acisShell.getFaces()
if (len(faces) > 0):
color = getColor(acisShell)
if (color is None): color = parentColor
shell = OPEN_SHELL('',[])
for acisFace in faces:
face = _convertFace(acisFace, color, representation.context)
shell.addFace(face)
assignColor(color, shell, representation.context)
return shell
return None
def _convertLump(acisLump, name, appContext, parentColor, transformation):
#MC:
#NOTA quando si volesse usare Part nativo, siccome li le trasformate le ho gia applicate, bastera esportare in STEP
# Da OCCT
#product_definition
# A shape corresponding to the component type of for components. Each assembly or component has its own product_definition. It is used as a starting point for translation when read.step.product.mode is ON.
#product_definition_shape
# This entity provides a link between product_definition and corresponding shape_definition_representation, or between next_assembly_usage_occurence and corresponding context_dependent_shape_representation.
#shape_definition_representation
# A TopoDS_Compound for assemblies, a CASCADE shape corresponding to the component type for components. Each assembly or component has its own shape_definition_representation. The graph of dependencies is modified in such a way that shape_definition_representations of all components of the assembly are referred by the shape_definition_representation of the assembly.
#next_assembly_usage_occurence
# This entity defines a relationship between the assembly and its component. It is used to introduce (in the dependencies graph) the links between shape_definition_representation of the assembly and shape_definition_representations and context_dependent_shape_representations of all its components.
#context_dependent_shape_representation
# This entity is associated with the next_assembly_usage_occurence entity and defines a placement of the component in the assembly. The graph of dependencies is modified so that each context_dependent_shape_representation is referred by shape_definition_representation of the corresponding assembly.
#shape_representation_relationship_with_transformation
# This entity is associated with context_dependent_shape_representation and defines a transformation necessary to apply to the component in order to locate it in its place in the assembly.
#item_defined_transformation
# This entity defines a transformation operator used by shape_representation_relationship_with_transformation or mapped_item entity
name = "%s_L_%02d" %(name, acisLump.index)
frames = [PRODUCT_CONTEXT('', appContext, 'mechanical')]
prod = PRODUCT(name, frames)
prod_def_fmt = PRODUCT_DEFINITION_FORMATION(name + '_def_fmt', prod)
prod_def_ctx = PRODUCT_DEFINITION_CONTEXT(name + '_def_ctx', appContext, 'design')
prod_transf_def = PRODUCT_DEFINITION(name, prod_def_fmt, prod_def_ctx)
prod_def_shape = PRODUCT_DEFINITION_SHAPE(name + '_def_shape', '', prod_transf_def)
shapeOriginalWithProductInfo = SHAPE_DEFINITION_REPRESENTATION(name, prod_def_shape)
unit = _createUnit(1e-7)
lump = SHELL_BASED_SURFACE_MODEL()
color = getColor(acisLump)
if (color is None): color = parentColor
assignColor(color, lump, unit)
if ((not transformation is None) and (_isIdentity(transformation)==False)):
placement = TRANSFORM_NONE.Base
zDir = DIR_Z
xDir = DIR_X
ident_transf = _createAxis2Placement3D('', placement, '', zDir, '', xDir, '')
advShapeRepresentation = ADVANCED_BREP_SHAPE_REPRESENTATION('', [], unit)
advShapeRepresentation.items.append(lump)
advShapeRepresentation.items.append(ident_transf) # a rhino basta questo con la trasformata effettiva, senza relazioni niente
placement = transformation.Base
zDir = _rotate(DIR_Z, transformation.Rotation)
xDir = _rotate(DIR_X, transformation.Rotation)
transf = _createAxis2Placement3D('', placement, '', zDir, '', xDir, '')
# rappresentazione contenente tutte le trasformate utilizzate nelle istanze
shapeRepresentation_trsfs = SHAPE_REPRESENTATION(unit)
shapeRepresentation_trsfs.items.append(ident_transf)
shapeRepresentation_trsfs.items.append(transf)
idt = ITEM_DEFINED_TRANSFORMATION('', None, ident_transf, transf)
rr_transf = _createTransformation(advShapeRepresentation, shapeRepresentation_trsfs, idt)
prod_transf = PRODUCT('', frames)
prod_transf_def_form = PRODUCT_DEFINITION_FORMATION(prod_transf.name + '_trans_def_form', prod_transf)
prod_transf_def = PRODUCT_DEFINITION(prod.name + '_trans_def', prod_transf_def_form, prod_def_ctx)
prod_transf_def_shape = PRODUCT_DEFINITION_SHAPE(name + '_transdef_shape', '', prod_transf_def)
shapeToBeTransformed = SHAPE_DEFINITION_REPRESENTATION(name, prod_transf_def_shape)
shapeToBeTransformed.representation = advShapeRepresentation
nas = NEXT_ASSEMBLY_USAGE_OCCURRENCE(name + '_inst', name + '_inst', '', shapeOriginalWithProductInfo.definition.definition, shapeToBeTransformed.definition.definition)
prod_def_shape = PRODUCT_DEFINITION_SHAPE(None, None, nas)
CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(rr_transf, prod_def_shape)
shapeRet = shapeToBeTransformed
else:
shapeRepresentation = SHAPE_REPRESENTATION(unit)
shapeRepresentation.items.append(lump)
shapeOriginalWithProductInfo.representation = shapeRepresentation
shapeRet = shapeOriginalWithProductInfo
for acisShell in acisLump.getShells():
shell = _convertShell(acisShell, shapeRet.representation, color)
if (not lump.add(shell)):
logError("Failed to create shell %s", acisShell)
return shapeRet
def _convertBody(acisBody, appPrtDef):
bodies = []
name = acisBody.getName()
if ((name is None) or (len(name) == 0)):
name = "Body_%02d" %(acisBody.index)
transform = acisBody.getTransform()
if (transform):
transformation = transform.getPlacement()
else:
transformation = TRANSFORM_NONE
for acisLump in acisBody.getLumps():
lump = _convertLump(acisLump, name, appPrtDef.application, getColor(acisBody), transformation)
if (lump):
bodies.append(lump.getProduct())
return bodies
def _initExport():
global _pointsVertex, _pointsCartesian, _directions, _vectors
global _edgeCurves, _lines, _ellipses, _curveBSplines
global _cones, _cylinders, _planes, _spheres
global _assignments
global _colorPalette
global _entities
_pointsVertex.clear()
_pointsCartesian.clear()
_directions.clear()
_edgeCurves.clear()
_lines.clear()
_ellipses.clear()
_vectors.clear()
_cones.clear()
_cylinders.clear()
_planes.clear()
_spheres.clear()
_curveBSplines.clear()
_assignments.clear()
_colorPalette.clear()
_entities[:]= []
return
def _finalizeExport():
global _pointsVertex, _pointsCartesian, _directions, _vectors
global _edgeCurves, _lines, _ellipses, _curveBSplines
global _cones, _cylinders, _planes, _spheres
global _assignments
global _colorPalette
global _entities
_pointsVertex.clear()
_pointsCartesian.clear()
_directions.clear()
_edgeCurves.clear()
_lines.clear()
_ellipses.clear()
_vectors.clear()
_cones.clear()
_cylinders.clear()
_planes.clear()
_spheres.clear()
_curveBSplines.clear()
_assignments.clear()
_entities[:] = []
def _setExported(l, b):
if ((type(l) == dict) or (type(l) == list)):
for p in l:
if (isinstance(p, ExportEntity)):
p.has_been_exported = b
else:
l[p].has_been_exported = b
if (isinstance(l, ExportEntity)):
l.has_been_exported = b
def _createGeometricRepresentationList(*entities):
return (GEOMETRIC_REPRESENTATION_CONTEXT(len(entities)),) + entities
#############################################################
# global classes
#############################################################
class E(object):
def __init__(self, value):
self.value = str(value).upper()
def __str__(self):
return self.value
def __repr__(self):
return u".%s." %(self.value)
class AnyEntity(object):
def __init__(self):
super(AnyEntity, self).__init__()
def __repr__(self):
return '*'
class AnonymEntity(object):
def __init__(self):
global _entities
self.id = len(_entities) + 1
_entities.append(self)
def _getParameters(self):
return []
def _getClassName(self):
return ""
def getAttribute(self):
l = [_obj2str(p) for p in self._getParameters()]
return "%s(%s)" %(self._getClassName(), ",".join(l))
def toString(self):
l = [_obj2str(p) for p in self._getParameters()]
return "%s(%s)" %(self._getClassName(), ",".join(l))
def __str__(self):
return self.toString()
def __repr__(self):
l = [_obj2str(p) for p in self._getParameters()]
return u"#%d\t= %s(%s)" %(self.id, self._getClassName(), ",".join(l))
class ExportEntity(AnonymEntity):
def __init__(self):
super(ExportEntity, self).__init__()
self.has_been_exported = False
def _getClassName(self):
return self.__class__.__name__
def exportProperties(self):
step = u""
variables = self._getParameters()
for a in variables:
try:
if (isinstance(a, ReferencedEntity)):
step += a.exportSTEP()
elif (type(a) in (list, tuple)):
step += _exportInternalList_(a)
except:
logError(traceback.format_exc())
return step
def exportSTEP(self):
if (self.has_been_exported):
return ''
step = u""
if (hasattr(self, '__acis__')):
if (self.__acis__.subtype == 'ref'):
step += u"/*\n * ref = %d\n */\n" %(self.__acis__.ref)
else:
step += u"/*\n * $%d\n */\n" %(self.__acis__.index)
step += u"%s;\n" %(self.__repr__())
step += self.exportProperties()
self.has_been_exported = True
return step
class ReferencedEntity(ExportEntity):
def __init__(self):
super(ReferencedEntity, self).__init__()
def __str__(self):
return '#%d' %(self.id)
def _getClassName(self):
return self.__class__.__name__
class NamedEntity(ReferencedEntity):
def __init__(self, name = ''):
super(NamedEntity, self).__init__()
self.name = name
def _getParameters(self):
return super(NamedEntity, self)._getParameters() + [self.name]
class COLOUR_RGB(NamedEntity):
def __init__(self, name = '', red = 0.749019607843137, green = 0.749019607843137, blue = 0.749019607843137):
super(COLOUR_RGB, self).__init__(name)
self.red = red
self.green = green
self.blue = blue
def _getParameters(self):
return super(COLOUR_RGB, self)._getParameters() + [self.red, self.green, self.blue]
class FILL_AREA_STYLE_COLOUR(NamedEntity):
def __init__(self, color):
super(FILL_AREA_STYLE_COLOUR, self).__init__()
self.colour = color
def _getParameters(self):
return super(FILL_AREA_STYLE_COLOUR, self)._getParameters() + [self.colour]
class FILL_AREA_STYLE(NamedEntity):
def __init__(self, color):
super(FILL_AREA_STYLE, self).__init__()
self.styles = [FILL_AREA_STYLE_COLOUR(color)]
def _getParameters(self):
return super(FILL_AREA_STYLE, self)._getParameters() + [self.styles]
class SURFACE_STYLE_FILL_AREA(ReferencedEntity):
def __init__(self, color):
super(SURFACE_STYLE_FILL_AREA, self).__init__()
self.style = FILL_AREA_STYLE(color)
def _getParameters(self):
return super(SURFACE_STYLE_FILL_AREA, self)._getParameters() + [self.style]
class SURFACE_SIDE_STYLE(NamedEntity):
def __init__(self, color):
super(SURFACE_SIDE_STYLE, self).__init__()
self.styles = [SURFACE_STYLE_FILL_AREA(color)]
def _getParameters(self):
return super(SURFACE_SIDE_STYLE, self)._getParameters() + [self.styles]
class SURFACE_STYLE_USAGE(ReferencedEntity):
def __init__(self, color):
super(SURFACE_STYLE_USAGE, self).__init__()
self.sides = _getE('BOTH')
self.style = SURFACE_SIDE_STYLE(color)
def _getParameters(self):
return super(SURFACE_STYLE_USAGE, self)._getParameters() + [self.sides, self.style]
class PRESENTATION_STYLE_ASSIGNMENT(ReferencedEntity):
def __init__(self, color):
super(PRESENTATION_STYLE_ASSIGNMENT, self).__init__()
self.styles = [SURFACE_STYLE_USAGE(color)]
def _getParameters(self):
return super(PRESENTATION_STYLE_ASSIGNMENT, self)._getParameters() + [self.styles]
class APPLICATION_CONTEXT(NamedEntity):
def __init__(self, name = 'Core Data for Automotive Mechanical Design Process'):
super(APPLICATION_CONTEXT, self).__init__(name)
class APPLICATION_PROTOCOL_DEFINITION(NamedEntity):
def __init__(self, name = 'international standard'):
super(APPLICATION_PROTOCOL_DEFINITION, self).__init__(name)