File size: 12,384 Bytes
da48dbe
 
 
 
 
fb140f6
da48dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
da48dbe
fb140f6
 
da48dbe
 
 
 
 
fb140f6
da48dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
da48dbe
 
fb140f6
da48dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
da48dbe
fb140f6
 
da48dbe
fb140f6
 
da48dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
da48dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
da48dbe
 
fb140f6
da48dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
da48dbe
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
da48dbe
fb140f6
da48dbe
 
 
fb140f6
da48dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
da48dbe
fb140f6
da48dbe
fb140f6
da48dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb140f6
 
 
 
da48dbe
 
 
 
 
 
 
 
 
 
 
fb140f6
da48dbe
 
 
 
 
 
 
 
 
fb140f6
da48dbe
 
 
 
 
 
 
fb140f6
da48dbe
 
 
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
import bpy
import sys, os
from math import radians
import mathutils
import bmesh

print(sys.exec_prefix)
from tqdm import tqdm
import numpy as np

##################################################
# Globals
##################################################

views = 120

render = 'eevee'
cycles_gpu = False

quality_preview = False
samples_preview = 16
samples_final = 256

resolution_x = 512
resolution_y = 512

shadows = False

# diffuse_color = (57.0/255.0, 108.0/255.0, 189.0/255.0, 1.0)
# diffuse_color = (18/255., 139/255., 142/255.,1)     #correct
# diffuse_color = (251/255., 60/255., 60/255.,1)    #wrong

smooth = False

wireframe = False
line_thickness = 0.1
quads = False

object_transparent = False
mouth_transparent = False

compositor_background_image = False
compositor_image_scale = 1.0
compositor_alpha = 0.7

##################################################
# Helper functions
##################################################


def blender_print(*args, **kwargs):
    print(*args, **kwargs, file=sys.stderr)


def using_app():
    ''' Returns if script is running through Blender application (GUI or background processing)'''
    return (not sys.argv[0].endswith('.py'))


def setup_diffuse_transparent_material(target, color, object_transparent, backface_transparent):
    ''' Sets up diffuse/transparent material with backface culling in cycles'''

    mat = target.active_material
    if mat is None:
        # Create material
        mat = bpy.data.materials.new(name='Material')
        target.data.materials.append(mat)

    mat.use_nodes = True
    nodes = mat.node_tree.nodes
    for node in nodes:
        nodes.remove(node)

    node_geometry = nodes.new('ShaderNodeNewGeometry')

    node_diffuse = nodes.new('ShaderNodeBsdfDiffuse')
    node_diffuse.inputs[0].default_value = color

    node_transparent = nodes.new('ShaderNodeBsdfTransparent')
    node_transparent.inputs[0].default_value = (1.0, 1.0, 1.0, 1.0)

    node_emission = nodes.new('ShaderNodeEmission')
    node_emission.inputs[0].default_value = (0.0, 0.0, 0.0, 1.0)

    node_mix = nodes.new(type='ShaderNodeMixShader')
    if object_transparent:
        node_mix.inputs[0].default_value = 1.0
    else:
        node_mix.inputs[0].default_value = 0.0

    node_mix_mouth = nodes.new(type='ShaderNodeMixShader')
    if object_transparent or backface_transparent:
        node_mix_mouth.inputs[0].default_value = 1.0
    else:
        node_mix_mouth.inputs[0].default_value = 0.0

    node_mix_backface = nodes.new(type='ShaderNodeMixShader')

    node_output = nodes.new(type='ShaderNodeOutputMaterial')

    links = mat.node_tree.links

    links.new(node_geometry.outputs[6], node_mix_backface.inputs[0])

    links.new(node_diffuse.outputs[0], node_mix.inputs[1])
    links.new(node_transparent.outputs[0], node_mix.inputs[2])
    links.new(node_mix.outputs[0], node_mix_backface.inputs[1])

    links.new(node_emission.outputs[0], node_mix_mouth.inputs[1])
    links.new(node_transparent.outputs[0], node_mix_mouth.inputs[2])
    links.new(node_mix_mouth.outputs[0], node_mix_backface.inputs[2])

    links.new(node_mix_backface.outputs[0], node_output.inputs[0])
    return


##################################################


