forked from hlorus/CAD_Sketcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass_defines.py
3583 lines (2820 loc) · 103 KB
/
class_defines.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
from typing import Generator, Union, Tuple, Type
import logging
import math
from statistics import mean
import bpy
from bpy.types import PropertyGroup, Context, UILayout
from bpy.props import (
CollectionProperty,
PointerProperty,
FloatProperty,
IntProperty,
BoolProperty,
IntVectorProperty,
FloatVectorProperty,
EnumProperty,
StringProperty,
)
import bgl
from bpy_extras.view3d_utils import location_3d_to_region_2d
import gpu
from gpu_extras.batch import batch_for_shader
import mathutils
from mathutils import Vector, Matrix, Euler
from mathutils.geometry import intersect_line_line_2d, intersect_sphere_sphere_2d, intersect_line_sphere_2d, distance_point_to_plane
from . import global_data, functions
from .utilities import preferences
from .shaders import Shaders
from .solver import solve_system, Solver
from .functions import pol2cart, unique_attribute_setter
from .declarations import Operators
from .global_data import WpReq
from .utilities.constants import FULL_TURN, HALF_TURN, QUARTER_TURN
logger = logging.getLogger(__name__)
class SlvsGenericEntity:
def entity_name_getter(self):
return self.get("name", str(self))
def entity_name_setter(self, new_name):
self["name"] = new_name
slvs_index: IntProperty(name="Global Index", default=-1)
name: StringProperty(
name="Name",
get=entity_name_getter,
set=entity_name_setter,
options={"SKIP_SAVE"},
)
fixed: BoolProperty(name="Fixed")
visible: BoolProperty(name="Visible", default=True, update=functions.update_cb)
origin: BoolProperty(name="Origin")
construction: BoolProperty(name="Construction")
dirty: BoolProperty(name="Needs Update", default=True, options={"SKIP_SAVE"})
@classmethod
@property
def type(cls) -> str:
return cls.__name__
@property
def is_dirty(self) -> bool:
if self.dirty:
return True
if not hasattr(self, "dependencies"):
return False
deps = self.dependencies()
for e in deps:
# NOTE: might has to ckech through deps recursively -> e.is_dirty
if e.dirty:
return True
return False
@is_dirty.setter
def is_dirty(self, value: bool):
self.dirty = value
@property
def _shader(self):
if self.is_point():
return Shaders.uniform_color_3d()
return Shaders.uniform_color_line_3d()
@property
def _id_shader(self):
if self.is_point():
return Shaders.id_shader_3d()
return Shaders.id_line_3d()
@property
def point_size(self):
return 5 * preferences.get_scale()
@property
def point_size_select(self):
return 20 * preferences.get_scale()
@property
def line_width(self):
scale = preferences.get_scale()
if self.construction:
return 1.5 * scale
return 2 * scale
@property
def line_width_select(self):
return 20 * preferences.get_scale()
def __str__(self):
_, local_index = functions.breakdown_index(self.slvs_index)
return "{}({})".format(self.__class__.__name__, str(local_index))
@property
def py_data(self):
return global_data.entities[self.slvs_index]
@py_data.setter
def py_data(self, handle):
global_data.entities[self.slvs_index] = handle
# NOTE: It's not possible to store python runtime data on an instance of a PropertyGroup,
# workaround this by saving python objects in a global list
@property
def _batch(self):
return global_data.batches[self.slvs_index]
@_batch.setter
def _batch(self, value):
global_data.batches[self.slvs_index] = value
# NOTE: hover and select could be replaced by actual props with getter and setter funcs
# selected: BoolProperty(name="Selected")
@property
def hover(self):
return global_data.hover == self.slvs_index
@hover.setter
def hover(self, value):
if value:
global_data.hover = self.slvs_index
else:
global_data.hover = -1
@property
def selected(self):
return self.slvs_index in global_data.selected
@selected.setter
def selected(self, value):
slvs_index = self.slvs_index
list = global_data.selected
if slvs_index in list:
i = list.index(slvs_index)
if not value:
list.pop(i)
elif value:
list.append(slvs_index)
def is_active(self, active_sketch):
if hasattr(self, "sketch"):
return self.sketch == active_sketch
else:
return not active_sketch
def is_selectable(self, context: Context):
if not self.is_visible(context):
return False
if preferences.use_experimental("all_entities_selectable", False):
return True
active_sketch = context.scene.sketcher.active_sketch
if active_sketch and hasattr(self, "sketch"):
# Allow to select entities that share the active sketch's wp
return active_sketch.wp == self.sketch.wp
return self.is_active(active_sketch)
def is_highlight(self):
return self.hover or self in global_data.highlight_entities
def color(self, context: Context):
prefs = functions.get_prefs()
ts = prefs.theme_settings
active = self.is_active(context.scene.sketcher.active_sketch)
highlight = self.is_highlight()
if not active:
if highlight:
return ts.entity.highlight
if self.selected:
return ts.entity.inactive_selected
return ts.entity.inactive
elif self.selected:
if highlight:
return ts.entity.selected_highlight
return ts.entity.selected
elif highlight:
return ts.entity.highlight
return ts.entity.default
@staticmethod
def restore_opengl_defaults():
bgl.glLineWidth(1)
bgl.glPointSize(1) # ?
bgl.glDisable(bgl.GL_BLEND)
def is_visible(self, context: Context) -> bool:
if self.origin:
return context.scene.sketcher.show_origin
if hasattr(self, "sketch"):
return self.sketch.is_visible(context) and self.visible
return self.visible
def is_dashed(self):
return False
def draw(self, context):
if not self.is_visible(context):
return None
shader = self._shader
shader.bind()
bgl.glEnable(bgl.GL_BLEND)
bgl.glPointSize(self.point_size)
col = self.color(context)
shader.uniform_float("color", col)
if not self.is_point():
shader.uniform_bool("dashed", (self.is_dashed(),))
if not self.is_point():
viewport = [context.area.width, context.area.height]
shader.uniform_float("Viewport", viewport)
shader.uniform_float("thickness", self.line_width)
self._batch.draw(shader)
gpu.shader.unbind()
self.restore_opengl_defaults()
def draw_id(self, context):
# Note: Design Question, should it be possible to select elements that are not active?!
# e.g. to activate a sketch
# maybe it should be dynamically defined what is selectable (points only, lines only, ...)
batch = self._batch
shader = self._id_shader
shader.bind()
bgl.glPointSize(self.point_size_select)
shader.uniform_float("color", (*functions.index_to_rgb(self.slvs_index), 1.0))
if not self.is_point():
viewport = [context.area.width, context.area.height]
shader.uniform_float("Viewport", viewport)
shader.uniform_float("thickness", self.line_width_select)
shader.uniform_bool("dashed", (False,))
batch.draw(shader)
gpu.shader.unbind()
self.restore_opengl_defaults()
def create_slvs_data(self, solvesys):
"""Create a solvespace entity from parameters"""
raise NotImplementedError
def update_from_slvs(self, solvesys):
"""Update parameters from the solvespace entity"""
pass
def update_pointers(self, index_old, index_new):
def _update(name):
prop = getattr(self, name)
if prop == index_old:
logger.debug(
"Update reference {} of {} to {}: ".format(name, self, index_new)
)
setattr(self, name, index_new)
for prop_name in dir(self):
if not prop_name.endswith("_i"):
continue
_update(prop_name)
if hasattr(self, "target_object") and self.target_object:
ob = self.target_object
if ob.sketch_index == index_old:
ob.sketch_index = index_new
def dependencies(self):
return []
def draw_props(self, layout):
is_experimental = preferences.is_experimental()
# Header
layout.prop(self, "name", text="")
# Info block
layout.separator()
layout.label(text="Type: " + type(self).__name__)
layout.label(text="Is Origin: " + str(self.origin))
if is_experimental:
sub = layout.column()
sub.scale_y = 0.8
sub.label(text="Index: " + str(self.slvs_index))
sub.label(text="Dependencies:")
for e in self.dependencies():
sub.label(text=str(e))
# General props
layout.separator()
layout.prop(self, "visible")
layout.prop(self, "fixed")
layout.prop(self, "construction")
# Specific prop
layout.separator()
sub = layout.column()
# Delete
layout.separator()
layout.operator(Operators.DeleteEntity, icon='X').index = self.slvs_index
return sub
def tag_update(self, _context=None):
# context argument ignored
if not self.is_dirty:
self.is_dirty = True
def is_3d(self):
return not hasattr(self, "sketch")
def is_2d(self):
return hasattr(self, "sketch")
@classmethod
def is_point(cls):
return False
@classmethod
def is_line(cls):
return False
@classmethod
def is_curve(cls):
return False
@classmethod
def is_closed(cls):
return False
@classmethod
def is_segment(cls):
return False
# Drawing a point might not include points coord itself but rather a series of virtual points around it
# so a Entity might refer another point entity and/or add a set of coords
#
# Different shaders are needed:
# - faces shader
# - outlines shader
# each needs a matching batch
def slvs_entity_pointer(cls, name, **kwargs):
index_prop = name + "_i"
annotations = {}
if hasattr(cls, "__annotations__"):
annotations = cls.__annotations__.copy()
annotations[index_prop] = IntProperty(name=name + " index", default=-1, **kwargs)
setattr(cls, "__annotations__", annotations)
@property
def func(self):
index = getattr(self, index_prop)
if index == -1:
return None
else:
return bpy.context.scene.sketcher.entities.get(index)
setattr(cls, name, func)
@func.setter
def setter(self, entity):
index = entity.slvs_index if entity else -1
setattr(self, index_prop, index)
setattr(cls, name, setter)
def tag_update(self, context: Context):
self.tag_update()
class Point3D(SlvsGenericEntity):
@classmethod
def is_point(cls):
return True
def update(self):
if bpy.app.background:
return
coords, indices = functions.draw_cube_3d(*self.location, 0.05)
self._batch = batch_for_shader(
self._shader, "POINTS", {"pos": (self.location[:],)}
)
self.is_dirty = False
# TODO: maybe rename -> pivot_point, midpoint
def placement(self):
return self.location
def create_slvs_data(self, solvesys, coords=None, group=Solver.group_fixed):
if not coords:
coords = self.location
self.params = [solvesys.addParamV(v, group) for v in coords]
handle = solvesys.addPoint3d(*self.params, group=group)
self.py_data = handle
def update_from_slvs(self, solvesys):
coords = [solvesys.getParam(i).val for i in self.params]
self.location = coords
def closest_picking_point(self, origin, view_vector):
"""Returns the point on this entity which is closest to the picking ray"""
return self.location
class SlvsPoint3D(Point3D, PropertyGroup):
"""Representation of a point in 3D Space.
Arguments:
location (FloatVectorProperty): Point's location in the form (x, y, z)
"""
location: FloatVectorProperty(
name="Location",
description="The location of the point",
subtype="XYZ",
unit="LENGTH",
update=SlvsGenericEntity.tag_update
)
def draw_props(self, layout):
sub = super().draw_props(layout)
sub.prop(self, "location")
return sub
class SlvsLine3D(SlvsGenericEntity, PropertyGroup):
"""Representation of a line in 3D Space.
Arguments:
p1 (SlvsPoint3D): Line's startpoint
p2 (SlvsPoint3D): Line's endpoint
"""
@classmethod
def is_line(cls):
return True
@classmethod
def is_segment(cls):
return True
def dependencies(self):
return [self.p1, self.p2]
def is_dashed(self):
return self.construction
def update(self):
if bpy.app.background:
return
p1, p2 = self.p1.location, self.p2.location
coords = (p1, p2)
kwargs = {"pos": coords}
self._batch = batch_for_shader(self._shader, "LINES", kwargs)
self.is_dirty = False
def create_slvs_data(self, solvesys, group=Solver.group_fixed):
handle = solvesys.addLineSegment(self.p1.py_data, self.p2.py_data, group=group)
self.py_data = handle
def closest_picking_point(self, origin, view_vector):
"""Returns the point on this entity which is closest to the picking ray"""
p1 = self.p1.location
d1 = self.p2.location - p1 # normalize?
return functions.nearest_point_line_line(p1, d1, origin, view_vector)
def placement(self):
return (self.p1.location + self.p2.location) / 2
@property
def length(self):
return (self.p2.location - self.p1.location).length
slvs_entity_pointer(SlvsLine3D, "p1")
slvs_entity_pointer(SlvsLine3D, "p2")
class Normal3D(SlvsGenericEntity):
def update(self):
self.is_dirty = False
def draw(self, context: Context):
pass
def draw_id(self, context: Context):
pass
def create_slvs_data(self, solvesys, group=Solver.group_fixed):
quat = self.orientation
handle = solvesys.addNormal3dV(quat.w, quat.x, quat.y, quat.z, group=group)
self.py_data = handle
class SlvsNormal3D(Normal3D, PropertyGroup):
"""Representation of a normal in 3D Space which is used to
store a direction.
This entity isn't currently exposed to the user and gets created
implicitly when needed.
Arguments:
orientation (Quaternion): A quaternion which describes the rotation
"""
orientation: FloatVectorProperty(
name="Orientation",
description="Quaternion which describes the orientation of the normal",
subtype="QUATERNION",
size=4,
update=SlvsGenericEntity.tag_update,
)
pass
def get_face_orientation(mesh, face):
# returns quaternion describing the face orientation in objectspace
normal = mathutils.geometry.normal([mesh.vertices[i].co for i in face.vertices])
return normal.to_track_quat("Z", "X")
def get_face_midpoint(quat, ob, face):
""" Average distance from origin to face vertices. """
mesh = ob.data
coords = [mesh.vertices[i].co.copy() for i in face.vertices]
quat_inv = quat.inverted()
for v in coords:
v.rotate(quat_inv)
dist = mean([co[2] for co in coords])
# offset origin along normal by average distance
pos = Vector((0, 0, dist))
pos.rotate(quat)
return ob.matrix_world @ pos
class SlvsWorkplane(SlvsGenericEntity, PropertyGroup):
"""Representation of a plane which is defined by an origin point
and a normal. Workplanes are used to define the position of 2D entities
which only store the coordinates on the plane.
Arguments:
p1 (SlvsPoint3D): Origin Point of the Plane
nm (SlvsNormal3D): Normal which defines the orientation
"""
size = 0.4
def dependencies(self):
return [self.p1, self.nm]
# def is_active(self, active_sketch):
# return not active_sketch
# def is_selectable(self, context):
# return self.is_active(context.scene.sketcher.active_sketch)
def update(self):
if bpy.app.background:
return
p1, nm = self.p1, self.nm
coords = functions.draw_rect_2d(0, 0, self.size, self.size)
coords = [(Vector(co))[:] for co in coords]
indices = ((0, 1), (1, 2), (2, 3), (3, 0))
self._batch = batch_for_shader(
self._shader, "LINES", {"pos": coords}, indices=indices
)
self.is_dirty = False
# NOTE: probably better to avoid overwriting draw func..
def draw(self, context):
if not self.is_visible(context):
return
with gpu.matrix.push_pop():
scale = context.region_data.view_distance
gpu.matrix.multiply_matrix(self.matrix_basis)
gpu.matrix.scale(Vector((scale, scale, scale)))
col = self.color(context)
# Let parent draw outline
super().draw(context)
# Additionally draw a face
col_surface = col[:-1] + (0.2,)
shader = Shaders.uniform_color_3d()
shader.bind()
bgl.glEnable(bgl.GL_BLEND)
shader.uniform_float("color", col_surface)
coords = functions.draw_rect_2d(0, 0, self.size, self.size)
coords = [Vector(co)[:] for co in coords]
indices = ((0, 1, 2), (0, 2, 3))
batch = batch_for_shader(shader, "TRIS", {"pos": coords}, indices=indices)
batch.draw(shader)
self.restore_opengl_defaults()
def draw_id(self, context):
with gpu.matrix.push_pop():
scale = context.region_data.view_distance
gpu.matrix.multiply_matrix(self.matrix_basis)
gpu.matrix.scale(Vector((scale, scale, scale)))
super().draw_id(context)
def create_slvs_data(self, solvesys, group=Solver.group_fixed):
handle = solvesys.addWorkplane(self.p1.py_data, self.nm.py_data, group=group)
self.py_data = handle
@property
def matrix_basis(self):
mat_rot = self.nm.orientation.to_matrix().to_4x4()
return Matrix.Translation(self.p1.location) @ mat_rot
@property
def normal(self):
v = global_data.Z_AXIS.copy()
quat = self.nm.orientation
v.rotate(quat)
return v
slvs_entity_pointer(SlvsWorkplane, "p1")
slvs_entity_pointer(SlvsWorkplane, "nm")
convert_items = [
("NONE", "None", "", 1),
("BEZIER", "Bezier", "", 2),
("MESH", "Mesh", "", 3),
]
# TODO: draw sketches and allow selecting
class SlvsSketch(SlvsGenericEntity, PropertyGroup):
"""A sketch groups 2 dimensional entities together and is used to later
convert geometry to native blender types.
Entities that belong to a sketch can only be edited as long as the sketch is active.
Arguments:
wp (SlvsWorkplane): The base workplane of the sketch
"""
unique_names = ["name"]
def hide_sketch(self, context):
if self.convert_type != "NONE":
self.visible = False
convert_type: EnumProperty(
name="Convert Type",
items=convert_items,
description="Define how the sketch should be converted in order to be usable in native blender",
update=hide_sketch,
)
fill_shape: BoolProperty(
name="Fill Shape",
description="Fill the resulting shape if it's closed",
default=True,
)
solver_state: EnumProperty(
name="Solver Status", items=global_data.solver_state_items
)
dof: IntProperty(name="Degrees of Freedom", max=6)
target_curve: PointerProperty(type=bpy.types.Curve)
target_curve_object: PointerProperty(type=bpy.types.Object)
target_mesh: PointerProperty(type=bpy.types.Mesh)
target_object: PointerProperty(type=bpy.types.Object)
def dependencies(self):
return [
self.wp,
]
def sketch_entities(self, context):
for e in context.scene.sketcher.entities.all:
if not hasattr(e, "sketch"):
continue
if e.sketch != self:
continue
yield e
def update(self):
self.is_dirty = False
def draw(self, context):
pass
def draw_id(self, context):
pass
def create_slvs_data(self, solvesys, group=Solver.group_fixed):
pass
def remove_objects(self):
for ob in (self.target_object, self.target_curve_object):
if not ob:
continue
bpy.data.objects.remove(ob)
def is_visible(self, context):
if context.scene.sketcher.active_sketch_i == self.slvs_index:
return True
return self.visible
def get_solver_state(self):
return functions.bpyEnum(
global_data.solver_state_items, identifier=self.solver_state
)
def solve(self, context):
return solve_system(context, sketch=self)
slvs_entity_pointer(SlvsSketch, "wp")
SlvsSketch.__setattr__ = unique_attribute_setter
class Entity2D:
@property
def wp(self):
return self.sketch.wp
class Point2D(SlvsGenericEntity, Entity2D):
@classmethod
def is_point(cls):
return True
def update(self):
if bpy.app.background:
return
u, v = self.co
mat_local = Matrix.Translation(Vector((u, v, 0)))
mat = self.wp.matrix_basis @ mat_local
size = 0.1
coords = functions.draw_rect_2d(0, 0, size, size)
coords = [(mat @ Vector(co))[:] for co in coords]
indices = ((0, 1, 2), (0, 2, 3))
pos = self.location
self._batch = batch_for_shader(self._shader, "POINTS", {"pos": (pos[:],)})
self.is_dirty = False
@property
def location(self):
u, v = self.co
mat_local = Matrix.Translation(Vector((u, v, 0)))
mat = self.wp.matrix_basis @ mat_local
return mat @ Vector((0, 0, 0))
def placement(self):
return self.location
def create_slvs_data(self, solvesys, coords=None, group=Solver.group_fixed):
if not coords:
coords = self.co
self.params = [solvesys.addParamV(v, group) for v in coords]
handle = solvesys.addPoint2d(self.wp.py_data, *self.params, group=group)
self.py_data = handle
def update_from_slvs(self, solvesys):
coords = [solvesys.getParam(i).val for i in self.params]
self.co = coords
def closest_picking_point(self, origin, view_vector):
"""Returns the point on this entity which is closest to the picking ray"""
return self.location
slvs_entity_pointer(Point2D, "sketch")
class SlvsPoint2D(Point2D, PropertyGroup):
"""Representation of a point in 2D space.
Arguments:
co (FloatVectorProperty): The coordinates of the point on the worpkplane in the form (U, V)
sketch (SlvsSketch): The sketch this entity belongs to
"""
co: FloatVectorProperty(
name="Coordinates",
description="The coordinates of the point on it's sketch",
subtype="XYZ",
size=2,
unit="LENGTH",
update=SlvsGenericEntity.tag_update
)
def dependencies(self):
return [
self.sketch,
]
def tweak(self, solvesys, pos, group):
wrkpln = self.sketch.wp
u, v, _ = wrkpln.matrix_basis.inverted() @ pos
self.create_slvs_data(solvesys, group=group)
# NOTE: When simply initializing the point on the tweaking positions
# the solver fails regularly, addWhereDragged fixes a point and might
# overconstrain a system. When not using addWhereDragged the tweak point
# might just jump to the tweaked geometry. Bypass this by creating a line
# perpendicular to move vector and constrain that.
orig_pos = self.co
tweak_pos = Vector((u, v))
tweak_vec = tweak_pos - orig_pos
perpendicular_vec = Vector((tweak_vec[1], -tweak_vec[0]))
params = [solvesys.addParamV(val, group) for val in (u, v)]
startpoint = solvesys.addPoint2d(wrkpln.py_data, *params, group=group)
p2 = tweak_pos + perpendicular_vec
params = [solvesys.addParamV(val, group) for val in (p2.x, p2.y)]
endpoint = solvesys.addPoint2d(wrkpln.py_data, *params, group=group)
edge = solvesys.addLineSegment(startpoint, endpoint, group=group)
make_coincident(
solvesys, self.py_data, edge, wrkpln.py_data, group, entity_type=SlvsLine2D
)
def draw_props(self, layout):
sub = super().draw_props(layout)
sub.prop(self, "co")
return sub
def round_v(vec, ndigits=None):
values = []
for v in vec:
values.append(round(v, ndigits=ndigits))
return Vector(values)
class SlvsLine2D(SlvsGenericEntity, PropertyGroup, Entity2D):
"""Representation of a line in 2D space. Connects p1 and p2 and lies on the
sketche's workplane.
Arguments:
p1 (SlvsPoint2D): Line's startpoint
p2 (SlvsPoint2D): Line's endpoint
sketch (SlvsSketch): The sketch this entity belongs to
"""
@classmethod
def is_line(cls):
return True
@classmethod
def is_segment(cls):
return True
def dependencies(self):
return [self.p1, self.p2, self.sketch]
def is_dashed(self):
return self.construction
def update(self):
if bpy.app.background:
return
p1, p2 = self.p1.location, self.p2.location
coords = (p1, p2)
kwargs = {"pos": coords}
self._batch = batch_for_shader(self._shader, "LINES", kwargs)
self.is_dirty = False
def create_slvs_data(self, solvesys, group=Solver.group_fixed):
handle = solvesys.addLineSegment(self.p1.py_data, self.p2.py_data, group=group)
self.py_data = handle
def closest_picking_point(self, origin, view_vector):
"""Returns the point on this entity which is closest to the picking ray"""
# NOTE: for 2d entities it could be enough precise to simply take the intersection point with the workplane
p1 = self.p1.location
d1 = self.p2.location - p1 # normalize?
return functions.nearest_point_line_line(p1, d1, origin, view_vector)
def placement(self):
return (self.p1.location + self.p2.location) / 2
def connection_points(self):
return [self.p1, self.p2]
def direction(self, point, is_endpoint=False):
"""Returns the direction of the line, true if inverted"""
if is_endpoint:
return point == self.p1
else:
return point == self.p2
def to_bezier(
self, spline, startpoint, endpoint, invert_direction, set_startpoint=False
):
locations = [self.p1.co.to_3d(), self.p2.co.to_3d()]
if invert_direction:
locations.reverse()
if set_startpoint:
startpoint.co = locations[0]
endpoint.co = locations[1]
startpoint.handle_right = locations[0]
startpoint.handle_right_type = "VECTOR"
endpoint.handle_left = locations[1]
endpoint.handle_left_type = "VECTOR"
return endpoint
def midpoint(self):
return (self.p1.co + self.p2.co) / 2
def direction_vec(self):
return (self.p2.co - self.p1.co).normalized()
@property
def length(self):
return (self.p2.co - self.p1.co).length
def overlaps_endpoint(self, co):
precision = 5
co_rounded = round_v(co, ndigits=precision)
if any(
[
co_rounded == round_v(v, ndigits=precision)
for v in (self.p1.co, self.p2.co)
]
):
return True
return False
def intersect(self, other):
# NOTE: There can be multiple intersections when intersecting with one or more curves
def parse_retval(value):
if not value:
return ()
if self.overlaps_endpoint(value) or other.overlaps_endpoint(value):
return ()
return (value,)
if other.is_line():
return parse_retval(
intersect_line_line_2d(self.p1.co, self.p2.co, other.p1.co, other.p2.co)