-
Notifications
You must be signed in to change notification settings - Fork 158
/
vertex_normals.py
1527 lines (1300 loc) · 55 KB
/
vertex_normals.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
# Copyright (C) 2014-2017 Triumph LLC
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
# Original idea from the Recalc Vertex Normals add-on by adsn
import bpy
import mathutils
import bgl
from bpy.types import Panel
from rna_prop_ui import PropertyPanel
from mathutils import (Vector, Quaternion, Matrix)
import copy
from collections import namedtuple
from math import sqrt
from math import radians
import blend4web
b4w_modules = ["translator",]
for m in b4w_modules:
exec(blend4web.load_module_script.format(m))
from blend4web.translator import _, p_
global b4w_vertex_to_loops_map
b4w_vertex_to_loops_map = {}
global b4w_loops_normals
b4w_loops_normals = []
global b4w_loops_normals_select
b4w_loops_normals_select = []
global helper_handle
helper_handle = None
global b4w_vn_customnormal_updated
b4w_vn_customnormal_updated = False
class RotationHelperParams:
is_active = False
local_space = False
constraint = None
typed_number = None
c_world = Vector()
mouse_local = Vector()
mouse_world = Vector()
AXES_MAP = {"X": Vector((1,0,0)),
"Y": Vector((0,1,0)),
"Z": Vector((0,0,1))}
global modal_operator_helper_params
modal_operator_helper_params = RotationHelperParams()
def set_vertex_normal(index, value):
(x,y,z) = value
l = sqrt(x*x + y*y + z*z)
if l!= 0: # case when "Copy" not pressed yet
newvalue = (x/l, y/l, z/l)
if index in b4w_vertex_to_loops_map:
for i in b4w_vertex_to_loops_map[index]:
b4w_loops_normals[i] = newvalue
def resize_array_if_need(array, length, el = (0,0,0)):
if len(array) != length:
array.clear()
for i in range(length):
array.append(el)
return True
else:
return False
def load_loops_normals(ob):
loops_normals = []
vertex_to_loops_map = {}
ob.data.calc_normals_split()
i = 0
resize_array_if_need(loops_normals, len(ob.data.loops))
for i in range(len(ob.data.loops)):
l = ob.data.loops[i]
if not l.vertex_index in vertex_to_loops_map:
vertex_to_loops_map[l.vertex_index] = []
vertex_to_loops_map[l.vertex_index].append(i)
loops_normals[i] = (l.normal.x, l.normal.y, l.normal.z)
return (loops_normals, vertex_to_loops_map)
def load_loops_normals_into_global_cache(ob):
global b4w_loops_normals
global b4w_vertex_to_loops_map
b4w_loops_normals, b4w_vertex_to_loops_map = load_loops_normals(ob)
resize_array_if_need(b4w_loops_normals_select, len(b4w_loops_normals))
def check_b4w_obj_prop(context):
if 'b4w_select' not in context.active_object:
context.active_object['b4w_select'] = 0
if 'b4w_select_vertex' not in context.active_object:
context.active_object['b4w_select_vertex'] = 0
def prepare(context):
check_b4w_obj_prop(context)
load_loops_normals_into_global_cache(context.active_object)
class B4W_ShapeKeysNormal(bpy.types.PropertyGroup):
normal = bpy.props.FloatVectorProperty(name=_("Normal"), subtype="NONE",
unit="NONE", size=3)
def b4w_select(self, context):
b4w_split = context.window_manager.b4w_split
obj = context.active_object
size = 0
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.object.mode_set(mode="EDIT")
prepare(context)
sel_vert = find_single_selected_vertex(obj)
if sel_vert != -1:
context.active_object['b4w_select_vertex'] = sel_vert
b4w_select_vertex = context.active_object['b4w_select_vertex']
array = []
if not b4w_split:
size = len(context.active_object.data.vertices)
array = context.active_object.data.vertices
else:
size = len(b4w_vertex_to_loops_map[b4w_select_vertex])
array = b4w_vertex_to_loops_map[b4w_select_vertex]
obj['b4w_select'] = obj['b4w_select'] % size
b4w_select = obj['b4w_select']
if not b4w_split:
obj['b4w_select_vertex'] = obj['b4w_select']
bpy.ops.object.mode_set(mode='OBJECT')
for i in range(size):
select = i == b4w_select
if not b4w_split:
array[i].select = copy.copy(select)
else:
b4w_loops_normals_select[array[i]] = copy.copy(select)
if select:
global b4w_vn_customnormal_updated
b4w_vn_customnormal_updated = True
context.window_manager.b4w_vn_customnormal1 = copy.copy(
b4w_loops_normals[array[i]])
b4w_vn_customnormal_updated = False
bpy.ops.object.mode_set(mode='EDIT')
class B4W_VertexNormalsUI(bpy.types.Panel):
# draw UI buttons
bl_idname = "B4W_VIEW3D_PT_normal_editor"
bl_label = _('Normal Editor')
bl_space_type = 'VIEW_3D'
bl_region_type = 'TOOLS'
bl_category = "Blend4Web"
def __init__(self):
pass
@classmethod
def poll(self, context):
try:
ob = context.active_object
if ob.type == 'MESH':
return True
else:
return False
except AttributeError:
return False
def draw(self, context):
is_edit_mode = context.active_object.mode == 'EDIT'
layout = self.layout
row = layout.row(align=True)
row.prop(context.active_object.data, 'use_auto_smooth',
text=_('Activate'), toggle=True, icon='MOD_NORMALEDIT')
layout.label(text="Settings:")
# draw normals
row = layout.row(align=True)
row.active = context.active_object.data.use_auto_smooth
row.prop(context.active_object.data, 'show_normal_loop', text=_('Show Normals'),
toggle=True, icon='LOOPSEL')
row.enabled = is_edit_mode
row.prop(bpy.context.scene.tool_settings, 'normal_size', text=_('Size'))
row.enabled = is_edit_mode
# Split normals
row = layout.row()
row.prop(context.window_manager, 'b4w_split', text = _('Split Mode'),
toggle=True)
row.enabled = is_edit_mode
row.active = context.active_object.data.use_auto_smooth
# selection tools
# selected single vertex index
row.prop(context.active_object, 'b4w_select', text=_('Index'))
# Direct editing
layout.label(text="Direct Edit:")
row = layout.row()
row.active = context.active_object.data.use_auto_smooth
row.enabled = is_edit_mode
col = row.column()
col.operator('object.b4w_normal_rotate', text = p_('Rotate', "Operator"), icon='MAN_ROT')
col = row.column()
col.operator('object.b4w_normal_scale', text = p_('Scale', "Operator"), icon='MAN_SCALE')
row = layout.row()
row.active = context.active_object.data.use_auto_smooth
row.prop(context.window_manager, 'b4w_normal_edit_mode', expand=True)
if context.window_manager.b4w_normal_edit_mode == "ABSOLUTE":
# manipulate normals
row = layout.row()
row.active = context.active_object.data.use_auto_smooth
row.column().prop(context.window_manager, 'b4w_vn_customnormal2',
expand=True, text='')
row.enabled = is_edit_mode
# ball
row.prop(context.window_manager, 'b4w_vn_customnormal1', text='')
row.enabled = is_edit_mode
else:
row = layout.row(align=True)
row.column(align=True).prop(context.window_manager, 'b4w_customnormal_offset', text='', expand=True)
row = layout.row(align=True)
row.operator("object.b4w_apply_offset", text="Sub", icon='ZOOMOUT').sign = -1
row.operator("object.b4w_apply_offset", text="Add", icon='ZOOMIN').sign = 1
# Transform operators
layout.label(text="Transform:")
# average
row = layout.row(align=True)
row.enabled = is_edit_mode
row.active = context.active_object.data.use_auto_smooth
row.operator('object.b4w_smooth_normals', text = p_('Average', "Operator"))
# restore/smooth
row = layout.row(align=True)
row.active = context.active_object.data.use_auto_smooth
row.operator('object.b4w_restore_normals', text = p_('Restore', "Operator"))
row.enabled = is_edit_mode
# Alignment operators
layout.label(text="Align:")
row = layout.row(align=True)
row.active = context.active_object.data.use_auto_smooth
row.operator('object.cursor_align_vertex_normals', text = p_('3D Cursor', "Operator"), icon='CURSOR')
row.operator('object.axis_align_vertex_normals', text = p_('Axis', "Operator"), icon='MANIPUL')
row.operator('object.face_vertex_normals', text = p_('Face', "Operator"), icon='FACESEL')
row.enabled = not context.window_manager.b4w_split and is_edit_mode
# Transfer tools and operators
layout.label(text="Transfer:")
row = layout.row(align=True)
row.active = context.active_object.data.use_auto_smooth
row.operator('object.copy_normal', text = p_('Copy', "Operator"), icon='COPYDOWN')
row.operator('object.paste_normal', text = p_('Paste', "Operator"), icon='PASTEDOWN')
row.enabled = is_edit_mode
row = layout.row(align=True)
row.active = context.active_object.data.use_auto_smooth
if context.window_manager.b4w_copy_normal_method == "MATCHED":
row.operator('object.copy_normals_from_mesh', text = p_('Copy From Mesh', "Operator"))
else:
row.operator('b4w.approx_normals_from_mesh', text = p_('Copy From Mesh', "Operator"))
row.prop(context.window_manager, 'b4w_copy_normal_method', text='')
row.enabled = not is_edit_mode
def lerp_to_vertex_loop_normal(index, value, t):
n = b4w_loops_normals[index]
n = value.lerp(n, 1-t).normalized()
b4w_loops_normals[index] = (n.x, n.y, n.z)
def lerp_to_vertex_normal(index, value, t):
if index in b4w_vertex_to_loops_map:
loops = b4w_vertex_to_loops_map[index]
for j in loops:
n = b4w_loops_normals[j]
n = value.lerp(n, 1-t).normalized()
b4w_loops_normals[j] = (n.x, n.y, n.z)
class B4W_CursorAlignVertexNormals(bpy.types.Operator):
bl_idname = 'object.cursor_align_vertex_normals'
bl_label = p_('Vertex Normal Cursor', "Operator")
bl_description = _('Align selected verts pointing away from 3d cursor')
bl_options = {"INTERNAL", "REGISTER", "UNDO"}
towards = bpy.props.BoolProperty(
name = "Towards",
description = _("Point normals towards the 3D cursor"),
default = 0
)
factor = bpy.props.FloatProperty(
name = "Factor",
description = _("Factor"),
subtype = 'FACTOR',
min = 0,
max = 1,
default = 1
)
def execute(self, context):
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
prepare(context)
obj = context.active_object
vert_index = len(bpy.context.active_object.data.vertices)
obmat = context.active_object.matrix_world
vec1 = obmat.inverted() * context.scene.cursor_location
bpy.ops.object.mode_set(mode='OBJECT')
for i in range(vert_index):
if context.active_object.data.vertices[i].select == True:
vec2 = obj.data.vertices[i].co
newnormal = vec1 - vec2 if self.towards else vec2 - vec1
newnormal = newnormal.normalized()
lerp_to_vertex_normal(i, newnormal, self.factor)
bpy.ops.object.mode_set(mode='OBJECT')
obj.data.normals_split_custom_set(b4w_loops_normals)
bpy.ops.object.mode_set(mode='EDIT')
context.area.tag_redraw()
return {'FINISHED'}
class B4W_AxisAlignVertexNormals(bpy.types.Operator):
# align selected verts to selected axis
bl_idname = 'object.axis_align_vertex_normals'
bl_label = p_('Vertex Normal Axis', "Operator")
bl_description = _('Selected verts to Z axis')
bl_options = {"INTERNAL", "REGISTER", "UNDO"}
towards = bpy.props.BoolProperty(
name = "Towards",
description = _("Point normals towards the 3D cursor"),
default = True
)
axis = bpy.props.EnumProperty(
name = "Axis",
description = _("Alignment axis"),
items = [
("X", _("X"), _("Align verts to positive X axis"), 0),
("Y", _("Y"), _("Align verts to positive Y axis"), 1),
("Z", _("Z"), _("Align verts to positive Z axis"), 2),
],
default = "Z"
)
space = bpy.props.EnumProperty(
name = "Space",
description = _("Transform Space"),
items = [
("Global", _("Global"), _("Use global transform space"), 0),
("Local", _("Local"), _("Use local transform space"), 1)
],
default = "Global"
)
factor = bpy.props.FloatProperty(
name = "Factor",
description = _("Factor"),
subtype = 'FACTOR',
min = 0,
max = 1,
default = 1
)
def execute(self, context):
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
prepare(context)
obj = context.active_object
num_verts = len(bpy.context.active_object.data.vertices)
align_vector = copy.copy(AXES_MAP[self.axis])
if not self.towards:
align_vector = -align_vector
if self.space == 'Global':
align_vector = obj.rotation_euler.to_matrix().inverted() * align_vector
align_vector.normalize()
bpy.ops.object.mode_set(mode='OBJECT')
for i in range(num_verts):
if context.active_object.data.vertices[i].select == True:
lerp_to_vertex_normal(i, align_vector, self.factor)
bpy.ops.object.mode_set(mode='OBJECT')
obj.data.normals_split_custom_set(b4w_loops_normals)
bpy.ops.object.mode_set(mode='EDIT')
context.area.tag_redraw()
return {'FINISHED'}
class B4W_FaceVertexNormals(bpy.types.Operator):
# face orientation
bl_idname = 'object.face_vertex_normals'
bl_label = p_('Vertex Normal Face', "Operator")
bl_description = _('Copy face normal')
bl_options = {"INTERNAL", "REGISTER", "UNDO"}
smooth_shared = bpy.props.BoolProperty(
name = "Smooth Shared",
description = _("Smooth shared normals of shared vertices"),
default = True
)
factor = bpy.props.FloatProperty(
name = "Factor",
description = _("Factor"),
subtype = 'FACTOR',
min = 0,
max = 1,
default = 1
)
def execute(self, context):
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
prepare(context)
obj = context.active_object
mesh = obj.data
bpy.ops.object.mode_set(mode='OBJECT')
sel_indices = []
for i in range(len(mesh.vertices)):
if mesh.vertices[i].select == True:
sel_indices.append(i)
if len(sel_indices) < 3:
self.report({'INFO'}, _('Please select at least 3 vertices'))
return {"FINISHED"}
sel_polys = []
for poly in mesh.polygons:
if poly.select == True:
sel_polys.append(poly)
if self.smooth_shared:
for i in sel_indices:
n = Vector((0,0,0))
for poly in sel_polys:
if i in poly.vertices:
n = n + poly.normal
n.normalize()
lerp_to_vertex_normal(i, n, self.factor)
else:
for poly in sel_polys:
n = poly.normal
for loop_i in poly.loop_indices:
lerp_to_vertex_loop_normal(loop_i, n, self.factor)
bpy.ops.object.mode_set(mode='OBJECT')
obj.data.normals_split_custom_set(b4w_loops_normals)
bpy.ops.object.mode_set(mode='EDIT')
context.area.tag_redraw()
return {'FINISHED'}
class B4W_CopyNormalsFromMesh(bpy.types.Operator):
# copy normals from another mesh if |v1 - v2| -> 0
bl_idname = 'object.copy_normals_from_mesh'
bl_label = p_("B4W Copy Normals From Mesh (Matched)", "Operator")
bl_description = _('Copy normals from the selected to the active mesh' +
' for selected vertices')
bl_options = {"REGISTER", "UNDO", "INTERNAL"}
threshold = bpy.props.FloatProperty(
name = "Threshold",
description = _("Threshold"),
min = 0.00001,
max = 10,
step = 0.01,
precision = 4,
default = 0.001
)
factor = bpy.props.FloatProperty(
name = "Factor",
description = _("Factor"),
subtype = 'FACTOR',
min = 0,
max = 1,
default = 1
)
def execute(self, context):
prepare(context)
norm_edited = False
if len(bpy.context.selected_objects) != 2:
print('Wrong selection')
else:
obj_target = context.active_object
if context.selected_objects[0].name!=obj_target.name:
obj_source = context.selected_objects[0]
else:
obj_source = context.selected_objects[1]
verts_target = obj_target.data.vertices
verts_source = obj_source.data.vertices
src_loops_normals, src_vert_to_loops_map = load_loops_normals(obj_source)
verts_is_selected = False
for v in verts_target:
if v.select:
verts_is_selected = True
break
verts_target_count = len(verts_target)
for i in range(verts_target_count):
if not verts_is_selected or verts_target[i].select:
for j in range(len(verts_source)):
if (verts_target[i].co - verts_source[j].co).length < self.threshold:
n = Vector()
for l in src_vert_to_loops_map[j]:
n = n + Vector(src_loops_normals[l])
n = n / len(src_vert_to_loops_map[j])
lerp_to_vertex_normal(i, n, self.factor)
norm_edited = True
if norm_edited:
obj_target.data.normals_split_custom_set(b4w_loops_normals)
context.area.tag_redraw()
return {'FINISHED'}
class B4W_ApproxNormalsFromMesh(bpy.types.Operator):
# copy normals from the nearest vertices of another mesh
bl_idname = "b4w.approx_normals_from_mesh"
bl_label = p_("B4W Copy Normals From Mesh (Nearest)", "Operator")
bl_description = _("Approximate target mesh normals from source mesh")
bl_options = {"INTERNAL", "REGISTER", "UNDO"}
factor = bpy.props.FloatProperty(
name = "Factor",
description = _("Factor"),
subtype = 'FACTOR',
min = 0,
max = 1,
default = 1
)
def execute(self, context):
prepare(context)
if len(bpy.context.selected_objects) != 2:
print('Wrong selection')
self.report({'INFO'}, _('Please select 2 meshes'))
else:
self.approx_normals(context)
context.area.tag_redraw()
return {"FINISHED"}
def approx_normals(self, context):
obj_dst = context.active_object
if context.selected_objects[0].name!=obj_dst.name:
obj_src = context.selected_objects[0]
else:
obj_src = context.selected_objects[1]
mesh_src = obj_src.data
mesh_dst = obj_dst.data
src_loops_normals, src_vert_to_loops_map = load_loops_normals(obj_src)
dst_vert_list = mesh_dst.vertices
src_vert_list = mesh_src.vertices
matr_src = obj_src.matrix_world
matr_dst = obj_dst.matrix_world
# remember old vertices positions
old_dst_co_list = [0] * 3 * len(dst_vert_list)
old_src_co_list = [0] * 3 * len(src_vert_list)
for i in range(len(dst_vert_list)):
old_dst_co_list[i * 3] = dst_vert_list[i].co[0]
old_dst_co_list[i * 3 + 1] = dst_vert_list[i].co[1]
old_dst_co_list[i * 3 + 2] = dst_vert_list[i].co[2]
for i in range(len(src_vert_list)):
old_src_co_list[i * 3] = src_vert_list[i].co[0]
old_src_co_list[i * 3 + 1] = src_vert_list[i].co[1]
old_src_co_list[i * 3 + 2] = src_vert_list[i].co[2]
# transform vertices to world space
for vert_dst in dst_vert_list:
vert_dst.co = matr_dst * vert_dst.co
for vert_src in src_vert_list:
vert_src.co = matr_src * vert_src.co
# approximate normals
verts_is_selected = False
for v in dst_vert_list:
if v.select:
verts_is_selected = True
break
for vert_dst in dst_vert_list:
if not verts_is_selected or vert_dst.select == True:
min_distance = 1E10
min_index = -1
for vert_src in src_vert_list:
distance = sqrt(pow(vert_dst.co[0]-vert_src.co[0],2) \
+ pow(vert_dst.co[1]-vert_src.co[1],2)
+ pow(vert_dst.co[2]-vert_src.co[2],2))
if distance<min_distance:
if vert_src.index in src_vert_to_loops_map: # vertex must be connected
min_distance = distance
min_index = vert_src.index
n = Vector()
for l in src_vert_to_loops_map[min_index]:
n = n + Vector(src_loops_normals[l])
n = n / len(src_vert_to_loops_map[min_index])
n = matr_dst.to_quaternion().inverted() \
* matr_src.to_quaternion() \
* n
lerp_to_vertex_normal(vert_dst.index, n, self.factor)
# reset destination mesh's vertices positions
for vert_dst in dst_vert_list:
vert_dst.co[0] = old_dst_co_list[vert_dst.index * 3]
vert_dst.co[1] = old_dst_co_list[vert_dst.index * 3 + 1]
vert_dst.co[2] = old_dst_co_list[vert_dst.index * 3 + 2]
# reset source mesh's vertices positions
for vert_src in src_vert_list:
vert_src.co[0] = old_src_co_list[vert_src.index * 3]
vert_src.co[1] = old_src_co_list[vert_src.index * 3 + 1]
vert_src.co[2] = old_src_co_list[vert_src.index * 3 + 2]
obj_dst.data.normals_split_custom_set(b4w_loops_normals)
def get_selected_split_normal_idx(obj):
vert_index = len(obj.data.vertices)
for i in range(vert_index):
if obj.data.vertices[i].select == True:
obj["b4w_select_vertex"] = i
break
array = b4w_vertex_to_loops_map[obj["b4w_select_vertex"]]
return array[obj["b4w_select"]%len(array)]
# main function for update custom normals
# trans_param depends on trans_type
# if trans_type == rotate -> strans_param == rotation matrix,
# else trans_param is normal vector
def update_custom_normal(self, context, trans_param, trans_type = "set",
init_normals = None):
global b4w_loops_normals
# toggle mode for update selection
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.object.mode_set(mode="EDIT")
check_b4w_obj_prop(context)
# forced to load normals always because smooth/flat shading can be changed
# no simple way to detect this change
load_loops_normals_into_global_cache(context.active_object)
#
normals_edited = False
obj = context.active_object
vert_index = len(obj.data.vertices)
if not context.window_manager.b4w_split:
for i in range(vert_index):
# selected verts align on custom normal
if obj.data.vertices[i].select == True:
normals_edited = True
if trans_type == "transform":
n = Vector(init_normals[i])
n = trans_param * n
elif trans_type == "set":
n = copy.copy(trans_param)
n.normalize()
set_vertex_normal(i, (n.x, n.y, n.z))
else:
ind = get_selected_split_normal_idx(obj)
if trans_type == "transform":
n = Vector(init_normals[ind])
n = trans_param * n
elif trans_type == "set":
n = copy.copy(trans_param)
n.normalize()
b4w_loops_normals[ind] = (n.x, n.y, n.z)
normals_edited = True
if normals_edited:
bpy.ops.object.mode_set(mode="OBJECT")
obj.data.normals_split_custom_set(b4w_loops_normals)
bpy.ops.object.mode_set(mode="EDIT")
def update_custom_normal1(self, context):
global b4w_vn_customnormal_updated
b4w_vn_customnormal_updated = b4w_vn_customnormal_updated + 1
if b4w_vn_customnormal_updated > 1:
b4w_vn_customnormal_updated = 0
return
normal = context.active_object.rotation_euler.to_matrix().inverted() * \
context.window_manager.b4w_vn_customnormal1
update_custom_normal(self, context, normal)
context.window_manager.b4w_vn_customnormal2 = copy.copy(
context.window_manager.b4w_vn_customnormal1)
def update_custom_normal2(self, context):
global b4w_vn_customnormal_updated
b4w_vn_customnormal_updated = b4w_vn_customnormal_updated + 1
if b4w_vn_customnormal_updated > 1:
b4w_vn_customnormal_updated = 0
return
normal = context.active_object.rotation_euler.to_matrix().inverted() * \
context.window_manager.b4w_vn_customnormal2
update_custom_normal(self, context, normal)
if context.window_manager.b4w_vn_customnormal2.length != 0:
context.window_manager.b4w_vn_customnormal1 = copy.copy(
context.window_manager.b4w_vn_customnormal2)
def find_single_selected_vertex(object):
vertices = object.data.vertices
found = 0
last = -1
for i in range(len(vertices)):
if vertices[i].select:
last = i
found += 1
if found == 1:
return last
else:
return -1
class B4W_CopyNormal(bpy.types.Operator):
# copy normal
bl_idname = 'object.copy_normal'
bl_label = p_('Copy Normal', "Operator")
bl_description = _('Copies normal from selected Vertex')
bl_options = {"INTERNAL", "REGISTER", "UNDO"}
def execute(self, context):
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.object.mode_set(mode="EDIT")
prepare(context)
obj = context.active_object
vert_index = len(context.active_object.data.vertices)
if not context.window_manager.b4w_split:
check = 0
# inverse selection
for h in range(vert_index):
if context.active_object.data.vertices[h].select == True:
check += 1
if check == 1:
for i in range(vert_index):
if context.active_object.data.vertices[i].select == True:
result = Vector()
for l in b4w_vertex_to_loops_map[i]:
result = result + Vector(b4w_loops_normals[l])
result = result / len(b4w_vertex_to_loops_map[i])
context.window_manager.b4w_vn_copynormal = result
else:
self.report({'INFO'}, _('Please select a single vertex'))
return {'FINISHED'}
else:
for i in range(vert_index):
if obj.data.vertices[i].select == True:
obj["b4w_select_vertex"] = i
break
array = b4w_vertex_to_loops_map[obj["b4w_select_vertex"]]
ind = array[obj["b4w_select"]%len(array)]
context.window_manager.b4w_vn_copynormal = Vector(b4w_loops_normals[ind])
return {'FINISHED'}
class B4W_PasteNormal(bpy.types.Operator):
# paste normal
bl_idname = 'object.paste_normal'
bl_label = p_('Paste Normal', "Operator")
bl_description = _('Paste normal to selected Vertex')
bl_options = {"INTERNAL", "REGISTER", "UNDO"}
def execute(self, context):
bpy.ops.object.mode_set(mode="OBJECT")
bpy.ops.object.mode_set(mode="EDIT")
obj = context.active_object
check_b4w_obj_prop(context)
load_loops_normals_into_global_cache(obj)
vert_index = len(context.active_object.data.vertices)
check = 0
normals_edited = False
if not context.window_manager.b4w_split:
for h in range(vert_index):
if context.active_object.data.vertices[h].select == True:
check += 1
if check >= 1:
for i in range(vert_index):
if context.active_object.data.vertices[i].select == True:
n = context.window_manager.b4w_vn_copynormal
set_vertex_normal(i, (n[0], n[1], n[2]))
normals_edited = True
else:
self.report({'INFO'}, _('Please select at least one vertex'))
else:
array = b4w_vertex_to_loops_map[obj["b4w_select_vertex"]]
ind = array[obj["b4w_select"]%len(array)]
n = context.window_manager.b4w_vn_copynormal
b4w_loops_normals[ind] = (n[0], n[1], n[2])
normals_edited = True
if normals_edited:
bpy.ops.object.mode_set(mode="OBJECT")
obj.data.normals_split_custom_set(b4w_loops_normals)
bpy.ops.object.mode_set(mode="EDIT")
return {'FINISHED'}
class B4W_ApplyOffset(bpy.types.Operator):
bl_idname = "object.b4w_apply_offset"
bl_label = p_("Apply offset", "Operator")
bl_description = _('Apply offset for selected normals')
bl_options = {"INTERNAL", "UNDO"}
sign = bpy.props.IntProperty(
name = "B4W: offset sign",
description = _("Offset sign"),
default = 1,
min=-1,
max=1,
)
def execute(self, context):
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
vertices = context.active_object.data.vertices
check_b4w_obj_prop(context)
load_loops_normals_into_global_cache(context.active_object)
context.active_object.data.calc_normals()
offset = context.active_object.rotation_euler.to_matrix().inverted() * context.window_manager.b4w_customnormal_offset
if context.window_manager.b4w_split:
idx = get_selected_split_normal_idx(context.active_object)
self.apply(idx, offset)
else:
for i in range(len(vertices)):
if vertices[i].select:
for l in b4w_vertex_to_loops_map[i]:
self.apply(l, offset)
bpy.ops.object.mode_set(mode='OBJECT')
context.active_object.data.normals_split_custom_set(b4w_loops_normals)
bpy.ops.object.mode_set(mode='EDIT')
return{'FINISHED'}
def apply(self, idx, offset):
x, y, z = b4w_loops_normals[idx]
n = Vector((x + self.sign * offset.x,
y + self.sign * offset.y,
z + self.sign * offset.z)).normalized()
b4w_loops_normals[idx] = (n.x, n.y, n.z)
class B4W_RestoreNormals(bpy.types.Operator):
# clean up normal list
bl_idname = "object.b4w_restore_normals"
bl_label = p_("Restore Normals from vertices", "Operator")
bl_description = _('Restore normals from vertices')
bl_options = {"INTERNAL", "REGISTER", "UNDO"}
def execute(self, context):
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
vertices = context.active_object.data.vertices
polygons = context.active_object.data.polygons
check_b4w_obj_prop(context)
load_loops_normals_into_global_cache(context.active_object)
context.active_object.data.calc_normals()
if not context.window_manager.b4w_split:
# copy normals from vertexes
for i in range(len(vertices)):
n = vertices[i].normal
if vertices[i].select == True:
set_vertex_normal(i, (n.x,n.y,n.z))
else:
# copy normals from polygons
# bruteforce, so it is very slow
for i in range(len(vertices)):
if vertices[i].select:
for l in b4w_vertex_to_loops_map[i]:
for p in polygons:
for li in p.loop_indices:
if li == l:
n = p.normal
b4w_loops_normals[l] = (n.x, n.y, n.z)
bpy.ops.object.mode_set(mode='OBJECT')
context.active_object.data.normals_split_custom_set(b4w_loops_normals)
bpy.ops.object.mode_set(mode='EDIT')
return{'FINISHED'}
class B4W_SmoothNormals(bpy.types.Operator):
# clean up normal list
bl_idname = "object.b4w_smooth_normals"
bl_label = p_("Average Normals", "Operator")
bl_description = _('Average normals')
bl_options = {"INTERNAL", "REGISTER", "UNDO"}
def execute(self, context):
vertices = context.active_object.data.vertices
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.object.mode_set(mode='OBJECT')
check_b4w_obj_prop(context)
load_loops_normals_into_global_cache(context.active_object)
N = Vector()
for i in range(len(vertices)):
if vertices[i].select:
n = Vector()
for j in b4w_vertex_to_loops_map[i]:
n = n + Vector(b4w_loops_normals[j])
n.normalize()
if context.window_manager.b4w_split:
set_vertex_normal(i, (n.x,n.y,n.z))
else:
N += n
N.normalize()
if not context.window_manager.b4w_split:
for i in range(len(vertices)):
if vertices[i].select:
set_vertex_normal(i, (N.x, N.y, N.z))
bpy.ops.object.mode_set(mode='OBJECT')
context.active_object.data.normals_split_custom_set(b4w_loops_normals)
bpy.ops.object.mode_set(mode='EDIT')
return{'FINISHED'}
#------------ scale normal ------------
class EditNormalModalOperator():
number_strs =\
[["ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE"],
["NUMPAD_0", "NUMPAD_1", "NUMPAD_2", "NUMPAD_3", "NUMPAD_4", "NUMPAD_5", "NUMPAD_6", "NUMPAD_7", "NUMPAD_8", "NUMPAD_9"]]
mouse_x = 0
mouse_y = 0
def event_str_to_int_str(self, number_str):
try:
try:
n = self.number_strs[0].index(number_str)
except ValueError:
n = None
if n is not None:
return str(n)
else:
return str(self.number_strs[1].index(number_str))
except ValueError:
if "PERIOD" == number_str or "NUMPAD_PERIOD" == number_str:
return "."
return None
def calc_mouse_view(self, context):
a = None
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
for r in area.regions:
if r.type == 'WINDOW':
if (r.x <= self.mouse_x < (r.x+area.width) and
r.y <= self.mouse_y < (r.y + area.height)):
a = r
if a:
width = a.width
height = a.height
a_x = a.x
a_y = a.y
else:
return None
mouse = Vector(((self.mouse_x- a_x)/width*2 -1,