[
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2016 Panmari\nCopyright (c) 2020 Markus Völk\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Stanford Shapenet Renderer\n\nA little helper script to render .obj files (such as from the stanford shapenet database) with Blender.\n\nTested on Linux, but should also work for other operating systems.\nBy default, this scripts generates 30 images by rotating the camera around the object.\nAdditionally, depth, albedo, normal and id maps are dumped for every image.\n\nTested with Blender 2.9\n\n## Example invocation\n\nTo render a single `.obj` file, run\n\n    blender --background --python render_blender.py -- --output_folder /tmp path_to_model.obj\n\nTo get raw values that are easiest for further use, use `--format OPEN_EXR`. If the .obj file references any materials defined in a `.mtl` file, it is assumed to be in the same folder with the same name.\n\n## Batch rendering\n\nTo render a whole batch, you can e. g. use the unix tool find:\n\n    find . -name *.obj -exec blender --background --python render_blender.py -- --output_folder /tmp {} \\;\n\nTo speed up the process, you can also use xargs to have multiple blender instances run in parallel using the `-P` argument\n\n    find . -name *.obj -print0 | xargs -0 -n1 -P3 -I {} blender --background --python render_blender.py -- --output_folder /tmp {}\n\n## Example images\n\nHere is one chair model rendered with 30 different views:\n\n![Chairs](examples/out_without_specular.png)\n\nor a teapot with all available outputs\n\n![Teapots](examples/teapot_all_outputs.jpg)\n"
  },
  {
    "path": "render_blender.py",
    "content": "# A simple script that uses blender to render views of a single object by rotation the camera around it.\n# Also produces depth map at the same time.\n#\n# Tested with Blender 2.9\n#\n# Example:\n# blender --background --python mytest.py -- --views 10 /path/to/my.obj\n#\n\nimport argparse, sys, os, math, re\nimport bpy\nfrom glob import glob\n\nparser = argparse.ArgumentParser(description='Renders given obj file by rotation a camera around it.')\nparser.add_argument('--views', type=int, default=30,\n                    help='number of views to be rendered')\nparser.add_argument('obj', type=str,\n                    help='Path to the obj file to be rendered.')\nparser.add_argument('--output_folder', type=str, default='/tmp',\n                    help='The path the output will be dumped to.')\nparser.add_argument('--scale', type=float, default=1,\n                    help='Scaling factor applied to model. Depends on size of mesh.')\nparser.add_argument('--remove_doubles', type=bool, default=True,\n                    help='Remove double vertices to improve mesh quality.')\nparser.add_argument('--edge_split', type=bool, default=True,\n                    help='Adds edge split filter.')\nparser.add_argument('--depth_scale', type=float, default=1.4,\n                    help='Scaling that is applied to depth. Depends on size of mesh. Try out various values until you get a good result. Ignored if format is OPEN_EXR.')\nparser.add_argument('--color_depth', type=str, default='8',\n                    help='Number of bit per channel used for output. Either 8 or 16.')\nparser.add_argument('--format', type=str, default='PNG',\n                    help='Format of files generated. Either PNG or OPEN_EXR')\nparser.add_argument('--resolution', type=int, default=600,\n                    help='Resolution of the images.')\nparser.add_argument('--engine', type=str, default='BLENDER_EEVEE',\n                    help='Blender internal engine for rendering. E.g. CYCLES, BLENDER_EEVEE, ...')\n\nargv = sys.argv[sys.argv.index(\"--\") + 1:]\nargs = parser.parse_args(argv)\n\n# Set up rendering\ncontext = bpy.context\nscene = bpy.context.scene\nrender = bpy.context.scene.render\n\nrender.engine = args.engine\nrender.image_settings.color_mode = 'RGBA' # ('RGB', 'RGBA', ...)\nrender.image_settings.color_depth = args.color_depth # ('8', '16')\nrender.image_settings.file_format = args.format # ('PNG', 'OPEN_EXR', 'JPEG, ...)\nrender.resolution_x = args.resolution\nrender.resolution_y = args.resolution\nrender.resolution_percentage = 100\nrender.film_transparent = True\n\nscene.use_nodes = True\nscene.view_layers[\"View Layer\"].use_pass_normal = True\nscene.view_layers[\"View Layer\"].use_pass_diffuse_color = True\nscene.view_layers[\"View Layer\"].use_pass_object_index = True\n\nnodes = bpy.context.scene.node_tree.nodes\nlinks = bpy.context.scene.node_tree.links\n\n# Clear default nodes\nfor n in nodes:\n    nodes.remove(n)\n\n# Create input render layer node\nrender_layers = nodes.new('CompositorNodeRLayers')\n\n# Create depth output nodes\ndepth_file_output = nodes.new(type=\"CompositorNodeOutputFile\")\ndepth_file_output.label = 'Depth Output'\ndepth_file_output.base_path = ''\ndepth_file_output.file_slots[0].use_node_format = True\ndepth_file_output.format.file_format = args.format\ndepth_file_output.format.color_depth = args.color_depth\nif args.format == 'OPEN_EXR':\n    links.new(render_layers.outputs['Depth'], depth_file_output.inputs[0])\nelse:\n    depth_file_output.format.color_mode = \"BW\"\n\n    # Remap as other types can not represent the full range of depth.\n    map = nodes.new(type=\"CompositorNodeMapValue\")\n    # Size is chosen kind of arbitrarily, try out until you're satisfied with resulting depth map.\n    map.offset = [-0.7]\n    map.size = [args.depth_scale]\n    map.use_min = True\n    map.min = [0]\n\n    links.new(render_layers.outputs['Depth'], map.inputs[0])\n    links.new(map.outputs[0], depth_file_output.inputs[0])\n\n# Create normal output nodes\nscale_node = nodes.new(type=\"CompositorNodeMixRGB\")\nscale_node.blend_type = 'MULTIPLY'\n# scale_node.use_alpha = True\nscale_node.inputs[2].default_value = (0.5, 0.5, 0.5, 1)\nlinks.new(render_layers.outputs['Normal'], scale_node.inputs[1])\n\nbias_node = nodes.new(type=\"CompositorNodeMixRGB\")\nbias_node.blend_type = 'ADD'\n# bias_node.use_alpha = True\nbias_node.inputs[2].default_value = (0.5, 0.5, 0.5, 0)\nlinks.new(scale_node.outputs[0], bias_node.inputs[1])\n\nnormal_file_output = nodes.new(type=\"CompositorNodeOutputFile\")\nnormal_file_output.label = 'Normal Output'\nnormal_file_output.base_path = ''\nnormal_file_output.file_slots[0].use_node_format = True\nnormal_file_output.format.file_format = args.format\nlinks.new(bias_node.outputs[0], normal_file_output.inputs[0])\n\n# Create albedo output nodes\nalpha_albedo = nodes.new(type=\"CompositorNodeSetAlpha\")\nlinks.new(render_layers.outputs['DiffCol'], alpha_albedo.inputs['Image'])\nlinks.new(render_layers.outputs['Alpha'], alpha_albedo.inputs['Alpha'])\n\nalbedo_file_output = nodes.new(type=\"CompositorNodeOutputFile\")\nalbedo_file_output.label = 'Albedo Output'\nalbedo_file_output.base_path = ''\nalbedo_file_output.file_slots[0].use_node_format = True\nalbedo_file_output.format.file_format = args.format\nalbedo_file_output.format.color_mode = 'RGBA'\nalbedo_file_output.format.color_depth = args.color_depth\nlinks.new(alpha_albedo.outputs['Image'], albedo_file_output.inputs[0])\n\n# Create id map output nodes\nid_file_output = nodes.new(type=\"CompositorNodeOutputFile\")\nid_file_output.label = 'ID Output'\nid_file_output.base_path = ''\nid_file_output.file_slots[0].use_node_format = True\nid_file_output.format.file_format = args.format\nid_file_output.format.color_depth = args.color_depth\n\nif args.format == 'OPEN_EXR':\n    links.new(render_layers.outputs['IndexOB'], id_file_output.inputs[0])\nelse:\n    id_file_output.format.color_mode = 'BW'\n\n    divide_node = nodes.new(type='CompositorNodeMath')\n    divide_node.operation = 'DIVIDE'\n    divide_node.use_clamp = False\n    divide_node.inputs[1].default_value = 2**int(args.color_depth)\n\n    links.new(render_layers.outputs['IndexOB'], divide_node.inputs[0])\n    links.new(divide_node.outputs[0], id_file_output.inputs[0])\n\n# Delete default cube\ncontext.active_object.select_set(True)\nbpy.ops.object.delete()\n\n# Import textured mesh\nbpy.ops.object.select_all(action='DESELECT')\n\nbpy.ops.import_scene.obj(filepath=args.obj)\n\nobj = bpy.context.selected_objects[0]\ncontext.view_layer.objects.active = obj\n\n# Possibly disable specular shading\nfor slot in obj.material_slots:\n    node = slot.material.node_tree.nodes['Principled BSDF']\n    node.inputs['Specular'].default_value = 0.05\n\nif args.scale != 1:\n    bpy.ops.transform.resize(value=(args.scale,args.scale,args.scale))\n    bpy.ops.object.transform_apply(scale=True)\nif args.remove_doubles:\n    bpy.ops.object.mode_set(mode='EDIT')\n    bpy.ops.mesh.remove_doubles()\n    bpy.ops.object.mode_set(mode='OBJECT')\nif args.edge_split:\n    bpy.ops.object.modifier_add(type='EDGE_SPLIT')\n    context.object.modifiers[\"EdgeSplit\"].split_angle = 1.32645\n    bpy.ops.object.modifier_apply(modifier=\"EdgeSplit\")\n\n# Set objekt IDs\nobj.pass_index = 1\n\n# Make light just directional, disable shadows.\nlight = bpy.data.lights['Light']\nlight.type = 'SUN'\nlight.use_shadow = False\n# Possibly disable specular shading:\nlight.specular_factor = 1.0\nlight.energy = 10.0\n\n# Add another light source so stuff facing away from light is not completely dark\nbpy.ops.object.light_add(type='SUN')\nlight2 = bpy.data.lights['Sun']\nlight2.use_shadow = False\nlight2.specular_factor = 1.0\nlight2.energy = 0.015\nbpy.data.objects['Sun'].rotation_euler = bpy.data.objects['Light'].rotation_euler\nbpy.data.objects['Sun'].rotation_euler[0] += 180\n\n# Place camera\ncam = scene.objects['Camera']\ncam.location = (0, 1, 0.6)\ncam.data.lens = 35\ncam.data.sensor_width = 32\n\ncam_constraint = cam.constraints.new(type='TRACK_TO')\ncam_constraint.track_axis = 'TRACK_NEGATIVE_Z'\ncam_constraint.up_axis = 'UP_Y'\n\ncam_empty = bpy.data.objects.new(\"Empty\", None)\ncam_empty.location = (0, 0, 0)\ncam.parent = cam_empty\n\nscene.collection.objects.link(cam_empty)\ncontext.view_layer.objects.active = cam_empty\ncam_constraint.target = cam_empty\n\nstepsize = 360.0 / args.views\nrotation_mode = 'XYZ'\n\nmodel_identifier = os.path.split(os.path.split(args.obj)[0])[1]\nfp = os.path.join(os.path.abspath(args.output_folder), model_identifier, model_identifier)\n\nfor i in range(0, args.views):\n    print(\"Rotation {}, {}\".format((stepsize * i), math.radians(stepsize * i)))\n\n    render_file_path = fp + '_r_{0:03d}'.format(int(i * stepsize))\n\n    scene.render.filepath = render_file_path\n    depth_file_output.file_slots[0].path = render_file_path + \"_depth\"\n    normal_file_output.file_slots[0].path = render_file_path + \"_normal\"\n    albedo_file_output.file_slots[0].path = render_file_path + \"_albedo\"\n    id_file_output.file_slots[0].path = render_file_path + \"_id\"\n\n    bpy.ops.render.render(write_still=True)  # render still\n\n    cam_empty.rotation_euler[2] += math.radians(stepsize)\n\n# For debugging the workflow\n#bpy.ops.wm.save_as_mainfile(filepath='debug.blend')\n"
  }
]