-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathmeasureit_arch_geometry.py
4491 lines (3548 loc) · 154 KB
/
measureit_arch_geometry.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
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.a
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####
# ----------------------------------------------------------
# support routines for OpenGL
# Author: Antonio Vazquez (antonioya), Kevan Cress
#
# ----------------------------------------------------------
from textwrap import fill
import bpy
import gpu
import blf
import bmesh
import math
import numpy as np
import svgwrite
import time
import os
from bpy_extras import mesh_utils
from datetime import datetime
from gpu_extras.batch import batch_for_shader
from math import fabs, degrees, radians, sin, pi
from mathutils import Vector, Matrix, Euler, Quaternion
from mathutils.geometry import area_tri
from sys import getrecursionlimit, setrecursionlimit
from . import svg_shaders
from . import dxf_shaders
from .measureit_arch_baseclass import TextField, recalc_dimWrapper_index
from .measureit_arch_units import BU_TO_INCHES, format_distance, format_angle, \
format_area
from .measureit_arch_utils import get_rv3d, get_view, interpolate3d, get_camera_z_dist, get_camera_z, pts_to_px, recursionlimit,\
OpenGL_Settings, get_sv3d, safe_name, _imp_scales_dict, _metric_scales_dict, _cad_col_dict, get_resolution, get_scale, px_to_m,\
load_shader_str, get_projection_matrix, rgb_gamma_correct, Inst_Sort
from .vector_utils import get_axis_aligned_bounds
lastMode = {}
AllLinesBuffer = {}
HiddenLinesBuffer = {}
bufferVBOKeysList = [
"coords",
"weights",
"colors",
"rounded",
"coord_dirs",
"coord_signs",
"coord_uvs",
]
bufferUniformKeysList = [
"invalid",
"offset",
"objMat",
"dashed",
"dash_sizes",
"gap_sizes",
]
AllLinesBatchs = {}
HiddenLinesBatchs = {}
scene_objlist = []
offscreen_text_buffers = {}
# define Shaders
aafrag = load_shader_str("aa_frag.glsl")
basevert = load_shader_str("base_vert.glsl")
basefrag = load_shader_str("base_frag.glsl")
dashedfrag = load_shader_str("Dashed_Line_Frag.glsl", directory="Dashed_Line_Shader")
# Tri Shader info
tri_shader_info = gpu.types.GPUShaderCreateInfo()
tri_shader_info.push_constant('MAT4', "viewProjectionMatrix")
tri_shader_info.push_constant('FLOAT', "offset")
tri_shader_info.push_constant('VEC4',"finalColor")
tri_shader_info.vertex_in(0, 'VEC3', "pos")
tri_shader_info.fragment_out(0, 'VEC4', "fragColor")
tri_shader_info.vertex_source(basevert)
tri_shader_info.fragment_source(basefrag)
triShader = gpu.shader.create_from_info(tri_shader_info)
del tri_shader_info
# Point Shader
pointvert = load_shader_str("Point_Vert.glsl", directory="Point_Shader")
pointfrag = load_shader_str("Point_Frag.glsl", directory="Point_Shader")
point_vert_out = gpu.types.GPUStageInterfaceInfo("my_interface")
point_vert_out.smooth('VEC2', "uv")
point_shader_info = gpu.types.GPUShaderCreateInfo()
point_shader_info.push_constant('MAT4', "viewProjectionMatrix")
point_shader_info.push_constant('VEC3', "view_dir")
point_shader_info.push_constant('FLOAT', "offset")
point_shader_info.push_constant('FLOAT', "pointSize")
point_shader_info.push_constant('VEC4',"finalColor")
point_shader_info.push_constant('FLOAT', "view_scale")
point_shader_info.vertex_in(0, 'VEC3', "pos")
point_shader_info.vertex_in(1, 'VEC2', "exp_dir")
point_shader_info.vertex_out(point_vert_out)
point_shader_info.fragment_out(0, 'VEC4', "fragColor")
point_shader_info.vertex_source(pointvert)
point_shader_info.fragment_source(pointfrag)
pointShader = gpu.shader.create_from_info(point_shader_info)
del point_shader_info
# Text Shader
textvert = load_shader_str("Text_Vert.glsl", directory="Text_Shader")
textfrag = load_shader_str("Text_Frag.glsl", directory="Text_Shader")
text_vert_out = gpu.types.GPUStageInterfaceInfo("my_interface")
text_vert_out.smooth('VEC2', "uvInterp")
text_shader_info = gpu.types.GPUShaderCreateInfo()
text_shader_info.push_constant('MAT4', "viewProjectionMatrix")
text_shader_info.sampler(0, 'FLOAT_2D', "image")
text_shader_info.vertex_in(0, 'VEC3', "pos")
text_shader_info.vertex_in(1, 'VEC2', "uv")
text_shader_info.vertex_out(text_vert_out)
text_shader_info.fragment_out(0, 'VEC4', "fragColor")
text_shader_info.vertex_source(textvert)
text_shader_info.fragment_source(textfrag)
textShader = gpu.shader.create_from_info(text_shader_info)
del text_shader_info
del text_vert_out
# Line Shader
linevert = load_shader_str("cc_line_vert.glsl", directory="CC_Line_Shader")
linefrag = load_shader_str("cc_line_frag.glsl", directory="CC_Line_Shader")
line_vert_out = gpu.types.GPUStageInterfaceInfo("my_interface")
line_vert_out.smooth('VEC4', "color")
line_vert_out.smooth('VEC2', "uv")
line_shader_info = gpu.types.GPUShaderCreateInfo()
line_shader_info.push_constant('MAT4', "viewProjectionMatrix")
line_shader_info.push_constant('FLOAT', "offset")
line_shader_info.push_constant('MAT4', "objectMatrix")
line_shader_info.push_constant('MAT4', "extMatrix")
line_shader_info.push_constant('VEC4', "overlay_color")
line_shader_info.push_constant('VEC3', "view_dir")
line_shader_info.push_constant('BOOL', "depth_pass")
line_shader_info.push_constant('VEC4', "dash_sizes")
line_shader_info.push_constant('VEC4', "gap_sizes")
line_shader_info.push_constant('BOOL', "dashed")
line_shader_info.push_constant('FLOAT', "view_scale")
line_shader_info.vertex_in(0, 'VEC3', "pos")
line_shader_info.vertex_in(1, 'VEC4', "col")
line_shader_info.vertex_in(2, 'VEC3', "dir")
line_shader_info.vertex_in(3, 'INT', "thick_sign")
line_shader_info.vertex_in(4, 'FLOAT', "weight")
line_shader_info.vertex_in(5, 'VEC2', "v_uv")
line_shader_info.vertex_out(line_vert_out)
line_shader_info.fragment_out(0, 'VEC4', "fragColor")
line_shader_info.vertex_source(linevert)
line_shader_info.fragment_source(linefrag)
allLinesShader = gpu.shader.create_from_info(line_shader_info)
del line_shader_info
del line_vert_out
#allLinesShader = gpu.types.GPUShader(
# load_shader_str("All_Lines.vert.glsl", directory="All_Lines"),
# load_shader_str("All_Lines.frag.glsl", directory="All_Lines"),
# geocode = load_shader_str("All_Lines.geom.glsl", directory="All_Lines")
#)
def get_dim_tag(self, obj):
dimGen = obj.DimensionGenerator
itemType = self.itemType
idx = 0
for wrap in dimGen.wrapper:
try:
if itemType == wrap.itemType:
if self == eval('dimGen.' + itemType + '[wrap.itemIndex]'):
return idx
except IndexError:
print('Index Error in get_dim_tag')
return idx
idx += 1
return idx
def clear_batches():
AllLinesBatch = None
HiddenLinesBatch = None
def update_text(textobj, props, context, fields=[]):
scene = context.scene
sceneProps = scene.MeasureItArchProps
textFields = textobj.textFields
if len(fields) != 0:
textFields = fields
textField_idx = -1
for textField in textFields:
textField_idx += 1
if textobj.text_updated or props.text_updated or sceneProps.is_render_draw:
textField.text_updated = True
if textField.text_updated or sceneProps.text_updated:
# Get textitem Properties
rgb = rgb_gamma_correct(props.color)
size = props.fontSize
resolution = get_resolution()
# Get Font Id
badfonts = [None]
if 'Bfont Regular' in bpy.data.fonts or 'Bfont' in bpy.data.fonts:
try:
badfonts.append(bpy.data.fonts['Bfont Regular'])
badfonts.append(bpy.data.fonts['Bfont'])
except KeyError:
pass
if props.font not in badfonts:
vecFont = props.font
fontPath = vecFont.filepath
fontPath = bpy.path.abspath(fontPath)
font_id = blf.load(fontPath)
else:
font_id = 0
# Set BLF font Properties
blf.color(font_id, rgb[0], rgb[1], rgb[2], rgb[3])
blf.size(font_id, size * resolution/72)
text = textField.text
lines = text.split('\n')
# Calculate Optimal Dimensions for Text Texture.
line_height = blf.dimensions(font_id, 'Tpg')[1] *1.2
fheight = 0
fwidth = 0
for line in lines:
fheight += line_height
text = line
if props.all_caps:
text = line.upper()
line_width = blf.dimensions(font_id, text)[0]
if line_width > fwidth:
fwidth = line_width
width = math.ceil(fwidth)
height = math.ceil(fheight)
# Save Texture size to textobj Properties
textField.textHeight = height
textField.textWidth = width
# Start Offscreen Draw
if width != 0 and height != 0:
textOffscreen = gpu.types.GPUOffScreen(width, height)
with textOffscreen.bind():
fb = gpu.state.active_framebuffer_get()
fb.clear(color=(0.0, 0.0, 0.0, 0.0))
view_matrix = Matrix([
[2 / width, 0, 0, -1],
[0, 2 / height, 0, -1],
[0, 0, 1, 0],
[0, 0, 0, 1]])
gpu.matrix.reset()
gpu.matrix.load_matrix(view_matrix)
gpu.matrix.load_projection_matrix(Matrix.Identity(4))
idx = 1
y_offset = height - line_height * 0.8
for line in lines:
blf.position(font_id, 0, y_offset, 0)
text = line
if props.all_caps:
text = line.upper()
blf.draw(font_id, text)
idx += 1
y_offset -= line_height * 1.1
# Write Texture Buffer to ID Property as List
texture_buffer = fb.read_color(0, 0, width, height, 4, 0, 'FLOAT')
texture_buffer.dimensions = width*height*4
textField['texture'] = []
textField['texture'] = texture_buffer
textField.text_updated = False
textField.texture_updated = True
# ONLY USE FOR DEBUG. SERIOUSLY SLOWS PREFORMANCE
if sceneProps.measureit_arch_debug_text:
if not str('test') in bpy.data.images:
bpy.data.images.new(str('test'), width, height)
image = bpy.data.images[str('test')]
image.scale(width, height)
image.pixels = [v for v in texture_buffer]
del texture_buffer
textOffscreen.free()
textobj.text_updated = False
def draw_sheet_views(context, myobj, sheetGen, sheet_view, mat, svg=None, dxf=None):
pass
def get_hatch_name(mat_name, hatch, obj):
if hatch.use_object_pattern:
hatch_name = obj.MeasureItArchProps.obj_hatch_pattern.name + '_' + obj.name
else:
hatch_name = hatch.pattern.name
name = mat_name + '_' + hatch_name
#Check valid name
if " " in name:
name = name.replace(" ", "_")
return name
def draw_material_hatches(context, myobj, mat, svg=None, dxf=None, is_instance_draw = False):
sceneProps = context.scene.MeasureItArchProps
view = get_view()
scale = get_scale()
if sceneProps.is_vector_draw:
try:
svg_obj = svg.add(svg.g(id=myobj.name))
except UnicodeDecodeError:
svg_obj = svg.add(svg.g(id="BAD NAME AHHH"))
if not myobj.hide_render:
bm = bmesh.new()
# polys = mesh.polygons
if myobj.type == 'MESH':
if myobj.mode == 'OBJECT':
try:
bm.from_object(myobj, bpy.context.view_layer.depsgraph)
#depsgraph = bpy.context.view_layer.depsgraph
#eval_obj = myobj.evaluated_get(depsgraph)
#temp_mesh = eval_obj.data
#bm.from_mesh(temp_mesh)
except ValueError:
mesh = myobj.data
bm.from_mesh(mesh)
else:
mesh = myobj.data
bm = bmesh.from_edit_mesh(mesh)
if myobj.type == 'CURVE':
if sceneProps.is_vector_draw:
svg_shaders.svg_fill_from_curve_shader(myobj,svg=svg,mat=mat)
return
#bpy.data.meshes.remove(mesh)
if bm == None:
return
bm.edges.ensure_lookup_table()
bm.faces.ensure_lookup_table()
faces = bm.faces
faces = z_order_faces(faces, myobj)
matSlots = myobj.material_slots
objMaterials = []
hatchDict = {}
#Write Patterns for all hatches on the object
for slot in matSlots:
if slot.material is None:
continue
hatch = slot.material.Hatch
objMaterials.append(slot.material)
pattern = hatch.pattern
maxX = 1
maxY = 1
if pattern != None:
# get pattern bounds
coords = []
for obj in pattern.all_objects:
bounds = obj.bound_box
for coord in bounds:
coords.append(obj.matrix_world @ Vector(coord))
maxX, minX, maxY, minY, maxZ, minZ = get_axis_aligned_bounds(coords)
sizex = hatch.patternSize * ( (maxX/get_scale()) * BU_TO_INCHES * get_resolution())
sizey = hatch.patternSize * ( (maxY/get_scale()) * BU_TO_INCHES * get_resolution())
size = hatch.patternSize * ( (1/get_scale()) * BU_TO_INCHES * get_resolution())
rotation = math.degrees(hatch.patternRot)
if hatch.use_object_pattern:
pattern = myobj.MeasureItArchProps.obj_hatch_pattern
sizex = myobj.MeasureItArchProps.obj_patternSize * ( (maxX/get_scale()) * BU_TO_INCHES * get_resolution())
sizey = myobj.MeasureItArchProps.obj_patternSize * ( (maxY/get_scale()) * BU_TO_INCHES * get_resolution())
size = myobj.MeasureItArchProps.obj_patternSize * ( (1/get_scale()) * BU_TO_INCHES * get_resolution())
rotation = math.degrees(myobj.MeasureItArchProps.obj_patternRot)
if pattern is not None:
name = get_hatch_name(slot.material.name, hatch, myobj)
objs = pattern.objects
weight = hatch.patternWeight
scale = get_scale()
ortho_scale = view.camera.data.ortho_scale
color = hatch.line_color
if sceneProps.is_vector_draw:
pattern = svgwrite.pattern.Pattern(width="{}px".format(sizex), height="{}px".format(sizey), id=name, patternUnits="userSpaceOnUse", **{
'patternTransform': 'rotate({} {} {})'.format(
rotation, 0, 0
)})
svg_shaders.svg_line_pattern_shader(
pattern, svg, objs, weight, color, size)
svg.defs.add(pattern)
for face in faces:
matIdx = face.material_index
try:
faceMat = objMaterials[matIdx]
except:
continue
# Check For Material Override
hatch = faceMat.Hatch
if context.view_layer.material_override != None:
print('HAS OVERRIDE')
hatch = context.view_layer.material_override.Hatch
pattern = hatch.pattern
if hatch.use_object_pattern:
pattern = myobj.MeasureItArchProps.obj_hatch_pattern
if hatch.visible :
if hatch.use_object_color:
fillRGB = rgb_gamma_correct(myobj.color)
else:
fillRGB = rgb_gamma_correct(hatch.fill_color)
lineRGB = rgb_gamma_correct(hatch.line_color)
weight = hatch.lineWeight
fillURL = ''
if pattern is not None:
name = get_hatch_name(faceMat.name,hatch,myobj)
fillURL = 'url(#{})'.format(name)
coords = []
for vert in face.verts:
coords.append(mat @ vert.co)
try:
if sceneProps.is_vector_draw:
svg_hatch = svg_obj.add(svg.g(id=slot.material.name))
svg_shaders.svg_poly_fill_shader(
hatch, coords, fillRGB, svg, parent=svg_hatch,
line_color=lineRGB, lineWeight=weight, fillURL=fillURL)
except AttributeError:
print('Error Drawing Hatch, Maybe Empty Material Slot?')
if sceneProps.is_dxf_draw:
dxf_shaders.dxf_hatch_shader(hatch,coords,dxf,faceMat)
def draw_alignedDimension(context, myobj, measureGen, dim, mat=None, svg=None, dxf=None):
scene = context.scene
sceneProps = scene.MeasureItArchProps
dimProps = get_style(dim,'alignedDimensions')
# Enable GL Settings
lineWeight = dimProps.lineWeight
# check all visibility conditions
if not check_vis(dim, dimProps):
return
# Obj Properties
scene = context.scene
rgb = get_color(dimProps.color, dimProps.cad_col_idx)
rgb_overlay = get_overlay_color(myobj,dim.is_active)
if rgb_overlay != [0,0,0,0]:
rgb = Vector(rgb_overlay)
# get points positions from indicies
aMatrix = dim.dimObjectA.matrix_world
bMatrix = dim.dimObjectB.matrix_world
if mat is not None:
aMatrix = mat @ aMatrix
bMatrix = mat @ bMatrix
# get points positions from indicies
p1Local = None
p2Local = None
try:
p1Local = get_mesh_vertex(
dim.dimObjectA, dim.dimPointA, dimProps.evalMods)
p2Local = get_mesh_vertex(
dim.dimObjectB, dim.dimPointB, dimProps.evalMods)
except IndexError:
print('point excepted for ' + dim.name + ' on ' + myobj.name)
dimGen = myobj.DimensionGenerator
try:
wrapTag = get_dim_tag(dim, myobj)
wrapper = dimGen.wrapper[wrapTag]
tag = wrapper.itemIndex
dimGen.alignedDimensions.remove(tag)
dimGen.wrapper.remove(wrapTag)
except IndexError:
dimGen.alignedDimensions.remove(0)
recalc_dimWrapper_index(None, context)
return
p1 = get_point(p1Local, aMatrix)
p2 = get_point(p2Local, bMatrix)
try:
if format_distance(1,dim) != dim['last_units']:
dim.is_invalid = True
dim['last_units'] = format_distance(1,dim)
if [p1.x,p1.y,p1.z] != dim['last_p1'].to_list():
dim['last_p1'] = p1
dim.is_invalid = True
if [p2.x,p2.y,p2.z] != dim['last_p2'].to_list():
#rrprint('invalid due to change in p2')
dim['last_p2'] = p2
dim.is_invalid = True
except KeyError:
dim.is_invalid = True
dim['last_p1'] = p1
dim['last_p2'] = p2
dim['last_units'] = format_distance(1,dim)
# Check invalid textfields
text_field_invalid = False
for textField in dim.textFields:
if textField.is_invalid:
text_field_invalid = True
break
if dim.is_invalid or dimProps.is_invalid or text_field_invalid or sceneProps.is_render_draw:
# Define Caps as a tuple of capA and capB to reduce code duplications
caps = (dimProps.endcapA, dimProps.endcapB)
capSize = dimProps.endcapSize
offset = dimProps.dimOffset
if dim.uses_style:
offset += dim.tweakOffset
geoOffset = dimProps.dimLeaderOffset
# check dominant Axis
sortedPoints = sortPoints(p1, p2)
p1 = sortedPoints[0]
p2 = sortedPoints[1]
# calculate distance & Midpoint
distVector = Vector(p1) - Vector(p2)
dist = distVector.length
midpoint = interpolate3d(p1, p2, fabs(dist / 2))
normDistVector = distVector.normalized()
# Compute offset vector from face normal and user input
rotation = dimProps.dimRotation
rotationMatrix = Matrix.Rotation(rotation, 4, normDistVector)
selectedNormal = Vector(select_normal(
myobj, dim, normDistVector, midpoint, dimProps))
userOffsetVector = rotationMatrix @ selectedNormal
offsetDistance = userOffsetVector * offset
geoOffsetDistance = offsetDistance.normalized() * geoOffset
if offsetDistance < geoOffsetDistance:
offsetDistance = geoOffsetDistance
# Define Lines
cap_ext = cap_extension(offsetDistance, capSize, dimProps.endcapArrowAngle)
leadStartA = Vector(p1) + geoOffsetDistance
leadEndA = Vector(p1) + offsetDistance + cap_ext
leadStartB = Vector(p2) + geoOffsetDistance
leadEndB = Vector(p2) + offsetDistance + cap_ext
dimLineStart = Vector(p1) + offsetDistance
dimLineEnd = Vector(p2) + offsetDistance
textLoc = interpolate3d(dimLineStart, dimLineEnd, fabs(dist / 2))
# Set Gizmo Props
dim.gizLoc = textLoc
dim.gizRotDir = userOffsetVector
dim['length'] = dist
origin = Vector(textLoc)
placementResults = setup_dim_text(myobj,dim,dimProps,dist,origin,distVector,offsetDistance)
flipCaps = placementResults[0]
dimLineExtension = placementResults[1]
origin = placementResults[2]
# Add the Extension to the dimension line
dimLineVec = dimLineStart - dimLineEnd
dimLineVec.normalize()
dimLineEndCoord = dimLineEnd - dimLineVec * dimLineExtension
dimLineStartCoord = dimLineStart + dimLineVec * dimLineExtension
# Collect coords and endcaps
coords = [leadStartA, leadEndA, leadStartB,
leadEndB, dimLineStartCoord, dimLineEndCoord]
filledCoords = []
pos = (dimLineStart, dimLineEnd)
for i, cap in enumerate(caps):
capCoords = generate_end_caps(
context, dimProps, cap, capSize, pos[i], userOffsetVector, textLoc, i, flipCaps)
coords.extend(capCoords[0])
filledCoords.extend(capCoords[1])
dim['filled_coords'] = filledCoords
dim['coords'] = coords
dim.is_invalid = False
else:
for textField in dim.textFields:
draw_text_3D(context, textField, dimProps, myobj)
# Filled Coords Call
if len(dim['filled_coords']) != 0:
draw_filled_coords(dim['filled_coords'], rgb)
# Line Shader Calls
draw_lines(lineWeight, rgb, dim['coords'])
if sceneProps.is_vector_draw:
svg_dim = svg.add(svg.g(id=dim.name))
svg_shaders.svg_line_shader(
dim, dimProps, coords, lineWeight, rgb, svg, parent=svg_dim)
svg_shaders.svg_fill_shader(
dim, filledCoords, rgb, svg, parent=svg_dim)
for textField in dim.textFields:
textcard = textField['textcard']
svg_shaders.svg_text_shader(
dim, dimProps, textField.text, origin, textcard, rgb, svg, parent=svg_dim)
if sceneProps.is_dxf_draw:
dxf_shaders.dxf_aligned_dimension(dim, dimProps, p1, p2, origin, dxf)
def draw_boundsDimension(context, myobj, measureGen, dim, mat, svg=None, dxf=None):
sceneProps = context.scene.MeasureItArchProps
dimProps = get_style(dim,'alignedDimensions')
with OpenGL_Settings(dimProps):
lineWeight = dimProps.lineWeight
if not check_vis(dim, dimProps):
return
# Obj Properties
# For Collection Bounding Box
if dim.dimCollection is not None:
collection = dim.dimCollection
objects = collection.all_objects
# get the axis aligned bounding coords for each object
coords = []
for myobj in objects:
boundsStr = str(myobj.name) + "_bounds"
rotStr = str(myobj.name) + "_lastRot"
locStr = str(myobj.name) + "_lastLoc"
scaleStr = str(myobj.name) + "_lastScale"
# if no rotation or non mesh obj just use the Objects bounding Box
# Also clean up any chached values
if myobj.matrix_world.to_quaternion() == Quaternion((1.0, 0.0, 0.0, 0.0)) or myobj.type != 'MESH':
bounds = myobj.bound_box
for coord in bounds:
coords.append(myobj.matrix_world @ Vector(coord))
# Also clean up any chached values
try:
del dim[locStr]
del dim[rotStr]
del dim[boundsStr]
del dim[scaleStr]
except KeyError:
pass
else: # otherwise get its points and calc its AABB directly
try:
if (myobj.matrix_world.to_quaternion() != Quaternion(dim[rotStr]) or
myobj.location != Vector(dim[locStr]) or
myobj.scale != Vector(dim[scaleStr])):
obverts = get_mesh_vertices(myobj)
worldObverts = [myobj.matrix_world @
coord for coord in obverts]
maxX, minX, maxY, minY, maxZ, minZ = get_axis_aligned_bounds(
worldObverts)
dim[boundsStr] = [maxX, minX, maxY, minY, maxZ, minZ]
dim[rotStr] = myobj.matrix_world.to_quaternion()
dim[locStr] = myobj.location
dim[scaleStr] = myobj.scale
else:
maxX, minX, maxY, minY, maxZ, minZ = dim[boundsStr]
except KeyError:
obverts = get_mesh_vertices(myobj)
worldObverts = [myobj.matrix_world @
coord for coord in obverts]
maxX, minX, maxY, minY, maxZ, minZ = get_axis_aligned_bounds(
worldObverts)
dim[boundsStr] = [maxX, minX, maxY, minY, maxZ, minZ]
dim[rotStr] = myobj.matrix_world.to_quaternion()
dim[locStr] = myobj.location
dim[scaleStr] = myobj.scale
coords.append(Vector((maxX, maxY, maxZ)))
coords.append(Vector((minX, minY, minZ)))
# Get the axis aligned bounding coords for that set of coords
maxX, minX, maxY, minY, maxZ, minZ = get_axis_aligned_bounds(coords)
# distX = maxX - minX
# distY = maxY - minY
# distZ = maxZ - minZ
p0 = Vector((minX, minY, minZ))
p1 = Vector((minX, minY, maxZ))
p2 = Vector((minX, maxY, maxZ))
p3 = Vector((minX, maxY, minZ))
p4 = Vector((maxX, minY, minZ))
p5 = Vector((maxX, minY, maxZ))
p6 = Vector((maxX, maxY, maxZ))
p7 = Vector((maxX, maxY, minZ))
bounds = [p0, p1, p2, p3, p4, p5, p6, p7]
# print ("X: " + str(distX) + ", Y: " + str(distY) + ", Z: " + str(distZ))
# Single object bounding Box
else:
if not dim.calcAxisAligned:
bounds = myobj.bound_box
tempbounds = []
for bound in bounds:
tempbounds.append(myobj.matrix_world @ Vector(bound))
bounds = tempbounds
else: # Calc AABB when rotation changes
try:
if myobj.matrix_world.to_quaternion() != Quaternion(dim['lastRot']):
obverts = get_mesh_vertices(myobj)
rot = myobj.matrix_world.to_quaternion()
# Compose Rotation Matrix
rotMatrix = Matrix.Identity(3)
rotMatrix.rotate(rot)
rotMatrix.resize_4x4()
rotVerts = [rotMatrix @ coord for coord in obverts]
maxX, minX, maxY, minY, maxZ, minZ = get_axis_aligned_bounds(rotVerts)
dim['bounds'] = [maxX, minX, maxY, minY, maxZ, minZ]
dim['lastRot'] = myobj.matrix_world.to_quaternion()
else:
maxX, minX, maxY, minY, maxZ, minZ = dim['bounds']
except KeyError:
obverts = get_mesh_vertices(myobj)
rot = myobj.matrix_world.to_quaternion()
# Compose Rotation Matrix
rotMatrix = Matrix.Identity(3)
rotMatrix.rotate(rot)
rotMatrix.resize_4x4()
rotVerts = [rotMatrix @ coord for coord in obverts]
maxX, minX, maxY, minY, maxZ, minZ = get_axis_aligned_bounds(rotVerts)
dim['bounds'] = [maxX, minX, maxY, minY, maxZ, minZ]
dim['lastRot'] = myobj.matrix_world.to_quaternion()
# distX = maxX - minX
# distY = maxY - minY
# distZ = maxZ - minZ
locMatrix = Matrix.Translation(myobj.location)
xscaleMatrix = Matrix.Scale(myobj.scale.x,4,Vector((1,0,0)))
yscaleMatrix = Matrix.Scale(myobj.scale.y,4,Vector((0,1,0)))
zscaleMatrix = Matrix.Scale(myobj.scale.z,4,Vector((0,0,1)))
locScaleMat = locMatrix @ xscaleMatrix @ yscaleMatrix @ zscaleMatrix
p0 = locScaleMat @ Vector((minX, minY, minZ))
p1 = locScaleMat @ Vector((minX, minY, maxZ))
p2 = locScaleMat @ Vector((minX, maxY, maxZ))
p3 = locScaleMat @ Vector((minX, maxY, minZ))
p4 = locScaleMat @ Vector((maxX, minY, minZ))
p5 = locScaleMat @ Vector((maxX, minY, maxZ))
p6 = locScaleMat @ Vector((maxX, maxY, maxZ))
p7 = locScaleMat @ Vector((maxX, maxY, minZ))
bounds = [p0, p1, p2, p3, p4, p5, p6, p7]
# Points for Bounding Box
#
# 2-----------6
# / /|
# / / |
# / / |
# 1 ----------5 7 Z
# | | / | y
# | | / | /
# | |/ |/
# 0-----------4 |--------X
# identify axis pairs
zpairs = [[0, 1],
[2, 3],
[4, 5],
[6, 7]]
xpairs = [[0, 4],
[1, 5],
[2, 6],
[3, 7]]
ypairs = [[0, 3],
[1, 2],
[4, 7],
[5, 6]]
# measureAxis = []
# scene = context.scene
rgb = get_color(dimProps.color, dimProps.cad_col_idx)
# Define Caps as a tuple of capA and capB to reduce code duplications
caps = (dimProps.endcapA, dimProps.endcapB)
capSize = dimProps.endcapSize
offset = dimProps.dimOffset
if dim.uses_style:
offset += dim.tweakOffset
geoOffset = dim.dimLeaderOffset
# get view vector
i = Vector((1, 0, 0)) # X Unit Vector
j = Vector((0, 1, 0)) # Y Unit Vector
k = Vector((0, 0, 1)) # Z Unit Vector
viewVec = Vector((0, 0, 0)) # dummy vector to avoid errors
if not sceneProps.is_render_draw:
viewRot = context.area.spaces[0].region_3d.view_rotation
viewVec = k.copy()
viewVec.rotate(viewRot)
bestPairs = [xpairs[2], ypairs[1], zpairs[0]]
# establish measure loop
# this runs through the X, Y and Z axis
idx = 0
placementVec = [j, -i, -i]
for axis in dim.drawAxis:
if axis:
# get points
p1 = Vector(bounds[bestPairs[idx][0]])
p2 = Vector(bounds[bestPairs[idx][1]])
# check dominant Axis
sortedPoints = sortPoints(p1, p2)
p1 = sortedPoints[0]
p2 = sortedPoints[1]
# calculate distance & MidpointGY
distVector = Vector(p1) - Vector(p2)
dist = distVector.length
midpoint = interpolate3d(p1, p2, fabs(dist / 2))
normDistVector = distVector.normalized()
# Compute offset vector from face normal and user input
axisViewVec = viewVec.copy()
axisViewVec[idx] = 0
rotationMatrix = Matrix.Rotation(
dim.dimRotation, 4, normDistVector)
selectedNormal = placementVec[idx]
if dim.dimCollection is None and not dim.calcAxisAligned:
rot = myobj.matrix_world.to_quaternion()
selectedNormal.rotate(rot)
userOffsetVector = rotationMatrix @ selectedNormal
offsetDistance = userOffsetVector * offset
geoOffsetDistance = offsetDistance.normalized() * geoOffset
if offsetDistance < geoOffsetDistance:
offsetDistance = geoOffsetDistance
# Set Gizmo Props
dim.gizLoc = Vector(midpoint) + \
(userOffsetVector * dim.dimOffset)
dim.gizRotDir = userOffsetVector
# Define Lines
leadStartA = Vector(p1) + geoOffsetDistance
leadEndA = Vector(p1) + offsetDistance + cap_extension(
offsetDistance, capSize, dimProps.endcapArrowAngle)
leadStartB = Vector(p2) + geoOffsetDistance
leadEndB = Vector(p2) + offsetDistance + cap_extension(
offsetDistance, capSize, dimProps.endcapArrowAngle)
dimLineStart = Vector(p1) + offsetDistance
dimLineEnd = Vector(p2) + offsetDistance
textLoc = interpolate3d(
dimLineStart, dimLineEnd, fabs(dist / 2))
origin = Vector(textLoc)
# i,j,k as card axis
i = Vector((1, 0, 0))
j = Vector((0, 1, 0))
k = Vector((0, 0, 1))
# Check for text field
dimText = dim.textFields[idx]
# format text and update if necessary
distanceText = format_distance(dist,dim=dim)
if dimText.text != distanceText:
dimText.text = distanceText
dimText.text_updated = True
placementResults = dim_text_placement(
dim, dimProps, origin, dist, distVector, offsetDistance, capSize, textField = dimText)
flipCaps = placementResults[0]
dimLineExtension = placementResults[1]
origin = placementResults[2]
# Add the Extension to the dimension line
dimLineVec = dimLineStart - dimLineEnd