def setup_scene():
    global render
    global cycles_gpu
    global quality_preview
    global resolution_x
    global resolution_y
    global shadows
    global wireframe
    global line_thickness
    global compositor_background_image

    # Remove default cube
    if 'Cube' in bpy.data.objects:
        bpy.data.objects['Cube'].select_set(True)
        bpy.ops.object.delete()

    scene = bpy.data.scenes['Scene']

    # Setup render engine
    if render == 'cycles':
        scene.render.engine = 'CYCLES'
    else:
        scene.render.engine = 'BLENDER_EEVEE'

    scene.render.resolution_x = resolution_x
    scene.render.resolution_y = resolution_y
    scene.render.resolution_percentage = 100
    scene.render.film_transparent = True
    if quality_preview:
        scene.cycles.samples = samples_preview
    else:
        scene.cycles.samples = samples_final

    # Setup Cycles CUDA GPU acceleration if requested
    if render == 'cycles':
        if cycles_gpu:
            print('Activating GPU acceleration')
            bpy.context.preferences.addons['cycles'].preferences.compute_device_type = 'CUDA'

            if bpy.app.version[0] >= 3:
                cuda_devices = bpy.context.preferences.addons[
                    'cycles'].preferences.get_devices_for_type(compute_device_type='CUDA')
            else:
                (cuda_devices, opencl_devices
                ) = bpy.context.preferences.addons['cycles'].preferences.get_devices()

            if (len(cuda_devices) < 1):
                print('ERROR: CUDA GPU acceleration not available')
                sys.exit(1)

            for cuda_device in cuda_devices:
                if cuda_device.type == 'CUDA':
                    cuda_device.use = True
                    print('Using CUDA device: ' + str(cuda_device.name))
                else:
                    cuda_device.use = False
                    print('Igoring CUDA device: ' + str(cuda_device.name))

            scene.cycles.device = 'GPU'
            if bpy.app.version[0] < 3:
                scene.render.tile_x = 256
                scene.render.tile_y = 256
        else:
            scene.cycles.device = 'CPU'
            if bpy.app.version[0] < 3:
                scene.render.tile_x = 64
                scene.render.tile_y = 64

    # Disable Blender 3 denoiser to properly measure Cycles render speed
    if bpy.app.version[0] >= 3:
        scene.cycles.use_denoising = False

    # Setup camera
    camera = bpy.data.objects['Camera']
    camera.location = (0.0, -3, 1.8)
    camera.rotation_euler = (radians(74), 0.0, 0)
    bpy.data.cameras['Camera'].lens = 55

    # Setup light

    # Setup lights
    light = bpy.data.objects['Light']
    light.location = (-2, -3.0, 0.0)
    light.rotation_euler = (radians(90.0), 0.0, 0.0)
    bpy.data.lights['Light'].type = 'POINT'
    bpy.data.lights['Light'].energy = 2
    light.data.cycles.cast_shadow = False

    if 'Sun' not in bpy.data.objects:
        bpy.ops.object.light_add(type='SUN')
        light_sun = bpy.context.active_object
        light_sun.location = (0.0, -3, 0.0)
        light_sun.rotation_euler = (radians(45.0), 0.0, radians(30))
        bpy.data.lights['Sun'].energy = 2
        light_sun.data.cycles.cast_shadow = shadows
    else:
        light_sun = bpy.data.objects['Sun']

    if shadows:
        # Setup shadow catcher
        bpy.ops.mesh.primitive_plane_add()
        plane = bpy.context.active_object
        plane.scale = (5.0, 5.0, 1)

        plane.cycles.is_shadow_catcher = True

        # Exclude plane from diffuse cycles contribution to avoid bright pixel noise in body rendering
        # plane.cycles_visibility.diffuse = False

        if wireframe:
            # Unmark freestyle edges
            bpy.ops.object.mode_set(mode='EDIT')
            bpy.ops.mesh.mark_freestyle_edge(clear=True)
            bpy.ops.object.mode_set(mode='OBJECT')

    # Setup freestyle mode for wireframe overlay rendering
    if wireframe:
        scene.render.use_freestyle = True
        scene.render.line_thickness = line_thickness
        bpy.context.view_layer.freestyle_settings.linesets[0].select_edge_mark = True

        # Disable border edges so that we don't see contour of shadow catcher plane
        bpy.context.view_layer.freestyle_settings.linesets[0].select_border = False
    else:
        scene.render.use_freestyle = False

    if compositor_background_image:
        # Setup compositing when using background image
        setup_compositing()
    else:
        # Output transparent image when no background is used
        scene.render.image_settings.color_mode = 'RGBA'


##################################################


