forked from hlorus/CAD_Sketcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperators.py
3371 lines (2637 loc) · 103 KB
/
operators.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
############### Operators ###############
import bpy, bgl, gpu
from gpu_extras.batch import batch_for_shader
from bpy.types import Operator
from . import global_data, functions, class_defines, convertors
from bpy.props import (
IntProperty,
StringProperty,
FloatProperty,
FloatVectorProperty,
EnumProperty,
BoolProperty,
)
import math
from mathutils import Vector, Matrix
from mathutils.geometry import intersect_line_plane, distance_point_to_plane
import functools
import logging
logger = logging.getLogger(__name__)
def draw_selection_buffer(context):
# Draw elements offscreen
region = context.region
# create offscreen
width, height = region.width, region.height
offscreen = global_data.offscreen = gpu.types.GPUOffScreen(width, height)
with offscreen.bind():
bgl.glClearColor(0.0, 0.0, 0.0, 0.0)
bgl.glClear(bgl.GL_COLOR_BUFFER_BIT)
entities = list(context.scene.sketcher.entities.all)
for e in reversed(entities):
if e.slvs_index in global_data.ignore_list:
continue
if not hasattr(e, "draw_id"):
continue
if not e.is_selectable(context):
continue
e.draw_id(context)
def ensure_selection_texture(context):
if not global_data.redraw_selection_buffer:
return
draw_selection_buffer(context)
global_data.redraw_selection_buffer = False
# TODO: Avoid to always update batches and selection texture
def update_elements(context, force=False):
entities = list(context.scene.sketcher.entities.all)
msg = ""
for e in reversed(entities):
if not hasattr(e, "update"):
continue
if not force and not e.is_dirty:
continue
msg += "\n - " + str(e) + str(e.is_dirty)
e.update()
if msg:
logger.debug("Update geometry batches:" + msg)
def draw_elements(context):
for e in context.scene.sketcher.entities.all:
if hasattr(e, "draw"):
e.draw(context)
def draw_cb():
context = bpy.context
prefs = functions.get_prefs()
update_elements(context, force=prefs.force_redraw)
draw_elements(context)
global_data.redraw_selection_buffer = True
class HighlightElement:
"""
Mix-in class to highlight the element this operator acts on. The element can
either be an entity or a constraint. The element has to be specified by an index
property for entities and additionaly with a type property for constraints.
index: IntProperty
type: StringProperty
Note that this defines the invoke and description functions, an operator that
defines one of those has to manually make a call to either of the following:
self.handle_highlight_active(context) -> from invoke()
cls.handle_highlight_hover(context, properties) -> from description()
Settings:
highlight_hover -> highlights the element as soon as the tooltip is shown
highlight_active -> highlights the element when the operator is invoked
highlight_members -> highlights the element members e.g. the entities dependencies or
the entities the constraint acts on
"""
highlight_hover: BoolProperty(name="Highlight Hover")
highlight_active: BoolProperty(name="Highlight Hover")
highlight_members: BoolProperty(name="Highlight Members")
@classmethod
def _do_highlight(cls, context, properties):
if not properties.is_property_set("index"):
return cls.__doc__
index = properties.index
members = properties.highlight_members
if hasattr(properties, "type") and properties.is_property_set("type"):
type = properties.type
c = context.scene.sketcher.constraints.get_from_type_index(type, index)
if members:
global_data.highlight_entities.extend(c.entities())
else:
global_data.highlight_constraint = c
else:
if members:
e = context.scene.sketcher.entities.get(index)
global_data.highlight_entities.extend(e.dependencies())
else:
# Set hover so this could be used as selection
global_data.hover = properties.index
context.area.tag_redraw()
return cls.__doc__
def handle_highlight_active(self, context):
properties = self.properties
if properties.highlight_active:
self._do_highlight(context, properties)
@classmethod
def handle_highlight_hover(cls, context, properties):
if properties.highlight_hover:
cls._do_highlight(context, properties)
@classmethod
def description(cls, context, properties):
cls.handle_highlight_hover(context, properties)
def invoke(self, context, event):
self.handle_highlight_active(context)
return self.execute(context)
class View3D_OT_slvs_register_draw_cb(Operator):
bl_idname = "view3d.slvs_register_draw_cb"
bl_label = "Register Draw Callback"
def execute(self, context):
global_data.draw_handle = bpy.types.SpaceView3D.draw_handler_add(
draw_cb, (), "WINDOW", "POST_VIEW"
)
return {"FINISHED"}
class View3D_OT_slvs_unregister_draw_cb(Operator):
bl_idname = "view3d.slvs_unregister_draw_cb"
bl_label = ""
def execute(self, context):
global_data.draw_handler.remove_handle()
return {"FINISHED"}
def deselect_all(context):
global_data.selected.clear()
def entities_3d(context):
for e in context.scene.sketcher.entities.all:
if hasattr(e, "sketch"):
continue
yield e
def select_all(context):
sketch = context.scene.sketcher.active_sketch
if sketch:
generator = sketch.sketch_entities(context)
else:
generator = entities_3d(context)
for e in generator:
if e.selected:
continue
if not e.is_visible(context):
continue
if not e.is_active(context.scene.sketcher.active_sketch):
continue
e.selected = True
class View3D_OT_slvs_select(Operator, HighlightElement):
"""
Select an entity
Either the entity specified by the index property or the hovered index
if the index property is not set
"""
bl_idname = "view3d.slvs_select"
bl_label = "Select Solvespace Entities"
index: IntProperty(name="Index", default=-1)
# TODO: Add selection modes
@classmethod
def poll(cls, context):
return True
def execute(self, context):
index = self.index if self.properties.is_property_set("index") else global_data.hover
if index != -1:
entity = context.scene.sketcher.entities.get(index)
entity.selected = not entity.selected
else:
deselect_all(context)
context.area.tag_redraw()
return {"FINISHED"}
class View3D_OT_slvs_select_all(Operator):
"""Select / Deselect all entities"""
bl_idname = "view3d.slvs_select_all"
bl_label = "Select / Deselect Entities"
deselect: BoolProperty(name="Deselect")
def execute(self, context):
if self.deselect:
deselect_all(context)
else:
select_all(context)
context.area.tag_redraw()
return {"FINISHED"}
class View3D_OT_slvs_context_menu(Operator, HighlightElement):
"""Show element's settings"""
bl_idname = "view3d.slvs_context_menu"
bl_label = "Solvespace Context Menu"
type: StringProperty(name="Type", options={'SKIP_SAVE'})
index: IntProperty(name="Index", default=-1, options={'SKIP_SAVE'})
@classmethod
def poll(cls, context):
return True
def execute(self, context):
is_entity = True
entity_index = None
constraint_index = None
element = None
# Constraints
if self.properties.is_property_set("type"):
constraint_index = self.index
constraints = context.scene.sketcher.constraints
element = constraints.get_from_type_index(self.type, self.index)
is_entity = False
else:
# Entities
entity_index = self.index if self.properties.is_property_set("index") else global_data.hover
if entity_index != -1:
element = context.scene.sketcher.entities.get(entity_index)
def draw_context_menu(self, context):
col = self.layout.column()
if not element:
col.label(text="Nothing hovered")
return
col.label(text="Type: " + type(element).__name__)
if is_entity:
if functions.get_prefs().show_debug_settings:
col.label(text="Index: " + str(element.slvs_index))
col.label(text="Is Origin: " + str(element.origin))
col.separator()
col.prop(element, "visible")
col.prop(element, "fixed")
col.prop(element, "construction")
elif element.failed:
col.label(text="Failed", icon="ERROR")
col.separator()
if hasattr(element, "draw_props"):
element.draw_props(col)
col.separator()
# Delete operator
if is_entity:
col.operator(View3D_OT_slvs_delete_entity.bl_idname, icon='X').index = element.slvs_index
else:
props = col.operator(View3D_OT_slvs_delete_constraint.bl_idname, icon='X')
props.type = element.type
props.index = constraint_index
context.window_manager.popup_menu(draw_context_menu)
return {"FINISHED"}
class View3D_OT_slvs_show_solver_state(Operator):
"""Show details about solver status"""
bl_idname = "view3d.slvs_show_solver_state"
bl_label = "Solver Status"
index: IntProperty(default=-1)
@classmethod
def poll(cls, context):
return True
def execute(self, context):
index = self.index
if index == -1:
return {"CANCELLED"}
def draw_item(self, context):
layout = self.layout
sketch = context.scene.sketcher.entities.get(index)
state = sketch.get_solver_state()
row = layout.row(align=True)
row.alignment = "LEFT"
row.label(text=state.name, icon=state.icon)
layout.separator()
layout.label(text=state.description)
context.window_manager.popup_menu(draw_item)
return {"FINISHED"}
from .solver import Solver, solve_system
class View3D_OT_slvs_solve(Operator):
bl_idname = "view3d.slvs_solve"
bl_label = "Solve"
all: BoolProperty(name="Solve All", options={"SKIP_SAVE"})
def execute(self, context):
sketch = context.scene.sketcher.active_sketch
solver = Solver(context, sketch, all=self.all)
ok = solver.solve()
# Keep messages simple, sketches are marked with solvestate
if ok:
self.report({"INFO"}, "Successfully solved")
else:
self.report({"WARNING"}, "Solver failed")
context.area.tag_redraw()
return {"FINISHED"}
def add_point(context, pos, name=""):
data = bpy.data
ob = data.objects.new(name, None)
ob.location = pos
context.collection.objects.link(ob)
return ob
class View3D_OT_slvs_tweak(Operator):
"""Tweak the hovered element"""
bl_idname = "view3d.slvs_tweak"
bl_label = "Tweak Solvespace Entities"
bl_options = {"UNDO"}
@classmethod
def poll(cls, context):
return True
def invoke(self, context, event):
index = global_data.hover
# TODO: hover should be -1 if nothing is hovered, not None!
if index == None or index == -1:
return {"CANCELLED"}
entity = context.scene.sketcher.entities.get(index)
self.entity = entity
coords = (event.mouse_region_x, event.mouse_region_y)
origin, view_vector = functions.get_picking_origin_dir(context, coords)
if not hasattr(entity, "closest_picking_point"):
if not hasattr(entity, "sketch"):
self.report(
{"WARNING"}, "Cannot tweak element of type {}".format(type(entity))
)
return {"CANCELLED"}
# For 2D entities it should be enough precise to get picking point from intersection with workplane
wp = entity.sketch.wp
coords = (event.mouse_region_x, event.mouse_region_y)
origin, dir = functions.get_picking_origin_dir(context, coords)
end_point = dir * context.space_data.clip_end + origin
pos = intersect_line_plane(origin, end_point, wp.p1.location, wp.normal)
else:
pos = entity.closest_picking_point(origin, view_vector)
# find the depth
self.depth = (pos - origin).length
context.window_manager.modal_handler_add(self)
return {"RUNNING_MODAL"}
def modal(self, context, event):
if event.type == "LEFTMOUSE" and event.value == "RELEASE":
context.window.cursor_modal_restore()
return {"FINISHED"}
context.window.cursor_modal_set("HAND")
if event.type == "MOUSEMOVE":
entity = self.entity
coords = (event.mouse_region_x, event.mouse_region_y)
# Get tweaking position
origin, dir = functions.get_picking_origin_dir(context, coords)
if hasattr(entity, "sketch"):
wp = entity.wp
end_point = dir * context.space_data.clip_end + origin
pos = intersect_line_plane(origin, end_point, wp.p1.location, wp.normal)
else:
pos = dir * self.depth + origin
sketch = context.scene.sketcher.active_sketch
solver = Solver(context, sketch)
solver.tweak(entity, pos)
retval = solver.solve(report=False)
# NOTE: There's no blocking cursor
# also solving frequently returns an error while tweaking which causes flickering
# if retval != 0:
# context.window.cursor_modal_set("WAIT")
# self.report({'WARNING'}, "Cannot solve sketch, error: {}".format(retval))
context.area.tag_redraw()
return {"RUNNING_MODAL"}
def write_selection_buffer_image(image_name):
offscreen = global_data.offscreen
width, height = offscreen.width, offscreen.height
buffer = bgl.Buffer(bgl.GL_FLOAT, width * height * 4)
with offscreen.bind():
bgl.glReadPixels(0, 0, width, height, bgl.GL_RGBA, bgl.GL_FLOAT, buffer)
if not image_name in bpy.data.images:
bpy.data.images.new(image_name, width, height)
image = bpy.data.images[image_name]
image.scale(width, height)
image.pixels = buffer
return image
class VIEW3D_OT_slvs_write_selection_texture(Operator):
"""Write selection texture to image for debuging"""
bl_idname = "view3d.slvs_write_selection_texture"
bl_label = "Write selection texture"
def execute(self, context):
if context.area.type != "VIEW_3D":
self.report({"WARNING"}, "View3D not found, cannot run operator")
return {"CANCELLED"}
if not global_data.offscreen:
self.report({'WARNING'}, "Selection texture is not available")
return {'CANCELLED'}
image = write_selection_buffer_image("selection_buffer")
self.report({"INFO"}, "Wrote buffer to image: {}".format(image.name))
return {"FINISHED"}
# NOTE: The draw handler has to be registered before this has any effect, currently it's possible that
# entities are first created with an entity that was hovered in the previous state
# Not sure if it's possible to force draw handlers...
# Also note that a running modal operator might prevent redraws, avoid returning running_modal
def ignore_hover(entity):
ignore_list = global_data.ignore_list
ignore_list.append(entity.slvs_index)
# TODO: could probably check entity type only through index, instead of getting the entity first...
def get_hovered(context, *types):
hovered = global_data.hover
entity = None
if hovered != -1:
entity = context.scene.sketcher.entities.get(hovered)
if type(entity) in types:
return entity
return None
def format_types(types):
entity_names = ", ".join([e.__name__ for e in types])
return "[" + entity_names + "]"
def state_desc(name, desc, types):
type_desc = ""
if types:
type_desc = "Types: " + format_types(types)
return " ".join((name + ":", desc, type_desc))
def stateful_op_desc(base, *state_descs):
states = ""
length = len(state_descs)
for i, state in enumerate(state_descs):
states += " - {}{}".format(
state, (" \n" if i < length - 1 else "")
)
desc = "{} \n \nStates: \n{}".format(base, states)
return desc
numeric_events = (
"ZERO",
"ONE",
"TWO",
"THREE",
"FOUR",
"FIVE",
"SIX",
"SEVEN",
"EIGHT",
"NINE",
"PERIOD",
"NUMPAD_0",
"NUMPAD_1",
"NUMPAD_2",
"NUMPAD_3",
"NUMPAD_4",
"NUMPAD_5",
"NUMPAD_6",
"NUMPAD_7",
"NUMPAD_8",
"NUMPAD_9",
"NUMPAD_PERIOD",
"MINUS",
"NUMPAD_MINUS",
)
def get_evaluated_obj(context, object):
return object.evaluated_get(context.evaluated_depsgraph_get())
def get_mesh_element(context, coords, vertex=False, edge=False, face=False, threshold=0.5, object=None):
from bpy_extras import view3d_utils
# get the ray from the viewport and mouse
region = context.region
rv3d = context.region_data
view_vector = view3d_utils.region_2d_to_vector_3d(region, rv3d, coords)
ray_origin = view3d_utils.region_2d_to_origin_3d(region, rv3d, coords)
depsgraph = context.view_layer.depsgraph
scene = context.scene
result, loc, _normal, face_index, ob, _matrix = scene.ray_cast(depsgraph, ray_origin, view_vector)
if object:
# Alternatively do a object raycast if we know the object already
tree = functions.bvhtree_from_object(ob)
loc, _normal, face_index, _distance = tree.ray_cast(ray_origin, view_vector)
result = loc != None
ob = object
if not result:
return None, None, None
obj_eval = get_evaluated_obj(context, ob)
closest_type = ""
closest_dist = None
loc = obj_eval.matrix_world.inverted() @ loc
me = obj_eval.data
polygon = me.polygons[face_index]
def get_closest(deltas):
index_min = min(range(len(deltas)), key=deltas.__getitem__)
if deltas[index_min] > threshold:
return None, None
return index_min, deltas[index_min]
def is_closer(distance, min_distance):
if min_distance is None:
return True
if distance < min_distance:
return True
return False
if vertex:
i, dist = get_closest([(me.vertices[i].co - loc).length for i in polygon.vertices])
if i is not None:
closest_type = "VERTEX"
closest_index = polygon.vertices[i]
closest_dist = dist
if edge:
face_edge_map = {ek: me.edges[i] for i, ek in enumerate(me.edge_keys)}
i, dist = get_closest(
[(((me.vertices[start].co + me.vertices[end].co)/2)-loc).length for start, end in polygon.edge_keys]
)
if i is not None and is_closer(dist, closest_dist):
closest_type = "EDGE"
closest_index = face_edge_map[polygon.edge_keys[i]].index
closest_dist = dist
if face:
# Check if face midpoint is closest
if is_closer((polygon.center - loc).length, closest_dist):
closest_type = "FACE"
closest_index = face_index
if closest_type:
return ob, closest_type, closest_index
return ob, bpy.types.Object, None
def to_list(val):
if val == None:
return []
if type(val) in (list, tuple):
return list(val)
return [val,]
def _get_pointer_get_set(index):
@property
def func(self):
return self.get_state_pointer(index=index)
@func.setter
def setter(self, value):
self.set_state_pointer(value, index=index)
return func, setter
mesh_element_types = bpy.types.MeshVertex, bpy.types.MeshEdge, bpy.types.MeshPolygon
class StatefulOperator:
state_index: IntProperty(options={"HIDDEN", "SKIP_SAVE"})
wait_for_input: BoolProperty(options={"HIDDEN", "SKIP_SAVE"}, default=True)
continuose_draw: BoolProperty(name="Continuose Draw", default=False)
executed = False
_state_data = {}
_last_coords = Vector((0, 0))
_numeric_input = {}
@classmethod
def _has_global_object(cls):
states = cls.get_states_definition()
return any([s.pointer == "object" for s in states])
def _get_global_object_index(cls):
states = cls.get_states_definition()
object_in_list = [s.pointer == "object" for s in states]
if not any(object_in_list):
return None
return object_in_list.index(True)
@classmethod
def register_properties(cls):
states = cls.get_states_definition()
annotations = cls.__annotations__.copy()
# Have some specific logic: pointer name "object" is used as global object
# otherwise define ob_name for each element
has_global_object = cls._has_global_object()
for i, s in enumerate(states):
pointer_name = s.pointer
types = s.types
if not pointer_name:
continue
if pointer_name in annotations.keys():
# Skip pointers that have a property defined
# Note: pointer might not need implicit props, thus no need for getter/setter
return
if hasattr(cls, pointer_name):
raise NameError("Cannot register state pointer getter/setter, class {} already has attribute of name {}".format(cls, pointer_name))
get, set = _get_pointer_get_set(i)
setattr(cls, pointer_name, get)
# Note: keep state pointers read-only, only set with set_state_pointer()
for a in annotations.keys():
if hasattr(cls, a):
raise NameError("Cannot register implicit pointer properties, class {} already has attribute of name {}".format(cls, a))
setattr(cls, "__annotations__", annotations)
def state_property(self, state_index):
return None
def get_state_pointer(self, index=None, implicit=False):
# Creates pointer value from it's implicitly stored props
if index is None:
index = self.state_index
state = self.get_states_definition()[index]
pointer_name = state.pointer
data = self._state_data.get(index, {})
if not "type" in data.keys():
return None
pointer_type = data["type"]
if not pointer_type:
return None
if pointer_type in (bpy.types.Object, *mesh_element_types):
if self._has_global_object():
global_ob_index = self._get_global_object_index()
obj_name = self._state_data[global_ob_index]["object_name"]
else:
obj_name = data["object_name"]
obj = get_evaluated_obj(bpy.context, bpy.data.objects[obj_name])
if pointer_type in mesh_element_types:
index = data["mesh_index"]
if pointer_type == bpy.types.Object:
if implicit:
return obj_name
return obj
elif pointer_type == bpy.types.MeshVertex:
if implicit:
return obj_name, index
return obj.data.vertices[index]
elif pointer_type == bpy.types.MeshEdge:
if implicit:
return obj_name, index
return obj.data.edges[index]
elif pointer_type == bpy.types.MeshPolygon:
if implicit:
return obj_name, index
return obj.data.polygons[index]
def set_state_pointer(self, values, index=None, implicit=False):
# handles type specific setters
if index is None:
index = self.state_index
state = self.get_states_definition()[index]
pointer_name = state.pointer
data = self._state_data.get(index, {})
pointer_type = data["type"]
def get_value(index):
if values == None:
return None
return values[index]
if pointer_type == bpy.types.Object:
if implicit:
val = get_value(0)
else:
val = get_value(0).name
data["object_name"] = val
return True
elif pointer_type in mesh_element_types:
obj_name = get_value(0) if implicit else get_value(0).name
if self._has_global_object():
self._state_data[self._get_global_object_index()]["object_name"] = obj_name
else:
data["object_name"] = obj_name
data["mesh_index"] = get_value(1) if implicit else get_value(1).index
return True
def pick_element(self, context, coords):
# return a list of implicit prop values if pointer need implicit props
state = self.state
data = self.state_data
types = {
"vertex": (bpy.types.MeshVertex in state.types),
"edge": (bpy.types.MeshEdge in state.types),
"face": (bpy.types.MeshPolygon in state.types),
}
do_object = bpy.types.Object in state.types
do_mesh_elem = any(types.values())
if not do_object and not do_mesh_elem:
return
global_ob = None
if self._has_global_object():
global_ob_name = self._state_data[self._get_global_object_index()].get("object_name")
if global_ob_name:
global_ob = bpy.data.objects[global_ob_name]
ob, type, index = get_mesh_element(context, coords, **types, object=global_ob)
if not ob:
return None
if bpy.types.Object in state.types:
data["type"] = bpy.types.Object
return ob.name
# maybe have type as return value
data["type"] = {
"VERTEX": bpy.types.MeshVertex,
"EDGE": bpy.types.MeshEdge,
"FACE": bpy.types.MeshPolygon,
}[type]
return ob.name, index
def get_property(self, index=None):
if index == None:
index = self.state_index
state = self.get_states()[index]
if state.property == None:
return None
if callable(state.property):
props = state.property(self, index)
elif state.property:
if callable(getattr(self, state.property)):
props = getattr(self, state.property)(index)
else:
props = state.property
elif hasattr(self, "state_property") and callable(self.state_property):
props = self.state_property(index)
else:
return None
retval = to_list(props)
return retval
@classmethod
def get_states_definition(cls):
if callable(cls.states):
return cls.states()
return cls.states
def get_states(self):
if callable(self.states):
return self.states(operator=self)
return self.states
@property
def state(self):
return self.get_states()[self.state_index]
def _index_from_state(self, state):
return [e.name for e in self.get_states()].index(state)
@state.setter
def state(self, state):
self.state_index = self._index_from_state(state)
def set_state(self, context, index):
self.state_index = index
self.init_numeric(False)
self.set_status_text(context)
def next_state(self, context):
i = self.state_index
if (i + 1) >= len(self.get_states()):
return False
self.set_state(context, i + 1)
return True
def set_status_text(self, context):
# Setup state
state = self.state
desc = (
state.description(self, state)
if callable(state.description)
else state.description
)
msg = state_desc(state.name, desc, state.types)
if self.state_data.get("is_numeric_edit", False):
index = self._substate_index
prop = self._stateprop
type = prop.type
array_length = prop.array_length if prop.array_length else 1
if type == "FLOAT":
input = [0.0] * array_length
for key, val in self._numeric_input.items():
input[key] = val
input[index] = "*" + str(input[index])
input = str(input).replace('"', "").replace("'", "")
elif type == "INT":
input = self.numeric_input
msg += " {}: {}".format(prop.subtype, input)
context.workspace.status_text_set(msg)
def check_numeric(self):
"""Check if the state supports numeric edit"""
# TODO: Allow to define custom logic
state = self.state
props = self.get_property()
# Disable for multi props
if not props or len(props) > 1:
return False
prop_name = props[0]
if not prop_name:
return False
prop = self.properties.rna_type.properties[prop_name]
if not prop.type in ("INT", "FLOAT"):
return False
return True
def init_numeric(self, is_numeric):
self._numeric_input = {}
self._substate_index = 0
ok = False
if is_numeric:
ok = self.check_numeric()
# TODO: not when iterating substates
self.state_data["is_numeric_edit"] = is_numeric and ok
self.init_substate()
return ok
def init_substate(self):
props = self.get_property()
if props and props[0]:
prop_name = props[0]
prop = self.properties.rna_type.properties[prop_name]
self._substate_count = prop.array_length
self._stateprop = prop
else:
self._substate_count = None
self._stateprop = None
def iterate_substate(self):
i = self._substate_index
if i + 1 >= self._substate_count:
i = 0
else:
i += 1
self._substate_index = i
@property
def numeric_input(self):
return self._numeric_input.get(self._substate_index, "")