-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtarget_convert.py
522 lines (386 loc) · 19.1 KB
/
target_convert.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
bl_info = {
"name" : "Target Conversion",
"description" : "Converts Target To Mesh", # To Allow Updating Of Mesh
"author" : "Steffenvy", #Jacob Morris
"blender" : (2, 80, 0),
"location" : "Properties > Modifiers > Target Conversion",
"version" : (1, 0),
"category" : "Object"
}
import bpy
import math
import bmesh
from bpy.props import StringProperty, BoolProperty, FloatProperty, FloatVectorProperty, PointerProperty, EnumProperty
import mathutils
compatibleTargetTypes = ['MESH', 'CURVE', 'SURFACE', 'META', 'FONT']
#bpy.types.Object.names = StringProperty(name = "Object Name", default = "")
#bpy.types.Object.rscale = BoolProperty(name = "Respect Scale?", default = False)
def object_poll(self, object):
return (object.type in compatibleTargetTypes) or (object.instance_type != 'NONE') #== 'CURVE' or object.type == 'MESH' or object.instance_type != 'NONE'
bpy.types.Object.useCollection = BoolProperty(name = "Use Collection", default = False)
bpy.types.Object.objectTarget = bpy.props.PointerProperty(name = "Target", type=bpy.types.Object, poll=object_poll)
bpy.types.Object.collectionTarget = bpy.props.PointerProperty(name = "Target", type=bpy.types.Collection)
bpy.types.Object.respectScale = BoolProperty(name = "Respect Scale", default = False)
bpy.types.Object.removeDoubles = BoolProperty(name = "Remove Doubles?", default = False)
bpy.types.Object.doublesDistance = FloatProperty(name = "Doubles Distance", default = 0.0001)
bpy.types.Object.recalcNormals = BoolProperty(name = "Recalculate Normals?", default = False)
bpy.types.Object.targetRelative = BoolProperty(name = "Respect Local Positions", default = True) #Prefit
bpy.types.Object.keepMaterials = BoolProperty(name = "Keep Current Materials?", default = True)
bpy.types.Object.unifyUVs = BoolProperty(name = "Unify UV Maps?", default = True) #This is important for dupli-groups (curves have "Octo" uvs, and meshes "UVMap")
bpy.types.Object.cubeProjection = BoolProperty(name = "Do Cube Projection?", default = False)
bpy.types.Object.unwrapType = EnumProperty(name='Unwrap Type', items = {('NONE', 'none', 'No Projection'), ('CUBE', 'cube', 'Cube Projection'), ('SPHERE', 'sphere', 'Sphere Projection'), ('Cylinder', 'cylinder', 'Cylinder Projection')},
default='NONE')
bpy.types.Object.transformUVs = BoolProperty(name = "Transform UVs?", default = False)
bpy.types.Object.uvStartScale = FloatVectorProperty(name = "UV First Scale",subtype='XYZ',precision=2,size=2,default=(1.0,1.0))
bpy.types.Object.uvRotation = FloatProperty(name = "UV Rotation", default = 0)
bpy.types.Object.uvScale = FloatVectorProperty(name = "UV Second Scale",subtype='XYZ',precision=2,size=2,default=(1.0,1.0))
bpy.types.Object.uvOffset = FloatVectorProperty(name = "UV Offset",subtype='XYZ',precision=2,size=2,default=(0,0))
#TODO: maybe make sure to have at least one uv map?
#TODO: problem with mirror modifiers and all that? modifiers that depend on other positions?
#make target relative be possible for collection mode but use world origin as default for offset
#hidden collections at least with instancing doesn't work
#instancing inside colleciton doesn't work when collection mode
#make it fail when the target is the same data as the o?
def rotate(origin, point, angle):
angle *= 0.0174533
ox, oy = origin
px, py = point
qx = ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy)
qy = oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)
return qx, qy
def TargetConvert(self, context):
o = context.object
if o.useCollection:
target = o.collectionTarget
else:
target = o.objectTarget
if o.data == target.data:
return
if target != None:
prevData = o.data.copy()
#Setup (prevents errors)
if bpy.context.active_object.mode == 'EDIT':
bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
o_hide = o.hide_viewport
o.hide_viewport = False
o_hide2 = o.hide_get()
o.hide_set(False)
#Single Object
if o.useCollection == False and ((target.instance_type == 'NONE') or (len(target.children) == 0 and target.instance_type != 'COLLECTION')): #seems that if it's a deleted but still existing child, it will still think there is one. meh.
#{
if o.targetRelative:
bpy.ops.object.select_all(action='DESELECT')
target.select_set(True)
context.view_layer.objects.active = target
depsgraph = bpy.context.evaluated_depsgraph_get()
print(depsgraph)
target_eval = target.evaluated_get(depsgraph)
print(target_eval)
tempData = target_eval.to_mesh(preserve_all_data_layers=True, depsgraph=depsgraph)
print(tempData)
#tempData = target.to_mesh(preserve_all_data_layers=True) #context.scene, True, 'PREVIEW', calc_tessface=True, calc_undeformed=False) #ob.data
bm = bmesh.new(use_operators=True) #o.data = bpy.data.meshes.new("Converted Mesh")
bm.from_mesh(tempData) # nonetype
bm.to_mesh(o.data)
bm.free()
#target.to_mesh_clear()
target_eval.to_mesh_clear()
target.select_set(False)
context.view_layer.objects.active = o
o.select_set(True)
#This process doesn't copy materials, unlike the other methods
if not o.keepMaterials:
o.data.materials.clear()
td = target.data
if len(td.materials) > 0: #To prevent a crash bug it seems. TODO: bug report?
for i in td.materials:
o.data.materials.append(i)
else:
o.data.materials.append(None)
else:
bpy.ops.object.select_all(action='DESELECT')
dupe = target.copy()
context.scene.collection.objects.link(dupe)
dupe.data = dupe.data.copy()
dupe.hide_viewport = False
dupe.select_set(True)
context.view_layer.objects.active = dupe
bpy.ops.object.convert(target='MESH')
o.select_set(True)
context.view_layer.objects.active = o
bm = bmesh.new() #use_operators=True) #o.data = bpy.data.meshes.new("Converted Mesh")
bm.to_mesh(o.data)
bm.free()
bpy.ops.object.join()
bpy.ops.object.select_all(action='DESELECT')
o.select_set(True)
context.view_layer.objects.active = o
if o.unifyUVs:
for uvmap in o.data.uv_layers :
uvmap.name = 'UVMap'
#}
else:
#{
#Remembers which collections were visible
c_hiddens = []
collections = bpy.data.collections
for c in collections:
c_hiddens.append(c.hide_render)
c.hide_render = False
bpy.ops.object.select_all(action='DESELECT')
#Gets duplicates, and selects them
if o.useCollection:
for t in target.all_objects:
if t.type in compatibleTargetTypes: #== "CURVE" or t.type == "MESH" or t.type == "TEXT":
if t != o:
tt = t.copy()
context.scene.collection.objects.link(tt)
tt.select_set(True)
else:
#Remembers some settings
instanceType = target.instance_type
instanceC = target.instance_collection
visib = target.hide_viewport
target.hide_viewport = False
hidd = target.hide_get()
target.hide_set(False)
#Makes real
target.select_set(True)
context.view_layer.objects.active = target
donts = target.children
bpy.ops.object.duplicates_make_real(use_base_parent=True, use_hierarchy=False) #dupli_type = target.dupli_type
target.select_set(False) #target.dupli_type = dupli_type
maybes = target.children
yesses = [x for x in maybes if x not in donts]
for x in yesses:
x.select_set(True)
#Reverts
target.instance_type = instanceType
target.instance_collection = instanceC
target.hide_viewport = visib
target.hide_set(hidd)
#Makes all be Meshes (not curves), at same time instantiating them
sels = context.selected_objects
bpy.ops.object.select_all(action='DESELECT')
for sel in sels:
sel.data = sel.data.copy()
sel.select_set(True)
context.view_layer.objects.active = sel
bpy.ops.object.convert(target='MESH')
if o.unifyUVs and sel.data.uv_layers:
for uvmap in sel.data.uv_layers :
uvmap.name = 'UVMap'
sel.select_set(False) # I could maybe do this without de then re selecting?
for sel in sels: #Reselects
sel.select_set(True)
#Clones
targ = o
useTempTarg = o.useCollection == False and o.targetRelative
if useTempTarg:
tempTarg = bpy.data.objects.new("temp", o.data)
context.scene.collection.objects.link(tempTarg)
tempTarg.matrix_world = target.matrix_world
tempTarg.hide_viewport = False
targ = tempTarg
#Clears mesh data
mesh = targ.data
bm = bmesh.new(use_operators=True)
bm.to_mesh(mesh)
bm.free()
#Joins the duplicates into the clone, then o, to preserve transformation differences
targ.select_set(True)
context.view_layer.objects.active = targ
bpy.ops.object.join()
o.data = targ.data #?
#Deletes Clone
bpy.ops.object.select_all(action='DESELECT')
if useTempTarg:
tempTarg.select_set(True)
bpy.ops.object.delete()
#Now select the result
o.select_set(True)
context.view_layer.objects.active = o
#Reverts Collection Visibility
i = 0
for c in collections:
c.hide_render = c_hiddens[i]
i += 1
#}
#Resets to previous materials
if o.keepMaterials:
o.data.materials.clear()
if len(prevData.materials) > 0: #To prevent a crash bug it seems. TODO: bug report?
for i in prevData.materials:
o.data.materials.append(i)
else:
o.data.materials.append(None)
#Scales object
if o.useCollection == False and o.respectScale == True: #and target.instance_type == 'NONE': #????
o.scale = target.scale
#Cube Projection preparation
if o.cubeProjection == True:
bpy.context.view_layer.objects.active = o
maxcount = 1000
while(len(o.data.uv_layers) and maxcount > 0): #is this paranoia?
bpy.ops.mesh.uv_texture_remove()
maxcount -= 1
#Remove Doubles
bpy.ops.object.mode_set(mode='EDIT', toggle=False)
bpy.ops.mesh.select_all(action='SELECT')
if o.removeDoubles == True:
bpy.ops.mesh.remove_doubles(threshold=o.doublesDistance) #0.0001)
bpy.ops.mesh.faces_shade_smooth()
#Recalculate Normals
if o.recalcNormals == True:
bpy.ops.mesh.normals_make_consistent()
#Cube Projection
if o.cubeProjection == True and len(o.data.vertices) > 2:
bpy.ops.uv.cube_project(cube_size=1.0)
#Cube Projection
bpy.ops.object.mode_set()
bm = bmesh.new(use_operators=True) #o.data = bpy.data.meshes.new("Converted Mesh")
bm.from_mesh(o.data)
uv_layer = bm.loops.layers.uv.active
if o.transformUVs:
for face in bm.faces:
for vert, loop in zip(face.verts, face.loops):
tuv = loop[uv_layer].uv #= #get_uvs(vert.index, face.index,...) #
tuv -= mathutils.Vector((.5,.5))
tuv.x *= o.uvStartScale.x
tuv.y *= o.uvStartScale.y
tuv = mathutils.Vector(rotate((0, 0), tuv, o.uvRotation))
tuv.x *= o.uvScale.x
tuv.y *= o.uvScale.y
tuv += mathutils.Vector((.5,.5))
tuv += o.uvOffset
loop[uv_layer].uv = tuv
bm.to_mesh(o.data)
bm.free()
#Rehides
o.hide_viewport = o_hide
o.hide_set(o_hide2)
else:
self.report({"ERROR"}, "Object Not Found")
class TargetConversionAdd(bpy.types.Operator):
bl_label = "Add Mesh Object"
bl_idname = "mesh.target_convert_add"
bl_options = {"UNDO"}
def execute(self, context):
target = context.object
na = target.name
clone = target.copy()
clone.data = target.data.copy()
#Collections
#context.scene.collection.objects.link(clone)
for c in target.users_collection:
c.objects.link(clone)
if ' Maker' in na:
clone.name = na.replace(' Maker', '')
else:
clone.name = na + ' Result' #' Mesh'
bpy.ops.object.select_all(action='DESELECT')
clone.select_set(True)
context.view_layer.objects.active = clone
bpy.ops.object.convert(target='MESH')
clone["objectTarget"] = target
clone.instance_type = 'NONE'
#Parents
target.select_set(True)
clone.select_set(True)
context.view_layer.objects.active = clone
target.parent = clone #bpy.ops.object.parent_no_inverse_set() #bpy.ops.object.parent_set(type='OBJECT', keep_transform=False) #True
target.matrix_local.identity() # = mathutils.Matrix.identity()
target.select_set(False)
#bpy.ops.target_converter.upgrade(clone) #?
return {"FINISHED"}
class TargetConversionUpdate(bpy.types.Operator):
bl_label = "Update Mesh"
bl_idname = "mesh.target_convert_update"
bl_options = {"UNDO"}
def execute(self, context):
TargetConvert(self, context)
return {"FINISHED"}
#Upgrading from curve_converter
class TCUpdate(bpy.types.Operator):
bl_label = "Upgrade From Curve-Converter"
bl_idname = "target_converter.upgrade"
bl_options = {"UNDO"}
def execute(self, context):
for o in context.blend_data.objects:
if "names" in o.keys():
if o["names"] != "":
try:
o["objectTarget"] = bpy.data.objects[o["names"]]
except:
pass
del o["names"]
if "rscale" in o.keys():
o["respectScale"] = o["rscale"]
del o["rscale"]
return {"FINISHED"}
class SelectTarget(bpy.types.Operator):
bl_label = "Select Target"
bl_idname = "target_converter.select_target"
bl_options = {"UNDO"}
def execute(self, context):
try:
o = bpy.context.active_object
target = o["objectTarget"]
target.hide_viewport = False
target.select_set(True)
context.view_layer.objects.active = target
o.select_set(False)
except:
pass
return {"FINISHED"}
class TargetConversionPanel(bpy.types.Panel):
bl_label = "Target Conversion"
bl_idname = "OBJECT_PT_convert"
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "modifier"
bl_options = {"DEFAULT_CLOSED"}
def draw(self, context):
layout = self.layout; o = context.object
if o.type == "MESH":
layout.prop(o, "useCollection", icon = "NONE");
if o.useCollection:
layout.prop(o, "collectionTarget", icon = "NONE") #layout.prop_search(o, "names", context.scene, "objects");
else:
layout.prop(o, "objectTarget", icon = "NONE")
layout.prop(o, "targetRelative", icon = "OUTLINER_OB_EMPTY")
layout.prop(o, "respectScale", icon="CON_SIZELIKE") #I can't find "MAN_SCALE" (scaling icon)
layout.prop(o, "keepMaterials", icon = "MATERIAL")
layout.prop(o, "recalcNormals", icon = "MOD_NORMALEDIT")
layout.separator_spacer()
layout.prop(o, "removeDoubles", icon = "NONE")
if o.removeDoubles:
layout.prop(o, "doublesDistance", icon = "NONE")
layout.separator_spacer()
layout.label(text="UVs:", icon = "GROUP_UVS")
layout.prop(o, "unifyUVs", icon = "NONE")
layout.prop(o, "cubeProjection", icon = "NONE")
layout.prop(o, "transformUVs", icon = "NONE")
if o.transformUVs:
layout.prop(o, "uvStartScale", icon = "NONE")
layout.prop(o, "uvRotation", icon = "NONE")
layout.prop(o, "uvScale", icon = "NONE")
layout.prop(o, "uvOffset", icon = "NONE")
layout.separator_spacer()
layout.operator(TargetConversionUpdate.bl_idname, text=TargetConversionUpdate.bl_label)
layout.separator(factor=5)
if o.type in compatibleTargetTypes: # == "CURVE" or o.type == "MESH":
layout.operator(TargetConversionAdd.bl_idname, text=TargetConversionAdd.bl_label)
if o.useCollection == False and o.objectTarget != None:
layout.separator(factor=5)
layout.operator(SelectTarget.bl_idname, text=SelectTarget.bl_label)
classes = (
TargetConversionAdd,
TargetConversionUpdate,
TargetConversionPanel,
TCUpdate,
SelectTarget
)
register, unregister = bpy.utils.register_classes_factory(classes)
if __name__ == "__main__":
register()