forked from blender/blender-addons
-
Notifications
You must be signed in to change notification settings - Fork 0
/
archipack_gl.py
1432 lines (1209 loc) · 43 KB
/
archipack_gl.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 -*-
# ##### 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.
#
# 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 #####
# <pep8 compliant>
# ----------------------------------------------------------
# Author: Stephen Leger (s-leger)
#
# ----------------------------------------------------------
import bgl
import blf
import gpu
from gpu_extras.batch import batch_for_shader
import bpy
import numpy as np
from math import sin, cos, atan2, pi
from mathutils import Vector, Matrix
from bpy_extras import view3d_utils, object_utils
# ------------------------------------------------------------------
# Define Gl Handle types
# ------------------------------------------------------------------
class DefaultColorScheme:
"""
Font sizes and basic colour scheme
default to this when not found in addon prefs
Colors are FloatVectorProperty of size 4 and type COLOR_GAMMA
"""
text_size = 14
feedback_size_main = 16
feedback_size_title = 14
feedback_size_shortcut = 11
feedback_colour_main = (0.95, 0.95, 0.95, 1.0)
feedback_colour_key = (0.67, 0.67, 0.67, 1.0)
feedback_colour_shortcut = (0.51, 0.51, 0.51, 1.0)
feedback_shortcut_area = (0, 0.4, 0.6, 0.2)
feedback_title_area = (0, 0.4, 0.6, 0.5)
handle_colour_normal = (1.0, 1.0, 1.0, 1.0)
handle_colour_hover = (1.0, 1.0, 0.0, 1.0)
handle_colour_active = (1.0, 0.0, 0.0, 1.0)
handle_colour_selected = (0.0, 0.0, 0.7, 1.0)
handle_colour_inactive = (0.3, 0.3, 0.3, 1.0)
def get_prefs(context):
global __name__
try:
addon_name = __name__.split('.')[0]
prefs = context.preferences.addons[addon_name].preferences
except:
prefs = DefaultColorScheme
pass
return prefs
g_poly = None
g_image = None
g_line = None
line_vertSrc = '''
uniform mat4 ModelViewProjectionMatrix;
in vec2 pos;
void main()
{
gl_Position = ModelViewProjectionMatrix * vec4(pos, 0.0, 1.0);
}
'''
line_fragSrc = '''
uniform vec4 color;
out vec4 fragColor;
void main()
{
fragColor = color;
}
'''
"""
# TESTS
_format = gpu.types.GPUVertFormat()
_pos_id = _format.attr_add(
id="pos",
comp_type="F32",
len=2,
fetch_mode="FLOAT")
coords = [(0,0), (200,100)]
vbo = gpu.types.GPUVertBuf(len=len(coords), format=_format)
"""
class GPU_Line:
def __init__(self):
# never call this in -b mode
if bpy.app.background:
return
self._format = gpu.types.GPUVertFormat()
self._pos_id = self._format.attr_add(
id="pos",
comp_type="F32",
len=2,
fetch_mode="FLOAT")
self.shader = gpu.types.GPUShader(line_vertSrc, line_fragSrc)
self.unif_color = self.shader.uniform_from_name("color")
self.color = np.array([0.0, 0.0, 0.0, 1.0], 'f')
def batch_line_strip_create(self, coords):
vbo = gpu.types.GPUVertBuf(len=len(coords), format=self._format)
vbo.attr_fill(id=self._pos_id, data=coords)
batch_lines = gpu.types.GPUBatch(type="LINE_STRIP", buf=vbo)
batch_lines.program_set(self.shader)
return batch_lines
def draw(self, color, list_verts_co):
if list_verts_co:
batch = self.batch_line_strip_create(list_verts_co)
self.color[0:4] = color[0:4]
self.shader.uniform_vector_float(self.unif_color, self.color, 4)
batch.draw()
del batch
class GPU_Poly:
def __init__(self):
if bpy.app.background:
return
self._format = gpu.types.GPUVertFormat()
self._pos_id = self._format.attr_add(
id="pos",
comp_type="F32",
len=2,
fetch_mode="FLOAT")
self.shader = gpu.types.GPUShader(line_vertSrc, line_fragSrc)
self.unif_color = self.shader.uniform_from_name("color")
self.color = np.array([0.0, 0.0, 0.0, 0.5], 'f')
def batch_create(self, coords):
vbo = gpu.types.GPUVertBuf(len=len(coords), format=self._format)
vbo.attr_fill(id=self._pos_id, data=coords)
batch = gpu.types.GPUBatch(type="TRI_FAN", buf=vbo)
# batch.program_set(self.shader)
# batch = batch_for_shader(self.shader, 'TRI_FAN', {"position": coords})
return batch
def draw(self, color, list_verts_co):
if list_verts_co:
self.shader.bind()
batch = self.batch_create(list_verts_co)
self.color[0:4] = color[0:4]
self.shader.uniform_vector_float(self.unif_color, self.color, 4)
batch.draw(self.shader)
class GPU_Image:
uvs = [(0, 0), (1, 0), (0, 1), (1, 1)]
indices = [(0, 1, 2), (2, 1, 3)]
def __init__(self):
if bpy.app.background:
return
self._format = gpu.types.GPUVertFormat()
self._pos_id = self._format.attr_add(
id="pos",
comp_type="F32",
len=2,
fetch_mode="FLOAT")
self.shader = gpu.shader.from_builtin('2D_IMAGE')
def batch_create(self, coords):
batch = batch_for_shader(self.shader, 'TRIS',
{"pos": coords,
"texCoord": self.uvs},
indices=self.indices)
return batch
def draw(self, texture_id, list_verts_co):
if list_verts_co:
batch = self.batch_create(list_verts_co)
# in case someone disabled it before
bgl.glEnable(bgl.GL_TEXTURE_2D)
# bind texture to image unit 0
bgl.glActiveTexture(bgl.GL_TEXTURE0)
bgl.glBindTexture(bgl.GL_TEXTURE_2D, texture_id)
self.shader.bind()
# tell shader to use the image that is bound to image unit 0
self.shader.uniform_int("image", 0)
batch.draw(self.shader)
bgl.glDisable(bgl.GL_TEXTURE_2D)
class Gl():
"""
handle 3d -> 2d gl drawing
d : dimensions
3 to convert pos from 3d
2 to keep pos as 2d absolute screen position
"""
def __init__(self,
d=3,
colour=(0.0, 0.0, 0.0, 1.0)):
global g_poly, g_image, g_line
if g_poly is None:
g_poly = GPU_Poly()
if g_image is None:
g_image = GPU_Image()
if g_line is None:
g_line = GPU_Line()
# nth dimensions of input coords 3=word coords 2=pixel screen coords
self.d = d
self.pos_2d = Vector((0, 0))
self.colour_inactive = colour
@property
def colour(self):
return self.colour_inactive
def position_2d_from_coord(self, context, coord, render=False):
""" coord given in local input coordsys
"""
if self.d == 2:
return Vector(coord)
if render:
return self.get_render_location(context, coord)
region = context.region
rv3d = context.region_data
loc = view3d_utils.location_3d_to_region_2d(region, rv3d, coord, self.pos_2d)
return Vector(loc)
def get_render_location(self, context, coord):
scene = context.scene
co_2d = object_utils.world_to_camera_view(scene, scene.camera, coord)
# Get pixel coords
render_scale = scene.render.resolution_percentage / 100
render_size = (int(scene.render.resolution_x * render_scale),
int(scene.render.resolution_y * render_scale))
return Vector(round(co_2d.x * render_size[0]), round(co_2d.y * render_size[1]))
class GlText(Gl):
def __init__(self,
d=3,
label="",
value=None,
precision=4,
unit_mode='AUTO',
unit_type='SIZE',
dimension=1,
angle=0,
font_size=None,
colour=(1, 1, 1, 1),
z_axis=Vector((0, 0, 1))):
"""
d: [2|3] coords type: 2 for coords in screen pixels, 3 for 3d world location
label : string label
value : float value (will add unit according following settings)
precision : integer rounding for values
dimension : [1 - 3] nth dimension of unit (single, square, cubic)
unit_mode : ['ADAPTIVE','METER','CENTIMETER','MILIMETER','FEET','INCH','RADIANS','DEGREE']
unit type to use to postfix values
ADAPTIVE use scene units setup
unit_type : ['SIZE','ANGLE']
unit type to add to value
angle : angle to rotate text
"""
self.z_axis = z_axis
# text, add as prefix to value
self.label = label
# value with unit related
self.value = value
self.precision = precision
self.dimension = dimension
self.unit_type = unit_type
self.unit_mode = unit_mode
if font_size is None:
prefs = get_prefs(bpy.context)
self.font_size = prefs.text_size
else:
self.font_size = font_size
self.angle = angle
Gl.__init__(self, d)
self.colour_inactive = colour
# store text with units
self._text = ""
self.cbuff = bgl.Buffer(bgl.GL_FLOAT, 4)
def text_size(self, context):
"""
overall on-screen size in pixels
"""
dpi, font_id = context.preferences.system.dpi, 0
if self.angle != 0:
blf.enable(font_id, blf.ROTATION)
blf.rotation(font_id, self.angle)
blf.aspect(font_id, 1.0)
blf.size(font_id, self.font_size, dpi)
x, y = blf.dimensions(font_id, self.text)
if self.angle != 0:
blf.disable(font_id, blf.ROTATION)
return Vector((x, y))
@property
def pts(self):
return [self.pos_3d]
@property
def text(self):
s = self.label + self._text
return s.strip()
def add_units(self, context):
if self.value is None:
return ""
system = context.scene.unit_settings.system
if self.unit_type == 'ANGLE':
scale = 1
mode = 'ADAPTIVE'
else:
scale = context.scene.unit_settings.scale_length
mode = self.unit_mode
if mode == 'AUTO':
mode = context.scene.unit_settings.length_unit.upper()
val = self.value * scale
if mode == 'ADAPTIVE':
if self.unit_type == 'ANGLE':
mode = context.scene.unit_settings.system_rotation
else:
if system == "IMPERIAL":
if round(val * (3.2808399 ** self.dimension), 2) >= 1.0:
mode = 'FOOT'
else:
mode = 'INCH'
elif context.scene.unit_settings.system == "METRIC":
if round(val, 2) >= 1.0:
mode = 'METER'
else:
if round(val, 2) >= 0.01:
mode = 'CENTIMETER'
else:
mode = 'MILIMETER'
# TODO: support for separate units (through 2.8 api)
# convert values
unit = ""
if mode == 'METER':
unit = "m"
elif mode == 'CENTIMETER':
val *= (100 ** self.dimension)
unit = "cm"
elif mode == 'MILIMETER':
val *= (1000 ** self.dimension)
unit = 'mm'
elif mode in {'FOOT', 'FEET'}:
val *= (3.2808399 ** self.dimension)
unit = "ft"
elif mode == 'INCH':
val *= (39.3700787 ** self.dimension)
unit = "in"
elif mode == 'RADIANS':
unit = ""
elif mode == 'DEGREES':
val = self.value / pi * 180
unit = "°"
if system == 'IMPERIAL':
if self.dimension == 2:
unit = "sq " + unit
elif self.dimension == 3:
unit = "cu " + unit
elif system == 'METRIC':
if self.dimension == 2:
unit += "\u00b2" # Superscript two
elif self.dimension == 3:
unit += "\u00b3" # Superscript three
fmt = "%1." + str(self.precision) + "f"
# remove trailing zeros
res = fmt % val
while res[-1] == '0':
res = res[:-1]
if res[-1] == ".":
res = res + '0'
return "{} {}".format(res, unit)
def set_pos(self, context, value, pos_3d, direction, angle=0, normal=Vector((0, 0, 1))):
self.up_axis = direction.normalized()
self.c_axis = self.up_axis.cross(normal)
self.pos_3d = pos_3d
self.value = value
self.angle = angle
self._text = self.add_units(context)
def draw(self, context, render=False):
# print("draw_text %s %s" % (self.text, type(self).__name__))
self.render = render
p = self.position_2d_from_coord(context, self.pts[0], render)
# dirty fast assignment
dpi, font_id = context.preferences.system.dpi, 0
# self.cbuff[0:4] = self.colour
# bgl.glEnableClientState(bgl.GL_COLOR_ARRAY)
# bgl.glColorPointer(4, bgl.GL_FLOAT, 0, self.cbuff)
blf.color(0, *self.colour)
if self.angle != 0:
blf.enable(font_id, blf.ROTATION)
blf.rotation(font_id, self.angle)
blf.size(font_id, self.font_size, dpi)
blf.position(font_id, p.x, p.y, 0)
blf.draw(font_id, self.text)
if self.angle != 0:
blf.disable(font_id, blf.ROTATION)
# bgl.glDisableClientState(bgl.GL_COLOR_ARRAY)
class GlBaseLine(Gl):
def __init__(self,
d=3,
width=1,
style=bgl.GL_LINE,
closed=False,
n_pts=2):
Gl.__init__(self, d)
# default line width
self.width = width
# default line style
self.style = style
# allow closed lines
self.closed = closed
self.n_pts = n_pts
def draw(self, context, render=False):
"""
render flag when rendering
"""
self.render = render
bgl.glEnable(bgl.GL_BLEND)
bgl.glLineWidth(self.width)
list_verts_co = [
tuple(self.position_2d_from_coord(context, pt, render)[0:2])
for i, pt in enumerate(self.pts)]
if self.closed:
list_verts_co.append(list_verts_co[0])
g_line.draw(self.colour, list_verts_co)
bgl.glLineWidth(1.0)
bgl.glDisable(bgl.GL_BLEND)
class GlLine(GlBaseLine):
"""
2d/3d Line
"""
def __init__(self, d=3, p=None, v=None, p0=None, p1=None, z_axis=None):
"""
d=3 use 3d coords, d=2 use 2d pixels coords
Init by either
p: Vector or tuple origin
v: Vector or tuple size and direction
or
p0: Vector or tuple 1 point location
p1: Vector or tuple 2 point location
Will convert any into Vector 3d
both optionnals
"""
if p is not None and v is not None:
self.p = Vector(p)
self.v = Vector(v)
elif p0 is not None and p1 is not None:
self.p = Vector(p0)
self.v = Vector(p1) - self.p
else:
self.p = Vector()
self.v = Vector()
if z_axis is not None:
self.z_axis = z_axis
else:
self.z_axis = Vector((0, 0, 1))
GlBaseLine.__init__(self, d, n_pts=2)
@property
def p0(self):
return self.p
@property
def p1(self):
return self.p + self.v
@p0.setter
def p0(self, p0):
"""
Note: setting p0
move p0 only
"""
p1 = self.p1
self.p = Vector(p0)
self.v = p1 - p0
@p1.setter
def p1(self, p1):
"""
Note: setting p1
move p1 only
"""
self.v = Vector(p1) - self.p
@property
def length(self):
return self.v.length
@property
def angle(self):
return atan2(self.v.y, self.v.x)
@property
def cross(self):
"""
Vector perpendicular on plane defined by z_axis
lie on the right side
p1
|--x
p0
"""
return self.v.cross(self.z_axis)
def normal(self, t=0):
"""
Line perpendicular on plane defined by z_axis
lie on the right side
p1
|--x
p0
"""
n = GlLine()
n.p = self.lerp(t)
n.v = self.cross
return n
def sized_normal(self, t, size):
"""
GlLine perpendicular on plane defined by z_axis and of given size
positioned at t in current line
lie on the right side
p1
|--x
p0
"""
n = GlLine()
n.p = self.lerp(t)
n.v = size * self.cross.normalized()
return n
def lerp(self, t):
"""
Interpolate along segment
t parameter [0, 1] where 0 is start of arc and 1 is end
"""
return self.p + self.v * t
def offset(self, offset):
"""
offset > 0 on the right part
"""
self.p += offset * self.cross.normalized()
def point_sur_segment(self, pt):
""" point_sur_segment (2d)
point: Vector 3d
t: param t de l'intersection sur le segment courant
d: distance laterale perpendiculaire positif a droite
"""
dp = (pt - self.p).to_2d()
v2d = self.v.to_2d()
dl = v2d.length
d = (self.v.x * dp.y - self.v.y * dp.x) / dl
t = v2d.dot(dp) / (dl * dl)
return t > 0 and t < 1, d, t
@property
def pts(self):
return [self.p0, self.p1]
class GlCircle(GlBaseLine):
def __init__(self,
d=3,
radius=0,
center=Vector((0, 0, 0)),
z_axis=Vector((0, 0, 1))):
self.r = radius
self.c = center
z = z_axis
if z.z < 1:
x = z.cross(Vector((0, 0, 1)))
y = x.cross(z)
else:
x = Vector((1, 0, 0))
y = Vector((0, 1, 0))
self.rM = Matrix([
Vector((x.x, y.x, z.x)),
Vector((x.y, y.y, z.y)),
Vector((x.z, y.z, z.z))
])
self.z_axis = z
self.a0 = 0
self.da = 2 * pi
GlBaseLine.__init__(self, d, n_pts=60)
def lerp(self, t):
"""
Linear interpolation
"""
a = self.a0 + t * self.da
return self.c + self.rM @ Vector((self.r * cos(a), self.r * sin(a), 0))
@property
def pts(self):
n_pts = max(1, int(round(abs(self.da) / pi * 30, 0)))
self.n_pts = n_pts
t_step = 1 / n_pts
return [self.lerp(i * t_step) for i in range(n_pts + 1)]
class GlArc(GlCircle):
def __init__(self,
d=3,
radius=0,
center=Vector((0, 0, 0)),
z_axis=Vector((0, 0, 1)),
a0=0,
da=0):
"""
a0 and da arguments are in radians
a0 = 0 on the x+ axis side
a0 = pi on the x- axis side
da > 0 CCW contrary-clockwise
da < 0 CW clockwise
"""
GlCircle.__init__(self, d, radius, center, z_axis)
self.da = da
self.a0 = a0
@property
def length(self):
return self.r * abs(self.da)
def normal(self, t=0):
"""
perpendicular line always on the right side
"""
n = GlLine(d=self.d, z_axis=self.z_axis)
n.p = self.lerp(t)
if self.da < 0:
n.v = self.c - n.p
else:
n.v = n.p - self.c
return n
def sized_normal(self, t, size):
n = GlLine(d=self.d, z_axis=self.z_axis)
n.p = self.lerp(t)
if self.da < 0:
n.v = size * (self.c - n.p).normalized()
else:
n.v = size * (n.p - self.c).normalized()
return n
def tangeant(self, t, length):
a = self.a0 + t * self.da
ca = cos(a)
sa = sin(a)
n = GlLine(d=self.d, z_axis=self.z_axis)
n.p = self.c + self.rM @ Vector((self.r * ca, self.r * sa, 0))
n.v = self.rM @ Vector((length * sa, -length * ca, 0))
if self.da > 0:
n.v = -n.v
return n
def offset(self, offset):
"""
offset > 0 on the right part
"""
if self.da > 0:
radius = self.r + offset
else:
radius = self.r - offset
return GlArc(d=self.d,
radius=radius,
center=self.c,
a0=self.a0,
da=self.da,
z_axis=self.z_axis)
class GlPolygon(Gl):
def __init__(self,
colour=(0.3, 0.3, 0.3, 1.0),
d=3, n_pts=60):
self.pts_3d = []
Gl.__init__(self, d, colour)
self.n_pts = min(n_pts, 60)
def set_pos(self, pts_3d):
self.pts_3d = pts_3d
@property
def pts(self):
return self.pts_3d
def draw(self, context, render=False):
"""
render flag when rendering
"""
# return
self.render = render
if self.n_pts == 0:
return
pts = self.pts
g_vertices = [
tuple(self.position_2d_from_coord(context, pt, render)[0:2])
for i, pt in enumerate(pts)]
bgl.glEnable(bgl.GL_BLEND)
g_poly.draw(self.colour, g_vertices)
bgl.glDisable(bgl.GL_BLEND)
class GlRect(GlPolygon):
def __init__(self,
colour=(0.0, 0.0, 0.0, 1.0),
d=2):
GlPolygon.__init__(self, colour, d, n_pts=4)
@property
def pts(self):
return self.pts_2d
def draw(self, context, render=False):
pts = [
self.position_2d_from_coord(context, pt, render)
for pt in self.pts_3d
]
x0, y0 = pts[0]
x1, y1 = pts[1]
self.pts_2d = [Vector((x, y)) for x, y in [(x0, y0), (x0, y1), (x1, y1), (x1, y0)]]
GlPolygon.draw(self, context, render)
class GlImage(Gl):
def __init__(self,
d=2,
image=None):
# GImage bindcode[0]
self.image = image
self.colour_inactive = (1, 1, 1, 1)
Gl.__init__(self, d)
self.pts_2d = [Vector((0, 0)), Vector((10, 10))]
self.n_pts = 4
def set_pos(self, pts):
self.pts_2d = pts
@property
def pts(self):
return self.pts_2d
def draw(self, context, render=False):
if self.image is None:
return
p0 = self.pts[0]
p1 = self.pts[1]
coords = [(p0.x, p0.y), (p1.x, p0.y), (p0.x, p1.y), (p1.x, p1.y)]
g_image.draw(self.image.bindcode, coords)
class GlPolyline(GlBaseLine):
def __init__(self, colour, d=3, n_pts=60):
self.pts_3d = []
GlBaseLine.__init__(self, d, n_pts=n_pts)
self.colour_inactive = colour
def set_pos(self, pts_3d):
self.pts_3d = pts_3d
# self.pts_3d.append(pts_3d[0])
@property
def pts(self):
return self.pts_3d
class GlHandle(GlPolygon):
def __init__(self, sensor_size, size, draggable=False, selectable=False, d=3, n_pts=4):
"""
sensor_size : 2d size in pixels of sensor area
size : 3d size of handle
"""
GlPolygon.__init__(self, d=d, n_pts=n_pts)
prefs = get_prefs(bpy.context)
self.colour_active = prefs.handle_colour_active
self.colour_hover = prefs.handle_colour_hover
self.colour_normal = prefs.handle_colour_normal
self.colour_selected = prefs.handle_colour_selected
self.colour_inactive = prefs.handle_colour_inactive
# variable symbol size in world coords
self.size = size
# constant symbol size in pixels
self.symbol_size = sensor_size
# scale factor for constant symbol pixel size
self.scale = 1
# sensor size in pixels
self.sensor_width = sensor_size
self.sensor_height = sensor_size
self.pos_3d = Vector((0, 0, 0))
self.up_axis = Vector((0, 0, 0))
self.c_axis = Vector((0, 0, 0))
self.hover = False
self.active = False
self.draggable = draggable
self.selectable = selectable
self.selected = False
def scale_factor(self, context, pts):
"""
Compute screen scale factor for symbol
given 2 points in symbol direction (eg start and end of arrow)
"""
prefs = get_prefs(context)
if not prefs.constant_handle_size:
return 1
p2d = []
for pt in pts:
p2d.append(self.position_2d_from_coord(context, pt))
sx = [p.x for p in p2d]
sy = [p.y for p in p2d]
x = max(sx) - min(sx)
y = max(sy) - min(sy)
s = max(x, y)
if s > 0:
fac = self.symbol_size / s
else:
fac = 1
return fac
def set_pos(self, context, pos_3d, direction, normal=Vector((0, 0, 1))):
self.up_axis = direction.normalized()
self.c_axis = self.up_axis.cross(normal)
self.pos_3d = pos_3d
self.pos_2d = self.position_2d_from_coord(context, self.sensor_center)
x = self.up_axis * 0.5 * self.size
y = self.c_axis * 0.5 * self.size
pts = [self.sensor_center + v for v in [-x, x, -y, y]]
self.scale = self.scale_factor(context, pts)
def check_hover(self, pos_2d):
if self.draggable:
dp = pos_2d - self.pos_2d
self.hover = abs(dp.x) < self.sensor_width and abs(dp.y) < self.sensor_height
@property
def sensor_center(self):
pts = self.pts
n = len(pts)
x, y, z = 0, 0, 0
for pt in pts:
x += pt.x
y += pt.y
z += pt.z
return Vector((x / n, y / n, z / n))
@property
def pts(self):
raise NotImplementedError
@property
def colour(self):
if self.render:
return self.colour_inactive
elif self.draggable:
if self.active:
return self.colour_active
elif self.hover:
return self.colour_hover
elif self.selected:
return self.colour_selected
return self.colour_normal
else:
return self.colour_inactive
class SquareHandle(GlHandle):
def __init__(self, sensor_size, size, draggable=False, selectable=False):
GlHandle.__init__(self, sensor_size, size, draggable, selectable, n_pts=4)
@property
def pts(self):
n = self.up_axis
c = self.c_axis
if self.selected or self.hover or self.active:
scale = 1
else:
scale = 0.5
x = n * self.scale * self.size * scale
y = c * self.scale * self.size * scale
return [self.pos_3d - x - y, self.pos_3d + x - y, self.pos_3d + x + y, self.pos_3d - x + y]
class TriHandle(GlHandle):
def __init__(self, sensor_size, size, draggable=False, selectable=False):
GlHandle.__init__(self, sensor_size, size, draggable, selectable, n_pts=3)
@property
def pts(self):
n = self.up_axis
c = self.c_axis
# does move sensitive area so disable for tri handle
# may implement sensor_center property to fix this
# if self.selected or self.hover or self.active:
scale = 1
# else:
# scale = 0.5
x = n * self.scale * self.size * 4 * scale
y = c * self.scale * self.size * scale
return [self.pos_3d - x + y, self.pos_3d - x - y, self.pos_3d]
class CruxHandle(GlHandle):
def __init__(self, sensor_size, size, draggable=True, selectable=False):
GlHandle.__init__(self, sensor_size, size, draggable, selectable, n_pts=0)
self.branch_0 = GlPolygon((1, 1, 1, 1), d=3, n_pts=4)
self.branch_1 = GlPolygon((1, 1, 1, 1), d=3, n_pts=4)
def set_pos(self, context, pos_3d, direction, normal=Vector((0, 0, 1))):
self.pos_3d = pos_3d
self.pos_2d = self.position_2d_from_coord(context, self.sensor_center)
o = self.pos_3d
d = 0.5 * self.size
x = direction.normalized()
y = x.cross(normal)
sx = x * 0.5 * self.size