-
Notifications
You must be signed in to change notification settings - Fork 104
/
carbon_tools.py
1442 lines (1195 loc) · 51.6 KB
/
carbon_tools.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# 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 #####
# Copyright (c) 2023 Jakub Uhlik
bl_info = {"name": "Carbon Tools",
"description": "Ever-evolving set of small tools, workflows and shortcuts focused mainly on processing photogrammetry scans.",
"author": "Jakub Uhlik",
"version": (0, 2, 3),
"blender": (2, 80, 0),
"location": "3D Viewport > Sidebar > Carbon Tools",
"warning": "",
"wiki_url": "",
"tracker_url": "",
"category": "Object", }
import os
import uuid
import sys
import math
import bpy
import bmesh
from bpy.types import Operator, Panel, AddonPreferences
from mathutils import Vector, Matrix
from bpy.props import FloatProperty, IntProperty, BoolProperty, StringProperty, EnumProperty, PointerProperty
from bpy.types import PropertyGroup
import numpy as np
DEBUG = False
def log(msg, indent=0, ):
m = "{0}> {1}".format(" " * indent, msg)
if(DEBUG):
print(m)
class ObjDiff():
_objects = None
@classmethod
def diff(cls):
obs = [o for o in bpy.data.objects]
if(cls._objects is None):
cls._objects = obs
return None, None, None
a = list(set(obs) - set(cls._objects))
d = list(set(cls._objects) - set(obs))
u = list((set(cls._objects) - set(a)) - set(d))
cls._objects = obs
return a, d, u
class Utils():
@classmethod
def activate_object(cls, o):
bpy.ops.object.select_all(action='DESELECT')
context = bpy.context
view_layer = context.view_layer
o.select_set(True)
view_layer.objects.active = o
@classmethod
def get_spaceview3d(cls):
for a in bpy.context.screen.areas:
if(a.type == "VIEW_3D"):
return a.spaces[0]
return None
@classmethod
def normalize(cls, v, vmin, vmax):
return (v - vmin) / (vmax - vmin)
@classmethod
def interpolate(cls, nv, vmin, vmax):
return vmin + (vmax - vmin) * nv
@classmethod
def map(cls, v, min1, max1, min2, max2):
return cls.remap(v, min1, max1, min2, max2)
@classmethod
def remap(cls, v, min1, max1, min2, max2):
v = cls.clamp(v, min1, max1)
r = cls.interpolate(cls.normalize(v, min1, max1), min2, max2)
r = cls.clamp(r, min2, max2)
return r
@classmethod
def clamp(cls, v, vmin, vmax):
if(vmax <= vmin):
raise ValueError("Maximum value is smaller than or equal to minimum.")
if(v <= vmin):
return vmin
if(v >= vmax):
return vmax
return v
@classmethod
def maprange(cls, v, ar, br, ):
(a1, a2), (b1, b2) = ar, br
return b1 + ((v - a1) * (b2 - b1) / (a2 - a1))
@classmethod
def distance_vectors(cls, a, b, ):
return ((a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2) ** 0.5
@classmethod
def distance_tuples(cls, a, b, ):
return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2) ** 0.5
@classmethod
def distance(cls, a, b, ):
if(type(a) is Vector and type(b) is Vector):
return cls.distance_vectors(a, b)
return cls.distance_tuples(a, b)
@classmethod
def real_length_to_relative(cls, matrix, length):
l, r, s = matrix.decompose()
ms = Matrix.Scale(s.x, 4)
l = Vector((length, 0, 0))
v = ms.inverted() @ l
return v.x
@classmethod
def shift_vert_along_normal(cls, tco, tno, v):
co = Vector(tco)
no = Vector(tno)
return co + (no.normalized() * v)
class Progress():
def __init__(self, total, indent=0, prefix="> ", ):
self.current = 0
self.percent = -1
self.last = -1
self.total = total
self.prefix = prefix
self.indent = indent
self.t = " "
self.r = "\r"
self.n = "\n"
def step(self, numdone=1):
if(not DEBUG):
return
self.current += numdone
self.percent = int(self.current / (self.total / 100))
if(self.percent > self.last):
sys.stdout.write(self.r)
sys.stdout.write("{0}{1}{2}%".format(self.t * self.indent, self.prefix, self.percent))
self.last = self.percent
if(self.percent >= 100 or self.total == self.current):
sys.stdout.write(self.r)
sys.stdout.write("{0}{1}{2}%{3}".format(self.t * self.indent, self.prefix, 100, self.n))
class CARBON_OT_quick_mesh_dyntopo_cleanup(Operator):
bl_idname = "carbon_tools.quick_mesh_dyntopo_cleanup_setup"
bl_label = "Quick Mesh Dyntopo Cleanup Setup"
bl_description = "From Object mode go to Sculpt mode, enable Dyntopo and set zero strength to default brush. This is for mesh topology cleanup, not sculpting."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
ob = context.active_object
return (ob and ob.type == 'MESH' and context.mode == 'OBJECT')
def execute(self, context):
ctp = context.scene.carbon_tools
bpy.ops.object.select_all(action='DESELECT')
bpy.context.object.show_wire = True
bpy.ops.sculpt.sculptmode_toggle()
bpy.data.brushes["SculptDraw"].strength = 0
if(not context.sculpt_object.use_dynamic_topology_sculpting):
bpy.ops.sculpt.dynamic_topology_toggle()
# bpy.context.scene.tool_settings.sculpt.detail_refine_method = 'COLLAPSE'
bpy.context.scene.tool_settings.sculpt.detail_refine_method = ctp.dyntopo_method
bpy.context.scene.tool_settings.sculpt.detail_type_method = 'CONSTANT'
# bpy.context.scene.tool_settings.sculpt.constant_detail_resolution = 500
bpy.context.scene.tool_settings.sculpt.constant_detail_resolution = ctp.dyntopo_resolution
bpy.context.scene.tool_settings.sculpt.use_symmetry_x = False
return {'FINISHED'}
class CARBON_OT_extract_mesh_part(Operator):
bl_idname = "carbon_tools.extract_mesh_part"
bl_label = "Extract Mesh Part aka Extract Subtool"
bl_description = "Extract selected part of mesh (in Edit mode) and put it in separate child object for faster mesh editing."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
o = context.active_object
# return (o and o.type == 'MESH' and context.mode == 'EDIT_MESH')
return (o and o.type == 'MESH')
def extract(self, context, ):
o = context.active_object
sm = context.tool_settings.mesh_select_mode[:]
context.tool_settings.mesh_select_mode = (False, False, True)
ObjDiff.diff()
bpy.ops.mesh.separate(type='SELECTED')
bpy.ops.object.mode_set(mode='OBJECT')
a, _, _ = ObjDiff.diff()
e = a[0]
Utils.activate_object(e)
n = o.name
e.name = "{}-{}-extracted".format(n, uuid.uuid1())
e.parent = o
e.matrix_world = o.matrix_world.copy()
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
context.tool_settings.mesh_select_mode = (True, False, False)
ctp = context.scene.carbon_tools
if(ctp.extract_protect):
bpy.ops.mesh.select_non_manifold()
bpy.ops.mesh.hide(unselected=False)
context.tool_settings.mesh_select_mode = sm
return True
def execute(self, context):
r = self.extract(context)
if(r is False):
return {'CANCELLED'}
return {'FINISHED'}
class CARBON_OT_insert_mesh_part(Operator):
bl_idname = "carbon_tools.insert_mesh_part"
bl_label = "Insert Mesh Part aka Insert Subtool"
bl_description = "Insert separated mesh part back to original mesh and merge."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
o = context.active_object
# return (o and o.type == 'MESH' and context.mode == 'EDIT_MESH')
return (o and o.type == 'MESH' and context.mode == 'OBJECT')
def insert(self, context):
o = context.active_object
p = o.parent
if(p is None):
self.report({'ERROR'}, "Not a subtool.")
return False
# bpy.ops.object.mode_set(mode='OBJECT')
if(context.mode != 'EDIT'):
Utils.activate_object(o)
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.reveal()
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
Utils.activate_object(p)
o.select_set(True)
bpy.ops.object.join()
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
context.tool_settings.mesh_select_mode = (True, False, False)
bpy.ops.mesh.select_non_manifold()
# t = real_length_to_relative(p.matrix_world, 0.00001)
bpy.ops.mesh.remove_doubles(threshold=0.0)
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.object.mode_set(mode='OBJECT')
return True
def execute(self, context):
r = self.insert(context)
if(r is False):
return {'CANCELLED'}
return {'FINISHED'}
class CARBON_OT_extract_non_manifold_elements(Operator):
bl_idname = "carbon_tools.extract_non_manifold_elements"
bl_label = "Extract Non-Manifold"
bl_description = "Extract non-manifold elements with part of mesh around them as subtool"
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
o = context.active_object
return (o and o.type == 'MESH' and context.mode == 'EDIT_MESH')
def execute(self, context):
o = context.active_object
sm = context.tool_settings.mesh_select_mode[:]
context.tool_settings.mesh_select_mode = (True, False, False)
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.mesh.select_non_manifold()
bpy.ops.object.mode_set(mode='OBJECT')
ok = sum([v.select for v in o.data.vertices])
bpy.ops.object.mode_set(mode='EDIT')
if(not ok):
self.report({'ERROR'}, "Nothing non-manifold found.")
return {'CANCELLED'}
for i in range(10):
bpy.ops.mesh.select_more()
ct = context.scene.carbon_tools
ctep = ct.extract_protect
ct.extract_protect = False
bpy.ops.carbon_tools.extract_mesh_part()
ct.extract_protect = ctep
context.tool_settings.mesh_select_mode = sm
return {'FINISHED'}
class CARBON_OT_copy_original_matrix(Operator):
bl_idname = "carbon_tools.copy_original_matrix"
bl_label = "Copy Original Matrix from Selected to Active"
bl_description = "Select matrix source object first and then target object. Matrix will be copied while keeping visual transformation intact."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
o = context.active_object
return (o and o.type == 'MESH' and len(context.selected_objects) == 2)
def execute(self, context):
o = context.active_object
s = [ob for ob in context.selected_objects if ob != o][0]
m = s.matrix_world.copy()
mi = m.inverted()
me = o.data
me.transform(o.matrix_world)
o.matrix_world = Matrix()
me.transform(mi)
o.matrix_world = m
me.update()
return {'FINISHED'}
class CARBON_OT_copy_transformation(Operator):
bl_idname = "carbon_tools.copy_transformation"
bl_label = "Copy Transformation from Selected to Active"
bl_description = "Copy transformation from selected to active. Useful for setting correct scale and orientation after initial import from PhotoScan."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
o = context.active_object
return (o and o.type == 'MESH' and len(context.selected_objects) == 2)
def execute(self, context):
o = context.active_object
m = o.matrix_world.copy()
s = [a for a in context.selected_objects if a != o][0]
s.matrix_world = m
return {'FINISHED'}
class CARBON_OT_export_obj_to_zbrush(Operator):
bl_idname = "carbon_tools.export_obj_to_zbrush"
bl_label = "Export OBJ to ZBrush"
bl_description = "Export active mesh to ZBrush."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
ob = context.active_object
d = bpy.data
# return (ob and ob.type == 'MESH' and context.mode == 'OBJECT' and d.is_saved and not d.is_dirty)
return (ob and ob.type == 'MESH' and context.mode == 'OBJECT' and d.is_saved)
def execute(self, context):
b = bpy.data.filepath
h, t = os.path.split(b)
n, e = os.path.splitext(t)
p = os.path.join(h, '{}.obj'.format(n))
d = {'filepath': p,
'apply_modifiers': False,
'apply_transformation': True,
'convert_axes': True,
'triangulate': False,
'use_normals': True,
'use_uv': True,
'use_vcols': False,
'global_scale': 1.0,
'precision': 6, }
try:
bpy.ops.export_mesh.fast_obj(**d)
except AttributeError:
self.report({'ERROR'}, "'Fast Wavefront^2' addon is not installed and activated")
return {'CANCELLED'}
return {'FINISHED'}
class CARBON_OT_import_obj_from_zbrush(Operator):
bl_idname = "carbon_tools.import_obj_from_zbrush"
bl_label = "Import OBJ from ZBrush"
bl_description = "Import OBJ from ZBrush."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
return (context.mode == 'OBJECT')
def execute(self, context):
d = {'convert_axes': True,
'with_uv': True,
'with_vertex_colors_mrgb': False,
'with_vertex_colors_extended': False,
'vcols_ext_with_gamma': False,
'use_m_as_vertex_group': False,
'with_polygroups': False,
'global_scale': 1.0,
'apply_conversion': True, }
try:
bpy.ops.import_mesh.fast_obj('INVOKE_DEFAULT', **d)
except AttributeError:
self.report({'ERROR'}, "'Fast Wavefront^2' addon is not installed and activated")
return {'CANCELLED'}
return {'FINISHED'}
class CARBON_OT_export_obj_to_photoscan(Operator):
bl_idname = "carbon_tools.export_obj_to_photoscan"
bl_label = "Export OBJ to PhotoScan"
bl_description = "Export active mesh to PhotoScan."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
ob = context.active_object
d = bpy.data
# return (ob and ob.type == 'MESH' and context.mode == 'OBJECT' and d.is_saved and not d.is_dirty)
return (ob and ob.type == 'MESH' and context.mode == 'OBJECT' and d.is_saved)
def execute(self, context):
b = bpy.data.filepath
h, t = os.path.split(b)
n, e = os.path.splitext(t)
p = os.path.join(h, '{}.obj'.format(n))
d = {'filepath': p,
'apply_modifiers': False,
'apply_transformation': False,
'convert_axes': False,
'triangulate': False,
'use_normals': True,
'use_uv': True,
'use_vcols': False,
'global_scale': 1.0,
'precision': 6, }
try:
bpy.ops.export_mesh.fast_obj(**d)
except AttributeError:
self.report({'ERROR'}, "'Fast Wavefront^2' addon is not installed and activated")
return {'CANCELLED'}
return {'FINISHED'}
class CARBON_OT_quick_texture_painting_setup(Operator):
bl_idname = "carbon_tools.quick_texture_painting_setup"
bl_label = "Quick Texture Painting Setup"
bl_description = "Setup Texture painting, basically just set settings for External editing of viewport snapshots."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
ob = context.active_object
return (ob and ob.type == 'MESH' and context.mode == 'OBJECT')
def execute(self, context):
bpy.ops.paint.texture_paint_toggle()
ctp = context.scene.carbon_tools
bpy.context.object.show_wire = False
r = int(ctp.tp_ext_resolution)
bpy.context.scene.tool_settings.image_paint.screen_grab_size[0] = r
bpy.context.scene.tool_settings.image_paint.screen_grab_size[1] = r
bpy.context.scene.tool_settings.image_paint.seam_bleed = 8
bpy.data.brushes["TexDraw"].strength = 0
v = Utils.get_spaceview3d()
if(v is not None):
v.shading.color_type = 'TEXTURE'
v.shading.light = 'FLAT'
v.overlay.show_overlays = False
return {'FINISHED'}
class CARBON_OT_save_all_images(Operator):
bl_idname = "carbon_tools.save_all_images"
bl_label = "Save All Images"
bl_description = "Shortcut to Texture Painting > Slots > Save All Images."
bl_options = {'REGISTER', }
@classmethod
def poll(cls, context):
ob = context.active_object
return (ob and ob.type == 'MESH' and context.mode == 'PAINT_TEXTURE')
def execute(self, context):
bpy.ops.image.save_all_modified()
return {'FINISHED'}
class CARBON_OT_end_current_procedure(Operator):
bl_idname = "carbon_tools.end_current_procedure"
bl_label = "End Current Procedure"
bl_description = "Well, that doesn't explain... why you've come all the way out here, all the way out here to hell. I, uh, have a job out in the town of Machine. Machine? That's the end of the line."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
ob = context.active_object
return (ob and ob.type == 'MESH' and context.mode != 'OBJECT')
def execute(self, context):
ctp = context.scene.carbon_tools
bpy.ops.object.mode_set(mode='OBJECT')
if(not ctp.end_keep_wire):
bpy.context.object.show_wire = False
Utils.activate_object(context.active_object)
v = Utils.get_spaceview3d()
if(v is not None):
v.shading.color_type = 'MATERIAL'
v.shading.light = 'STUDIO'
v.overlay.show_overlays = True
return {'FINISHED'}
class CARBON_OT_select_seams(Operator):
bl_idname = "carbon_tools.select_seams"
bl_label = "Select Seams"
bl_description = "Set seam edges selected"
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
ob = context.active_object
return (ob and ob.type == 'MESH' and (context.mode == 'EDIT_MESH' or context.mode == 'OBJECT'))
def execute(self, context):
if(context.mode == 'OBJECT'):
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
context.tool_settings.mesh_select_mode = (False, True, False)
bpy.ops.object.mode_set(mode='OBJECT')
o = context.active_object
m = o.data
for e in m.edges:
if(e.use_seam):
e.select = True
bpy.ops.object.mode_set(mode='EDIT')
return {'FINISHED'}
class CARBON_OT_mark_seams_from_uv_islands(Operator):
bl_idname = "carbon_tools.mark_seams_from_uv_islands"
bl_label = "Mark Seams From UV Islands"
bl_description = "Mark Seams From UV Islands"
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
ob = context.active_object
return (ob and ob.type == 'MESH' and (context.mode == 'EDIT_MESH' or context.mode == 'OBJECT') and len(ob.data.uv_layers) > 0)
def execute(self, context):
e = True
if(context.mode != 'EDIT_MESH'):
e = False
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.uv.seams_from_islands()
if(not e):
bpy.ops.object.mode_set(mode='OBJECT')
return {'FINISHED'}
class CARBON_OT_export_uv_layout(Operator):
bl_idname = "carbon_tools.export_uv_layout"
bl_label = "Export UV Layout"
bl_description = "Export UV layout and png with resolution preset and fill opacity 1.0"
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
ob = context.active_object
return (ob and ob.type == 'MESH' and context.mode == 'OBJECT' and len(ob.data.uv_layers) > 0)
def execute(self, context):
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
# original_type = context.area.type
# context.area.type = "IMAGE_EDITOR"
b = bpy.data.filepath
h, t = os.path.split(b)
n, e = os.path.splitext(t)
p = os.path.join(h, '{}.png'.format(n))
if(os.path.exists(p)):
p = os.path.join(h, '{}-{}.png'.format(n, uuid.uuid1()))
ctp = context.scene.carbon_tools
r = int(ctp.export_uv_layout_resolution)
# bpy.ops.uv.export_layout(filepath=p, check_existing=False, export_all=False, modified=False, mode='PNG', size=(r, r), opacity=1.0, tessellated=False, )
bpy.ops.uv.export_layout(filepath=p, export_all=False, modified=False, mode='PNG', size=(r, r), opacity=1.0, )
# context.area.type = original_type
bpy.ops.object.mode_set(mode='OBJECT')
return {'FINISHED'}
class CARBON_OT_toggle_unselected_wireframe(Operator):
bl_idname = "carbon_tools.toggle_unselected_wireframe"
bl_label = "Toggle Unselected Wireframe"
bl_description = "Set object to draw wire, all edges and unselect object to be better visible in viewport"
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
ob = context.active_object
return (ob and ob.type == 'MESH' and context.mode == 'OBJECT')
def execute(self, context):
ob = context.active_object
if(ob.show_wire):
ob.show_wire = False
ob.show_all_edges = False
# ob.select = True
ob.select_set(True)
else:
ob.show_wire = True
ob.show_all_edges = True
# ob.select = False
ob.select_set(False)
return {'FINISHED'}
class CARBON_OT_visualize_uv_seams_as_wireframe_mesh(Operator):
bl_idname = "carbon_tools.visualize_uv_seams_as_wireframe_mesh"
bl_label = "Visualize UV Seams As Wireframe Mesh"
bl_description = "Copy seam edges to a new mesh object"
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
ob = context.active_object
return (ob and ob.type == 'MESH' and context.mode == 'OBJECT')
def execute(self, context):
ObjDiff.diff()
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='DESELECT')
bpy.ops.carbon_tools.select_seams()
bpy.ops.mesh.duplicate(mode=1)
ob = context.active_object
bm = bmesh.from_edit_mesh(ob.data)
bm.verts.ensure_lookup_table()
ok = False
for v in bm.verts:
if(v.select):
ok = True
break
if(not ok):
self.report({'ERROR'}, "Mesh has no seams to be selected.")
return {'CANCELLED'}
bpy.ops.mesh.separate(type='SELECTED')
a, _, _ = ObjDiff.diff()
bpy.ops.object.mode_set(mode='OBJECT')
o = a[0]
Utils.activate_object(o)
bpy.ops.carbon_tools.toggle_unselected_wireframe()
return {'FINISHED'}
class CARBON_OT_select_non_manifold_extra(Operator):
bl_idname = "carbon_tools.select_non_manifold_extra"
bl_label = "Select Non-Manifold"
bl_description = "Select non-manifold and optionally center camera view on selected"
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
o = context.active_object
sm = tuple([i for i in context.tool_settings.mesh_select_mode]) != (False, False, True)
return (o and o.type == 'MESH' and context.mode == 'EDIT_MESH' and sm)
def execute(self, context):
bpy.ops.mesh.select_non_manifold()
ctp = context.scene.carbon_tools
if(ctp.select_non_manifold_extra_auto_view):
bpy.ops.view3d.view_selected(use_all_regions=False)
return {'FINISHED'}
class CARBON_OT_texture_to_vertex_colors(Operator):
bl_idname = "carbon_tools.texture_to_vertex_colors"
bl_label = "UVTex > VCols"
bl_description = "Copy image colors from active image texture node in active material using active UV layout to new vertex colors"
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
# o = context.active_object
# o_ok = (o is not None and o.type == 'MESH' and context.mode == 'OBJECT')
# m = o.active_material
# m_ok = (m is not None)
# n_ok = False
# i_ok = False
# u_ok = (o.data.uv_layers.active is not None)
# if(m_ok):
# n = m.node_tree.nodes.active
# n_ok = (n.type == 'TEX_IMAGE')
# if(n_ok):
# if(n.image is not None):
# i = n.image
# i_ok = os.path.exists(i.filepath_from_user())
# return (o_ok and m_ok and n_ok and i_ok and u_ok)
if(context.mode != 'OBJECT'):
return False
o = context.active_object
if(not o):
return False
if(o.type != 'MESH'):
return False
m = o.active_material
if(not m):
return False
d = o.data
if(not d.uv_layers.active):
return False
n = m.node_tree.nodes.active
if(not n):
return False
if(n.type != 'TEX_IMAGE'):
return False
if(not n.image):
return False
i = n.image
if(not os.path.exists(i.filepath_from_user())):
return False
return True
def execute(self, context):
log(self.bl_idname, 0)
def remap(v, min1, max1, min2, max2):
def clamp(v, vmin, vmax):
if(vmax <= vmin):
raise ValueError("Maximum value is smaller than or equal to minimum.")
if(v <= vmin):
return vmin
if(v >= vmax):
return vmax
return v
def normalize(v, vmin, vmax):
return (v - vmin) / (vmax - vmin)
def interpolate(nv, vmin, vmax):
return vmin + (vmax - vmin) * nv
v = clamp(v, min1, max1)
r = interpolate(normalize(v, min1, max1), min2, max2)
r = clamp(r, min2, max2)
return r
o = context.active_object
m = o.active_material
n = m.node_tree.nodes.active
im = n.image
im.update()
w, h = im.size
a = np.asarray(im.pixels)
a = a.reshape((h, w, 4))
o.data.vertex_colors.new(name=im.name)
bm = bmesh.new()
bm.from_mesh(o.data)
col_layer = bm.loops.layers.color.active
uvl = bm.loops.layers.uv.active
fs = bm.faces
uv_layers = o.data.uv_layers
prgs = Progress(len(fs), 1)
for f in fs:
prgs.step()
ls = f.loops
for l in ls:
x, y = l[uvl].uv.to_tuple()
xx = int(round(remap(x, 0.0, 1.0, 0, w - 1)))
yy = int(round(remap(y, 0.0, 1.0, 0, h - 1)))
l[col_layer] = a[yy][xx]
bm.to_mesh(o.data)
bm.free()
log("done.", 1)
return {'FINISHED'}
class CARBON_OT_vertex_group_to_vertex_colors(Operator):
bl_idname = "carbon_tools.vertex_group_to_vertex_colors"
bl_label = "Group > VCols"
bl_description = "Active vertex group to new vertex colors, vertex weight to rgba(weight, weight, weight, 1.0)"
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
if(context.mode != 'OBJECT'):
return False
o = context.active_object
if(not o):
return False
if(o.type != 'MESH'):
return False
if(not o.vertex_groups.active):
return False
return True
def execute(self, context):
log(self.bl_idname, 0)
o = context.active_object
me = o.data
vg = o.vertex_groups.active
# add zero to every vertex to have them all in group
indexes = [i for i in range(len(me.vertices))]
vg.add(indexes, 0.0, 'ADD')
vc = me.vertex_colors.new(name=vg.name)
me.vertex_colors.active = vc
vcd = vc.data
vcols = [None] * len(me.vertices)
log("precalculating colors:", 1)
prgs = Progress(len(me.vertices), 2)
for v in me.vertices:
prgs.step()
i = v.index
w = vg.weight(i)
vcols[i] = (w, w, w, 1.0)
log("assigning colors:", 1)
prgs = Progress(len(me.loops), 2)
for l in me.loops:
prgs.step()
li = l.index
vi = l.vertex_index
vcd[li].color = vcols[vi]
log("done.", 1)
return {'FINISHED'}
class CARBON_OT_vertex_colors_to_vertex_group(Operator):
bl_idname = "carbon_tools.vertex_colors_to_vertex_group"
bl_label = "VCols > Group"
bl_description = "Active vertex colors to new vertex group, vertex weight by color perceived luminance"
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
if(context.mode != 'OBJECT'):
return False
o = context.active_object
if(not o):
return False
if(o.type != 'MESH'):
return False
if(not o.data.vertex_colors.active):
return False
return True
def execute(self, context):
log(self.bl_idname, 0)
o = context.active_object
me = o.data
vc = me.vertex_colors.active
vs = me.vertices
ls = me.loops
vg = o.vertex_groups.new(name=vc.name)
bm = bmesh.new()
bm.from_mesh(me)
lums = [None] * len(vs)
cl = bm.loops.layers.color.active
bm.verts.ensure_lookup_table()
log("precalculating weights:", 1)
prgs = Progress(len(bm.verts), 2)
for i, v in enumerate(bm.verts):
prgs.step()
vi = v.index
lums[vi] = []
ll = v.link_loops
for l in ll:
r, g, b, _ = l[cl][:]
# http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
lum = math.sqrt(0.299 * r ** 2 + 0.587 * g ** 2 + 0.114 * b ** 2)
lums[vi].append(lum)
ws = [None] * len(vs)
for i, a in enumerate(lums):
ws[i] = sum(a) / float(len(a))
log("assigning weights:", 1)
prgs = Progress(len(vs), 2)
for i, v in enumerate(vs):
prgs.step()
w = ws[i]
# if l is None, means that vertex is not connected to any face > has no loops > has no color/weight
if(l is not None):
vg.add([i], w, 'REPLACE')
bm.free()
log("done.", 1)
return {'FINISHED'}
class CARBON_OT_two_meshes_difference_to_vertex_group(Operator):
bl_idname = "carbon_tools.two_meshes_difference_to_vertex_group"
bl_label = "Difference > Group"
bl_description = "Calculate difference between two selected meshes and write as vertex group to active mesh. Selected is consedered to be original, active to be modified. Objects should have the same transformation."
bl_options = {'REGISTER', 'UNDO', }
@classmethod
def poll(cls, context):
if(context.mode != 'OBJECT'):
return False
o = context.active_object
if(not o):
return False
if(o.type != 'MESH'):
return False
obs = context.selected_objects
if(len(obs) != 2):
return False
for o in obs:
if(o.type != 'MESH'):
return False
return True
def execute(self, context):
log(self.bl_idname, 0)
ctp = context.scene.carbon_tools
modified = context.active_object
original = [o for o in context.selected_objects if o is not modified][0]
identical = True
for i, r in enumerate(original.matrix_world):
for j, c in enumerate(r):
if(c != modified.matrix_world[i][j]):
identical = False
break
if(not identical):
log("Original object matrix and modified object matrix are not equal.", 1, )
log("Will copy matrix from modified to original..", 1, )
mos = repr(original.matrix_world).replace(' ', '').replace('\n', '')