def setup_compositing():

    global compositor_image_scale
    global compositor_alpha

    # Node editor compositing setup
    bpy.context.scene.use_nodes = True
    tree = bpy.context.scene.node_tree

    # Create input image node
    image_node = tree.nodes.new(type='CompositorNodeImage')

    scale_node = tree.nodes.new(type='CompositorNodeScale')
    scale_node.inputs[1].default_value = compositor_image_scale
    scale_node.inputs[2].default_value = compositor_image_scale

    blend_node = tree.nodes.new(type='CompositorNodeAlphaOver')
    blend_node.inputs[0].default_value = compositor_alpha

    # Link nodes
    links = tree.links
    links.new(image_node.outputs[0], scale_node.inputs[0])

    links.new(scale_node.outputs[0], blend_node.inputs[1])
    links.new(tree.nodes['Render Layers'].outputs[0], blend_node.inputs[2])

    links.new(blend_node.outputs[0], tree.nodes['Composite'].inputs[0])


def render_file(input_file, input_dir, output_file, output_dir, yaw, correct):
    '''Render image of given model file'''
    global smooth
    global object_transparent
    global mouth_transparent
    global compositor_background_image
    global quads

    path = input_dir + input_file

    # Import object into scene
    bpy.ops.import_scene.obj(filepath=path)
    object = bpy.context.selected_objects[0]

    object.rotation_euler = (radians(90.0), 0.0, radians(yaw))
    z_bottom = np.min(np.array([vert.co for vert in object.data.vertices])[:, 1])
    # z_top = np.max(np.array([vert.co for vert in object.data.vertices])[:,1])
    # blender_print(radians(90.0), z_bottom, z_top)
    object.location -= mathutils.Vector((0.0, 0.0, z_bottom))

    if quads:
        bpy.context.view_layer.objects.active = object
        bpy.ops.object.mode_set(mode='EDIT')
        bpy.ops.mesh.tris_convert_to_quads()
        bpy.ops.object.mode_set(mode='OBJECT')

    if smooth:
        bpy.ops.object.shade_smooth()

    # Mark freestyle edges
    bpy.context.view_layer.objects.active = object
    bpy.ops.object.mode_set(mode='EDIT')
    bpy.ops.mesh.mark_freestyle_edge(clear=False)
    bpy.ops.object.mode_set(mode='OBJECT')

    if correct:
        diffuse_color = (18 / 255., 139 / 255., 142 / 255., 1)    #correct
    else:
        diffuse_color = (251 / 255., 60 / 255., 60 / 255., 1)    #wrong

    setup_diffuse_transparent_material(object, diffuse_color, object_transparent, mouth_transparent)

    if compositor_background_image:
        # Set background image
        image_path = input_dir + input_file.replace('.obj', '_original.png')
        bpy.context.scene.node_tree.nodes['Image'].image = bpy.data.images.load(image_path)

    # Render
    bpy.context.scene.render.filepath = os.path.join(output_dir, output_file)

    # Silence console output of bpy.ops.render.render by redirecting stdout to file
    # Note: Does not actually write the output to file (Windows 7)
    sys.stdout.flush()
    old = os.dup(1)
    os.close(1)
    os.open('blender_render.log', os.O_WRONLY | os.O_CREAT)

    # Render
    bpy.ops.render.render(write_still=True)

    # Remove temporary output redirection
    #    sys.stdout.flush()
    #    os.close(1)
    #    os.dup(old)
    #    os.close(old)

    # Delete last selected object from scene
    object.select_set(True)
    bpy.ops.object.delete()


def process_file(input_file, input_dir, output_file, output_dir, correct=True):
    global views
    global quality_preview

    if not input_file.endswith('.obj'):
        print('ERROR: Invalid input: ' + input_file)
        return

    print('Processing: ' + input_file)
    if output_file == '':
        output_file = input_file[:-4]

    if quality_preview:
        output_file = output_file.replace('.png', '-preview.png')

    angle = 360.0 / views
    pbar = tqdm(range(0, views))
    for view in pbar:
        pbar.set_description(f"{os.path.basename(output_file)} | View:{str(view)}")
        yaw = view * angle
        output_file_view = f"{output_file}/{view:03d}.png"
        if not os.path.exists(os.path.join(output_dir, output_file_view)):
            render_file(input_file, input_dir, output_file_view, output_dir, yaw, correct)

    cmd = "ffmpeg -loglevel quiet -r 30 -f lavfi -i color=c=white:s=512x512 -i " + os.path.join(output_dir, output_file, '%3d.png') + \
        " -shortest -filter_complex \"[0:v][1:v]overlay=shortest=1,format=yuv420p[out]\" -map \"[out]\" -y " + output_dir+"/"+output_file+".mp4"
    os.system(cmd)