-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathAcis.py
5710 lines (5488 loc) · 234 KB
/
Acis.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 -*-
from __future__ import unicode_literals
__author__ = 'Jens M. Plonka'
__copyright__ = 'Copyright 2023, Germany'
__url__ = "https://www.github.com/jmplonka/InventorLoader"
'''
Acis.py:
Collection of classes necessary to read and analyse Standard ACIS Text (*.sat) files.
'''
import traceback, Part, FreeCAD, re
from importerUtils import *
from FreeCAD import Vector as VEC, Placement as PLC, Matrix as MAT, Base
from math import inf, pi, fabs, degrees, asin, sin, cos, tan, atan2, ceil, e, cosh, sinh, tanh, acos, acosh, asin, asinh, atan, atanh, log, sqrt, exp, log10
from importerConstants import MIN_0, MIN_PI, MIN_PI2, MIN_INF, MAX_2PI, MAX_PI, MAX_PI2, MAX_INF, MAX_LEN, CENTER, DIR_X, DIR_Y, DIR_Z, ENCODING_FS
V2D = Base.Vector2d
if (sys.version_info.major > 2):
long = int
# Primitives for Binary File Format (.sab)
TAG_CHAR = 2 # 0x02 -> character (unsigned 8 bit)
TAG_SHORT = 3 # 0x03 -> 16Bit signed value
TAG_LONG = 4 # 0x04 -> 32/64Bit signed value
TAG_FLOAT = 5 # 0x05 -> 32Bit IEEE Float value
TAG_DOUBLE = 6 # 0x06 -> 64Bit IEEE Float value
TAG_UTF8_U8 = 7 # 0x07 -> 8Bit length + UTF8-Char
TAG_UTF8_U16 = 8 # 0x08 -> 16Bit length + UTF8-Char
TAG_UTF8_U32_A = 9 # 0x09 -> 32Bit length + UTF8-Char
TAG_TRUE = 10 # 0x0A -> Logical true value
TAG_FALSE = 11 # 0x0B -> Logical false value
TAG_ENTITY_REF = 12 # 0x0C -> Entity reference
TAG_IDENT = 13 # 0x0D -> Sub-Class-Name
TAG_SUBIDENT = 14 # 0x0E -> Base-Class-Namme
TAG_SUBTYPE_OPEN = 15 # 0x0F -> Opening block tag
TAG_SUBTYPE_CLOSE = 16 # 0x10 -> Closing block tag
TAG_TERMINATOR = 17 # 0x11 -> '#' sign
TAG_UTF8_U32_B = 18 # 0x12 -> 32Bit length + UTF8-Char
TAG_POSITION = 19 # 0x13 -> 3D-Vector scaled (scaling will be done later because of text file handling!)
TAG_VECTOR_3D = 20 # 0x14 -> 3D-Vector normalized
TAG_ENUM_VALUE = 21 # 0x15 -> value of an enumeration
TAG_VECTOR_2D = 22 # 0x16 -> U-V-Vector
TAG_INT64 = 23 # 0x17 -> used by AutoCAD ASM int64 attributes
# TAG_FALSE, TAG_TRUE value mappings
def __build_bool_enum__(false_value, true_value, true_key = 'T'):
return {
TAG_TRUE: true_value, true_key: true_value, 1: true_value,
TAG_FALSE: false_value, 'F': false_value, 0: false_value,
}
RANGE = __build_bool_enum__('I', 'F', 'I')
REFLECTION = __build_bool_enum__('no_reflect', 'reflect')
SURF_RIGID = __build_bool_enum__('non_rigid', 'rigid')
SURF_AXIS_SWEEP = __build_bool_enum__('non_axis_sweep', 'axis_sweep')
ROTATION = __build_bool_enum__('no_rotate', 'rotate')
SHEAR = __build_bool_enum__('no_shear', 'shear')
SENSE = __build_bool_enum__('forward', 'reversed')
SENSEV = __build_bool_enum__('forward_v', 'reverse_v')
SIDES = __build_bool_enum__('single', 'double')
SIDE = __build_bool_enum__('out', 'in')
SURF_BOOL = __build_bool_enum__('FALSE', 'TRUE')
SURF_NORM = __build_bool_enum__('ISO', 'UNKNOWN')
SURF_DIR = __build_bool_enum__('SKIN', 'PERPENDICULAR')
SURF_SWEEP = __build_bool_enum__('angled', 'normal')
CIRC_TYP = __build_bool_enum__('non_cross', 'cross')
CIRC_SMTH = __build_bool_enum__('non_smooth', 'smooth')
CALIBRATED = __build_bool_enum__('uncalibrated', 'calibrated')
CHAMFER_TYPE = __build_bool_enum__('const', 'radius')
CONVEXITY = __build_bool_enum__('concave', 'convex')
RENDER_BLEND = __build_bool_enum__('rb_snapshot', 'rb_envelope')
BOOLEAN = __build_bool_enum__('F', 'T')
# TAG_ENUM value mappings
RAD_FORM_ENTS = ('unknown', 'two_ends', 'functional', 'fixed_width')
VAR_RADIUS = {0: 'single_radius', 1: 'two_radii'}
VAR_CHAMFER = {3: 'rounded_chamfer'}
CLOSURE = {0: 'open', 1: 'closed', 2: 'periodic', TAG_FALSE: 'open', TAG_TRUE: 'periodic'}
SINGULARITY = {0: 'full', 1: 'v', 2: 'none', TAG_FALSE: 'none', TAG_TRUE: 'full'}
VBL_CIRLE = {0: 'circle', 1: 'ellipse', 3: 'unknown', 'cylinder': 'circle'}
CURV_DIR = {0: 'left', 2: 'right'}
scale = 1.0
_nameMtchAttr = {}
_dcIdxAttributes = {} # dict of an attribute list
LENGTH_TEXT = re.compile('[ \t]*(\\d+) +(.*)')
TOKEN_TRANSLATIONS = {
'0x0a': TAG_TRUE,
'0x0A': TAG_TRUE,
'0x0b': TAG_FALSE,
'0x0B': TAG_FALSE,
'{': TAG_SUBTYPE_OPEN,
'}': TAG_SUBTYPE_CLOSE,
'#': TAG_TERMINATOR
}
_reader = None
_getSLong = getSInt32
_getULong = getUInt32
def getReader():
'''
Returns the current reader for the ACIS document.
'''
global _reader
return _reader
def setReader(reader):
'''
Sets the reader for the current ACIS document.
Parameters:
reader: AcisReader
The current ACIS document's reader
'''
global _reader
clearEntities()
_reader = reader
def getDcAttributes():
global _dcIdxAttributes
return _dcIdxAttributes
def _getStr_DEFAULT(data, offset, end):
txt = data[offset: end].decode('cp1252')
if (sys.version_info.major < 3):
txt = txt.encode(ENCODING_FS).decode("utf8")
return txt, end
SPACE_CLAIM={}
SPACE_CLAIM_A={}
def _getStr_SpaceClaim(data, offset, end):
blob = data[offset: end]
i = blob.find(b'%')
if (i>=0):
txt = blob[0:i].decode('cp1252')
if (sys.version_info.major < 3):
txt = txt.encode(ENCODING_FS).decode("utf8")
if (len(blob) == i + 2):
idx, _ = getUInt8(blob, i + 1)
if (i == 0):
txt = SPACE_CLAIM_A[idx]
else:
SPACE_CLAIM_A[idx] = txt
elif (len(blob) == i + 5):
idx, _ = _getULong(blob, i + 1)
if (i == 0):
txt = SPACE_CLAIM[idx]
else:
SPACE_CLAIM[idx] = txt
else:
txt = blob.decode('cp1252')
if (sys.version_info.major < 3):
txt = txt.encode(ENCODING_FS).decode("utf8")
return txt, end
_getStr_ = _getStr_DEFAULT
def _set_attribute_DEFAULT(self, record, pos):
i = pos
self._next, i = getRefNode(record, i, 'attrib')
self._previous, i = getRefNode(record, i, 'attrib')
self._owner, i = getRefNode(record, i, None)
if ((getVersion() > 15.0) and (isASM() == False)): i += 18 # skip ???
return i
def _set_attribute_SpaceClaim(self, record, pos):
i = pos
self._next, i = getRefNode(record, i, 'attrib')
self._previous, i = getRefNode(record, i, 'attrib')
self._owner, i = getRefNode(record, i, None)
i += 1 # skip ???
return i
_set_attribute_ = _set_attribute_DEFAULT
def _handle_topology_DEFAULT(obj, pos):
i = pos
vrs = getVersion()
if ((vrs > 10.0) and (isASM() == False)): i += 1 # skip ???
if (vrs > 6.0): i += 1 # skip ???
return i
def _handle_topology_SpaceClaim(obj, pos):
i = pos
i += 2 # UINT32, REF, UINT32
return i
_handle_topology_ = _handle_topology_DEFAULT
def COS(x): return (cos(x))
def COSH(x): return (cosh(x))
def COT(x): return (cos(x)/sin(x))
def COTH(x): return (cosh(x)/sinh(x))
def CSC(x): return (1/sin(x))
def CSCH(x): return (1/sinh(x))
def SEC(x): return (1/cos(x))
def SECH(x): return (1/cosh(x))
def SIN(x): return (sin(x))
def SINH(x): return (sinh(x))
def TAN(x): return (tan(x))
def TANH(x): return (tanh(x))
def ARCCOS(x): return (acos(x))
def ARCCOSH(x): return (acosh(x))
def ARCOT(x): return (pi/2 - atan(x))
def ARCOTH(x): return (0.5*log((x+1)/(x-1)))
def ARCCSC(x): return (asin(1/x))
def ARCCSCH(x): return (log((1+sqrt(1+x**2))/x))
def ARCSEC(x): return (acos(1/x))
def ARCSECH(x): return (log((1+sqrt(1-x**2))/x))
def ARCSIN(x): return (asin(x))
def ARCSINH(x): return (asinh(x))
def ARCTAN(x): return (atan(x))
def ARCTANH(x): return (atanh(x))
def ABS(x): return (abs(x))
def EXP(x): return (exp(x))
def LN(x): return (log(x))
def LOG(x): return (log10(x))
def NORM(value): return VEC(value.x, value.y, value.z).normalize()
def ROTATE(v, t): return t.rotate(v)
def CROSS(v1, v2): return v1.cross(v2)
def DOT(v1, v2): return v1.dot(v2)
def SET(x):
if (x > 0.0): return 1
return -1 if (x < 0.0) else 0
def SIGN(x): return SET(x)
def SIZE(v): return v.Length()
#def STEP(l1, n1, l2, n2, ...) ... will throw an error if found in evaluation
def TERM(v, n): return v.__getitem__(n)
def TRANS(v, t):
return t.transpose(v)
def MIN(*x): return min(x)
def MAX(*x): return max(x)
#def NOT(x) ... will throw an error if found in evaluation
def DCUR(c, x): return c.parameter(x)
def DSURF(c, u, v): return c.parameter(u, v)
def vec2sat(v): return u"%s %s %s" %(v.x, v.y, v.z)
class Law(object):
# Laws:
# trigonometric:
# cos(x), cosh(x), cot(x) = cos(x)/sin(x), coth(x)
# csc(x) = 1/sin(x), csch(x), sec(x) = 1/cos(x), sech(x)
# sin(x), sinh(x), tan(x), tanh(x)
# arccos(x), arccosh(x), arcot(x), arcoth(x)
# arccsc(x), arccsch(x), arcsec(x), arcsech(x)
# arcsin(x), arcsinh(x), arctan(x), arctanh(x)
# functions:
# vec(x,y,z), norm(X)
# abs(x), exp(x), ln(x), log(x), sqrt(x)
# rotate(x,y), set(x) = sign(x), size(x), step(...)
# term(X,n), trans(X,y)
# min(x), max(x), not(x)
# operators:
# +,-,*,/,x,^,<,>,<=,>=
# constants
# e = 2.718
# pi= 3.141
def __init__(self, eq):
#FIXME: how to handle cross operator???
# convert ^ into **
self.eq = eq.replace('^', ' ** ')
def evaluate(self, X):
try:
return eval(self.eq)
except Exception as e:
logError(u" Can't evaluate '%s': %s", self.eq, e)
return None
def init():
global _dcIdxAttributes
clearEntities()
_dcIdxAttributes.clear()
def clearEntities():
'''
Clears all cached enties.
'''
global _nameMtchAttr
_nameMtchAttr.clear()
def getScale():
return getReader().scale
def setVersion(vers):
global version
version = vers
def getVersion():
return getReader().version
def isASM():
header = getReader().header
return (hasattr(header, 'asm'))
def getAsmMajor():
# e.g.: Inventor 2010 -> 215, 2020 -> 225
global _reader
header = _reader.header
if (hasattr(header, 'asm')):
return header.asm[0]
return 0
def createEntity(record):
if (record is None): return None
if (record.index < 0): return None
if (record.entity): return record.entity
try:
entity = RECORD_2_ENTITY[record.name]()
except:
#Found unknown class: try to find the base class
types = record.name.split('-')
i = 1
entity = Entity()
t = 'Entity'
while (i<len(types)):
try:
t = "-".join(types[i:])
entity = RECORD_2_ENTITY[t]()
break
except:
i += 1
logError(u" Missing class implementation for '%s' - using base class '%s'!", record.name, t)
try:
if (hasattr(entity, 'set')):
entity.set(record)
except:
#MC e' importante recuperare quando non si riesce a parsare un item
return None
return entity
def getValue(chunks, index):
val = chunks[index].val
return val, index + 1
def getRefNode(record, index, name):
chunk = record.chunks[index]
if (chunk.tag == TAG_ENTITY_REF):
ref = chunk.record
if (name is not None) and (ref is not None) and (ref.name.endswith(name) == False):
raise Exception("Expected %s but found %s (-%s)" %(name, ref.name, record.index))
return ref, index + 1
raise Exception("Chunk at index=%d, is not a reference" %(index))
def getBoolean(chunks, index):
chunk = chunks[index]
if (chunk.tag == TAG_UTF8_U8):
if (chunk.val == 'T'):
chunk = AcisChunkEnumValue(TAG_TRUE, TAG_TRUE, BOOLEAN)
else:
chunk = AcisChunkEnumValue(TAG_FALSE, TAG_FALSE, BOOLEAN)
chunks[index] = chunk
elif (chunk.tag in [TAG_TRUE, TAG_FALSE]):
chunk.values = BOOLEAN
return chunk.tag == TAG_TRUE, index + 1
def getInteger(chunks, index):
val, i = getValue(chunks, index)
return int(val), i
def getIntegers(chunks, index, count):
i = index
arr = []
for n in range(0, count):
n, i = getInteger(chunks, i)
arr.append(n)
return arr, i
def getDcIndexMappings(chunks, index, attr):
global _dcIdxAttributes
m = []
count, i = getInteger(chunks, index)
for n in range(count):
dcIdx, i = getInteger(chunks, i)
value, i = getInteger(chunks, i)
m.append((dcIdx, value))
try:
indexMappings = _dcIdxAttributes[dcIdx]
except:
indexMappings = IndexMappings()
_dcIdxAttributes[dcIdx] = indexMappings
indexMappings.append(attr)
return m, i
def getLong(chunks, index):
val, i = getValue(chunks, index)
return long(val), i
def getFloat(chunks, index):
val, i = getValue(chunks, index)
return float(val), i
def getFloats(chunks, index, count):
i = index
arr = []
n = 0
while n < count:
chunk = chunks[i]
i += 1
if (chunk.tag in [TAG_POSITION, TAG_VECTOR_3D]):
arr += chunk.val
n += len(chunk.val)
else:
arr.append(float(chunk.val))
n += 1
return arr, i
def getFloatsScaled(chunks, index, count):
s = getScale()
i = index
arr = []
for n in range(0, count):
f, i = getFloat(chunks, i)
arr.append(f * s)
return arr, i
def getFloatArray(chunks, index):
n, i = getInteger(chunks, index)
arr, i = getFloats(chunks, i, n)
return arr, i
def getLength(chunks, index):
l, i = getFloat(chunks, index)
return l * getScale(), i
def getText(chunks, index):
chunk = chunks[index]
if (chunk.tag == TAG_DOUBLE):
return getValue(chunks, index+1)
return getValue(chunks, index)
def getEnumByTag(chunks, index, values):
chunk = chunks[index]
if (chunk.tag == TAG_UTF8_U8):
chunk = AcisChunkEnumValue(TAG_ENUM_VALUE, chunk.val, values)
idx = 0
for key in values:
if (type(values) == dict):
if (chunk.val == values[key]):
chunk.val = key
break;
else:
if (chunk.val == idx):
chunk.val = idx
break;
idx += 1
chunks[index] = chunk
elif (chunk.tag == TAG_DOUBLE):
chunk = AcisChunkEnumValue(TAG_ENUM_VALUE, 11 - int(chunk.val), values)
chunks[index] = chunk
else:
chunk.values = values
return values[chunk.val], index + 1
def getEnumByValue(chunks, index, values):
chunk = chunks[index]
try:
if (chunk.tag != TAG_ENUM_VALUE):
chunk = AcisChunkEnumValue(TAG_ENUM_VALUE, chunk.val, values)
chunks[index] = chunk
else:
chunk.values = values
return values[chunk.val], index + 1
except:
return chunk.val, index + 1
def getSides(chunks, index):
sides, i = getEnumByTag(chunks, index, SIDES)
if (sides == 'double'):
side, i = getEnumByTag(chunks, i, SIDE)
return sides, side, i
return sides, None, i
def getSingularity(chunks, index):
if (getVersion() > 4.0):
return getEnumByValue(chunks, index, SINGULARITY)
return 'full', index
def getUnknownFT(chunks, index):
i = index
val = 'F'
arr = []
val2 = 'F'
if ((getVersion() > 7.0) and (isASM() == False)):
val, i = getValue(chunks, i)
if (val == 'T'):
arr, i = getFloats(chunks, i, 6)
val2, i = getValue(chunks, i)
return (val, arr, val2), i
def getRange(chunks, index, default, scale):
type, i = getEnumByTag(chunks, index, RANGE)
val = default
if (type in ('F', TAG_FALSE)):
val, i = getFloat(chunks, i)
elif (type == 'T'):
arr, i = getFloats(chunks, i, 7)
val = arr[0]
return Range(type, val, scale), i
def getInterval(chunks, index, defMin, defMax, scale):
lower, i = getRange(chunks, index, defMin, scale)
upper, i = getRange(chunks, i, defMax, scale)
return Interval(lower, upper), i
def getPoint(chunks, index):
chunk = chunks[index]
if (chunk.tag in [TAG_POSITION, TAG_VECTOR_3D]):
return chunk.val, index + 1
x, i = getFloat(chunks, index)
y, i = getFloat(chunks, i)
z, i = getFloat(chunks, i)
return (x, y, z), i
def getVector(chunks, index):
p, i = getPoint(chunks, index)
return VEC(p[0], p[1], p[2]), i
def getLocation(chunks, index):
v, i = getVector(chunks, index)
return v * getScale(), i
def getDimensionCurve(chunks, index):
# DIMENSION = (nullbs|nurbs [:NUMBER:]|nubs [:NUMBER:])
val, i = getValue(chunks, index)
if (val == 'nullbs'):
return val, 0, i
if (val in ('nurbs', 'nubs')):
degrees, i = getInteger(chunks, i)
return val, degrees, i
raise Exception("Unknown DIMENSION '%s'" %(val))
def getDimensionSurface(chunks, index):
# DIMENSION = (nullbs|nurbs [:NUMBER:]|nubs [:NUMBER:]|summary [:NUMBER: Version > 17])
val, i = getValue(chunks, index)
if (val == 'nullbs'):
return val, None, None, i
if (val in ('nurbs', 'nubs', 'summary')):
degreesU, i = getInteger(chunks, i)
degreesV, i = getInteger(chunks, i)
return val, degreesU, degreesV, i
raise Exception("Unknown DIMENSION '%s'" %(val))
def getClosureCurve(chunks, index):
# CLOSURE = (open=0|closed=1|periodic=2)
closure, i = getEnumByValue(chunks, index, CLOSURE)
if (closure in ('open', 'closed', 'periodic')):
knots, i = getInteger(chunks, i)
return closure, knots, i
raise Exception("Unknown closure '%s'!" %(closure))
def getClosureSurface(chunks, index):
# Syntax: [:CLOSURE:] [:CLOSURE:] [:FULL:] [:FULL:] [:NUMBER:] [:NUMBER:]
# CLOSURE = (open=0|closed=1|periodic=2)
# FULL = (full=0|none=1)
closureU, i = getEnumByValue(chunks, index, CLOSURE)
if (closureU in ('both', 'u', 'v')):
closureU, i = getEnumByValue(chunks, i, CLOSURE)
if (closureU in ('open', 'closed', 'periodic')):
# open none none 2 2
closureV, i = getEnumByValue(chunks, i, CLOSURE)
singularityU, i = getEnumByValue(chunks, i, SINGULARITY)
singularityV, i = getEnumByValue(chunks, i, SINGULARITY)
countU, i = getInteger(chunks, i)
countV, i = getInteger(chunks, i)
return closureU, closureV, singularityU, singularityV, countU, countV, i
raise Exception("Unknown closure '%s'!" %(closureU))
def readKnotsMults(count, chunks, index):
knots = []
mults = []
i = index
for j in range(count):
knot, i = getFloat(chunks, i)
mult, i = getInteger(chunks, i)
knots.append(knot)
mults.append(mult)
return knots, mults, i
def adjustMultsKnots(knots, mults, degree):
mults[0] = degree + 1
mults[-1] = degree + 1
return knots, mults
def readPoints2DList(spline, count, chunks, index):
spline.uKnots, spline.uMults, i = readKnotsMults(count, chunks, index)
us = sum(spline.uMults) - (spline.uDegree - 1)
spline.poles = [None for r in range(0, us)]
spline.weights = [1 for r in range(0, us)] if (spline.rational) else None
for k in range(0, us):
u, i = getLength(chunks, i)
v, i = getLength(chunks, i)
spline.poles[k] = V2D(u, v)
if (spline.rational): spline.weights[k], i = getFloat(chunks, i)
spline.uKnots, spline.uMults = adjustMultsKnots(spline.uKnots, spline.uMults, spline.uDegree)
return spline, i
def readPoints3DList(spline, count, chunks, index):
spline.uKnots, spline.uMults, i = readKnotsMults(count, chunks, index)
us = sum(spline.uMults) - (spline.uDegree - 1)
spline.poles = [None for r in range(0, us)]
spline.weights = [1 for r in range(0, us)] if (spline.rational) else None
for u in range(0, us):
spline.poles[u], i = getLocation(chunks, i)
if (spline.rational): spline.weights[u], i = getFloat(chunks, i)
spline.uKnots, spline.uMults = adjustMultsKnots(spline.uKnots, spline.uMults, spline.uDegree)
return spline, i
def readPoints3DSurface(spline, countU, countV, chunks, index):
# row definitions
spline.uKnots, spline.uMults, i = readKnotsMults(countU, chunks, index)
# column definitions
spline.vKnots, spline.vMults, i = readKnotsMults(countV, chunks, i)
us = sum(spline.uMults) - (spline.uDegree - 1)
vs = sum(spline.vMults) - (spline.vDegree - 1)
spline.poles = [[None for c in range(0, vs)] for r in range(0, us)]
spline.weights = [[1 for c in range(0, vs)] for r in range(0, us)] if (spline.rational) else None
for v in range(0, vs):
for u in range(0, us):
spline.poles[u][v], i = getLocation(chunks, i)
if (spline.rational): spline.weights[u][v], i = getFloat(chunks, i)
spline.uKnots, spline.uMults = adjustMultsKnots(spline.uKnots, spline.uMults, spline.uDegree)
spline.vKnots, spline.vMults = adjustMultsKnots(spline.vKnots, spline.vMults, spline.vDegree)
return spline, i
def readBlend(chunks, index):
nubs, i = readBS2Curve(chunks, index)
if (nubs is not None):
nubs.sense, i = getEnumByTag(chunks, i, SENSE)
nubs.factor, i = getFloat(chunks, i)
return nubs, i
return None, index
def readLaw(chunks, index):
n, i = getText(chunks, index)
if (n == 'TRANS'):
v = Transform()
i = v.setBulk(chunks, i)
return (n, v), i
if (n == 'EDGE'):
c, i = readCurve(chunks, i)
f, i = getFloats(chunks, i, 2)
return (n, c, f), i
if (n == 'SPLINE_LAW'):
a, i = getInteger(chunks, i)
b, i = getFloatArray(chunks, i)
c, i = getFloatArray(chunks, i)
d, i = getPoint(chunks, i)
return (n, a, b, c, d), i
if (n == 'null_law'):
return (n, None), i
return Law(n), i
def newInstance(CLASSES, key):
cls = CLASSES[key]
if (cls): return cls()
return None
def readCurve(chunks, index):
val, i = getValue(chunks, index)
try:
curve = newInstance(CURVES, val)
if (curve is not None):
i = curve.setSubtype(chunks, i)
return curve, i
except:
logError(traceback.format_exc())
raise Exception(" Unknown curve-type '%s'!" % (val))
def readSurface(chunks, index):
chunk = chunks[index]
i = index + 1
subtype = chunk.val
if (chunk.tag in [TAG_UTF8_U8, TAG_IDENT]):
try:
surface = newInstance(SURFACES, subtype)
if (surface is not None):
i = surface.setSubtype(chunks, i)
except:
logError(traceback.format_exc())
raise Exception("Unknown surface-type '%s'!" % (subtype))
return surface, i
#FIXME: this is a dirty hack :(
if (chunk.tag == TAG_DOUBLE):
a, i = getFloats(chunks, index, 5)
return None, i
if (chunk.tag in [TAG_POSITION, TAG_VECTOR_3D]):
a, i = getFloats(chunks, i, 2)
return None, i
def getDiscontinuityInfo(chunks, index, inventor):
a1, i = getFloatArray(chunks, index)
a2, i = getFloatArray(chunks, i)
a3, i = getFloatArray(chunks, i)
a4, i = getFloatArray(chunks, i)
a5, i = getFloatArray(chunks, i)
a6, i = getFloatArray(chunks, i)
if (inventor):
e, i = getBoolean(chunks, i)
else:
e = False
return (a1, a2, a3, a4, a5, a6, e), i
def rotateShape(shape, dir):
# Setting the axis directly doesn't work for directions other than x-axis!
angle = degrees(DIR_Z.getAngle(dir))
if (not isEqual1D(angle, 0)):
axis = DIR_Z.cross(dir) if angle != 180 else DIR_X
shape.rotate(PLC(CENTER, axis, angle))
return
def isBetween(a, c, b):
ac = a.distanceToPoint(c)
cb = c.distanceToPoint(b)
ab = a.distanceToPoint(b)
return ac + cb == ab
def isOnLine(sEdge, fEdge):
# either start- or endpoint mus be same!
sp = [v.Point for v in sEdge.Vertexes]
fp = [v.Point for v in fEdge.Vertexes]
# if (isEqual(sp[0], fp[0]) or isEqual(sp[1], fp[0])): return isBetween(sp[0], fp[1], sp[1])
# if (isEqual(sp[0], fp[1]) or isEqual(sp[1], fp[1])): return isBetween(sp[0], fp[0], sp[1])
if (isEqual(sp[0], fp[0])): return isBetween(sp[0], fp[1], sp[1])
if (isEqual(sp[1], fp[1])): return isBetween(sp[0], fp[0], sp[1])
return False
def isOnCircle(sEdge, fEdge):
sc = sEdge.Curve
fc = fEdge.Curve
if (isEqual1D(fc.Radius, sc.Radius)):
# if (isEqual(fc.Axis, sc.Axis) or isEqual(-1 * fc.Axis, sc.Axis)):
if (isEqual(fc.Axis, sc.Axis)):
sp = [v.Point for v in sEdge.Vertexes]
fp = [v.Point for v in fEdge.Vertexes]
return (isEqual(sp[0], fp[0]))
return False
def isOnEllipse(se, fe):
sc = se.Curve
fc = fe.Curve
if (isEqual(fc.Location, sc.Location)):
if (isEqual(fc.Axis, sc.Axis)):
if (isEqual(fc.Focus1, sc.Focus1)):
if (isEqual1D(fc.MajorRadius, sc.MajorRadius)):
return isEqual1D(fc.MinorRadius, sc.MinorRadius)
return False
def isOnBSplineCurve(sEdge, fEdge):
sp = [v.Point for v in sEdge.Vertexes]
fp = [v.Point for v in fEdge.Vertexes]
if (len(sp) != len(fp)):
return False
for i, p in enumerate(sp):
if (not isEqual(p, fp[i])):
return False
return True
def isSeam(edge, face):
c = edge.Curve
for fEdge in face.Edges:
try:
if (isinstance(c, fEdge.Curve.__class__)):
if (isinstance(c, Part.Line)):
if isOnLine(edge, fEdge): return True
elif (isinstance(c, Part.LineSegment)):
if isOnLine(edge, fEdge): return True
elif (isinstance(c, Part.Circle)):
if isOnCircle(edge, fEdge): return True
elif (isinstance(c, Part.Ellipse)):
if isOnEllipse(edge, fEdge): return True
elif (isinstance(c, Part.BSplineCurve)):
if isOnBSplineCurve(edge, fEdge): return True
elif (isinstance(c, Part.ArcOfCircle)):
if isOnCircle(c.Circle, fEdge.Curve.Circle): return True
elif (isinstance(c, Part.ArcOfEllipse)):
if isOnEllipse(c.Ellipse, fEdge.Curve.Ellipse): return True
else:
logError(u" Unknown edge type '%s'!", c.__class__.__name)
except Exception as e:
pass
return False
def findMostMatches(faces):
if (len(faces) > 0):
matches = faces.keys()
matches = sorted(matches)
return faces[matches[-1]]
return []
def eliminateOuterFaces(faces, edges):
_faces = [f for f in faces if f.isValid()]
if (len(_faces) == 0):
return None
if (len(_faces) == 1):
return _faces[0]
for face in _faces:
matching = True
for edge in edges:
if (not isSeam(edge, face)):
matching = False
if (matching):
return face
return None
def createCircle(center, normal, radius):
circle = Part.Circle(center, normal, radius.Length)
circle.XAxis = radius
return circle
def createEllipse(center, normal, major, ratio):
if (ratio == 1):
return createCircle(center, normal, major)
if (ratio <= 1):
s1 = center + major
s2 = center + major.cross(normal).normalize() * major.Length * ratio
else:
s2 = center + major
s1 = center + major.cross(normal).normalize() * major.Length / ratio
try:
return Part.Ellipse(s1, s2, center)
except:
try:
return Part.Ellipse(s2, s1, center)
except:
logError(" Can't create ellipse for center=(%s), normal=(%s), major=(%s), ratio=%g", center, normal, major, ratio)
def createLine(start, end):
line = Part.makeLine(start, end)
return line
def createPolygon(points):
if (len(points) < 2):
return None
return Part.makePolygon(points)
def createBSplinesPCurve(pcurve, surface, sense):
if (pcurve is None):
return None
if (surface is None):
return None
surf = surface.build()
if (surf is None):
return None
bsc = Part.Geom2d.BSplineCurve2d()
_weights = pcurve.weights if (pcurve.rational) else None
try:
bsc.buildFromPolesMultsKnots( \
poles = pcurve.poles, \
mults = pcurve.uMults, \
knots = pcurve.uKnots, \
periodic = pcurve.uPeriodic, \
degree = pcurve.uDegree, \
weights = _weights \
)
except:
bsc.buildFromPolesMultsKnots( \
poles = pcurve.poles, \
mults = pcurve.uMults, \
knots = pcurve.uKnots, \
periodic = False, \
degree = pcurve.uDegree, \
weights = _weights \
)
shape = bsc.toShape(surf, bsc.FirstParameter, bsc.LastParameter)
if (shape is not None):
shape.Orientation = 'Reversed' if (sense == 'reversed') else 'Forward'
return shape
def createBSplinesCurve(nubs, sense, subtype):
if (nubs is None):
return None
number_of_poles = len(nubs.poles)
if (number_of_poles == 2): # if there are only two poles we can simply draw a line
shape = createLine(nubs.poles[0], nubs.poles[1])
else:
shape = None
try:
bsc = Part.BSplineCurve()
_weights = nubs.weights if (nubs.rational) else None
try:
bsc.buildFromPolesMultsKnots( \
poles = nubs.poles, \
mults = nubs.uMults, \
knots = nubs.uKnots, \
periodic = nubs.uPeriodic, \
degree = nubs.uDegree, \
weights = _weights \
)
except:
bsc.buildFromPolesMultsKnots( \
poles = nubs.poles, \
mults = nubs.uMults, \
knots = nubs.uKnots, \
periodic = False, \
degree = nubs.uDegree, \
weights = _weights \
)
shape = bsc.toShape()
except Exception as e:
logWarning("Can't create BSpline-Curve for suptype '%s'!" %(subtype))
if (shape is not None):
shape.Orientation = str('Reversed') if (sense == 'reversed') else str('Forward')
return shape
def createBSplinesSurface(nubs):
if (nubs is None):
return None
bss = Part.BSplineSurface()
_weights = nubs.weights if (nubs.rational) else None
try:
bss.buildFromPolesMultsKnots( \
poles = nubs.poles, \
umults = nubs.uMults, \
vmults = nubs.vMults, \
uknots = nubs.uKnots, \
vknots = nubs.vKnots, \
uperiodic = nubs.uPeriodic, \
vperiodic = nubs.vPeriodic, \
udegree = nubs.uDegree, \
vdegree = nubs.vDegree, \
weights = _weights \
)
except:
bss.buildFromPolesMultsKnots( \
poles = nubs.poles, \
umults = nubs.uMults, \
vmults = nubs.vMults, \
uknots = nubs.uKnots, \
vknots = nubs.vKnots, \
uperiodic = False, \
vperiodic = False, \
udegree = nubs.uDegree, \
vdegree = nubs.vDegree, \
weights = _weights \
)
return bss.toShape()
def readBS2Curve(chunks, index):
nbs, dgr, i = getDimensionCurve(chunks, index)
if (nbs == 'nullbs'):
return None, i
if (nbs in ('nubs', 'nurbs')):
closure, knots, i = getClosureCurve(chunks, i)
spline = BS_Curve(nbs == 'nurbs', closure == 'periodic', dgr)
return readPoints2DList(spline, knots, chunks, i)
return None, index
def readBS3Curve(chunks, index):
nbs, dgr, i = getDimensionCurve(chunks, index)
if (nbs == 'nullbs'):
return None, i
if (nbs in ('nubs', 'nurbs')):
closure, knots, i = getClosureCurve(chunks, i)
spline = BS_Curve(nbs == 'nurbs', closure == 'periodic', dgr)
return readPoints3DList(spline, knots, chunks, i)
return None, index
def readBS3Surface(chunks, index):
nbs, degreeU, degreeV, i = getDimensionSurface(chunks, index)
if (nbs == 'nullbs'):
return None, i
if (nbs in ('nubs', 'nurbs')):
closureU, closureV, singularityU, singularityV, countU, countV, i = getClosureSurface(chunks, i)
spline = BS_Surface(nbs == 'nurbs', closureU == 'periodic', closureV == 'periodic', degreeU, degreeV)
return readPoints3DSurface(spline, countU, countV, chunks, i)
if (nbs == 'summary'):
x, i = getFloat(chunks, i)
arr, i = getFloatArray(chunks, i)
tol, i = getLength(chunks, i)
closureU, i = getEnumByValue(chunks, i, CLOSURE)